wrangler 0.0.0-bfbb0be → 0.0.0-bfbe49d0

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 (161) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +99 -114
  3. package/package.json +194 -155
  4. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  5. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  6. package/templates/__tests__/tsconfig.json +8 -0
  7. package/templates/checked-fetch.js +30 -0
  8. package/templates/facade.d.ts +17 -0
  9. package/templates/gitignore +1 -0
  10. package/templates/init-tests/test-jest-new-worker.js +23 -0
  11. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  12. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  13. package/templates/middleware/common.ts +67 -0
  14. package/templates/middleware/loader-modules.ts +137 -0
  15. package/templates/middleware/loader-sw.ts +228 -0
  16. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  17. package/templates/middleware/middleware-d1-beta.ts +244 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  20. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  21. package/templates/middleware/middleware-pretty-error.ts +40 -0
  22. package/templates/middleware/middleware-scheduled.ts +15 -0
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/new-worker-scheduled.js +3 -3
  26. package/templates/new-worker-scheduled.ts +16 -16
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +19 -16
  29. package/templates/no-op-worker.js +8 -8
  30. package/templates/pages-dev-pipeline.ts +31 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +159 -124
  34. package/templates/pages-template-worker.ts +161 -124
  35. package/templates/tsconfig-sanity.ts +11 -0
  36. package/templates/tsconfig.init.json +105 -0
  37. package/templates/tsconfig.json +6 -103
  38. package/wrangler-dist/cli.d.ts +1732 -0
  39. package/wrangler-dist/cli.js +112895 -89619
  40. package/wrangler-dist/wasm-sync.wasm +0 -0
  41. package/import_meta_url.js +0 -3
  42. package/miniflare-config-stubs/.env.empty +0 -0
  43. package/miniflare-config-stubs/package.empty.json +0 -1
  44. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  45. package/miniflare-dist/index.mjs +0 -4886
  46. package/src/__tests__/config-cache.test.ts +0 -36
  47. package/src/__tests__/configuration.test.ts +0 -3548
  48. package/src/__tests__/dev.test.tsx +0 -1055
  49. package/src/__tests__/guess-worker-format.test.ts +0 -85
  50. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  51. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  52. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  53. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  54. package/src/__tests__/helpers/mock-bin.ts +0 -36
  55. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  56. package/src/__tests__/helpers/mock-console.ts +0 -97
  57. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  58. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  59. package/src/__tests__/helpers/mock-istty.ts +0 -32
  60. package/src/__tests__/helpers/mock-kv.ts +0 -33
  61. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  62. package/src/__tests__/helpers/mock-process.ts +0 -39
  63. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  64. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  65. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  66. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  67. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  68. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  69. package/src/__tests__/https-options.test.ts +0 -130
  70. package/src/__tests__/index.test.ts +0 -258
  71. package/src/__tests__/init.test.ts +0 -1992
  72. package/src/__tests__/jest.setup.ts +0 -107
  73. package/src/__tests__/kv.test.ts +0 -1619
  74. package/src/__tests__/logger.test.ts +0 -141
  75. package/src/__tests__/package-manager.test.ts +0 -353
  76. package/src/__tests__/pages.test.ts +0 -1242
  77. package/src/__tests__/parse.test.ts +0 -330
  78. package/src/__tests__/publish.test.ts +0 -6188
  79. package/src/__tests__/r2.test.ts +0 -233
  80. package/src/__tests__/route.test.ts +0 -45
  81. package/src/__tests__/secret.test.ts +0 -486
  82. package/src/__tests__/tail.test.ts +0 -690
  83. package/src/__tests__/user.test.ts +0 -132
  84. package/src/__tests__/whoami.test.tsx +0 -139
  85. package/src/abort.d.ts +0 -3
  86. package/src/bundle-reporter.tsx +0 -29
  87. package/src/bundle.ts +0 -204
  88. package/src/cfetch/index.ts +0 -121
  89. package/src/cfetch/internal.ts +0 -142
  90. package/src/cli.ts +0 -13
  91. package/src/config/README.md +0 -107
  92. package/src/config/config.ts +0 -243
  93. package/src/config/diagnostics.ts +0 -80
  94. package/src/config/environment.ts +0 -420
  95. package/src/config/index.ts +0 -225
  96. package/src/config/validation-helpers.ts +0 -584
  97. package/src/config/validation.ts +0 -1580
  98. package/src/config-cache.ts +0 -44
  99. package/src/create-worker-preview.ts +0 -185
  100. package/src/create-worker-upload-form.ts +0 -254
  101. package/src/dev/dev-vars.ts +0 -36
  102. package/src/dev/dev.tsx +0 -399
  103. package/src/dev/local.tsx +0 -321
  104. package/src/dev/remote.tsx +0 -282
  105. package/src/dev/use-esbuild.ts +0 -112
  106. package/src/dialogs.tsx +0 -135
  107. package/src/durable.ts +0 -102
  108. package/src/entry.ts +0 -328
  109. package/src/environment-variables.ts +0 -35
  110. package/src/errors.ts +0 -11
  111. package/src/git-client.ts +0 -42
  112. package/src/https-options.ts +0 -123
  113. package/src/index.tsx +0 -2908
  114. package/src/inspect.ts +0 -662
  115. package/src/intl-polyfill.d.ts +0 -139
  116. package/src/kv.ts +0 -408
  117. package/src/logger.ts +0 -73
  118. package/src/miniflare-cli/README.md +0 -30
  119. package/src/miniflare-cli/enum-keys.ts +0 -17
  120. package/src/miniflare-cli/index.ts +0 -41
  121. package/src/miniflare-cli/request-context.ts +0 -40
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -17
  124. package/src/package-manager.ts +0 -174
  125. package/src/pages/build.tsx +0 -202
  126. package/src/pages/constants.ts +0 -7
  127. package/src/pages/deployments.tsx +0 -101
  128. package/src/pages/dev.tsx +0 -948
  129. package/src/pages/functions/buildPlugin.ts +0 -105
  130. package/src/pages/functions/buildWorker.ts +0 -151
  131. package/src/pages/functions/filepath-routing.test.ts +0 -234
  132. package/src/pages/functions/filepath-routing.ts +0 -189
  133. package/src/pages/functions/identifiers.ts +0 -78
  134. package/src/pages/functions/routes.ts +0 -151
  135. package/src/pages/index.tsx +0 -84
  136. package/src/pages/projects.tsx +0 -157
  137. package/src/pages/publish.tsx +0 -325
  138. package/src/pages/types.ts +0 -40
  139. package/src/pages/upload.tsx +0 -363
  140. package/src/pages/utils.ts +0 -12
  141. package/src/parse.ts +0 -222
  142. package/src/paths.ts +0 -26
  143. package/src/proxy.ts +0 -476
  144. package/src/publish.ts +0 -739
  145. package/src/r2.ts +0 -50
  146. package/src/selfsigned.d.ts +0 -29
  147. package/src/sites.tsx +0 -372
  148. package/src/tail/filters.ts +0 -279
  149. package/src/tail/index.ts +0 -299
  150. package/src/tail/printing.ts +0 -67
  151. package/src/update-check.ts +0 -19
  152. package/src/user/choose-account.tsx +0 -60
  153. package/src/user/env-vars.ts +0 -17
  154. package/src/user/generate-auth-url.ts +0 -33
  155. package/src/user/generate-random-state.ts +0 -16
  156. package/src/user/index.ts +0 -3
  157. package/src/user/user.tsx +0 -1133
  158. package/src/whoami.tsx +0 -71
  159. package/src/worker.ts +0 -181
  160. package/src/zones.ts +0 -73
  161. package/templates/static-asset-facade.js +0 -43
