wrangler 0.0.0-eebdb6c → 0.0.0-eec2a7074

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 (120) 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 -81
  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 +210065 -116154
  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 -32
  55. package/pages/functions/filepath-routing.ts +0 -225
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -158
  58. package/pages/functions/template-worker.ts +0 -135
  59. package/src/__tests__/clipboardy-mock.js +0 -4
  60. package/src/__tests__/index.test.ts +0 -287
  61. package/src/__tests__/jest.setup.ts +0 -22
  62. package/src/__tests__/kv.test.ts +0 -1098
  63. package/src/__tests__/mock-cfetch.ts +0 -171
  64. package/src/__tests__/mock-dialogs.ts +0 -65
  65. package/src/__tests__/run-in-tmp.ts +0 -19
  66. package/src/__tests__/run-wrangler.ts +0 -32
  67. package/src/api/form_data.ts +0 -131
  68. package/src/api/inspect.ts +0 -430
  69. package/src/api/preview.ts +0 -128
  70. package/src/api/worker.ts +0 -155
  71. package/src/cfetch/index.ts +0 -103
  72. package/src/cfetch/internal.ts +0 -69
  73. package/src/cli.ts +0 -9
  74. package/src/config.ts +0 -131
  75. package/src/dev.tsx +0 -879
  76. package/src/dialogs.tsx +0 -77
  77. package/src/index.tsx +0 -1904
  78. package/src/kv.tsx +0 -267
  79. package/src/module-collection.ts +0 -64
  80. package/src/pages.tsx +0 -921
  81. package/src/proxy.ts +0 -103
  82. package/src/publish.ts +0 -350
  83. package/src/sites.tsx +0 -114
  84. package/src/tail.tsx +0 -73
  85. package/src/user.tsx +0 -1022
  86. package/static-asset-facade.js +0 -47
  87. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  88. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  89. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  90. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  91. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  92. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  93. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  94. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  95. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  96. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  97. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  98. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  99. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  100. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  101. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  102. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  103. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  104. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  105. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  106. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  107. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  108. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  109. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  110. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  111. package/vendor/wrangler-mime/LICENSE +0 -21
  112. package/vendor/wrangler-mime/Mime.js +0 -97
  113. package/vendor/wrangler-mime/README.md +0 -187
  114. package/vendor/wrangler-mime/cli.js +0 -46
  115. package/vendor/wrangler-mime/index.js +0 -4
  116. package/vendor/wrangler-mime/lite.js +0 -4
  117. package/vendor/wrangler-mime/package.json +0 -52
  118. package/vendor/wrangler-mime/types/other.js +0 -1
  119. package/vendor/wrangler-mime/types/standard.js +0 -1
  120. 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,32 +0,0 @@
