Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add excludedPath to in-source config #5717

Merged
merged 4 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/zip-it-and-ship-it/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import { arch, platform } from 'process'
import type { InvocationMode } from './function.js'
import type { TrafficRules } from './rate_limit.js'
import type { FunctionResult } from './utils/format_result.js'
import type { Route } from './utils/routes.js'
import type { ExtendedRoute, Route } from './utils/routes.js'

interface ManifestFunction {
buildData?: Record<string, unknown>
invocationMode?: InvocationMode
mainFile: string
name: string
path: string
routes?: Route[]
routes?: ExtendedRoute[]
excludedRoutes?: Route[]
runtime: string
runtimeVersion?: string
schedule?: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import { z } from 'zod'
import { FunctionConfig, functionConfig } from '../../../config.js'
import { InvocationMode, INVOCATION_MODE } from '../../../function.js'
import { rateLimit } from '../../../rate_limit.js'
import { ensureArray } from '../../../utils/ensure_array.js'
import { FunctionBundlingUserError } from '../../../utils/error.js'
import { Route, getRoutes } from '../../../utils/routes.js'
import { ExtendedRoute, Route, getRoutes } from '../../../utils/routes.js'
import { RUNTIME } from '../../runtime.js'
import { createBindingsMethod } from '../parser/bindings.js'
import { traverseNodes } from '../parser/exports.js'
Expand All @@ -22,24 +23,24 @@ export const IN_SOURCE_CONFIG_MODULE = '@netlify/functions'

export interface StaticAnalysisResult {
config: InSourceConfig
excludedRoutes?: Route[]
inputModuleFormat?: ModuleFormat
invocationMode?: InvocationMode
routes?: Route[]
routes?: ExtendedRoute[]
runtimeAPIVersion?: number
}

interface FindISCDeclarationsOptions {
functionName: string
}

const ensureArray = (input: unknown) => (Array.isArray(input) ? input : [input])

const httpMethods = z.preprocess(
(input) => (typeof input === 'string' ? input.toUpperCase() : input),
z.enum(['GET', 'POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE', 'HEAD']),
)
const httpMethod = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE', 'HEAD'])
const httpMethods = z.preprocess((input) => (typeof input === 'string' ? input.toUpperCase() : input), httpMethod)
const path = z.string().startsWith('/', { message: "Must start with a '/'" })

export type HttpMethod = z.infer<typeof httpMethod>
export type HttpMethods = z.infer<typeof httpMethods>

export const inSourceConfig = functionConfig
.pick({
externalNodeModules: true,
Expand All @@ -63,6 +64,10 @@ export const inSourceConfig = functionConfig
.union([path, z.array(path)], { errorMap: () => ({ message: 'Must be a string or array of strings' }) })
.transform(ensureArray)
.optional(),
excludedPath: z
.union([path, z.array(path)], { errorMap: () => ({ message: 'Must be a string or array of strings' }) })
.transform(ensureArray)
.optional(),
preferStatic: z.boolean().optional().catch(undefined),
rateLimit: rateLimit.optional().catch(undefined),
})
Expand Down Expand Up @@ -138,12 +143,12 @@ export const parseSource = (source: string, { functionName }: FindISCDeclaration

if (success) {
result.config = data
result.routes = getRoutes({
functionName,
result.excludedRoutes = getRoutes(functionName, data.excludedPath)
result.routes = getRoutes(functionName, data.path).map((route) => ({
...route,
methods: data.method ?? [],
path: data.path,
preferStatic: data.preferStatic,
})
prefer_static: data.preferStatic || undefined,
}))
} else {
// TODO: Handle multiple errors.
const [issue] = error.issues
Expand Down
1 change: 1 addition & 0 deletions packages/zip-it-and-ship-it/src/utils/ensure_array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const ensureArray = <T>(input: T | T[]) => (Array.isArray(input) ? input : [input])
6 changes: 4 additions & 2 deletions packages/zip-it-and-ship-it/src/utils/format_result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { FunctionArchive } from '../function.js'
import { RuntimeName } from '../runtimes/runtime.js'

import { removeUndefined } from './remove_undefined.js'
import type { Route } from './routes.js'
import type { ExtendedRoute, Route } from './routes.js'

export type FunctionResult = Omit<FunctionArchive, 'runtime'> & {
routes?: Route[]
routes?: ExtendedRoute[]
excludedRoutes?: Route[]
runtime: RuntimeName
schedule?: string
runtimeAPIVersion?: number
Expand All @@ -17,6 +18,7 @@ export const formatZipResult = (archive: FunctionArchive) => {
...archive,
staticAnalysisResult: undefined,
routes: archive.staticAnalysisResult?.routes,
excludedRoutes: archive.staticAnalysisResult?.excludedRoutes,
runtime: archive.runtime.name,
schedule: archive.staticAnalysisResult?.config?.schedule ?? archive?.config?.schedule,
runtimeAPIVersion: archive.staticAnalysisResult?.runtimeAPIVersion,
Expand Down
44 changes: 7 additions & 37 deletions packages/zip-it-and-ship-it/src/utils/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import { FunctionBundlingUserError } from './error.js'
import { nonNullable } from './non_nullable.js'
import { ExtendedURLPattern } from './urlpattern.js'

export type Route = { pattern: string; methods: string[]; prefer_static?: boolean } & (
| { literal: string }
| { expression: string }
)
export type Route = { pattern: string } & ({ literal: string } | { expression: string })
export type ExtendedRoute = Route & { methods?: string[]; prefer_static?: boolean }

// Based on https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API.
const isExpression = (part: string) =>
Expand All @@ -21,18 +19,11 @@ const isPathLiteral = (path: string) => {
return parts.every((part) => !isExpression(part))
}

interface GetRouteOption {
functionName: string
methods: string[]
path: unknown
preferStatic: boolean
}

/**
* Takes an element from a `path` declaration and returns a Route element that
* represents it.
*/
const getRoute = ({ functionName, methods, path, preferStatic }: GetRouteOption): Route | undefined => {
const getRoute = (functionName: string, path: string): ExtendedRoute | undefined => {
if (typeof path !== 'string') {
throw new FunctionBundlingUserError(`'path' property must be a string, found '${JSON.stringify(path)}'`, {
functionName,
Expand All @@ -48,7 +39,7 @@ const getRoute = ({ functionName, methods, path, preferStatic }: GetRouteOption)
}

if (isPathLiteral(path)) {
return { pattern: path, literal: path, methods, prefer_static: preferStatic || undefined }
return { pattern: path, literal: path }
}

try {
Expand All @@ -63,7 +54,7 @@ const getRoute = ({ functionName, methods, path, preferStatic }: GetRouteOption)
// for both `/foo` and `/foo/`.
const normalizedRegex = `^${regex}\\/?$`

return { pattern: path, expression: normalizedRegex, methods, prefer_static: preferStatic || undefined }
return { pattern: path, expression: normalizedRegex }
} catch {
throw new FunctionBundlingUserError(`'${path}' is not a valid path according to the URLPattern specification`, {
functionName,
Expand All @@ -72,38 +63,17 @@ const getRoute = ({ functionName, methods, path, preferStatic }: GetRouteOption)
}
}

interface GetRoutesOptions {
functionName: string
methods: string[]
path: unknown
preferStatic?: boolean
}

/**
* Takes a `path` declaration, normalizes it into an array, and processes the
* individual elements to obtain an array of `Route` expressions.
*/
export const getRoutes = ({
functionName,
methods,
path: pathOrPaths,
preferStatic = false,
}: GetRoutesOptions): Route[] => {
export const getRoutes = (functionName: string, pathOrPaths: unknown): ExtendedRoute[] => {
if (!pathOrPaths) {
return []
}

const paths = [...new Set(Array.isArray(pathOrPaths) ? pathOrPaths : [pathOrPaths])]
const routes = paths
.map((path) =>
getRoute({
functionName,
methods,
path,
preferStatic,
}),
)
.filter(nonNullable)
const routes = paths.map((path) => getRoute(functionName, path)).filter(nonNullable)

return routes
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default async () =>
new Response('<h1>Hello world</h1>', {
headers: {
'content-type': 'text/html',
},
})

export const config = {
path: '/products/:id',
excludedPath: '/products/sale*',
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default async () =>
new Response('<h1>Hello world</h1>', {
headers: {
'content-type': 'text/html',
},
})

export const config = {
path: '/products/:id',
excludedPath: '/products/jacket',
method: ['GET', 'POST'],
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default async () =>
new Response('<h1>Hello world</h1>', {
headers: {
'content-type': 'text/html',
},
})

export const config = {
path: '/products/:id',
excludedPath: ['/products/sale*', '/products/jacket'],
}
Loading
Loading