wrangler 0.0.0-e1c615f → 0.0.0-e3a458e

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 (95) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +34 -15
  3. package/pages/functions/buildWorker.ts +6 -1
  4. package/pages/functions/filepath-routing.test.ts +212 -28
  5. package/pages/functions/filepath-routing.ts +91 -131
  6. package/pages/functions/routes.ts +11 -18
  7. package/pages/functions/template-worker.ts +21 -28
  8. package/src/__tests__/configuration.test.ts +2598 -0
  9. package/src/__tests__/dev.test.tsx +437 -58
  10. package/src/__tests__/dev2.test.tsx +154 -0
  11. package/src/__tests__/guess-worker-format.test.ts +58 -0
  12. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  13. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  14. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +55 -19
  18. package/src/__tests__/helpers/mock-console.ts +70 -0
  19. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  20. package/src/__tests__/helpers/mock-kv.ts +33 -0
  21. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  22. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  23. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  24. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  25. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  26. package/src/__tests__/https-options.test.ts +127 -0
  27. package/src/__tests__/index.test.ts +779 -75
  28. package/src/__tests__/jest.setup.ts +53 -6
  29. package/src/__tests__/kv.test.ts +726 -442
  30. package/src/__tests__/logout.test.ts +52 -0
  31. package/src/__tests__/package-manager.test.ts +206 -0
  32. package/src/__tests__/pages.test.ts +44 -0
  33. package/src/__tests__/parse.test.ts +322 -0
  34. package/src/__tests__/publish.test.ts +2611 -0
  35. package/src/__tests__/r2.test.ts +198 -0
  36. package/src/__tests__/route.test.ts +45 -0
  37. package/src/__tests__/secret.test.ts +425 -0
  38. package/src/__tests__/sentry.test.ts +146 -0
  39. package/src/__tests__/tail.test.ts +564 -0
  40. package/src/__tests__/whoami.test.tsx +100 -0
  41. package/src/bundle.ts +142 -0
  42. package/src/cfetch/index.ts +21 -19
  43. package/src/cfetch/internal.ts +94 -24
  44. package/src/cli.ts +10 -0
  45. package/src/config/README.md +107 -0
  46. package/src/config/config.ts +279 -0
  47. package/src/config/diagnostics.ts +80 -0
  48. package/src/config/environment.ts +305 -0
  49. package/src/config/index.ts +52 -0
  50. package/src/config/validation-helpers.ts +468 -0
  51. package/src/config/validation.ts +1057 -0
  52. package/src/{api/preview.ts → create-worker-preview.ts} +61 -23
  53. package/src/create-worker-upload-form.ts +217 -0
  54. package/src/dev/dev.tsx +362 -0
  55. package/src/dev/local.tsx +247 -0
  56. package/src/dev/remote.tsx +203 -0
  57. package/src/dev/use-esbuild.ts +100 -0
  58. package/src/dialogs.tsx +2 -2
  59. package/src/entry.ts +159 -0
  60. package/src/environment-variables.ts +33 -0
  61. package/src/https-options.ts +122 -0
  62. package/src/index.tsx +1231 -795
  63. package/src/inspect.ts +617 -0
  64. package/src/{kv.tsx → kv.ts} +132 -60
  65. package/src/module-collection.ts +215 -26
  66. package/src/open-in-browser.ts +25 -0
  67. package/src/package-manager.ts +126 -0
  68. package/src/pages.tsx +140 -63
  69. package/src/parse.ts +183 -0
  70. package/src/paths.ts +26 -0
  71. package/src/proxy.ts +414 -77
  72. package/src/publish.ts +296 -292
  73. package/src/r2.ts +50 -0
  74. package/src/reporting.ts +131 -0
  75. package/src/selfsigned.d.ts +29 -0
  76. package/src/sites.tsx +217 -58
  77. package/src/tail/filters.ts +279 -0
  78. package/src/tail/index.ts +299 -0
  79. package/src/tail/printing.ts +62 -0
  80. package/src/user.tsx +284 -188
  81. package/src/whoami.tsx +69 -0
  82. package/src/{api/worker.ts → worker.ts} +51 -43
  83. package/templates/new-worker.js +15 -0
  84. package/templates/new-worker.ts +15 -0
  85. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  86. package/templates/tsconfig.json +105 -0
  87. package/wrangler-dist/cli.js +130585 -112306
  88. package/wrangler-dist/cli.js.map +3 -3
  89. package/src/__tests__/run-in-tmp.ts +0 -19
  90. package/src/__tests__/run-wrangler.ts +0 -32
  91. package/src/api/form_data.ts +0 -131
  92. package/src/api/inspect.ts +0 -430
  93. package/src/config.ts +0 -131
  94. package/src/dev.tsx +0 -874
  95. package/src/tail.tsx +0 -73
