wrangler 0.0.0-e1c615f → 0.0.0-e1d2fd668

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.
Files changed (121) hide show
  1. package/README.md +50 -15
  2. package/bin/wrangler.js +94 -31
  3. package/config-schema.json +3126 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +155 -82
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +170 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +29 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +15 -0
  30. package/templates/new-worker.ts +33 -0
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +32 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +8 -0
  42. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  43. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  44. package/wrangler-dist/ProxyWorker.js +241 -0
  45. package/wrangler-dist/ProxyWorker.js.map +6 -0
  46. package/wrangler-dist/cli.d.ts +26506 -0
  47. package/wrangler-dist/cli.js +211253 -116921
  48. package/wrangler-dist/wasm-sync.wasm +0 -0
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/pages/functions/buildWorker.ts +0 -57
  54. package/pages/functions/filepath-routing.test.ts +0 -39
  55. package/pages/functions/filepath-routing.ts +0 -221
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -158
  58. package/pages/functions/template-worker.ts +0 -137
  59. package/src/__tests__/clipboardy-mock.js +0 -4
  60. package/src/__tests__/dev.test.tsx +0 -66
  61. package/src/__tests__/index.test.ts +0 -287
  62. package/src/__tests__/jest.setup.ts +0 -22
  63. package/src/__tests__/kv.test.ts +0 -1098
  64. package/src/__tests__/mock-cfetch.ts +0 -171
  65. package/src/__tests__/mock-dialogs.ts +0 -65
  66. package/src/__tests__/run-in-tmp.ts +0 -19
  67. package/src/__tests__/run-wrangler.ts +0 -32
  68. package/src/api/form_data.ts +0 -131
  69. package/src/api/inspect.ts +0 -430
  70. package/src/api/preview.ts +0 -128
  71. package/src/api/worker.ts +0 -155
  72. package/src/cfetch/index.ts +0 -102
  73. package/src/cfetch/internal.ts +0 -69
  74. package/src/cli.ts +0 -9
  75. package/src/config.ts +0 -131
  76. package/src/dev.tsx +0 -874
  77. package/src/dialogs.tsx +0 -77
  78. package/src/index.tsx +0 -1929
  79. package/src/kv.tsx +0 -267
  80. package/src/module-collection.ts +0 -64
  81. package/src/pages.tsx +0 -968
  82. package/src/proxy.ts +0 -103
  83. package/src/publish.ts +0 -350
  84. package/src/sites.tsx +0 -114
  85. package/src/tail.tsx +0 -73
  86. package/src/user.tsx +0 -1022
  87. package/static-asset-facade.js +0 -47
  88. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  89. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  90. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  91. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  92. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  93. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  94. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  95. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  96. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  97. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  98. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  99. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  100. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  101. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  102. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  103. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  104. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  105. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  106. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  107. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  108. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  109. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  110. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  111. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  112. package/vendor/wrangler-mime/LICENSE +0 -21
  113. package/vendor/wrangler-mime/Mime.js +0 -97
  114. package/vendor/wrangler-mime/README.md +0 -187
  115. package/vendor/wrangler-mime/cli.js +0 -46
  116. package/vendor/wrangler-mime/index.js +0 -4
  117. package/vendor/wrangler-mime/lite.js +0 -4
  118. package/vendor/wrangler-mime/package.json +0 -52
  119. package/vendor/wrangler-mime/types/other.js +0 -1
  120. package/vendor/wrangler-mime/types/standard.js +0 -1
  121. package/wrangler-dist/cli.js.map +0 -7
