wrangler 0.0.0-fb43821 → 0.0.0-fe5dcfd

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 (41) hide show
  1. package/package.json +25 -10
  2. package/pages/functions/buildWorker.ts +62 -0
  3. package/pages/functions/filepath-routing.test.ts +39 -0
  4. package/pages/functions/filepath-routing.ts +228 -0
  5. package/pages/functions/identifiers.ts +78 -0
  6. package/pages/functions/routes.ts +158 -0
  7. package/pages/functions/template-worker.ts +136 -0
  8. package/src/__tests__/dev.test.tsx +67 -0
  9. package/src/__tests__/index.test.ts +42 -175
  10. package/src/__tests__/jest.setup.ts +22 -0
  11. package/src/__tests__/kv.test.ts +1199 -0
  12. package/src/__tests__/mock-cfetch.ts +173 -0
  13. package/src/__tests__/mock-dialogs.ts +65 -0
  14. package/src/__tests__/publish.test.ts +737 -0
  15. package/src/__tests__/run-in-tmp.ts +19 -0
  16. package/src/__tests__/run-wrangler.ts +32 -0
  17. package/src/__tests__/whoami.test.tsx +130 -0
  18. package/src/api/form_data.ts +66 -76
  19. package/src/api/preview.ts +4 -4
  20. package/src/api/worker.ts +38 -44
  21. package/src/cfetch/index.ts +110 -0
  22. package/src/cfetch/internal.ts +71 -0
  23. package/src/cli.ts +6 -7
  24. package/src/config.ts +634 -110
  25. package/src/dev.tsx +275 -272
  26. package/src/dialogs.tsx +2 -2
  27. package/src/index.tsx +504 -403
  28. package/src/inspect.ts +543 -0
  29. package/src/kv.tsx +109 -44
  30. package/src/pages.tsx +444 -222
  31. package/src/proxy.ts +302 -0
  32. package/src/publish.ts +123 -87
  33. package/src/sites.tsx +169 -41
  34. package/src/tail.tsx +5 -3
  35. package/src/user.tsx +64 -74
  36. package/src/whoami.tsx +69 -0
  37. package/wrangler-dist/cli.js +42792 -42619
  38. package/wrangler-dist/cli.js.map +3 -3
  39. package/src/__tests__/mock-cfetch.js +0 -42
  40. package/src/api/inspect.ts +0 -430
  41. package/src/cfetch.ts +0 -72
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-fb43821",
3
+ "version": "0.0.0-fe5dcfd",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
6
  "bin": {
@@ -36,35 +36,45 @@
36
36
  "cli"
37
37
  ],
38
38
  "dependencies": {
39
- "@cloudflare/pages-functions-compiler": "0.3.8",
40
39
  "esbuild": "0.14.1",
41
- "miniflare": "2.0.0-rc.4",
42
- "semiver": "^1.1.0"
40
+ "miniflare": "2.2.0",
41
+ "path-to-regexp": "^6.2.0",
42
+ "semiver": "^1.1.0",
43
+ "xxhash-addon": "^1.4.0"
43
44
  },
44
45
  "optionalDependencies": {
45
46
  "fsevents": "~2.3.2"
46
47
  },
47
48
  "devDependencies": {
49
+ "@babel/types": "^7.16.0",
48
50
  "@iarna/toml": "^2.2.5",
51
+ "@types/estree": "^0.0.50",
52
+ "@types/mime": "^2.0.3",
49
53
  "@types/react": "^17.0.37",
54
+ "@types/serve-static": "^1.13.10",
50
55
  "@types/signal-exit": "^3.0.1",
51
56
  "@types/ws": "^8.2.1",
52
57
  "@types/yargs": "^17.0.7",
58
+ "acorn": "^8.6.0",
59
+ "acorn-walk": "^8.2.0",
53
60
  "chokidar": "^3.5.2",
54
61
  "clipboardy": "^3.0.0",
55
62
  "command-exists": "^1.2.9",
63
+ "devtools-protocol": "^0.0.955664",
56
64
  "execa": "^6.0.0",
65
+ "faye-websocket": "^0.11.4",
57
66
  "finalhandler": "^1.1.2",
58
67
  "find-up": "^6.2.0",
59
68
  "formdata-node": "^4.3.1",
60
- "http-proxy": "^1.18.1",
69
+ "ignore": "^5.2.0",
61
70
  "ink": "^3.2.0",
62
71
  "ink-select-input": "^4.2.1",
63
72
  "ink-table": "^3.0.0",
73
+ "ink-testing-library": "^2.1.0",
64
74
  "ink-text-input": "^4.0.2",
65
- "node-fetch": "^3.1.0",
75
+ "mime": "^3.0.0",
76
+ "node-fetch": "3.1.1",
66
77
  "open": "^8.4.0",
67
- "path-to-regexp": "^6.2.0",
68
78
  "react": "^17.0.2",
69
79
  "react-error-boundary": "^3.1.4",
70
80
  "serve-static": "^1.14.1",
@@ -77,6 +87,7 @@
77
87
  "files": [
78
88
  "src",
79
89
  "bin",
90
+ "pages",
80
91
  "miniflare-config-stubs",
81
92
  "wrangler-dist",
82
93
  "static-asset-facade.js",
@@ -88,7 +99,8 @@
88
99
  "bundle": "node -r esbuild-register scripts/bundle.ts",
89
100
  "build": "npm run clean && npm run bundle",
90
101
  "start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
91
- "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
102
+ "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true",
103
+ "test-watch": "npm run test -- --runInBand --testTimeout=50000 --watch"
92
104
  },
93
105
  "engines": {
94
106
  "node": ">=16.7.0"
@@ -109,6 +121,9 @@
109
121
  "sourcemap": true
110
122
  }
111
123
  ]
112
- }
124
+ },
125
+ "setupFilesAfterEnv": [
126
+ "<rootDir>/src/__tests__/jest.setup.ts"
127
+ ]
113
128
  }
114
- }
129
+ }
@@ -0,0 +1,62 @@
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
+ 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
+ }
@@ -0,0 +1,39 @@
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
+ });
@@ -0,0 +1,228 @@
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" && declaration.id) {
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): [string | null, string[]] {
159
+ const parts = routePath.split(" ", 2);
160
+ // split() will guarantee at least one element.
161
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
162
+ const segmentedPath = parts.pop()!;
163
+ const method = parts.pop() ?? null;
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 (isNotEmpty(searchPaths)) {
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
+ }
222
+
223
+ interface NonEmptyArray<T> extends Array<T> {
224
+ shift(): T;
225
+ }
226
+ function isNotEmpty<T>(array: T[]): array is NonEmptyArray<T> {
227
+ return array.length > 0;
228
+ }
@@ -0,0 +1,78 @@
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
+ );
@@ -0,0 +1,158 @@
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
+ }