@@ -1,173 +1,126 @@
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
- };
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { build } from "esbuild";
4
+ import { toUrlPath } from "../../src/paths";
5
+ import type { UrlPath } from "../../src/paths";
6
+ import type { HTTPMethod, RouteConfig } from "./routes";
13
7
 
14
8
  export async function generateConfigFromFileTree({
15
9
  baseDir,
16
10
  baseURL,
17
- }: Arguments) {
18
- let routeEntries: [string, RouteConfig][] = [];
11
+ }: {
12
+ baseDir: string;
13
+ baseURL: UrlPath;
14
+ }) {
15
+ let routeEntries: RouteConfig[] = [];
19
16
 
20
17
  if (!baseURL.startsWith("/")) {
21
- baseURL = `/${baseURL}`;
18
+ baseURL = `/${baseURL}` as UrlPath;
22
19
  }
23
20
 
24
21
  if (baseURL.endsWith("/")) {
25
- baseURL = baseURL.slice(0, -1);
22
+ baseURL = baseURL.slice(0, -1) as UrlPath;
26
23
  }
27
24
 
28
25
  await forEachFile(baseDir, async (filepath) => {
29
26
  const ext = path.extname(filepath);
30
27
  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",
28
+ const { metafile } = await build({
29
+ metafile: true,
30
+ write: false,
31
+ bundle: false,
32
+ entryPoints: [path.resolve(filepath)],
34
33
  });
34
+ const exportNames: string[] = [];
35
+ if (metafile) {
36
+ for (const output in metafile?.outputs) {
37
+ exportNames.push(...metafile.outputs[output].exports);
38
+ }
39
+ }
40
+ for (const exportName of exportNames) {
41
+ const [match, method = ""] = (exportName.match(
42
+ /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
43
+ ) ?? []) as (string | undefined)[];
35
44
 
36
- // parse each file into an AST and search for module exports that match "onRequest" and friends
37
- const ast = acorn.parse(code, {
38
- ecmaVersion: "latest",
39
- sourceType: "module",
40
- });
41
- acornWalk.simple(ast, {
42
- ExportNamedDeclaration(_node: unknown) {
43
- // This dynamic cast assumes that the AST generated by acornWalk will generate nodes that
44
- // are compatible with the eslint AST nodes.
45
- const node = _node as ExportNamedDeclaration;
46
-
47
- // this is an array because multiple things can be exported from a single statement
48
- // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
49
- const exportNames: string[] = [];
50
-
51
- if (node.declaration) {
52
- const declaration = node.declaration;
53
-
54
- // `export async function onRequest() {...}`
55
- if (declaration.type === "FunctionDeclaration") {
56
- exportNames.push(declaration.id.name);
57
- }
58
-
59
- // `export const onRequestGet = () => {}, onRequestPost = () => {}`
60
- if (declaration.type === "VariableDeclaration") {
61
- exportNames.push(
62
- ...declaration.declarations.map(
63
- (variableDeclarator) =>
64
- (variableDeclarator.id as unknown as Identifier).name
65
- )
66
- );
67
- }
68
- }
45
+ if (match) {
46
+ const basename = path.basename(filepath).slice(0, -ext.length);
47
+
48
+ const isIndexFile = basename === "index";
49
+ // TODO: deprecate _middleware_ in favor of _middleware
50
+ const isMiddlewareFile =
51
+ basename === "_middleware" || basename === "_middleware_";
69
52
 
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
- );
53
+ let routePath = path
54
+ .relative(baseDir, filepath)
55
+ .slice(0, -ext.length);
56
+
57
+ if (isIndexFile || isMiddlewareFile) {
58
+ routePath = path.dirname(routePath);
78
59
  }
79
60
 
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
- }
61
+ if (routePath === ".") {
62
+ routePath = "";
124
63
  }
125
- },
126
- });
64
+
65
+ routePath = `${baseURL}/${routePath}`;
66
+
67
+ routePath = routePath.replace(/\[\[([^\]]+)\]\]/g, ":$1*"); // transform [[id]] => :id*
68
+ routePath = routePath.replaceAll(/\[([^\]]+)\]/g, ":$1"); // transform [id] => :id
69
+
70
+ // These are used as module specifiers so UrlPaths are okay to use even on Windows
71
+ const modulePath = toUrlPath(path.relative(baseDir, filepath));
72
+
73
+ const routeEntry: RouteConfig = {
74
+ routePath: toUrlPath(routePath),
75
+ method: method.toUpperCase() as HTTPMethod,
76
+ [isMiddlewareFile ? "middleware" : "module"]: [
77
+ `${modulePath}:${exportName}`,
78
+ ],
79
+ };
80
+
81
+ routeEntries.push(routeEntry);
82
+ }
83
+ }
127
84
  }