Binary file
@@ -1,3 +0,0 @@
1
- // as per https://github.com/evanw/esbuild/issues/1492
2
- // to make some libs work
3
- export const import_meta_url = require("url").pathToFileURL(__filename);
File without changes
@@ -1 +0,0 @@
1
- {}
File without changes
@@ -1,57 +0,0 @@
1
- import path from "path";
2
- import { build } from "esbuild";
3
-
4
- type Options = {
5
- routesModule: string;
6
- outfile: string;
7
- minify?: boolean;
8
- sourcemap?: boolean;
9
- watch?: boolean;
10
- onEnd?: () => void;
11
- };
12
-
13
- export function buildWorker({
14
- routesModule,
15
- outfile = "bundle.js",
16
- minify = false,
17
- sourcemap = false,
18
- watch = false,
19
- onEnd = () => {},
20
- }: Options) {
21
- return build({
22
- entryPoints: [
23
- path.resolve(__dirname, "../pages/functions/template-worker.ts"),
24
- ],
25
- inject: [routesModule],
26
- bundle: true,
27
- format: "esm",
28
- target: "esnext",
29
- outfile,
30
- minify,
31
- sourcemap,
32
- watch,
33
- allowOverwrite: true,
34
- plugins: [
35
- {
36
- name: "wrangler notifier and monitor",
37
- setup(pluginBuild) {
38
- pluginBuild.onEnd((result) => {
39
- if (result.errors.length > 0) {
40
- console.error(
41
- `${result.errors.length} error(s) and ${result.warnings.length} warning(s) when compiling Worker.`
42
- );
43
- } else if (result.warnings.length > 0) {
44
- console.warn(
45
- `${result.warnings.length} warning(s) when compiling Worker.`
46
- );
47
- onEnd();
48
- } else {
49
- console.log("Compiled Worker successfully.");
50
- onEnd();
51
- }
52
- });
53
- },
54
- },
55
- ],
56
- });
57
- }
@@ -1,39 +0,0 @@
1
- import { compareRoutes } from "./filepath-routing";
2
-
3
- describe("compareRoutes()", () => {
4
- test("routes / last", () => {
5
- expect(compareRoutes("/", "/foo")).toBeGreaterThanOrEqual(1);
6
- expect(compareRoutes("/", "/:foo")).toBeGreaterThanOrEqual(1);
7
- expect(compareRoutes("/", "/:foo*")).toBeGreaterThanOrEqual(1);
8
- });
9
-
10
- test("routes with fewer segments come after those with more segments", () => {
11
- expect(compareRoutes("/foo", "/foo/bar")).toBeGreaterThanOrEqual(1);
12
- expect(compareRoutes("/foo", "/foo/bar/cat")).toBeGreaterThanOrEqual(1);
13
- });
14
-
15
- test("routes with wildcard segments come after those without", () => {
16
- expect(compareRoutes("/:foo*", "/foo")).toBe(1);
17
- expect(compareRoutes("/:foo*", "/:foo")).toBe(1);
18
- });
19
-
20
- test("routes with dynamic segments come after those without", () => {
21
- expect(compareRoutes("/:foo", "/foo")).toBe(1);
22
- });
23
-
24
- test("routes with dynamic segments occuring earlier come after those with dynamic segments in later positions", () => {
25
- expect(compareRoutes("/foo/:id/bar", "/foo/bar/:id")).toBe(1);
26
- });
27
-
28
- test("routes with no HTTP method come after those specifying a method", () => {
29
- expect(compareRoutes("/foo", "GET /foo")).toBe(1);
30
- });
31
-
32
- test("two equal routes are sorted according to their original position in the list", () => {
33
- expect(compareRoutes("GET /foo", "GET /foo")).toBe(0);
34
- });
35
-
36
- test("it returns -1 if the first argument should appear first in the list", () => {
37
- expect(compareRoutes("GET /foo", "/foo")).toBe(-1);
38
- });
39
- });
@@ -1,221 +0,0 @@
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 type { Config, RouteConfig } from "./routes";
7
- import type { ExportNamedDeclaration, Identifier } from "estree";
8
-
9
- type Arguments = {
10
- baseDir: string;
11
- baseURL: string;
12
- };
13
-
14
- export async function generateConfigFromFileTree({
15
- baseDir,
16
- baseURL,
17
- }: Arguments) {
18
- let routeEntries: [string, RouteConfig][] = [];
19
-
20
- if (!baseURL.startsWith("/")) {
21
- baseURL = `/${baseURL}`;
22
- }
23
-
24
- if (baseURL.endsWith("/")) {
25
- baseURL = baseURL.slice(0, -1);
26
- }
27
-
28
- await forEachFile(baseDir, async (filepath) => {
29
- const ext = path.extname(filepath);
30
- if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
31
- // transform the code to ensure we're working with vanilla JS + ESM
32
- const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
33
- loader: ext === ".ts" ? "ts" : "js",
34
- });
35
-
36
- // parse each file into an AST and search for module exports that match "onRequest" and friends
37
- const ast = acorn.parse(code, {
38
- ecmaVersion: "latest",
39
- sourceType: "module",
40
- });
41
- acornWalk.simple(ast, {
42
- ExportNamedDeclaration(_node: unknown) {
43
- // This dynamic cast assumes that the AST generated by acornWalk will generate nodes that
44
- // are compatible with the eslint AST nodes.
45
- const node = _node as ExportNamedDeclaration;
46
-
47
- // this is an array because multiple things can be exported from a single statement
48
- // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
49
- const exportNames: string[] = [];
50
-
51
- if (node.declaration) {
52
- const declaration = node.declaration;
53
-
54
- // `export async function onRequest() {...}`
55
- if (declaration.type === "FunctionDeclaration") {
56
- exportNames.push(declaration.id.name);
57
- }
58
-
59
- // `export const onRequestGet = () => {}, onRequestPost = () => {}`
60
- if (declaration.type === "VariableDeclaration") {
61
- exportNames.push(
62
- ...declaration.declarations.map(
63
- (variableDeclarator) =>
64
- (variableDeclarator.id as unknown as Identifier).name
65
- )
66
- );
67
- }
68
- }
69
-
70
- // `export {foo, bar}`
71
- if (node.specifiers.length) {
72
- exportNames.push(
73
- ...node.specifiers.map(
74
- (exportSpecifier) =>
75
- (exportSpecifier.exported as unknown as Identifier).name
76
- )
77
- );
78
- }
79
-
80
- for (const exportName of exportNames) {
81
- const [match, method] =
82
- exportName.match(
83
- /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
84
- ) ?? [];
85
-
86
- if (match) {
87
- const basename = path.basename(filepath).slice(0, -ext.length);
88
-
89
- const isIndexFile = basename === "index";
90
- // TODO: deprecate _middleware_ in favor of _middleware
91
- const isMiddlewareFile =
92
- basename === "_middleware" || basename === "_middleware_";
93
-
94
- let routePath = path
95
- .relative(baseDir, filepath)
96
- .slice(0, -ext.length);
97
-
98
- if (isIndexFile || isMiddlewareFile) {
99
- routePath = path.dirname(routePath);
100
- }
101
-
102
- if (routePath === ".") {
103
- routePath = "";
104
- }
105
-
106
- routePath = `${baseURL}/${routePath}`;
107
-
108
- routePath = routePath.replace(/\[\[(.+)]]/g, ":$1*"); // transform [[id]] => :id*
109
- routePath = routePath.replace(/\[(.+)]/g, ":$1"); // transform [id] => :id
110
-
111
- if (method) {
112
- routePath = `${method.toUpperCase()} ${routePath}`;
113
- }
114
-
115
- routeEntries.push([
116
- routePath,
117
- {
118
- [isMiddlewareFile ? "middleware" : "module"]: [
119
- `${path.relative(baseDir, filepath)}:${exportName}`,
120
- ],
121
- },
122
- ]);
123
- }
124
- }
125
- },
126
- });
127
- }
128
- });
129
-
130
- // Combine together any routes (index routes) which contain both a module and a middleware
131
- routeEntries = routeEntries.reduce(
132
- (acc: typeof routeEntries, [routePath, routeHandler]) => {
133
- const existingRouteEntry = acc.find(
134
- (routeEntry) => routeEntry[0] === routePath
135
- );
136
- if (existingRouteEntry !== undefined) {
137
- existingRouteEntry[1] = {
138
- ...existingRouteEntry[1],
139
- ...routeHandler,
140
- };
141
- } else {
142
- acc.push([routePath, routeHandler]);
143
- }
144
- return acc;
145
- },
146
- []
147
- );
148
-
149
- routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB));
150
-
151
- return { routes: Object.fromEntries(routeEntries) } as Config;
152
- }
153
-
154
- // Ensure routes are produced in order of precedence so that
155
- // more specific routes aren't occluded from matching due to
156
- // less specific routes appearing first in the route list.
157
- export function compareRoutes(a: string, b: string) {
158
- function parseRoutePath(routePath: string) {
159
- let [method, segmentedPath] = routePath.split(" ");
160
- if (!segmentedPath) {
161
- segmentedPath = method;
162
- method = null;
163
- }
164
-
165
- const segments = segmentedPath.slice(1).split("/").filter(Boolean);
166
- return [method, segments];
167
- }
168
-
169
- const [methodA, segmentsA] = parseRoutePath(a);
170
- const [methodB, segmentsB] = parseRoutePath(b);
171
-
172
- // sort routes with fewer segments after those with more segments
173
- if (segmentsA.length !== segmentsB.length) {
174
- return segmentsB.length - segmentsA.length;
175
- }
176
-
177
- for (let i = 0; i < segmentsA.length; i++) {
178
- const isWildcardA = segmentsA[i].includes("*");
179
- const isWildcardB = segmentsB[i].includes("*");
180
- const isParamA = segmentsA[i].includes(":");
181
- const isParamB = segmentsB[i].includes(":");
182
-
183
- // sort wildcard segments after non-wildcard segments
184
- if (isWildcardA && !isWildcardB) return 1;
185
- if (!isWildcardA && isWildcardB) return -1;
186
-
187
- // sort dynamic param segments after non-param segments
188
- if (isParamA && !isParamB) return 1;
189
- if (!isParamA && isParamB) return -1;
190
- }
191
-
192
- // sort routes that specify an HTTP before those that don't
193
- if (methodA && !methodB) return -1;
194
- if (!methodA && methodB) return 1;
195
-
196
- // all else equal, just sort them lexicographically
197
- return a.localeCompare(b);
198
- }
199
-
200
- async function forEachFile<T>(
201
- baseDir: string,
202
- fn: (filepath: string) => T | Promise<T>
203
- ) {
204
- const searchPaths = [baseDir];
205
- const returnValues: T[] = [];
206
-
207
- while (searchPaths.length) {
208
- const cwd = searchPaths.shift();
209
- const dir = await fs.readdir(cwd, { withFileTypes: true });
210
- for (const entry of dir) {
211
- const pathname = path.join(cwd, entry.name);
212
- if (entry.isDirectory()) {
213
- searchPaths.push(pathname);
214
- } else if (entry.isFile()) {
215
- returnValues.push(await fn(pathname));
216
- }
217
- }
218
- }
219
-
220
- return returnValues;
221
- }
@@ -1,78 +0,0 @@
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(
56
- `^${RESERVED_KEYWORDS.join("|")}$`
57
- );
58
-
59
- export const identifierStartRegex = /[$_\p{ID_Start}]/u;
60
-
61
- export const identifierPartRegex = /[$_\u200C\u200D\p{ID_Continue}]/u;
62
-
63
- export const identifierNameRegex =
64
- /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
65
-
66
- export const validIdentifierRegex = new RegExp(
67
- `(?!(${reservedKeywordRegex.source})$)${identifierNameRegex.source}`,
68
- "u"
69
- );
70
-
71
- export const isValidIdentifier = (identifier: string) =>
72
- validIdentifierRegex.test(identifier);
73
-
74
- export const normalizeIdentifier = (identifier: string) =>
75
- identifier.replace(
76
- /(?:^[^$_\p{ID_Start}])|[^$_\u200C\u200D\p{ID_Continue}]/gu,
77
- "_"
78
- );
@@ -1,158 +0,0 @@
1
- import path from "path";
2
- import fs from "fs/promises";
3
- import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
4
-
5
- export const HTTP_METHODS = [
6
- "HEAD",
7
- "OPTIONS",
8
- "GET",
9
- "POST",
10
- "PUT",
11
- "PATCH",
12
- "DELETE",
13
- ] as const;
14
- export type HTTPMethod = typeof HTTP_METHODS[number];
15
- export function isHTTPMethod(
16
- maybeHTTPMethod: string
17
- ): maybeHTTPMethod is HTTPMethod {
18
- return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
19
- }
20
-
21
- export type RoutesCollection = Array<{
22
- routePath: string;
23
- methods: HTTPMethod[];
24
- modules: string[];
25
- middlewares: string[];
26
- }>;
27
-
28
- export type Config = {
29
- routes?: RoutesConfig;
30
- schedules?: unknown;
31
- };
32
-
33
- export type RoutesConfig = {
34
- [route: string]: RouteConfig;
35
- };
36
-
37
- export type RouteConfig = {
38
- middleware?: string | string[];
39
- module?: string | string[];
40
- };
41
-
42
- type ImportMap = Map<
43
- string,
44
- {
45
- filepath: string;
46
- name: string;
47
- identifier: string;
48
- }
49
- >;
50
-
51
- type Arguments = {
52
- config: Config;
53
- outfile: string;
54
- srcDir: string;
55
- };
56
-
57
- export async function writeRoutesModule({
58
- config,
59
- srcDir,
60
- outfile = "_routes.js",
61
- }: Arguments) {
62
- const { importMap, routes } = parseConfig(config, srcDir);
63
- const routesModule = generateRoutesModule(importMap, routes);
64
-
65
- await fs.writeFile(outfile, routesModule);
66
-
67
- return outfile;
68
- }
69
-
70
- export function parseConfig(config: Config, baseDir: string) {
71
- const routes: RoutesCollection = [];
72
- const importMap: ImportMap = new Map();
73
- const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
74
-
75
- function parseModuleIdentifiers(paths: string | string[] | undefined) {
76
- if (typeof paths === "undefined") {
77
- paths = [];
78
- }
79
-
80
- if (typeof paths === "string") {
81
- paths = [paths];
82
- }
83
-
84
- return paths.map((modulePath) => {
85
- const [filepath, name = "default"] = modulePath.split(":");
86
- let { identifier } = importMap.get(modulePath) ?? {};
87
-
88
- const resolvedPath = path.resolve(baseDir, filepath);
89
-
90
- // ensure the filepath isn't attempting to resolve to anything outside of the project
91
- if (path.relative(baseDir, resolvedPath).startsWith("..")) {
92
- throw new Error(`Invalid module path "${filepath}"`);
93
- }
94
-
95
- // ensure the module name (if provided) is a valid identifier to guard against injection attacks
96
- if (name !== "default" && !isValidIdentifier(name)) {
97
- throw new Error(`Invalid module identifier "${name}"`);
98
- }
99
-
100
- if (!identifier) {
101
- identifier = normalizeIdentifier(`__${filepath}_${name}`);
102
-
103
- let count = identifierCount.get(identifier) ?? 0;
104
- identifierCount.set(identifier, ++count);
105
-
106
- if (count > 1) {
107
- identifier += `_${count}`;
108
- }
109
-
110
- importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
111
- }
112
-
113
- return identifier;
114
- });
115
- }
116
-
117
- for (const [route, props] of Object.entries(config.routes)) {
118
- let [_methods, routePath] = route.split(" ");
119
- if (!routePath) {
120
- routePath = _methods;
121
- _methods = "";
122
- }
123
-
124
- routes.push({
125
- routePath,
126
- methods: _methods.split("|").filter(isHTTPMethod),
127
- middlewares: parseModuleIdentifiers(props.middleware),
128
- modules: parseModuleIdentifiers(props.module),
129
- });
130
- }
131
-
132
- return { routes, importMap };
133
- }
134
-
135
- export function generateRoutesModule(
136
- importMap: ImportMap,
137
- routes: RoutesCollection
138
- ) {
139
- return `${[...importMap.values()]
140
- .map(
141
- ({ filepath, name, identifier }) =>
142
- `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
143
- )
144
- .join("\n")}
145
-
146
- export const routes = [
147
- ${routes
148
- .map(
149
- (route) => ` {
150
- routePath: "${route.routePath}",
151
- methods: ${JSON.stringify(route.methods)},
152
- middlewares: [${route.middlewares.join(", ")}],
153
- modules: [${route.modules.join(", ")}],
154
- },`
155
- )
156
- .join("\n")}
157
- ]`;
158
- }
@@ -1,137 +0,0 @@
1
- import { match } from "path-to-regexp";
2
- import type { HTTPMethod } from "./routes";
3
-
4
- /* TODO: Grab these from @cloudflare/workers-types instead */
5
- type Params<P extends string = string> = Record<P, string | string[]>;
6
-
7
- type EventContext<Env, P extends string, Data> = {
8
- request: Request;
9
- waitUntil: (promise: Promise<unknown>) => 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
- P extends string = string,
19
- Data extends Record<string, unknown> = Record<string, unknown>
20
- > = (context: EventContext<Env, P, 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]: unknown;
36
- ASSETS: { fetch(url: string, init: RequestInit): Promise<Response> };
37
- };
38
-
39
- type WorkerContext = {
40
- waitUntil: (promise: Promise<unknown>) => 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 (backwards) and execute "middlewares" on partial route matches
47
- for (const route of [...routes].reverse()) {
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<
109
- unknown,
110
- string,
111
- Record<string, unknown>
112
- > = {
113
- request: new Request(request.clone()),
114
- next,
115
- params,
116
- data,
117
- env,
118
- waitUntil: workerContext.waitUntil.bind(workerContext),
119
- };
120
-
121
- const response = await handler(context);
122
-
123
- // https://fetch.spec.whatwg.org/#null-body-status
124
- return new Response(
125
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
126
- response
127
- );
128
- }
129
- };
130
-
131
- try {
132
- return next();
133
- } catch (err) {
134
- return new Response("Internal Error", { status: 500 });
135
- }
136
- },
137
- };