1
- import { compareRoutes } from "./filepath-routing";
2
-
3
- describe("compareRoutes()", () => {
4
- test("routes with fewer segments come after those with more segments", () => {
5
- expect(compareRoutes("/foo", "/foo/bar")).toBe(1);
6
- });
7
-
8
- test("routes with wildcard segments come after those without", () => {
9
- expect(compareRoutes("/:foo*", "/foo")).toBe(1);
10
- expect(compareRoutes("/:foo*", "/:foo")).toBe(1);
11
- });
12
-
13
- test("routes with dynamic segments come after those without", () => {
14
- expect(compareRoutes("/:foo", "/foo")).toBe(1);
15
- });
16
-
17
- test("routes with dynamic segments occuring earlier come after those with dynamic segments in later positions", () => {
18
- expect(compareRoutes("/foo/:id/bar", "/foo/bar/:id")).toBe(1);
19
- });
20
-
21
- test("routes with no HTTP method come after those specifying a method", () => {
22
- expect(compareRoutes("/foo", "GET /foo")).toBe(1);
23
- });
24
-
25
- test("two equal routes are sorted according to their original position in the list", () => {
26
- expect(compareRoutes("GET /foo", "GET /foo")).toBe(0);
27
- });
28
-
29
- test("it returns -1 if the first argument should appear first in the list", () => {
30
- expect(compareRoutes("GET /foo", "/foo")).toBe(-1);
31
- });
32
- });
@@ -1,225 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
-
3
- import path from "path";
4
- import fs from "fs/promises";
5
- import { transform } from "esbuild";
6
- import * as acorn from "acorn";
7
- import * as acornWalk from "acorn-walk";
8
- import type { Config } from "./routes";
9
- import type { Identifier } from "estree";
10
- import type { ExportNamedDeclaration } from "@babel/types";
11
-
12
- type Arguments = {
13
- baseDir: string;
14
- baseURL: string;
15
- };
16
-
17
- export async function generateConfigFromFileTree({
18
- baseDir,
19
- baseURL,
20
- }: Arguments) {
21
- let routeEntries: [
22
- string,
23
- { [key in "module" | "middleware"]?: string[] }
24
- ][] = [] as any;
25
-
26
- if (!baseURL.startsWith("/")) {
27
- baseURL = `/${baseURL}`;
28
- }
29
-
30
- if (baseURL.endsWith("/")) {
31
- baseURL = baseURL.slice(0, -1);
32
- }
33
-
34
- await forEachFile(baseDir, async (filepath) => {
35
- const ext = path.extname(filepath);
36
- if (/\.(mjs|js|ts)/.test(ext)) {
37
- // transform the code to ensure we're working with vanilla JS + ESM
38
- const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
39
- loader: ext === ".ts" ? "ts" : "js",
40
- });
41
-
42
- // parse each file into an AST and search for module exports that match "onRequest" and friends
43
- const ast = acorn.parse(code, {
44
- ecmaVersion: "latest",
45
- sourceType: "module",
46
- });
47
- acornWalk.simple(ast, {
48
- ExportNamedDeclaration(_node) {
49
- const node: ExportNamedDeclaration = _node as any;
50
-
51
- // this is an array because multiple things can be exported from a single statement
52
- // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
53
- const exportNames: string[] = [];
54
-
55
- if (node.declaration) {
56
- const declaration = node.declaration;
57
-
58
- // `export async function onRequest() {...}`
59
- if (declaration.type === "FunctionDeclaration") {
60
- exportNames.push(declaration.id.name);
61
- }
62
-
63
- // `export const onRequestGet = () => {}, onRequestPost = () => {}`
64
- if (declaration.type === "VariableDeclaration") {
65
- exportNames.push(
66
- ...declaration.declarations.map(
67
- (variableDeclarator) =>
68
- (variableDeclarator.id as unknown as Identifier).name
69
- )
70
- );
71
- }
72
- }
73
-
74
- // `export {foo, bar}`
75
- if (node.specifiers.length) {
76
- exportNames.push(
77
- ...node.specifiers.map(
78
- (exportSpecifier) =>
79
- (exportSpecifier.exported as unknown as Identifier).name
80
- )
81
- );
82
- }
83
-
84
- for (const exportName of exportNames) {
85
- const [match, method] =
86
- exportName.match(
87
- /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
88
- ) ?? [];
89
-
90
- if (match) {
91
- const basename = path.basename(filepath).slice(0, -ext.length);
92
-
93
- const isIndexFile = basename === "index";
94
- // TODO: deprecate _middleware_ in favor of _middleware
95
- const isMiddlewareFile =
96
- basename === "_middleware" || basename === "_middleware_";
97
-
98
- let routePath = path
99
- .relative(baseDir, filepath)
100
- .slice(0, -ext.length);
101
-
102
- if (isIndexFile || isMiddlewareFile) {
103
- routePath = path.dirname(routePath);
104
- }
105
-
106
- if (routePath === ".") {
107
- routePath = "";
108
- }
109
-
110
- routePath = `${baseURL}/${routePath}`;
111
-
112
- routePath = routePath.replace(/\[\[(.+)]]/g, ":$1*"); // transform [[id]] => :id*
113
- routePath = routePath.replace(/\[(.+)]/g, ":$1"); // transform [id] => :id
114
-
115
- if (method) {
116
- routePath = `${method.toUpperCase()} ${routePath}`;
117
- }
118
-
119
- routeEntries.push([
120
- routePath,
121
- {
122
- [isMiddlewareFile ? "middleware" : "module"]: [
123
- `${path.relative(baseDir, filepath)}:${exportName}`,
124
- ],
125
- },
126
- ]);
127
- }
128
- }
129
- },
130
- });
131
- }
132
- });
133
-
134
- // Combine together any routes (index routes) which contain both a module and a middleware
135
- routeEntries = routeEntries.reduce(
136
- (acc: typeof routeEntries, [routePath, routeHandler]) => {
137
- const existingRouteEntry = acc.find(
138
- (routeEntry) => routeEntry[0] === routePath
139
- );
140
- if (existingRouteEntry !== undefined) {
141
- existingRouteEntry[1] = {
142
- ...existingRouteEntry[1],
143
- ...routeHandler,
144
- };
145
- } else {
146
- acc.push([routePath, routeHandler]);
147
- }
148
- return acc;
149
- },
150
- []
151
- );
152
-
153
- routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB));
154
-
155
- return { routes: Object.fromEntries(routeEntries) } as Config;
156
- }
157
-
158
- // Ensure routes are produced in order of precedence so that
159
- // more specific routes aren't occluded from matching due to
160
- // less specific routes appearing first in the route list.
161
- export function compareRoutes(a: string, b: string) {
162
- function parseRoutePath(routePath: string) {
163
- let [method, segmentedPath] = routePath.split(" ");
164
- if (!segmentedPath) {
165
- segmentedPath = method;
166
- method = null;
167
- }
168
-
169
- const segments = segmentedPath.slice(1).split("/");
170
- return [method, segments];
171
- }
172
-
173
- const [methodA, segmentsA] = parseRoutePath(a);
174
- const [methodB, segmentsB] = parseRoutePath(b);
175
-
176
- // sort routes with fewer segments after those with more segments
177
- if (segmentsA.length !== segmentsB.length) {
178
- return segmentsB.length - segmentsA.length;
179
- }
180
-
181
- for (let i = 0; i < segmentsA.length; i++) {
182
- const isWildcardA = segmentsA[i].includes("*");
183
- const isWildcardB = segmentsB[i].includes("*");
184
- const isParamA = segmentsA[i].includes(":");
185
- const isParamB = segmentsB[i].includes(":");
186
-
187
- // sort wildcard segments after non-wildcard segments
188
- if (isWildcardA && !isWildcardB) return 1;
189
- if (!isWildcardA && isWildcardB) return -1;
190
-
191
- // sort dynamic param segments after non-param segments
192
- if (isParamA && !isParamB) return 1;
193
- if (!isParamA && isParamB) return -1;
194
- }
195
-
196
- // sort routes that specify an HTTP before those that don't
197
- if (methodA && !methodB) return -1;
198
- if (!methodA && methodB) return 1;
199
-
200
- // all else equal, just sort them lexicographically
201
- return a.localeCompare(b);
202
- }
203
-
204
- async function forEachFile<T>(
205
- baseDir: string,
206
- fn: (filepath: string) => T | Promise<T>
207
- ) {
208
- const searchPaths = [baseDir];
209
- const returnValues: T[] = [];
210
-
211
- while (searchPaths.length) {
212
- const cwd = searchPaths.shift();
213
- const dir = await fs.readdir(cwd, { withFileTypes: true });
214
- for (const entry of dir) {
215
- const pathname = path.join(cwd, entry.name);
216
- if (entry.isDirectory()) {
217
- searchPaths.push(pathname);
218
- } else if (entry.isFile()) {
219
- returnValues.push(await fn(pathname));
220
- }
221
- }
222
- }
223
-
224
- return returnValues;
225
- }
@@ -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 isValidIdentifer = (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
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
-
3
- import path from "path";
4
- import fs from "fs/promises";
5
- import { isValidIdentifer, normalizeIdentifier } from "./identifiers";
6
-
7
- export const HTTP_METHODS = [
8
- "HEAD",
9
- "OPTIONS",
10
- "GET",
11
- "POST",
12
- "PUT",
13
- "PATCH",
14
- "DELETE",
15
- ] as const;
16
- export type HTTPMethod = typeof HTTP_METHODS[number];
17
- export function isHTTPMethod(
18
- maybeHTTPMethod: string
19
- ): maybeHTTPMethod is HTTPMethod {
20
- return HTTP_METHODS.includes(maybeHTTPMethod as any);
21
- }
22
-
23
- export type RoutesCollection = Array<{
24
- routePath: string;
25
- methods: HTTPMethod[];
26
- modules: string[];
27
- middlewares: string[];
28
- }>;
29
-
30
- export type Config = {
31
- routes?: RoutesConfig;
32
- schedules?: any;
33
- };
34
-
35
- export type RoutesConfig = {
36
- [route: string]: {
37
- middleware?: string | string[];
38
- module?: string | string[];
39
- };
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" && !isValidIdentifer(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,135 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
-
3
- import { match } from "path-to-regexp";
4
- import type { HTTPMethod } from "./routes";
5
-
6
- /* TODO: Grab these from @cloudflare/workers-types instead */
7
- type Params<P extends string = any> = Record<P, string | string[]>;
8
-
9
- type EventContext<Env, P extends string, Data> = {
10
- request: Request;
11
- waitUntil: (promise: Promise<any>) => void;
12
- next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
13
- env: Env & { ASSETS: { fetch: typeof fetch } };
14
- params: Params<P>;
15
- data: Data;
16
- };
17
-
18
- declare type PagesFunction<
19
- Env = unknown,
20
- P extends string = any,
21
- Data extends Record<string, unknown> = Record<string, unknown>
22
- > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
23
- /* end @cloudflare/workers-types */
24
-
25
- type RouteHandler = {
26
- routePath: string;
27
- methods: HTTPMethod[];
28
- modules: PagesFunction[];
29
- middlewares: PagesFunction[];
30
- };
31
-
32
- // inject `routes` via ESBuild
33
- declare const routes: RouteHandler[];
34
-
35
- // expect an ASSETS fetcher binding pointing to the asset-server stage
36
- type Env = {
37
- [name: string]: any;
38
- ASSETS: { fetch(url: string, init: RequestInit): Promise<Response> };
39
- };
40
-
41
- type WorkerContext = {
42
- waitUntil: (promise: Promise<any>) => void;
43
- };
44
-
45
- function* executeRequest(request: Request, env: Env) {
46
- const requestPath = new URL(request.url).pathname;
47
-
48
- // First, iterate through the routes and execute "middlewares" on partial route matches
49
- for (const route of routes) {
50
- if (
51
- route.methods.length &&
52
- !route.methods.includes(request.method as HTTPMethod)
53
- ) {
54
- continue;
55
- }
56
-
57
- const routeMatcher = match(route.routePath, { end: false });
58
- const matchResult = routeMatcher(requestPath);
59
- if (matchResult) {
60
- for (const handler of route.middlewares.flat()) {
61
- yield {
62
- handler,
63
- params: matchResult.params as Params,
64
- };
65
- }
66
- }
67
- }
68
-
69
- // Then look for the first exact route match and execute its "modules"
70
- for (const route of routes) {
71
- if (
72
- route.methods.length &&
73
- !route.methods.includes(request.method as HTTPMethod)
74
- ) {
75
- continue;
76
- }
77
-
78
- const routeMatcher = match(route.routePath, { end: true });
79
- const matchResult = routeMatcher(requestPath);
80
- if (matchResult && route.modules.length) {
81
- for (const handler of route.modules.flat()) {
82
- yield {
83
- handler,
84
- params: matchResult.params as Params,
85
- };
86
- }
87
- break;
88
- }
89
- }
90
-
91
- // Finally, yield to the asset-server
92
- return {
93
- handler: () => env.ASSETS.fetch(request.url, request),
94
- params: {} as Params,
95
- };
96
- }
97
-
98
- export default {
99
- async fetch(request: Request, env: Env, workerContext: WorkerContext) {
100
- const handlerIterator = executeRequest(request, env);
101
- const data = {}; // arbitrary data the user can set between functions
102
- const next = async (input?: RequestInfo, init?: RequestInit) => {
103
- if (input !== undefined) {
104
- request = new Request(input, init);
105
- }
106
-
107
- const { value } = handlerIterator.next();
108
- if (value) {
109
- const { handler, params } = value;
110
- const context: EventContext<unknown, any, any> = {
111
- request: new Request(request.clone()),
112
- next,
113
- params,
114
- data,
115
- env,
116
- waitUntil: workerContext.waitUntil.bind(workerContext),
117
- };
118
-
119
- const response = await handler(context);
120
-
121
- // https://fetch.spec.whatwg.org/#null-body-status
122
- return new Response(
123
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
124
- response
125
- );
126
- }
127
- };
128
-
129
- try {
130
- return next();
131
- } catch (err) {
132
- return new Response("Internal Error", { status: 500 });
133
- }
134
- },
135
- };
@@ -1,4 +0,0 @@
1
- // We use this mock during tests because we're having trouble
2
- // properly compiling clipboardy for jest
3
- // We can revisit this if and when we write tests that test
4
- // the copying part of `dev`