wrangler 0.0.0-cd05d20 → 0.0.0-cf88928

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ import path from "path";
2
+ import { build } from "esbuild";
3
+ import { fileURLToPath } from "url";
4
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
5
+
6
+ type Options = {
7
+ routesModule: string;
8
+ outfile: string;
9
+ minify?: boolean;
10
+ watch?: boolean;
11
+ };
12
+
13
+ export function buildWorker({
14
+ routesModule,
15
+ outfile = "bundle.js",
16
+ minify = false,
17
+ watch = false,
18
+ }: Options) {
19
+ console.log(`Compiling worker to "${outfile}"`);
20
+ return build({
21
+ entryPoints: [
22
+ path.resolve(__dirname, "../lib/functions/template-worker.ts"),
23
+ ],
24
+ inject: [routesModule],
25
+ bundle: true,
26
+ format: "esm",
27
+ target: "esnext",
28
+ outfile,
29
+ minify,
30
+ watch,
31
+ allowOverwrite: true,
32
+ });
33
+ }
@@ -0,0 +1,67 @@
1
+ import path from 'path'
2
+ import { compareRoutes, generateConfigFromFileTree } from './filepath-routing'
3
+ import mock from 'mock-fs'
4
+
5
+ describe('generateConfigFromFileTree()', () => {
6
+ beforeEach(() => {
7
+ mock({
8
+ '/functions': {
9
+ api: {
10
+ 'hello.ts': 'export const onRequestGet = () => new Response("Hello from an API!");'
11
+ },
12
+ 'index.ts': 'export const onRequest = () => new Response("Hello, world!");',
13
+ '_middleware.ts':
14
+ 'export const onRequest = [async () => new Response("Hello from middleware!")];'
15
+ },
16
+ node_modules: mock.load(path.resolve(__dirname, './node_modules'))
17
+ })
18
+ })
19
+
20
+ afterEach(() => {
21
+ mock.restore()
22
+ })
23
+
24
+ test('it merges and sorts route entries', async () => {
25
+ const result = await generateConfigFromFileTree({ baseURL: '/', baseDir: '/functions' })
26
+ expect(result.routes).toEqual({
27
+ '/': {
28
+ middleware: ['_middleware.ts:onRequest'],
29
+ module: ['index.ts:onRequest']
30
+ },
31
+ 'GET /api/hello': {
32
+ module: ['api/hello.ts:onRequestGet']
33
+ }
34
+ })
35
+ })
36
+ })
37
+
38
+ describe('compareRoutes()', () => {
39
+ test('routes with fewer segments come after those with more segments', () => {
40
+ expect(compareRoutes('/foo', '/foo/bar')).toBe(1)
41
+ })
42
+
43
+ test('routes with wildcard segments come after those without', () => {
44
+ expect(compareRoutes('/:foo*', '/foo')).toBe(1)
45
+ expect(compareRoutes('/:foo*', '/:foo')).toBe(1)
46
+ })
47
+
48
+ test('routes with dynamic segments come after those without', () => {
49
+ expect(compareRoutes('/:foo', '/foo')).toBe(1)
50
+ })
51
+
52
+ test('routes with dynamic segments occuring earlier come after those with dynamic segments in later positions', () => {
53
+ expect(compareRoutes('/foo/:id/bar', '/foo/bar/:id')).toBe(1)
54
+ })
55
+
56
+ test('routes with no HTTP method come after those specifying a method', () => {
57
+ expect(compareRoutes('/foo', 'GET /foo')).toBe(1)
58
+ })
59
+
60
+ test('two equal routes are sorted according to their original position in the list', () => {
61
+ expect(compareRoutes('GET /foo', 'GET /foo')).toBe(0)
62
+ })
63
+
64
+ test('it returns -1 if the first argument should appear first in the list', () => {
65
+ expect(compareRoutes('GET /foo', '/foo')).toBe(-1)
66
+ })
67
+ })
@@ -0,0 +1,199 @@
1
+ import path from 'path'
2
+ import fs from 'fs/promises'
3
+ import { transform } from 'esbuild'
4
+ import * as acorn from 'acorn'
5
+ import * as acornWalk from 'acorn-walk'
6
+ import { Config } from './routes'
7
+ import { Identifier } from 'estree'
8
+ import { ExportNamedDeclaration } from '@babel/types'
9
+
10
+ type Arguments = {
11
+ baseDir: string
12
+ baseURL: string
13
+ }
14
+
15
+ export async function generateConfigFromFileTree({ baseDir, baseURL }: Arguments) {
16
+ let routeEntries: [string, { [key in 'module' | 'middleware']?: string[] }][] = [] as any
17
+
18
+ if (!baseURL.startsWith('/')) {
19
+ baseURL = `/${baseURL}`
20
+ }
21
+
22
+ if (baseURL.endsWith('/')) {
23
+ baseURL = baseURL.slice(0, -1)
24
+ }
25
+
26
+ await forEachFile(baseDir, async (filepath) => {
27
+ const ext = path.extname(filepath)
28
+ if (/\.(mjs|js|ts)/.test(ext)) {
29
+ // transform the code to ensure we're working with vanilla JS + ESM
30
+ const { code } = await transform(await fs.readFile(filepath, 'utf-8'), {
31
+ loader: ext === '.ts' ? 'ts' : 'js',
32
+ })
33
+
34
+ // parse each file into an AST and search for module exports that match "onRequest" and friends
35
+ const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' })
36
+ acornWalk.simple(ast, {
37
+ ExportNamedDeclaration(_node) {
38
+ const node: ExportNamedDeclaration = _node as any
39
+
40
+ // this is an array because multiple things can be exported from a single statement
41
+ // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
42
+ let exportNames: string[] = []
43
+
44
+ if (node.declaration) {
45
+ const declaration = node.declaration
46
+
47
+ // `export async function onRequest() {...}`
48
+ if (declaration.type === 'FunctionDeclaration') {
49
+ exportNames.push(declaration.id.name)
50
+ }
51
+
52
+ // `export const onRequestGet = () => {}, onRequestPost = () => {}`
53
+ if (declaration.type === 'VariableDeclaration') {
54
+ exportNames.push(
55
+ ...declaration.declarations.map(
56
+ (variableDeclarator) => ((variableDeclarator.id as unknown) as Identifier).name
57
+ )
58
+ )
59
+ }
60
+ }
61
+
62
+ // `export {foo, bar}`
63
+ if (node.specifiers.length) {
64
+ exportNames.push(
65
+ ...node.specifiers.map(
66
+ (exportSpecifier) => ((exportSpecifier.exported as unknown) as Identifier).name
67
+ )
68
+ )
69
+ }
70
+
71
+ for (const exportName of exportNames) {
72
+ const [match, method] =
73
+ exportName.match(/^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/) ?? []
74
+
75
+ if (match) {
76
+ const basename = path.basename(filepath).slice(0, -ext.length)
77
+
78
+ const isIndexFile = basename === 'index'
79
+ // TODO: deprecate _middleware_ in favor of _middleware
80
+ const isMiddlewareFile = basename === '_middleware' || basename === '_middleware_'
81
+
82
+ let routePath = path.relative(baseDir, filepath).slice(0, -ext.length)
83
+
84
+ if (isIndexFile || isMiddlewareFile) {
85
+ routePath = path.dirname(routePath)
86
+ }
87
+
88
+ if (routePath === '.') {
89
+ routePath = ''
90
+ }
91
+
92
+ routePath = `${baseURL}/${routePath}`
93
+
94
+ routePath = routePath.replace(/\[\[(.+)]]/g, ':$1*') // transform [[id]] => :id*
95
+ routePath = routePath.replace(/\[(.+)]/g, ':$1') // transform [id] => :id
96
+
97
+ if (method) {
98
+ routePath = `${method.toUpperCase()} ${routePath}`
99
+ }
100
+
101
+ routeEntries.push([
102
+ routePath,
103
+ {
104
+ [isMiddlewareFile ? 'middleware' : 'module']: [
105
+ `${path.relative(baseDir, filepath)}:${exportName}`,
106
+ ],
107
+ },
108
+ ])
109
+ }
110
+ }
111
+ },
112
+ })
113
+ }
114
+ })
115
+
116
+ // Combine together any routes (index routes) which contain both a module and a middleware
117
+ routeEntries = routeEntries.reduce((acc: typeof routeEntries, [routePath, routeHandler]) => {
118
+ const existingRouteEntry = acc.find(routeEntry => routeEntry[0] === routePath)
119
+ if (existingRouteEntry !== undefined) {
120
+ existingRouteEntry[1] = {
121
+ ...existingRouteEntry[1],
122
+ ...routeHandler
123
+ }
124
+ } else {
125
+ acc.push([routePath, routeHandler])
126
+ }
127
+ return acc
128
+ }, [])
129
+
130
+ routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB))
131
+
132
+ return { routes: Object.fromEntries(routeEntries) } as Config
133
+ }
134
+
135
+ // Ensure routes are produced in order of precedence so that
136
+ // more specific routes aren't occluded from matching due to
137
+ // less specific routes appearing first in the route list.
138
+ export function compareRoutes(a: string, b: string) {
139
+ function parseRoutePath(routePath: string) {
140
+ let [method, path] = routePath.split(' ')
141
+ if (!path) {
142
+ path = method
143
+ method = null
144
+ }
145
+
146
+ const segments = path.slice(1).split('/')
147
+ return [method, segments]
148
+ }
149
+
150
+ const [methodA, segmentsA] = parseRoutePath(a)
151
+ const [methodB, segmentsB] = parseRoutePath(b)
152
+
153
+ // sort routes with fewer segments after those with more segments
154
+ if (segmentsA.length !== segmentsB.length) {
155
+ return segmentsB.length - segmentsA.length
156
+ }
157
+
158
+ for (let i = 0; i < segmentsA.length; i++) {
159
+ const isWildcardA = segmentsA[i].includes('*')
160
+ const isWildcardB = segmentsB[i].includes('*')
161
+ const isParamA = segmentsA[i].includes(':')
162
+ const isParamB = segmentsB[i].includes(':')
163
+
164
+ // sort wildcard segments after non-wildcard segments
165
+ if (isWildcardA && !isWildcardB) return 1
166
+ if (!isWildcardA && isWildcardB) return -1
167
+
168
+ // sort dynamic param segments after non-param segments
169
+ if (isParamA && !isParamB) return 1
170
+ if (!isParamA && isParamB) return -1
171
+ }
172
+
173
+ // sort routes that specify an HTTP before those that don't
174
+ if (methodA && !methodB) return -1
175
+ if (!methodA && methodB) return 1
176
+
177
+ // all else equal, just sort them lexicographically
178
+ return a.localeCompare(b)
179
+ }
180
+
181
+ async function forEachFile<T>(baseDir: string, fn: (filepath: string) => T | Promise<T>) {
182
+ const searchPaths = [baseDir]
183
+ const returnValues: T[] = []
184
+
185
+ while (searchPaths.length) {
186
+ let cwd = searchPaths.shift()
187
+ const dir = await fs.readdir(cwd, { withFileTypes: true })
188
+ for (const entry of dir) {
189
+ const pathname = path.join(cwd, entry.name)
190
+ if (entry.isDirectory()) {
191
+ searchPaths.push(pathname)
192
+ } else if (entry.isFile()) {
193
+ returnValues.push(await fn(pathname))
194
+ }
195
+ }
196
+ }
197
+
198
+ return returnValues
199
+ }
@@ -0,0 +1,71 @@
1
+ export const RESERVED_KEYWORDS = [
2
+ 'do',
3
+ 'if',
4
+ 'in',
5
+ 'for',
6
+ 'let',
7
+ 'new',
8
+ 'try',
9
+ 'var',
10
+ 'case',
11
+ 'else',
12
+ 'enum',
13
+ 'eval',
14
+ 'null',
15
+ 'this',
16
+ 'true',
17
+ 'void',
18
+ 'with',
19
+ 'await',
20
+ 'break',
21
+ 'catch',
22
+ 'class',
23
+ 'const',
24
+ 'false',
25
+ 'super',
26
+ 'throw',
27
+ 'while',
28
+ 'yield',
29
+ 'delete',
30
+ 'export',
31
+ 'import',
32
+ 'public',
33
+ 'return',
34
+ 'static',
35
+ 'switch',
36
+ 'typeof',
37
+ 'default',
38
+ 'extends',
39
+ 'finally',
40
+ 'package',
41
+ 'private',
42
+ 'continue',
43
+ 'debugger',
44
+ 'function',
45
+ 'arguments',
46
+ 'interface',
47
+ 'protected',
48
+ 'implements',
49
+ 'instanceof',
50
+ 'NaN',
51
+ 'Infinity',
52
+ 'undefined',
53
+ ]
54
+
55
+ export const reservedKeywordRegex = new RegExp(`^${RESERVED_KEYWORDS.join('|')}$`)
56
+
57
+ export const identifierStartRegex = /[$_\p{ID_Start}]/u;
58
+
59
+ export const identifierPartRegex = /[$_\u200C\u200D\p{ID_Continue}]/u
60
+
61
+ export const identifierNameRegex = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u
62
+
63
+ export const validIdentifierRegex = new RegExp(
64
+ `(?!(${reservedKeywordRegex.source})$)${identifierNameRegex.source}`,
65
+ 'u'
66
+ )
67
+
68
+ export const isValidIdentifer = (identifier: string) => validIdentifierRegex.test(identifier)
69
+
70
+ export const normalizeIdentifier = (identifier: string) =>
71
+ identifier.replace(/(?:^[^$_\p{ID_Start}])|[^$_\u200C\u200D\p{ID_Continue}]/gu, '_')
@@ -0,0 +1,139 @@
1
+ import path from 'path'
2
+ import fs from 'fs/promises'
3
+ import { isValidIdentifer, normalizeIdentifier } from './identifiers'
4
+
5
+ export const HTTP_METHODS = ['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
6
+ export type HTTPMethod = typeof HTTP_METHODS[number]
7
+ export function isHTTPMethod(maybeHTTPMethod: string): maybeHTTPMethod is HTTPMethod {
8
+ return HTTP_METHODS.includes(maybeHTTPMethod as any)
9
+ }
10
+
11
+ export type RoutesCollection = Array<{
12
+ routePath: string
13
+ methods: HTTPMethod[]
14
+ modules: string[]
15
+ middlewares: string[]
16
+ }>
17
+
18
+ export type Config = {
19
+ routes?: RoutesConfig
20
+ schedules?: any
21
+ }
22
+
23
+ export type RoutesConfig = {
24
+ [route: string]: {
25
+ middleware?: string | string[]
26
+ module?: string | string[]
27
+ }
28
+ }
29
+
30
+ type ImportMap = Map<
31
+ string,
32
+ {
33
+ filepath: string
34
+ name: string
35
+ identifier: string
36
+ }
37
+ >
38
+
39
+ type Arguments = {
40
+ config: Config
41
+ outfile: string
42
+ srcDir: string
43
+ }
44
+
45
+ export async function writeRoutesModule({ config, srcDir, outfile = '_routes.js' }: Arguments) {
46
+ const { importMap, routes } = parseConfig(config, srcDir)
47
+ const routesModule = generateRoutesModule(importMap, routes)
48
+
49
+ await fs.writeFile(outfile, routesModule)
50
+
51
+ return outfile
52
+ }
53
+
54
+ export function parseConfig(config: Config, baseDir: string) {
55
+ const routes: RoutesCollection = []
56
+ const importMap: ImportMap = new Map()
57
+ const identifierCount = new Map<string, number>() // to keep track of identifier collisions
58
+
59
+ function parseModuleIdentifiers(paths: string | string[] | undefined) {
60
+ if (typeof paths === 'undefined') {
61
+ paths = []
62
+ }
63
+
64
+ if (typeof paths === 'string') {
65
+ paths = [paths]
66
+ }
67
+
68
+ return paths.map((modulePath) => {
69
+ const [filepath, name = 'default'] = modulePath.split(':')
70
+ let { identifier } = importMap.get(modulePath) ?? {}
71
+
72
+ const resolvedPath = path.resolve(baseDir, filepath)
73
+
74
+ // ensure the filepath isn't attempting to resolve to anything outside of the project
75
+ if (path.relative(baseDir, resolvedPath).startsWith('..')) {
76
+ throw new Error(`Invalid module path "${filepath}"`)
77
+ }
78
+
79
+ // ensure the module name (if provided) is a valid identifier to guard against injection attacks
80
+ if (name !== 'default' && !isValidIdentifer(name)) {
81
+ throw new Error(`Invalid module identifier "${name}"`)
82
+ }
83
+
84
+ if (!identifier) {
85
+ identifier = normalizeIdentifier(`__${filepath}_${name}`)
86
+
87
+ let count = identifierCount.get(identifier) ?? 0
88
+ identifierCount.set(identifier, ++count)
89
+
90
+ if (count > 1) {
91
+ identifier += `_${count}`
92
+ }
93
+
94
+ importMap.set(modulePath, { filepath: resolvedPath, name, identifier })
95
+ }
96
+
97
+ return identifier
98
+ })
99
+ }
100
+
101
+ for (const [route, props] of Object.entries(config.routes)) {
102
+ let [_methods, routePath] = route.split(' ')
103
+ if (!routePath) {
104
+ routePath = _methods
105
+ _methods = ''
106
+ }
107
+
108
+ routes.push({
109
+ routePath,
110
+ methods: _methods.split('|').filter(isHTTPMethod),
111
+ middlewares: parseModuleIdentifiers(props.middleware),
112
+ modules: parseModuleIdentifiers(props.module),
113
+ })
114
+ }
115
+
116
+ return { routes, importMap }
117
+ }
118
+
119
+ export function generateRoutesModule(importMap: ImportMap, routes: RoutesCollection) {
120
+ return `${[...importMap.values()]
121
+ .map(
122
+ ({ filepath, name, identifier }) =>
123
+ `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
124
+ )
125
+ .join('\n')}
126
+
127
+ export const routes = [
128
+ ${routes
129
+ .map(
130
+ (route) => ` {
131
+ routePath: "${route.routePath}",
132
+ methods: ${JSON.stringify(route.methods)},
133
+ middlewares: [${route.middlewares.join(', ')}],
134
+ modules: [${route.modules.join(', ')}],
135
+ },`
136
+ )
137
+ .join('\n')}
138
+ ]`
139
+ }
@@ -0,0 +1,133 @@
1
+ import { match } from "path-to-regexp";
2
+ import { HTTPMethod } from "./routes";
3
+
4
+ /* TODO: Grab these from @cloudflare/workers-types instead */
5
+ type Params<P extends string = any> = Record<P, string | string[]>;
6
+
7
+ type EventContext<Env, P extends string, Data> = {
8
+ request: Request;
9
+ waitUntil: (promise: Promise<any>) => void;
10
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
11
+ env: Env & { ASSETS: { fetch: typeof fetch } };
12
+ params: Params<P>;
13
+ data: Data;
14
+ };
15
+
16
+ declare type PagesFunction<
17
+ Env = unknown,
18
+ Params extends string = any,
19
+ Data extends Record<string, unknown> = Record<string, unknown>
20
+ > = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;
21
+ /* end @cloudflare/workers-types */
22
+
23
+ type RouteHandler = {
24
+ routePath: string;
25
+ methods: HTTPMethod[];
26
+ modules: PagesFunction[];
27
+ middlewares: PagesFunction[];
28
+ };
29
+
30
+ // inject `routes` via ESBuild
31
+ declare const routes: RouteHandler[];
32
+
33
+ // expect an ASSETS fetcher binding pointing to the asset-server stage
34
+ type Env = {
35
+ [name: string]: any;
36
+ ASSETS: { fetch(url: string, init: RequestInit): Promise<Response> };
37
+ };
38
+
39
+ type WorkerContext = {
40
+ waitUntil: (promise: Promise<any>) => void;
41
+ };
42
+
43
+ function* executeRequest(request: Request, env: Env) {
44
+ const requestPath = new URL(request.url).pathname;
45
+
46
+ // First, iterate through the routes and execute "middlewares" on partial route matches
47
+ for (const route of routes) {
48
+ if (
49
+ route.methods.length &&
50
+ !route.methods.includes(request.method as HTTPMethod)
51
+ ) {
52
+ continue;
53
+ }
54
+
55
+ const routeMatcher = match(route.routePath, { end: false });
56
+ const matchResult = routeMatcher(requestPath);
57
+ if (matchResult) {
58
+ for (const handler of route.middlewares.flat()) {
59
+ yield {
60
+ handler,
61
+ params: matchResult.params as Params,
62
+ };
63
+ }
64
+ }
65
+ }
66
+
67
+ // Then look for the first exact route match and execute its "modules"
68
+ for (const route of routes) {
69
+ if (
70
+ route.methods.length &&
71
+ !route.methods.includes(request.method as HTTPMethod)
72
+ ) {
73
+ continue;
74
+ }
75
+
76
+ const routeMatcher = match(route.routePath, { end: true });
77
+ const matchResult = routeMatcher(requestPath);
78
+ if (matchResult && route.modules.length) {
79
+ for (const handler of route.modules.flat()) {
80
+ yield {
81
+ handler,
82
+ params: matchResult.params as Params,
83
+ };
84
+ }
85
+ break;
86
+ }
87
+ }
88
+
89
+ // Finally, yield to the asset-server
90
+ return {
91
+ handler: () => env.ASSETS.fetch(request.url, request),
92
+ params: {} as Params,
93
+ };
94
+ }
95
+
96
+ export default {
97
+ async fetch(request: Request, env: Env, workerContext: WorkerContext) {
98
+ const handlerIterator = executeRequest(request, env);
99
+ const data = {}; // arbitrary data the user can set between functions
100
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
101
+ if (input !== undefined) {
102
+ request = new Request(input, init);
103
+ }
104
+
105
+ const { value } = handlerIterator.next();
106
+ if (value) {
107
+ const { handler, params } = value;
108
+ const context: EventContext<unknown, any, any> = {
109
+ request: new Request(request.clone()),
110
+ next,
111
+ params,
112
+ data,
113
+ env,
114
+ waitUntil: workerContext.waitUntil.bind(workerContext),
115
+ };
116
+
117
+ const response = await handler(context);
118
+
119
+ // https://fetch.spec.whatwg.org/#null-body-status
120
+ return new Response(
121
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
122
+ response
123
+ );
124
+ }
125
+ };
126
+
127
+ try {
128
+ return next();
129
+ } catch (err) {
130
+ return new Response("Internal Error", { status: 500 });
131
+ }
132
+ },
133
+ };