wrangler 0.0.0-e14e589 → 0.0.0-e2a26a0

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 (61) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +2 -2
  3. package/package.json +49 -30
  4. package/pages/functions/buildWorker.ts +62 -0
  5. package/pages/functions/filepath-routing.test.ts +47 -0
  6. package/pages/functions/filepath-routing.ts +231 -0
  7. package/pages/functions/identifiers.ts +78 -0
  8. package/pages/functions/routes.ts +160 -0
  9. package/pages/functions/template-worker.ts +136 -0
  10. package/src/__tests__/dev.test.tsx +71 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +509 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1222 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +85 -76
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +50 -35
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +630 -85
  37. package/src/dev.tsx +446 -282
  38. package/src/dialogs.tsx +6 -14
  39. package/src/index.tsx +773 -426
  40. package/src/inspect.ts +596 -0
  41. package/src/kv.tsx +118 -45
  42. package/src/module-collection.ts +63 -0
  43. package/src/package-manager.ts +120 -0
  44. package/src/pages.tsx +917 -211
  45. package/src/paths.ts +26 -0
  46. package/src/proxy.ts +370 -0
  47. package/src/publish.ts +220 -88
  48. package/src/sites.tsx +180 -55
  49. package/src/tail.tsx +6 -4
  50. package/src/user.tsx +77 -87
  51. package/src/whoami.tsx +69 -0
  52. package/templates/new-worker.js +15 -0
  53. package/templates/new-worker.ts +15 -0
  54. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  55. package/wrangler-dist/cli.js +125330 -557
  56. package/wrangler-dist/cli.js.map +3 -3
  57. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  58. package/src/__tests__/mock-cfetch.js +0 -46
  59. package/src/api/inspect.ts +0 -441
  60. package/src/cfetch.ts +0 -72
  61. package/src/util/fetch.ts +0 -74
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ ## 🤠 wrangler
2
+
3
+ `wrangler` is a command line tool for building [Cloudflare Workers](https://workers.cloudflare.com/).
4
+
5
+ [(Read the full stack week launch blog post.)](https://blog.cloudflare.com/wrangler-v2-beta/)
6
+
7
+ **DISCLAIMER**: This is a work in progress, and is NOT recommended for use in production. We are opening this preview for feedback from the community, and to openly share our [roadmap](https://github.com/cloudflare/wrangler2/issues/12) for the future. As such, expect APIs and documentation to change before the end of the preview.
8
+
9
+ Further, we will NOT do a general release until we are both feature complete, and have a full backward compatibility and incremental migration plan in place. For more details, follow the [parent roadmap issue](https://github.com/cloudflare/wrangler2/issues/12).
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ # Make a javascript file
15
+ $ echo "export default { fetch() { return new Response('hello world') } }" > index.js
16
+ # try it out
17
+ $ npx wrangler@beta dev index.js
18
+ # and then publish it
19
+ $ npx wrangler@beta publish index.js --name my-worker
20
+ # visit https://my-worker.<your workers subdomain>.workers.dev
21
+ ```
22
+
23
+ ## Installation:
24
+
25
+ ```bash
26
+ $ npm install wrangler@beta
27
+ ```
28
+
29
+ ## Commands
30
+
31
+ ### `wrangler init [name]`
32
+
33
+ Creates a `wrangler.toml` configuration file. For more details on the configuration keys and values, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration).
34
+
35
+ ### `wrangler dev [script]`
36
+
37
+ Start a local development server, with live reloading and devtools.
38
+
39
+ ### `wrangler publish [script] --name [name]`
40
+
41
+ Publish the given script to the worldwide Cloudflare network.
42
+
43
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/commands).
44
+
45
+ ### `wrangler pages dev [directory] [-- command]`
46
+
47
+ Either serves a static build asset directory, or proxies itself in front of a command.
48
+
49
+ Builds and runs functions from a `./functions` directory or uses a `_worker.js` file inside the static build asset directory.
50
+
51
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/pages/platform/functions#develop-and-preview-locally) or run `wrangler pages dev --help`.
package/bin/wrangler.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- const { spawn } = require("child_process");
3
- const { join } = require("path");
2
+ const { spawn } = require("node:child_process");
3
+ const { join } = require("node:path");
4
4
  const semiver = require("semiver");
5
5
 
6
6
  const MIN_NODE_VERSION = "16.7.0";
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-e14e589",
3
+ "version": "0.0.0-e2a26a0",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
- "bin": "./bin/wrangler.js",
6
+ "bin": {
7
+ "wrangler": "./bin/wrangler.js",
8
+ "wrangler2": "./bin/wrangler.js"
9
+ },
7
10
  "license": "MIT OR Apache-2.0",
8
11
  "bugs": {
9
12
  "url": "https://github.com/cloudflare/wrangler/issues"
@@ -33,72 +36,85 @@
33
36
  "cli"
34
37
  ],
35
38
  "dependencies": {
36
- "@cloudflare/pages-functions-compiler": "0.3.4",
37
- "esbuild": "0.13.12",
38
- "miniflare": "2.0.0-rc.2",
39
+ "esbuild": "0.14.14",
40
+ "miniflare": "2.2.0",
41
+ "path-to-regexp": "^6.2.0",
39
42
  "semiver": "^1.1.0",
40
- "serve": "^13.0.2"
43
+ "xxhash-addon": "^1.4.0"
41
44
  },
42
45
  "optionalDependencies": {
43
46
  "fsevents": "~2.3.2"
44
47
  },
45
48
  "devDependencies": {
49
+ "@babel/types": "^7.16.0",
46
50
  "@iarna/toml": "^2.2.5",
47
- "@types/cloudflare": "^2.7.6",
48
- "@types/express": "^4.17.13",
49
- "@types/react": "^17.0.34",
51
+ "@types/estree": "^0.0.50",
52
+ "@types/mime": "^2.0.3",
53
+ "@types/react": "^17.0.37",
54
+ "@types/serve-static": "^1.13.10",
50
55
  "@types/signal-exit": "^3.0.1",
51
- "@types/ws": "^8.2.0",
52
- "@types/yargs": "^17.0.5",
56
+ "@types/ws": "^8.2.1",
57
+ "@types/yargs": "^17.0.7",
58
+ "acorn": "^8.6.0",
59
+ "acorn-walk": "^8.2.0",
60
+ "chokidar": "^3.5.2",
53
61
  "clipboardy": "^3.0.0",
62
+ "cmd-shim": "^4.1.0",
54
63
  "command-exists": "^1.2.9",
55
- "execa": "^5.1.1",
56
- "express": "^4.17.1",
64
+ "devtools-protocol": "^0.0.955664",
65
+ "execa": "^6.0.0",
66
+ "faye-websocket": "^0.11.4",
57
67
  "finalhandler": "^1.1.2",
58
68
  "find-up": "^6.2.0",
59
- "formdata-node": "^4.3.1",
60
- "http-proxy": "^1.18.1",
61
- "http-proxy-middleware": "^2.0.1",
69
+ "ignore": "^5.2.0",
62
70
  "ink": "^3.2.0",
63
- "ink-select-input": "^4.2.0",
71
+ "ink-select-input": "^4.2.1",
64
72
  "ink-table": "^3.0.0",
65
- "ink-text-input": "^4.0.1",
66
- "node-fetch": "^3.1.0",
73
+ "ink-testing-library": "^2.1.0",
74
+ "ink-text-input": "^4.0.2",
75
+ "jest-fetch-mock": "^3.0.3",
76
+ "mime": "^3.0.0",
67
77
  "open": "^8.4.0",
68
- "path-to-regexp": "^6.2.0",
69
78
  "react": "^17.0.2",
79
+ "react-error-boundary": "^3.1.4",
70
80
  "serve-static": "^1.14.1",
71
- "signal-exit": "^3.0.5",
81
+ "signal-exit": "^3.0.6",
72
82
  "tmp-promise": "^3.0.3",
73
- "ws": "^8.2.3",
74
- "yargs": "^17.2.1"
83
+ "undici": "4.13.0",
84
+ "ws": "^8.3.0",
85
+ "yargs": "^17.3.0"
75
86
  },
76
87
  "files": [
77
88
  "src",
78
89
  "bin",
90
+ "pages",
79
91
  "miniflare-config-stubs",
80
92
  "wrangler-dist",
81
- "static-asset-facade.js",
93
+ "templates",
82
94
  "vendor",
83
95
  "import_meta_url.js"
84
96
  ],
85
97
  "scripts": {
86
98
  "clean": "rm -rf wrangler-dist",
99
+ "check:type": "tsc",
87
100
  "bundle": "node -r esbuild-register scripts/bundle.ts",
88
101
  "build": "npm run clean && npm run bundle",
89
102
  "start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
90
- "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
103
+ "test": "jest --silent=false --verbose=true",
104
+ "test-watch": "npm run test -- --runInBand --testTimeout=50000 --watch"
91
105
  },
92
106
  "engines": {
93
- "node": ">=16.0.0"
107
+ "node": ">=16.7.0"
94
108
  },
95
109
  "jest": {
110
+ "restoreMocks": true,
111
+ "testTimeout": 30000,
96
112
  "testRegex": ".*.(test|spec)\\.[jt]sx?$",
97
113
  "transformIgnorePatterns": [
98
- "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill)"
114
+ "node_modules/(?!find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
99
115
  ],
100
116
  "moduleNameMapper": {
101
- "clipboardy": "<rootDir>/src/__tests__/clipboardy-mock.js"
117
+ "clipboardy": "<rootDir>/src/__tests__/helpers/clipboardy-mock.js"
102
118
  },
103
119
  "transform": {
104
120
  "^.+\\.c?(t|j)sx?$": [
@@ -107,6 +123,9 @@
107
123
  "sourcemap": true
108
124
  }
109
125
  ]
110
- }
126
+ },
127
+ "setupFilesAfterEnv": [
128
+ "<rootDir>/src/__tests__/jest.setup.ts"
129
+ ]
111
130
  }
112
- }
131
+ }
@@ -0,0 +1,62 @@
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
+ }
@@ -0,0 +1,47 @@
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
+ });
@@ -0,0 +1,231 @@
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
+ }
@@ -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
+ );