package/src/pages/dev.tsx DELETED
@@ -1,948 +0,0 @@
1
- import { execSync, spawn } from "node:child_process";
2
- import { existsSync, lstatSync, readFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { URL } from "node:url";
6
- import { watch } from "chokidar";
7
- import { getType } from "mime";
8
- import { FatalError } from "../errors";
9
- import { logger } from "../logger";
10
- import { getRequestContextCheckOptions } from "../miniflare-cli/request-context";
11
- import openInBrowser from "../open-in-browser";
12
- import { buildFunctions } from "./build";
13
- import { SECONDS_TO_WAIT_FOR_PROXY } from "./constants";
14
- import { CLEANUP, CLEANUP_CALLBACKS, pagesBetaWarning } from "./utils";
15
- import type {
16
- fetch as miniflareFetch,
17
- Headers as MiniflareHeaders,
18
- } from "@miniflare/core";
19
- import type { MiniflareOptions, Request as MiniflareRequest } from "miniflare";
20
- import type { Argv, ArgumentsCamelCase } from "yargs";
21
-
22
- type PagesDevArgs = {
23
- directory?: string;
24
- command?: string;
25
- local: boolean;
26
- port: number;
27
- proxy?: number;
28
- "script-path": string;
29
- binding?: (string | number)[];
30
- kv?: (string | number)[];
31
- do?: (string | number)[];
32
- "live-reload": boolean;
33
- "node-compat": boolean;
34
- };
35
-
36
- export function Options(yargs: Argv): Argv<PagesDevArgs> {
37
- return yargs
38
- .positional("directory", {
39
- type: "string",
40
- demandOption: undefined,
41
- description: "The directory of static assets to serve",
42
- })
43
- .positional("command", {
44
- type: "string",
45
- demandOption: undefined,
46
- description: "The proxy command to run",
47
- })
48
- .options({
49
- local: {
50
- type: "boolean",
51
- default: true,
52
- description: "Run on my machine",
53
- },
54
- port: {
55
- type: "number",
56
- default: 8788,
57
- description: "The port to listen on (serve from)",
58
- },
59
- proxy: {
60
- type: "number",
61
- description: "The port to proxy (where the static assets are served)",
62
- },
63
- "script-path": {
64
- type: "string",
65
- default: "_worker.js",
66
- description:
67
- "The location of the single Worker script if not using functions",
68
- },
69
- binding: {
70
- type: "array",
71
- description: "Bind variable/secret (KEY=VALUE)",
72
- alias: "b",
73
- },
74
- kv: {
75
- type: "array",
76
- description: "KV namespace to bind",
77
- alias: "k",
78
- },
79
- do: {
80
- type: "array",
81
- description: "Durable Object to bind (NAME=CLASS)",
82
- alias: "o",
83
- },
84
- "live-reload": {
85
- type: "boolean",
86
- default: false,
87
- description: "Auto reload HTML pages when change is detected",
88
- },
89
- "node-compat": {
90
- describe: "Enable node.js compatibility",
91
- default: false,
92
- type: "boolean",
93
- hidden: true,
94
- },
95
- // // TODO: Miniflare user options
96
- })
97
- .epilogue(pagesBetaWarning);
98
- }
99
-
100
- export const Handler = async ({
101
- local,
102
- directory,
103
- port,
104
- proxy: requestedProxyPort,
105
- "script-path": singleWorkerScriptPath,
106
- binding: bindings = [],
107
- kv: kvs = [],
108
- do: durableObjects = [],
109
- "live-reload": liveReload,
110
- "node-compat": nodeCompat,
111
- _: [_pages, _dev, ...remaining],
112
- }: ArgumentsCamelCase<PagesDevArgs>) => {
113
- // Beta message for `wrangler pages <commands>` usage
114
- logger.log(pagesBetaWarning);
115
-
116
- if (!local) {
117
- logger.error("Only local mode is supported at the moment.");
118
- return;
119
- }
120
-
121
- const functionsDirectory = "./functions";
122
- const usingFunctions = existsSync(functionsDirectory);
123
-
124
- const command = remaining as (string | number)[];
125
-
126
- let proxyPort: number | void;
127
-
128
- if (directory === undefined) {
129
- proxyPort = await spawnProxyProcess({
130
- port: requestedProxyPort,
131
- command,
132
- });
133
- if (proxyPort === undefined) return undefined;
134
- }
135
-
136
- let miniflareArgs: MiniflareOptions = {};
137
-
138
- let scriptReadyResolve: () => void;
139
- const scriptReadyPromise = new Promise<void>(
140
- (resolve) => (scriptReadyResolve = resolve)
141
- );
142
-
143
- if (usingFunctions) {
144
- const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
145
-
146
- if (nodeCompat) {
147
- console.warn(
148
- "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
149
- );
150
- }
151
-
152
- logger.log(`Compiling worker to "${outfile}"...`);
153
-
154
- try {
155
- await buildFunctions({
156
- outfile,
157
- functionsDirectory,
158
- sourcemap: true,
159
- watch: true,
160
- onEnd: () => scriptReadyResolve(),
161
- buildOutputDirectory: directory,
162
- nodeCompat,
163
- });
164
- } catch {}
165
-
166
- watch([functionsDirectory], {
167
- persistent: true,
168
- ignoreInitial: true,
169
- }).on("all", async () => {
170
- await buildFunctions({
171
- outfile,
172
- functionsDirectory,
173
- sourcemap: true,
174
- watch: true,
175
- onEnd: () => scriptReadyResolve(),
176
- buildOutputDirectory: directory,
177
- nodeCompat,
178
- });
179
- });
180
-
181
- miniflareArgs = {
182
- scriptPath: outfile,
183
- };
184
- } else {
185
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
186
- scriptReadyResolve!();
187
-
188
- const scriptPath =
189
- directory !== undefined
190
- ? join(directory, singleWorkerScriptPath)
191
- : singleWorkerScriptPath;
192
-
193
- if (existsSync(scriptPath)) {
194
- miniflareArgs = {
195
- scriptPath,
196
- };
197
- } else {
198
- logger.log("No functions. Shimming...");
199
- miniflareArgs = {
200
- // cfFetch sets the `cf` object that a function could expect
201
- // If there are no functions, there's no reason to set this up (and not make that network call)
202
- cfFetch: false,
203
- // TODO: The fact that these request/response hacks are necessary is ridiculous.
204
- // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
205
- script: `
206
- export default {
207
- async fetch(request, env, context) {
208
- const response = await env.ASSETS.fetch(request.url, request)
209
- return new Response(response.body, response)
210
- }
211
- }`,
212
- };
213
- }
214
- }
215
-
216
- // Defer importing miniflare until we really need it
217
- const { Miniflare, Log, LogLevel } = await import("miniflare");
218
- const { Response, fetch } = await import("@miniflare/core");
219
-
220
- // Wait for esbuild to finish building before starting Miniflare.
221
- // This must be before the call to `new Miniflare`, as that will
222
- // asynchronously start loading the script. `await startServer()`
223
- // internally just waits for that promise to resolve.
224
- await scriptReadyPromise;
225
-
226
- // `assetsFetch()` will only be called if there is `proxyPort` defined.
227
- // We only define `proxyPort`, above, when there is no `directory` defined.
228
- const assetsFetch =
229
- directory !== undefined
230
- ? await generateAssetsFetch(directory)
231
- : invalidAssetsFetch;
232
-
233
- const requestContextCheckOptions = await getRequestContextCheckOptions();
234
-
235
- const miniflare = new Miniflare({
236
- port,
237
- watch: true,
238
- modules: true,
239
-
240
- log: new Log(LogLevel.ERROR, { prefix: "pages" }),
241
- logUnhandledRejections: true,
242
- sourceMap: true,
243
-
244
- kvNamespaces: kvs.map((kv) => kv.toString()),
245
-
246
- durableObjects: Object.fromEntries(
247
- durableObjects.map((durableObject) => durableObject.toString().split("="))
248
- ),
249
-
250
- // User bindings
251
- bindings: {
252
- ...Object.fromEntries(
253
- bindings
254
- .map((binding) => binding.toString().split("="))
255
- .map(([key, ...values]) => [key, values.join("=")])
256
- ),
257
- },
258
-
259
- // env.ASSETS.fetch
260
- serviceBindings: {
261
- async ASSETS(request: MiniflareRequest) {
262
- if (proxyPort) {
263
- try {
264
- const url = new URL(request.url);
265
- url.host = `localhost:${proxyPort}`;
266
- return await fetch(url, request);
267
- } catch (thrown) {
268
- logger.error(`Could not proxy request: ${thrown}`);
269
-
270
- // TODO: Pretty error page
271
- return new Response(
272
- `[wrangler] Could not proxy request: ${thrown}`,
273
- { status: 502 }
274
- );
275
- }
276
- } else {
277
- try {
278
- return await assetsFetch(request);
279
- } catch (thrown) {
280
- logger.error(`Could not serve static asset: ${thrown}`);
281
-
282
- // TODO: Pretty error page
283
- return new Response(
284
- `[wrangler] Could not serve static asset: ${thrown}`,
285
- { status: 502 }
286
- );
287
- }
288
- }
289
- },
290
- },
291
-
292
- kvPersist: true,
293
- durableObjectsPersist: true,
294
- cachePersist: true,
295
- liveReload,
296
-
297
- ...requestContextCheckOptions,
298
- ...miniflareArgs,
299
- });
300
-
301
- try {
302
- // `startServer` might throw if user code contains errors
303
- const server = await miniflare.startServer();
304
- logger.log(`Serving at http://localhost:${port}/`);
305
-
306
- if (process.env.BROWSER !== "none") {
307
- await openInBrowser(`http://localhost:${port}/`);
308
- }
309
-
310
- if (directory !== undefined && liveReload) {
311
- watch([directory], {
312
- persistent: true,
313
- ignoreInitial: true,
314
- }).on("all", async () => {
315
- await miniflare.reload();
316
- });
317
- }
318
-
319
- CLEANUP_CALLBACKS.push(() => {
320
- server.close();
321
- miniflare.dispose().catch((err) => miniflare.log.error(err));
322
- });
323
- } catch (e) {
324
- miniflare.log.error(e as Error);
325
- CLEANUP();
326
- throw new FatalError("Could not start Miniflare.", 1);
327
- }
328
- };
329
-
330
- function isWindows() {
331
- return process.platform === "win32";
332
- }
333
-
334
- async function sleep(ms: number) {
335
- await new Promise((resolve) => setTimeout(resolve, ms));
336
- }
337
-
338
- function getPids(pid: number) {
339
- const pids: number[] = [pid];
340
- let command: string, regExp: RegExp;
341
-
342
- if (isWindows()) {
343
- command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
344
- regExp = new RegExp(/(\d+)/);
345
- } else {
346
- command = `pgrep -P ${pid}`;
347
- regExp = new RegExp(/(\d+)/);
348
- }
349
-
350
- try {
351
- const newPids = (
352
- execSync(command)
353
- .toString()
354
- .split("\n")
355
- .map((line) => line.match(regExp))
356
- .filter((line) => line !== null) as RegExpExecArray[]
357
- ).map((match) => parseInt(match[1]));
358
-
359
- pids.push(...newPids.map(getPids).flat());
360
- } catch {}
361
-
362
- return pids;
363
- }
364
-
365
- function getPort(pid: number) {
366
- let command: string, regExp: RegExp;
367
-
368
- if (isWindows()) {
369
- command = "\\windows\\system32\\netstat.exe -nao";
370
- regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
371
- } else {
372
- command = "lsof -nPi";
373
- regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
374
- }
375
-
376
- try {
377
- const matches = execSync(command)
378
- .toString()
379
- .split("\n")
380
- .map((line) => line.match(regExp))
381
- .filter((line) => line !== null) as RegExpExecArray[];
382
-
383
- const match = matches[0];
384
- if (match) return parseInt(match[1]);
385
- } catch (thrown) {
386
- logger.error(
387
- `Error scanning for ports of process with PID ${pid}: ${thrown}`
388
- );
389
- }
390
- }
391
-
392
- async function spawnProxyProcess({
393
- port,
394
- command,
395
- }: {
396
- port?: number;
397
- command: (string | number)[];
398
- }): Promise<void | number> {
399
- if (command.length === 0) {
400
- CLEANUP();
401
- throw new FatalError(
402
- "Must specify a directory of static assets to serve or a command to run.",
403
- 1
404
- );
405
- }
406
-
407
- logger.log(`Running ${command.join(" ")}...`);
408
- const proxy = spawn(
409
- command[0].toString(),
410
- command.slice(1).map((value) => value.toString()),
411
- {
412
- shell: isWindows(),
413
- env: {
414
- BROWSER: "none",
415
- ...process.env,
416
- },
417
- }
418
- );
419
- CLEANUP_CALLBACKS.push(() => {
420
- proxy.kill();
421
- });
422
-
423
- proxy.stdout.on("data", (data) => {
424
- logger.log(`[proxy]: ${data}`);
425
- });
426
-
427
- proxy.stderr.on("data", (data) => {
428
- logger.error(`[proxy]: ${data}`);
429
- });
430
-
431
- proxy.on("close", (code) => {
432
- logger.error(`Proxy exited with status ${code}.`);
433
- });
434
-
435
- // Wait for proxy process to start...
436
- while (!proxy.pid) {}
437
-
438
- if (port === undefined) {
439
- logger.log(
440
- `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
441
- );
442
- logger.log("To skip, specify the proxy port with --proxy.");
443
- await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
444
-
445
- port = getPids(proxy.pid)
446
- .map(getPort)
447
- .filter((nr) => nr !== undefined)[0];
448
-
449
- if (port === undefined) {
450
- CLEANUP();
451
- throw new FatalError(
452
- "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
453
- 1
454
- );
455
- } else {
456
- logger.log(`Automatically determined the proxy port to be ${port}.`);
457
- }
458
- }
459
-
460
- return port;
461
- }
462
-
463
- function escapeRegex(str: string) {
464
- return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
465
- }
466
-
467
- type Replacements = Record<string, string>;
468
-
469
- function replacer(str: string, replacements: Replacements) {
470
- for (const [replacement, value] of Object.entries(replacements)) {
471
- str = str.replace(`:${replacement}`, value);
472
- }
473
- return str;
474
- }
475
-
476
- function generateRulesMatcher<T>(
477
- rules?: Record<string, T>,
478
- replacerFn: (match: T, replacements: Replacements) => T = (match) => match
479
- ) {
480
- // TODO: How can you test cross-host rules?
481
- if (!rules) return () => [];
482
-
483
- const compiledRules = Object.entries(rules)
484
- .map(([rule, match]) => {
485
- const crossHost = rule.startsWith("https://");
486
-
487
- rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
488
-
489
- const host_matches = rule.matchAll(
490
- /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
491
- );
492
- for (const hostMatch of host_matches) {
493
- rule = rule.split(hostMatch[0]).join(`(?<${hostMatch[1]}>[^/.]+)`);
494
- }
495
-
496
- const path_matches = rule.matchAll(/:(\w+)/g);
497
- for (const pathMatch of path_matches) {
498
- rule = rule.split(pathMatch[0]).join(`(?<${pathMatch[1]}>[^/]+)`);
499
- }
500
-
501
- rule = "^" + rule + "$";
502
-
503
- try {
504
- const regExp = new RegExp(rule);
505
- return [{ crossHost, regExp }, match];
506
- } catch {}
507
- })
508
- .filter((value) => value !== undefined) as [
509
- { crossHost: boolean; regExp: RegExp },
510
- T
511
- ][];
512
-
513
- return ({ request }: { request: MiniflareRequest }) => {
514
- const { pathname, host } = new URL(request.url);
515
-
516
- return compiledRules
517
- .map(([{ crossHost, regExp }, match]) => {
518
- const test = crossHost ? `https://${host}${pathname}` : pathname;
519
- const result = regExp.exec(test);
520
- if (result) {
521
- return replacerFn(match, result.groups || {});
522
- }
523
- })
524
- .filter((value) => value !== undefined) as T[];
525
- };
526
- }
527
-
528
- function generateHeadersMatcher(headersFile: string) {
529
- if (existsSync(headersFile)) {
530
- const contents = readFileSync(headersFile).toString();
531
-
532
- // TODO: Log errors
533
- const lines = contents
534
- .split("\n")
535
- .map((line) => line.trim())
536
- .filter((line) => !line.startsWith("#") && line !== "");
537
-
538
- const rules: Record<string, Record<string, string>> = {};
539
- let rule: { path: string; headers: Record<string, string> } | undefined =
540
- undefined;
541
-
542
- for (const line of lines) {
543
- if (/^([^\s]+:\/\/|^\/)/.test(line)) {
544
- if (rule && Object.keys(rule.headers).length > 0) {
545
- rules[rule.path] = rule.headers;
546
- }
547
-
548
- const path = validateURL(line);
549
- if (path) {
550
- rule = {
551
- path,
552
- headers: {},
553
- };
554
- continue;
555
- }
556
- }
557
-
558
- if (!line.includes(":")) continue;
559
-
560
- const [rawName, ...rawValue] = line.split(":");
561
- const name = rawName.trim().toLowerCase();
562
- const value = rawValue.join(":").trim();
563
-
564
- if (name === "") continue;
565
- if (!rule) continue;
566
-
567
- const existingValues = rule.headers[name];
568
- rule.headers[name] = existingValues
569
- ? `${existingValues}, ${value}`
570
- : value;
571
- }
572
-
573
- if (rule && Object.keys(rule.headers).length > 0) {
574
- rules[rule.path] = rule.headers;
575
- }
576
-
577
- const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
578
- Object.fromEntries(
579
- Object.entries(match).map(([name, value]) => [
580
- name,
581
- replacer(value, replacements),
582
- ])
583
- )
584
- );
585
-
586
- return (request: MiniflareRequest) => {
587
- const matches = rulesMatcher({
588
- request,
589
- });
590
- if (matches) return matches;
591
- };
592
- } else {
593
- return () => undefined;
594
- }
595
- }
596
-
597
- function generateRedirectsMatcher(redirectsFile: string) {
598
- if (existsSync(redirectsFile)) {
599
- const contents = readFileSync(redirectsFile).toString();
600
-
601
- // TODO: Log errors
602
- const lines = contents
603
- .split("\n")
604
- .map((line) => line.trim())
605
- .filter((line) => !line.startsWith("#") && line !== "");
606
-
607
- const rules = Object.fromEntries(
608
- lines
609
- .map((line) => line.split(" "))
610
- .filter((tokens) => tokens.length === 2 || tokens.length === 3)
611
- .map((tokens) => {
612
- const from = validateURL(tokens[0], true, false, false);
613
- const to = validateURL(tokens[1], false, true, true);
614
- let status: number | undefined = parseInt(tokens[2]) || 302;
615
- status = [301, 302, 303, 307, 308].includes(status)
616
- ? status
617
- : undefined;
618
-
619
- return from && to && status ? [from, { to, status }] : undefined;
620
- })
621
- .filter((rule) => rule !== undefined) as [
622
- string,
623
- { to: string; status?: number }
624
- ][]
625
- );
626
-
627
- const rulesMatcher = generateRulesMatcher(
628
- rules,
629
- ({ status, to }, replacements) => ({
630
- status,
631
- to: replacer(to, replacements),
632
- })
633
- );
634
-
635
- return (request: MiniflareRequest) => {
636
- const match = rulesMatcher({
637
- request,
638
- })[0];
639
- if (match) return match;
640
- };
641
- } else {
642
- return () => undefined;
643
- }
644
- }
645
-
646
- function extractPathname(
647
- path = "/",
648
- includeSearch: boolean,
649
- includeHash: boolean
650
- ) {
651
- if (!path.startsWith("/")) path = `/${path}`;
652
- const url = new URL(`//${path}`, "relative://");
653
- return `${url.pathname}${includeSearch ? url.search : ""}${
654
- includeHash ? url.hash : ""
655
- }`;
656
- }
657
-
658
- function validateURL(
659
- token: string,
660
- onlyRelative = false,
661
- includeSearch = false,
662
- includeHash = false
663
- ) {
664
- const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
665
- if (host && host.groups && host.groups.host) {
666
- if (onlyRelative) return;
667
-
668
- return `https://${host.groups.host}${extractPathname(
669
- host.groups.path,
670
- includeSearch,
671
- includeHash
672
- )}`;
673
- } else {
674
- if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
675
-
676
- const path = /^\//.exec(token);
677
- if (path) {
678
- try {
679
- return extractPathname(token, includeSearch, includeHash);
680
- } catch {}
681
- }
682
- }
683
- return "";
684
- }
685
-
686
- function hasFileExtension(pathname: string) {
687
- return /\/.+\.[a-z0-9]+$/i.test(pathname);
688
- }
689
-
690
- async function generateAssetsFetch(
691
- directory: string
692
- ): Promise<typeof miniflareFetch> {
693
- // Defer importing miniflare until we really need it
694
- const { Headers, Request, Response } = await import("@miniflare/core");
695
-
696
- const headersFile = join(directory, "_headers");
697
- const redirectsFile = join(directory, "_redirects");
698
- const workerFile = join(directory, "_worker.js");
699
-
700
- const ignoredFiles = [headersFile, redirectsFile, workerFile];
701
-
702
- const assetExists = (path: string) => {
703
- path = join(directory, path);
704
- return (
705
- existsSync(path) &&
706
- lstatSync(path).isFile() &&
707
- !ignoredFiles.includes(path)
708
- );
709
- };
710
-
711
- const getAsset = (path: string) => {
712
- if (assetExists(path)) {
713
- return join(directory, path);
714
- }
715
- };
716
-
717
- let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
718
- let headersMatcher = generateHeadersMatcher(headersFile);
719
-
720
- watch([headersFile, redirectsFile], {
721
- persistent: true,
722
- }).on("change", (path) => {
723
- switch (path) {
724
- case headersFile: {
725
- logger.log("_headers modified. Re-evaluating...");
726
- headersMatcher = generateHeadersMatcher(headersFile);
727
- break;
728
- }
729
- case redirectsFile: {
730
- logger.log("_redirects modified. Re-evaluating...");
731
- redirectsMatcher = generateRedirectsMatcher(redirectsFile);
732
- break;
733
- }
734
- }
735
- });
736
-
737
- const serveAsset = (file: string) => {
738
- return readFileSync(file);
739
- };
740
-
741
- const generateResponse = (request: MiniflareRequest) => {
742
- const url = new URL(request.url);
743
-
744
- const deconstructedResponse: {
745
- status: number;
746
- headers: MiniflareHeaders;
747
- body?: Buffer;
748
- } = {
749
- status: 200,
750
- headers: new Headers(),
751
- body: undefined,
752
- };
753
-
754
- const match = redirectsMatcher(request);
755
- if (match) {
756
- const { status, to } = match;
757
-
758
- let location = to;
759
- let search;
760
-
761
- if (to.startsWith("/")) {
762
- search = new URL(location, "http://fakehost").search;
763
- } else {
764
- search = new URL(location).search;
765
- }
766
-
767
- location = `${location}${search ? "" : url.search}`;
768
-
769
- if (status && [301, 302, 303, 307, 308].includes(status)) {
770
- deconstructedResponse.status = status;
771
- } else {
772
- deconstructedResponse.status = 302;
773
- }
774
-
775
- deconstructedResponse.headers.set("Location", location);
776
- return deconstructedResponse;
777
- }
778
-
779
- if (!request.method?.match(/^(get|head)$/i)) {
780
- deconstructedResponse.status = 405;
781
- return deconstructedResponse;
782
- }
783
-
784
- const notFound = () => {
785
- let cwd = url.pathname;
786
- while (cwd) {
787
- cwd = cwd.slice(0, cwd.lastIndexOf("/"));
788
-
789
- if ((asset = getAsset(`${cwd}/404.html`))) {
790
- deconstructedResponse.status = 404;
791
- deconstructedResponse.body = serveAsset(asset);
792
- deconstructedResponse.headers.set(
793
- "Content-Type",
794
- getType(asset) || "application/octet-stream"
795
- );
796
- return deconstructedResponse;
797
- }
798
- }
799
-
800
- if ((asset = getAsset(`/index.html`))) {
801
- deconstructedResponse.body = serveAsset(asset);
802
- deconstructedResponse.headers.set(
803
- "Content-Type",
804
- getType(asset) || "application/octet-stream"
805
- );
806
- return deconstructedResponse;
807
- }
808
-
809
- deconstructedResponse.status = 404;
810
- return deconstructedResponse;
811
- };
812
-
813
- let asset;
814
-
815
- if (url.pathname.endsWith("/")) {
816
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
817
- deconstructedResponse.body = serveAsset(asset);
818
- deconstructedResponse.headers.set(
819
- "Content-Type",
820
- getType(asset) || "application/octet-stream"
821
- );
822
- return deconstructedResponse;
823
- } else if (
824
- (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
825
- ) {
826
- deconstructedResponse.status = 301;
827
- deconstructedResponse.headers.set(
828
- "Location",
829
- `${url.pathname.slice(0, -1)}${url.search}`
830
- );
831
- return deconstructedResponse;
832
- }
833
- }
834
-
835
- if (url.pathname.endsWith("/index")) {
836
- deconstructedResponse.status = 301;
837
- deconstructedResponse.headers.set(
838
- "Location",
839
- `${url.pathname.slice(0, -"index".length)}${url.search}`
840
- );
841
- return deconstructedResponse;
842
- }
843
-
844
- if ((asset = getAsset(url.pathname))) {
845
- if (url.pathname.endsWith(".html")) {
846
- const extensionlessPath = url.pathname.slice(0, -".html".length);
847
- if (getAsset(extensionlessPath) || extensionlessPath === "/") {
848
- deconstructedResponse.body = serveAsset(asset);
849
- deconstructedResponse.headers.set(
850
- "Content-Type",
851
- getType(asset) || "application/octet-stream"
852
- );
853
- return deconstructedResponse;
854
- } else {
855
- deconstructedResponse.status = 301;
856
- deconstructedResponse.headers.set(
857
- "Location",
858
- `${extensionlessPath}${url.search}`
859
- );
860
- return deconstructedResponse;
861
- }
862
- } else {
863
- deconstructedResponse.body = serveAsset(asset);
864
- deconstructedResponse.headers.set(
865
- "Content-Type",
866
- getType(asset) || "application/octet-stream"
867
- );
868
- return deconstructedResponse;
869
- }
870
- } else if (hasFileExtension(url.pathname)) {
871
- notFound();
872
- return deconstructedResponse;
873
- }
874
-
875
- if ((asset = getAsset(`${url.pathname}.html`))) {
876
- deconstructedResponse.body = serveAsset(asset);
877
- deconstructedResponse.headers.set(
878
- "Content-Type",
879
- getType(asset) || "application/octet-stream"
880
- );
881
- return deconstructedResponse;
882
- }
883
-
884
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
885
- deconstructedResponse.status = 301;
886
- deconstructedResponse.headers.set(
887
- "Location",
888
- `${url.pathname}/${url.search}`
889
- );
890
- return deconstructedResponse;
891
- } else {
892
- notFound();
893
- return deconstructedResponse;
894
- }
895
- };
896
-
897
- const attachHeaders = (
898
- request: MiniflareRequest,
899
- deconstructedResponse: {
900
- status: number;
901
- headers: MiniflareHeaders;
902
- body?: Buffer;
903
- }
904
- ) => {
905
- const headers = deconstructedResponse.headers;
906
- const newHeaders = new Headers({});
907
- const matches = headersMatcher(request) || [];
908
-
909
- matches.forEach((match) => {
910
- Object.entries(match).forEach(([name, value]) => {
911
- newHeaders.append(name, `${value}`);
912
- });
913
- });
914
-
915
- const combinedHeaders = {
916
- ...Object.fromEntries(headers.entries()),
917
- ...Object.fromEntries(newHeaders.entries()),
918
- };
919
-
920
- deconstructedResponse.headers = new Headers({});
921
- Object.entries(combinedHeaders).forEach(([name, value]) => {
922
- if (value) deconstructedResponse.headers.set(name, value);
923
- });
924
- };
925
-
926
- return async (input, init) => {
927
- const request = new Request(input, init);
928
- const deconstructedResponse = generateResponse(request);
929
- attachHeaders(request, deconstructedResponse);
930
-
931
- const headers = new Headers();
932
-
933
- [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
934
- if (value) headers.set(name, value);
935
- });
936
-
937
- return new Response(deconstructedResponse.body, {
938
- headers,
939
- status: deconstructedResponse.status,
940
- });
941
- };
942
- }
943
-
944
- const invalidAssetsFetch: typeof miniflareFetch = () => {
945
- throw new Error(
946
- "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
947
- );
948
- };