128
85
  });
129
-
130
86
  // Combine together any routes (index routes) which contain both a module and a middleware
131
87
  routeEntries = routeEntries.reduce(
132
- (acc: typeof routeEntries, [routePath, routeHandler]) => {
88
+ (acc: typeof routeEntries, { routePath, ...rest }) => {
133
89
  const existingRouteEntry = acc.find(
134
- (routeEntry) => routeEntry[0] === routePath
90
+ (routeEntry) =>
91
+ routeEntry.routePath === routePath &&
92
+ routeEntry.method === rest.method
135
93
  );
136
94
  if (existingRouteEntry !== undefined) {
137
- existingRouteEntry[1] = {
138
- ...existingRouteEntry[1],
139
- ...routeHandler,
140
- };
95
+ Object.assign(existingRouteEntry, rest);
141
96
  } else {
142
- acc.push([routePath, routeHandler]);
97
+ acc.push({ routePath, ...rest });
143
98
  }
144
99
  return acc;
145
100
  },
146
101
  []
147
102
  );
148
103
 
149
- routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB));
104
+ routeEntries.sort((a, b) => compareRoutes(a, b));
150
105
 
151
- return { routes: Object.fromEntries(routeEntries) } as Config;
106
+ return {
107
+ routes: routeEntries,
108
+ };
152
109
  }
153
110
 
154
111
  // Ensure routes are produced in order of precedence so that
155
112
  // more specific routes aren't occluded from matching due to
156
113
  // less specific routes appearing first in the route list.
