wrangler 0.0.0-e2a26a0 → 0.0.0-e2b3306e1

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