wrangler 0.0.0-e9ab55a → 0.0.0-e9fae558

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