157
- export function compareRoutes(a: string, b: string) {
158
- function parseRoutePath(routePath: string) {
159
- let [method, segmentedPath] = routePath.split(" ");
160
- if (!segmentedPath) {
161
- segmentedPath = method;
162
- method = null;
163
- }
164
-
165
- const segments = segmentedPath.slice(1).split("/").filter(Boolean);
166
- return [method, segments];
114
+ export function compareRoutes(
115
+ { routePath: routePathA, method: methodA }: RouteConfig,
116
+ { routePath: routePathB, method: methodB }: RouteConfig
117
+ ) {
118
+ function parseRoutePath(routePath: UrlPath): string[] {
119
+ return routePath.slice(1).split("/").filter(Boolean);
167
120
  }
168
121
 
169
- const [methodA, segmentsA] = parseRoutePath(a);
170
- const [methodB, segmentsB] = parseRoutePath(b);
122
+ const segmentsA = parseRoutePath(routePathA);
123
+ const segmentsB = parseRoutePath(routePathB);
171
124
 
172
125
  // sort routes with fewer segments after those with more segments
173
126
  if (segmentsA.length !== segmentsB.length) {
@@ -193,8 +146,8 @@ export function compareRoutes(a: string, b: string) {
193
146
  if (methodA && !methodB) return -1;
194
147
  if (!methodA && methodB) return 1;
195
148
 
196
- // all else equal, just sort them lexicographically
197
- return a.localeCompare(b);
149
+ // all else equal, just sort the paths lexicographically
150
+ return routePathA.localeCompare(routePathB);
198
151
  }
199
152
 
200
153
  async function forEachFile<T>(
@@ -204,7 +157,7 @@ async function forEachFile<T>(
204
157
  const searchPaths = [baseDir];
205
158
  const returnValues: T[] = [];
206
159
 
207
- while (searchPaths.length) {
160
+ while (isNotEmpty(searchPaths)) {
208
161
  const cwd = searchPaths.shift();
209
162
  const dir = await fs.readdir(cwd, { withFileTypes: true });
210
163
  for (const entry of dir) {
@@ -219,3 +172,10 @@ async function forEachFile<T>(
219
172
 
220
173
  return returnValues;
221
174
  }
175
+
176
+ interface NonEmptyArray<T> extends Array<T> {
177
+ shift(): T;
178
+ }
179
+ function isNotEmpty<T>(array: T[]): array is NonEmptyArray<T> {
180
+ return array.length > 0;
181
+ }
@@ -1,6 +1,7 @@
1
- import path from "path";
2
- import fs from "fs/promises";
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
3
  import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
4
+ import type { UrlPath } from "../../src/paths";
4
5
 
5
6
  export const HTTP_METHODS = [
6
7
  "HEAD",
@@ -19,22 +20,20 @@ export function isHTTPMethod(
19
20
  }
20
21
 
21
22
  export type RoutesCollection = Array<{
22
- routePath: string;
23
- methods: HTTPMethod[];
23
+ routePath: UrlPath;
24
+ method?: HTTPMethod;
24
25
  modules: string[];
25
26
  middlewares: string[];
26
27
  }>;
27
28
 
28
29
  export type Config = {
29
- routes?: RoutesConfig;
30
+ routes?: RouteConfig[];
30
31
  schedules?: unknown;
31
32
  };
32
33
 
33
- export type RoutesConfig = {
34
- [route: string]: RouteConfig;
35
- };
36
-
37
34
  export type RouteConfig = {
35
+ routePath: UrlPath;
36
+ method?: HTTPMethod;
38
37
  middleware?: string | string[];
39
38
  module?: string | string[];
40
39
  };
@@ -114,16 +113,10 @@ export function parseConfig(config: Config, baseDir: string) {
114
113
  });
115
114
  }
116
115
 
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
-
116
+ for (const { routePath, method, ...props } of config.routes ?? []) {
124
117
  routes.push({
125
118
  routePath,
126
- methods: _methods.split("|").filter(isHTTPMethod),
119
+ method,
127
120
  middlewares: parseModuleIdentifiers(props.middleware),
128
121
  modules: parseModuleIdentifiers(props.module),
129
122
  });
@@ -148,7 +141,7 @@ export const routes = [
148
141
  .map(
149
142
  (route) => ` {
150
143
  routePath: "${route.routePath}",
151
- methods: ${JSON.stringify(route.methods)},
144
+ method: "${route.method}",
152
145
  middlewares: [${route.middlewares.join(", ")}],
153
146
  modules: [${route.modules.join(", ")}],
154
147
  },`
@@ -22,33 +22,32 @@ declare type PagesFunction<
22
22
 
23
23
  type RouteHandler = {
24
24
  routePath: string;
25
- methods: HTTPMethod[];
25
+ method?: HTTPMethod;
26
26
  modules: PagesFunction[];
27
27
  middlewares: PagesFunction[];
28
28
  };
29
29
 
30
30
  // inject `routes` via ESBuild
31
31
  declare const routes: RouteHandler[];
32
+ // define `__FALLBACK_SERVICE__` via ESBuild
33
+ declare const __FALLBACK_SERVICE__: string;
32
34
 
33
35
  // expect an ASSETS fetcher binding pointing to the asset-server stage
34
- type Env = {
35
- [name: string]: unknown;
36
- ASSETS: { fetch(url: string, init: RequestInit): Promise<Response> };
36
+ type FetchEnv = {
37
+ [name: string]: { fetch: typeof fetch };
38
+ ASSETS: { fetch: typeof fetch };
37
39
  };
38
40
 
39
41
  type WorkerContext = {
40
42
  waitUntil: (promise: Promise<unknown>) => void;
41
43
  };
42
44
 
43
- function* executeRequest(request: Request, env: Env) {
45
+ function* executeRequest(request: Request, _env: FetchEnv) {
44
46
  const requestPath = new URL(request.url).pathname;
45
47
 
46
48
  // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
47
49
  for (const route of [...routes].reverse()) {
48
- if (
49
- route.methods.length &&
50
- !route.methods.includes(request.method as HTTPMethod)
51
- ) {
50
+ if (route.method && route.method !== request.method) {
52
51
  continue;
53
52
  }
54
53
 
@@ -66,10 +65,7 @@ function* executeRequest(request: Request, env: Env) {
66
65
 
67
66
  // Then look for the first exact route match and execute its "modules"
68
67
  for (const route of routes) {
69
- if (
70
- route.methods.length &&
71
- !route.methods.includes(request.method as HTTPMethod)
72
- ) {
68
+ if (route.method && route.method !== request.method) {
73
69
  continue;
74
70
  }
75
71
 
@@ -85,16 +81,10 @@ function* executeRequest(request: Request, env: Env) {
85
81
  break;
86
82
  }
87
83
  }
88
-
89
- // Finally, yield to the asset-server
90
- return {
91
- handler: () => env.ASSETS.fetch(request.url, request),
92
- params: {} as Params,
93
- };
94
84
  }
95
85
 
96
86
  export default {
97
- async fetch(request: Request, env: Env, workerContext: WorkerContext) {
87
+ async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
98
88
  const handlerIterator = executeRequest(request, env);
99
89
  const data = {}; // arbitrary data the user can set between functions
100
90
  const next = async (input?: RequestInfo, init?: RequestInit) => {
@@ -102,14 +92,11 @@ export default {
102
92
  request = new Request(input, init);
103
93
  }
104
94
 
105
- const { value } = handlerIterator.next();
106
- if (value) {
107
- const { handler, params } = value;
108
- const context: EventContext<
109
- unknown,
110
- string,
111
- Record<string, unknown>
112
- > = {
95
+ const result = handlerIterator.next();
96
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
97
+ if (result.done == false) {
98
+ const { handler, params } = result.value;
99
+ const context = {
113
100
  request: new Request(request.clone()),
114
101
  next,
115
102
  params,
@@ -125,6 +112,12 @@ export default {
125
112
  [101, 204, 205, 304].includes(response.status) ? null : response.body,
126
113
  response
127
114
  );
115
+ } else if (__FALLBACK_SERVICE__) {
116
+ // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
117
+ return env[__FALLBACK_SERVICE__].fetch(request);
118
+ } else {
119
+ // There was not fallback service so actually make the request to the origin.
120
+ return fetch(request);
128
121
  }
129
122
  };
130
123