wrangler 0.0.0-e95e5a0 → 0.0.0-e981d0be5

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 (184) hide show
  1. package/README.md +46 -34
  2. package/bin/wrangler.js +84 -39
  3. package/config-schema.json +2278 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +132 -99
  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 +19 -0
  11. package/templates/gitignore +2 -3
  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 +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +33 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +13 -103
  42. package/templates/tsconfig.tsbuildinfo +1 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +238 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +26693 -0
  48. package/wrangler-dist/cli.js +148512 -106990
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/miniflare-dist/index.mjs +0 -4886
  54. package/pages/functions/buildPlugin.ts +0 -92
  55. package/pages/functions/buildWorker.ts +0 -138
  56. package/pages/functions/filepath-routing.test.ts +0 -234
  57. package/pages/functions/filepath-routing.ts +0 -189
  58. package/pages/functions/identifiers.ts +0 -78
  59. package/pages/functions/routes.ts +0 -156
  60. package/pages/functions/template-plugin.ts +0 -146
  61. package/pages/functions/template-worker.ts +0 -143
  62. package/src/__tests__/config-cache.test.ts +0 -36
  63. package/src/__tests__/configuration.test.ts +0 -3125
  64. package/src/__tests__/dev.test.tsx +0 -762
  65. package/src/__tests__/guess-worker-format.test.ts +0 -85
  66. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  67. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  68. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  69. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  70. package/src/__tests__/helpers/mock-bin.ts +0 -36
  71. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  72. package/src/__tests__/helpers/mock-console.ts +0 -87
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  74. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  75. package/src/__tests__/helpers/mock-istty.ts +0 -27
  76. package/src/__tests__/helpers/mock-kv.ts +0 -33
  77. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  78. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  79. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  80. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  81. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  82. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  83. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  84. package/src/__tests__/https-options.test.ts +0 -130
  85. package/src/__tests__/index.test.ts +0 -249
  86. package/src/__tests__/init.test.ts +0 -1516
  87. package/src/__tests__/jest.setup.ts +0 -69
  88. package/src/__tests__/kv.test.ts +0 -1454
  89. package/src/__tests__/logger.test.ts +0 -115
  90. package/src/__tests__/package-manager.test.ts +0 -206
  91. package/src/__tests__/pages.test.ts +0 -329
  92. package/src/__tests__/parse.test.ts +0 -322
  93. package/src/__tests__/publish.test.ts +0 -4875
  94. package/src/__tests__/r2.test.ts +0 -214
  95. package/src/__tests__/route.test.ts +0 -45
  96. package/src/__tests__/secret.test.ts +0 -446
  97. package/src/__tests__/tail.test.ts +0 -690
  98. package/src/__tests__/user.test.ts +0 -131
  99. package/src/__tests__/whoami.test.tsx +0 -105
  100. package/src/bundle.ts +0 -169
  101. package/src/cfetch/index.ts +0 -104
  102. package/src/cfetch/internal.ts +0 -137
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -394
  108. package/src/config/index.ts +0 -63
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1424
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -175
  113. package/src/create-worker-upload-form.ts +0 -240
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -418
  116. package/src/dev/local.tsx +0 -312
  117. package/src/dev/remote.tsx +0 -213
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -87
  120. package/src/entry.ts +0 -267
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/https-options.ts +0 -123
  124. package/src/index.tsx +0 -2668
  125. package/src/inspect.ts +0 -623
  126. package/src/intl-polyfill.d.ts +0 -139
  127. package/src/kv.ts +0 -319
  128. package/src/logger.ts +0 -66
  129. package/src/miniflare-cli/README.md +0 -30
  130. package/src/miniflare-cli/enum-keys.ts +0 -17
  131. package/src/miniflare-cli/index.ts +0 -41
  132. package/src/miniflare-cli/request-context.ts +0 -40
  133. package/src/module-collection.ts +0 -258
  134. package/src/open-in-browser.ts +0 -26
  135. package/src/package-manager.ts +0 -127
  136. package/src/pages.tsx +0 -1866
  137. package/src/parse.ts +0 -183
  138. package/src/paths.ts +0 -26
  139. package/src/proxy.ts +0 -449
  140. package/src/publish.ts +0 -469
  141. package/src/r2.ts +0 -50
  142. package/src/selfsigned.d.ts +0 -29
  143. package/src/sites.tsx +0 -293
  144. package/src/tail/filters.ts +0 -279
  145. package/src/tail/index.ts +0 -299
  146. package/src/tail/printing.ts +0 -67
  147. package/src/update-check.ts +0 -19
  148. package/src/user.tsx +0 -1193
  149. package/src/whoami.tsx +0 -70
  150. package/src/worker.ts +0 -172
  151. package/templates/static-asset-facade.js +0 -47
  152. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  153. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  155. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  156. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  158. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  160. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  166. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  168. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  169. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  170. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  171. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  174. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  175. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  176. package/vendor/wrangler-mime/LICENSE +0 -21
  177. package/vendor/wrangler-mime/Mime.js +0 -97
  178. package/vendor/wrangler-mime/README.md +0 -187
  179. package/vendor/wrangler-mime/cli.js +0 -46
  180. package/vendor/wrangler-mime/index.js +0 -4
  181. package/vendor/wrangler-mime/lite.js +0 -4
  182. package/vendor/wrangler-mime/package.json +0 -52
  183. package/vendor/wrangler-mime/types/other.js +0 -1
  184. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/pages.tsx DELETED
@@ -1,1866 +0,0 @@
1
- /* eslint-disable no-shadow */
2
-
3
- import { execSync, spawn } from "node:child_process";
4
- import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
- import { readdir, readFile, stat } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import { dirname, join, sep } from "node:path";
8
- import { cwd } from "node:process";
9
- import { URL } from "node:url";
10
- import { hash } from "blake3-wasm";
11
- import { watch } from "chokidar";
12
- import { render, Text } from "ink";
13
- import SelectInput from "ink-select-input";
14
- import Spinner from "ink-spinner";
15
- import Table from "ink-table";
16
- import { getType } from "mime";
17
- import prettyBytes from "pretty-bytes";
18
- import React from "react";
19
- import { format as timeagoFormat } from "timeago.js";
20
- import { File, FormData } from "undici";
21
- import { buildPlugin } from "../pages/functions/buildPlugin";
22
- import { buildWorker } from "../pages/functions/buildWorker";
23
- import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
24
- import { writeRoutesModule } from "../pages/functions/routes";
25
- import { fetchResult } from "./cfetch";
26
- import { getConfigCache, saveToConfigCache } from "./config-cache";
27
- import { prompt } from "./dialogs";
28
- import { FatalError } from "./errors";
29
- import { logger } from "./logger";
30
- import { getRequestContextCheckOptions } from "./miniflare-cli/request-context";
31
- import openInBrowser from "./open-in-browser";
32
- import { toUrlPath } from "./paths";
33
- import { requireAuth } from "./user";
34
- import type { Config } from "../pages/functions/routes";
35
- import type { Headers, Request, fetch } from "@miniflare/core";
36
- import type { BuildResult } from "esbuild";
37
- import type { MiniflareOptions } from "miniflare";
38
- import type { BuilderCallback, CommandModule } from "yargs";
39
-
40
- export type Project = {
41
- name: string;
42
- subdomain: string;
43
- domains: Array<string>;
44
- source?: {
45
- type: string;
46
- };
47
- latest_deployment?: {
48
- modified_on: string;
49
- };
50
- created_on: string;
51
- production_branch: string;
52
- };
53
-
54
- export type Deployment = {
55
- id: string;
56
- environment: string;
57
- deployment_trigger: {
58
- metadata: {
59
- commit_hash: string;
60
- branch: string;
61
- };
62
- };
63
- url: string;
64
- latest_stage: {
65
- status: string;
66
- ended_on: string;
67
- };
68
- project_name: string;
69
- };
70
-
71
- interface PagesConfigCache {
72
- account_id?: string;
73
- project_name?: string;
74
- }
75
-
76
- const PAGES_CONFIG_CACHE_FILENAME = "pages.json";
77
-
78
- // Defer importing miniflare until we really need it. This takes ~0.5s
79
- // and also modifies some `stream/web` and `undici` prototypes, so we
80
- // don't want to do this if pages commands aren't being called.
81
-
82
- export const pagesBetaWarning =
83
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
84
-
85
- const CLEANUP_CALLBACKS: (() => void)[] = [];
86
- const CLEANUP = () => {
87
- CLEANUP_CALLBACKS.forEach((callback) => callback());
88
- RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
89
- };
90
-
91
- process.on("SIGINT", () => {
92
- CLEANUP();
93
- process.exit();
94
- });
95
- process.on("SIGTERM", () => {
96
- CLEANUP();
97
- process.exit();
98
- });
99
-
100
- function isWindows() {
101
- return process.platform === "win32";
102
- }
103
-
104
- const SECONDS_TO_WAIT_FOR_PROXY = 5;
105
-
106
- async function sleep(ms: number) {
107
- await new Promise((resolve) => setTimeout(resolve, ms));
108
- }
109
-
110
- function getPids(pid: number) {
111
- const pids: number[] = [pid];
112
- let command: string, regExp: RegExp;
113
-
114
- if (isWindows()) {
115
- command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
116
- regExp = new RegExp(/(\d+)/);
117
- } else {
118
- command = `pgrep -P ${pid}`;
119
- regExp = new RegExp(/(\d+)/);
120
- }
121
-
122
- try {
123
- const newPids = (
124
- execSync(command)
125
- .toString()
126
- .split("\n")
127
- .map((line) => line.match(regExp))
128
- .filter((line) => line !== null) as RegExpExecArray[]
129
- ).map((match) => parseInt(match[1]));
130
-
131
- pids.push(...newPids.map(getPids).flat());
132
- } catch {}
133
-
134
- return pids;
135
- }
136
-
137
- function getPort(pid: number) {
138
- let command: string, regExp: RegExp;
139
-
140
- if (isWindows()) {
141
- command = "\\windows\\system32\\netstat.exe -nao";
142
- regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
143
- } else {
144
- command = "lsof -nPi";
145
- regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
146
- }
147
-
148
- try {
149
- const matches = execSync(command)
150
- .toString()
151
- .split("\n")
152
- .map((line) => line.match(regExp))
153
- .filter((line) => line !== null) as RegExpExecArray[];
154
-
155
- const match = matches[0];
156
- if (match) return parseInt(match[1]);
157
- } catch (thrown) {
158
- logger.error(
159
- `Error scanning for ports of process with PID ${pid}: ${thrown}`
160
- );
161
- }
162
- }
163
-
164
- async function spawnProxyProcess({
165
- port,
166
- command,
167
- }: {
168
- port?: number;
169
- command: (string | number)[];
170
- }): Promise<void | number> {
171
- if (command.length === 0) {
172
- CLEANUP();
173
- throw new FatalError(
174
- "Must specify a directory of static assets to serve or a command to run.",
175
- 1
176
- );
177
- }
178
-
179
- logger.log(`Running ${command.join(" ")}...`);
180
- const proxy = spawn(
181
- command[0].toString(),
182
- command.slice(1).map((value) => value.toString()),
183
- {
184
- shell: isWindows(),
185
- env: {
186
- BROWSER: "none",
187
- ...process.env,
188
- },
189
- }
190
- );
191
- CLEANUP_CALLBACKS.push(() => {
192
- proxy.kill();
193
- });
194
-
195
- proxy.stdout.on("data", (data) => {
196
- logger.log(`[proxy]: ${data}`);
197
- });
198
-
199
- proxy.stderr.on("data", (data) => {
200
- logger.error(`[proxy]: ${data}`);
201
- });
202
-
203
- proxy.on("close", (code) => {
204
- logger.error(`Proxy exited with status ${code}.`);
205
- });
206
-
207
- // Wait for proxy process to start...
208
- while (!proxy.pid) {}
209
-
210
- if (port === undefined) {
211
- logger.log(
212
- `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
213
- );
214
- logger.log("To skip, specify the proxy port with --proxy.");
215
- await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
216
-
217
- port = getPids(proxy.pid)
218
- .map(getPort)
219
- .filter((port) => port !== undefined)[0];
220
-
221
- if (port === undefined) {
222
- CLEANUP();
223
- throw new FatalError(
224
- "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
225
- 1
226
- );
227
- } else {
228
- logger.log(`Automatically determined the proxy port to be ${port}.`);
229
- }
230
- }
231
-
232
- return port;
233
- }
234
-
235
- function escapeRegex(str: string) {
236
- return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
237
- }
238
-
239
- type Replacements = Record<string, string>;
240
-
241
- function replacer(str: string, replacements: Replacements) {
242
- for (const [replacement, value] of Object.entries(replacements)) {
243
- str = str.replace(`:${replacement}`, value);
244
- }
245
- return str;
246
- }
247
-
248
- function generateRulesMatcher<T>(
249
- rules?: Record<string, T>,
250
- replacer: (match: T, replacements: Replacements) => T = (match) => match
251
- ) {
252
- // TODO: How can you test cross-host rules?
253
- if (!rules) return () => [];
254
-
255
- const compiledRules = Object.entries(rules)
256
- .map(([rule, match]) => {
257
- const crossHost = rule.startsWith("https://");
258
-
259
- rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
260
-
261
- const host_matches = rule.matchAll(
262
- /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
263
- );
264
- for (const match of host_matches) {
265
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
266
- }
267
-
268
- const path_matches = rule.matchAll(/:(\w+)/g);
269
- for (const match of path_matches) {
270
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
271
- }
272
-
273
- rule = "^" + rule + "$";
274
-
275
- try {
276
- const regExp = new RegExp(rule);
277
- return [{ crossHost, regExp }, match];
278
- } catch {}
279
- })
280
- .filter((value) => value !== undefined) as [
281
- { crossHost: boolean; regExp: RegExp },
282
- T
283
- ][];
284
-
285
- return ({ request }: { request: Request }) => {
286
- const { pathname, host } = new URL(request.url);
287
-
288
- return compiledRules
289
- .map(([{ crossHost, regExp }, match]) => {
290
- const test = crossHost ? `https://${host}${pathname}` : pathname;
291
- const result = regExp.exec(test);
292
- if (result) {
293
- return replacer(match, result.groups || {});
294
- }
295
- })
296
- .filter((value) => value !== undefined) as T[];
297
- };
298
- }
299
-
300
- function generateHeadersMatcher(headersFile: string) {
301
- if (existsSync(headersFile)) {
302
- const contents = readFileSync(headersFile).toString();
303
-
304
- // TODO: Log errors
305
- const lines = contents
306
- .split("\n")
307
- .map((line) => line.trim())
308
- .filter((line) => !line.startsWith("#") && line !== "");
309
-
310
- const rules: Record<string, Record<string, string>> = {};
311
- let rule: { path: string; headers: Record<string, string> } | undefined =
312
- undefined;
313
-
314
- for (const line of lines) {
315
- if (/^([^\s]+:\/\/|^\/)/.test(line)) {
316
- if (rule && Object.keys(rule.headers).length > 0) {
317
- rules[rule.path] = rule.headers;
318
- }
319
-
320
- const path = validateURL(line);
321
- if (path) {
322
- rule = {
323
- path,
324
- headers: {},
325
- };
326
- continue;
327
- }
328
- }
329
-
330
- if (!line.includes(":")) continue;
331
-
332
- const [rawName, ...rawValue] = line.split(":");
333
- const name = rawName.trim().toLowerCase();
334
- const value = rawValue.join(":").trim();
335
-
336
- if (name === "") continue;
337
- if (!rule) continue;
338
-
339
- const existingValues = rule.headers[name];
340
- rule.headers[name] = existingValues
341
- ? `${existingValues}, ${value}`
342
- : value;
343
- }
344
-
345
- if (rule && Object.keys(rule.headers).length > 0) {
346
- rules[rule.path] = rule.headers;
347
- }
348
-
349
- const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
350
- Object.fromEntries(
351
- Object.entries(match).map(([name, value]) => [
352
- name,
353
- replacer(value, replacements),
354
- ])
355
- )
356
- );
357
-
358
- return (request: Request) => {
359
- const matches = rulesMatcher({
360
- request,
361
- });
362
- if (matches) return matches;
363
- };
364
- } else {
365
- return () => undefined;
366
- }
367
- }
368
-
369
- function generateRedirectsMatcher(redirectsFile: string) {
370
- if (existsSync(redirectsFile)) {
371
- const contents = readFileSync(redirectsFile).toString();
372
-
373
- // TODO: Log errors
374
- const lines = contents
375
- .split("\n")
376
- .map((line) => line.trim())
377
- .filter((line) => !line.startsWith("#") && line !== "");
378
-
379
- const rules = Object.fromEntries(
380
- lines
381
- .map((line) => line.split(" "))
382
- .filter((tokens) => tokens.length === 2 || tokens.length === 3)
383
- .map((tokens) => {
384
- const from = validateURL(tokens[0], true, false, false);
385
- const to = validateURL(tokens[1], false, true, true);
386
- let status: number | undefined = parseInt(tokens[2]) || 302;
387
- status = [301, 302, 303, 307, 308].includes(status)
388
- ? status
389
- : undefined;
390
-
391
- return from && to && status ? [from, { to, status }] : undefined;
392
- })
393
- .filter((rule) => rule !== undefined) as [
394
- string,
395
- { to: string; status?: number }
396
- ][]
397
- );
398
-
399
- const rulesMatcher = generateRulesMatcher(
400
- rules,
401
- ({ status, to }, replacements) => ({
402
- status,
403
- to: replacer(to, replacements),
404
- })
405
- );
406
-
407
- return (request: Request) => {
408
- const match = rulesMatcher({
409
- request,
410
- })[0];
411
- if (match) return match;
412
- };
413
- } else {
414
- return () => undefined;
415
- }
416
- }
417
-
418
- function extractPathname(
419
- path = "/",
420
- includeSearch: boolean,
421
- includeHash: boolean
422
- ) {
423
- if (!path.startsWith("/")) path = `/${path}`;
424
- const url = new URL(`//${path}`, "relative://");
425
- return `${url.pathname}${includeSearch ? url.search : ""}${
426
- includeHash ? url.hash : ""
427
- }`;
428
- }
429
-
430
- function validateURL(
431
- token: string,
432
- onlyRelative = false,
433
- includeSearch = false,
434
- includeHash = false
435
- ) {
436
- const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
437
- if (host && host.groups && host.groups.host) {
438
- if (onlyRelative) return;
439
-
440
- return `https://${host.groups.host}${extractPathname(
441
- host.groups.path,
442
- includeSearch,
443
- includeHash
444
- )}`;
445
- } else {
446
- if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
447
-
448
- const path = /^\//.exec(token);
449
- if (path) {
450
- try {
451
- return extractPathname(token, includeSearch, includeHash);
452
- } catch {}
453
- }
454
- }
455
- return "";
456
- }
457
-
458
- function hasFileExtension(pathname: string) {
459
- return /\/.+\.[a-z0-9]+$/i.test(pathname);
460
- }
461
-
462
- async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
463
- // Defer importing miniflare until we really need it
464
- const { Headers, Request, Response } = await import("@miniflare/core");
465
-
466
- const headersFile = join(directory, "_headers");
467
- const redirectsFile = join(directory, "_redirects");
468
- const workerFile = join(directory, "_worker.js");
469
-
470
- const ignoredFiles = [headersFile, redirectsFile, workerFile];
471
-
472
- const assetExists = (path: string) => {
473
- path = join(directory, path);
474
- return (
475
- existsSync(path) &&
476
- lstatSync(path).isFile() &&
477
- !ignoredFiles.includes(path)
478
- );
479
- };
480
-
481
- const getAsset = (path: string) => {
482
- if (assetExists(path)) {
483
- return join(directory, path);
484
- }
485
- };
486
-
487
- let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
488
- let headersMatcher = generateHeadersMatcher(headersFile);
489
-
490
- watch([headersFile, redirectsFile], {
491
- persistent: true,
492
- }).on("change", (path) => {
493
- switch (path) {
494
- case headersFile: {
495
- logger.log("_headers modified. Re-evaluating...");
496
- headersMatcher = generateHeadersMatcher(headersFile);
497
- break;
498
- }
499
- case redirectsFile: {
500
- logger.log("_redirects modified. Re-evaluating...");
501
- redirectsMatcher = generateRedirectsMatcher(redirectsFile);
502
- break;
503
- }
504
- }
505
- });
506
-
507
- const serveAsset = (file: string) => {
508
- return readFileSync(file);
509
- };
510
-
511
- const generateResponse = (request: Request) => {
512
- const url = new URL(request.url);
513
-
514
- const deconstructedResponse: {
515
- status: number;
516
- headers: Headers;
517
- body?: Buffer;
518
- } = {
519
- status: 200,
520
- headers: new Headers(),
521
- body: undefined,
522
- };
523
-
524
- const match = redirectsMatcher(request);
525
- if (match) {
526
- const { status, to } = match;
527
-
528
- let location = to;
529
- let search;
530
-
531
- if (to.startsWith("/")) {
532
- search = new URL(location, "http://fakehost").search;
533
- } else {
534
- search = new URL(location).search;
535
- }
536
-
537
- location = `${location}${search ? "" : url.search}`;
538
-
539
- if (status && [301, 302, 303, 307, 308].includes(status)) {
540
- deconstructedResponse.status = status;
541
- } else {
542
- deconstructedResponse.status = 302;
543
- }
544
-
545
- deconstructedResponse.headers.set("Location", location);
546
- return deconstructedResponse;
547
- }
548
-
549
- if (!request.method?.match(/^(get|head)$/i)) {
550
- deconstructedResponse.status = 405;
551
- return deconstructedResponse;
552
- }
553
-
554
- const notFound = () => {
555
- let cwd = url.pathname;
556
- while (cwd) {
557
- cwd = cwd.slice(0, cwd.lastIndexOf("/"));
558
-
559
- if ((asset = getAsset(`${cwd}/404.html`))) {
560
- deconstructedResponse.status = 404;
561
- deconstructedResponse.body = serveAsset(asset);
562
- deconstructedResponse.headers.set(
563
- "Content-Type",
564
- getType(asset) || "application/octet-stream"
565
- );
566
- return deconstructedResponse;
567
- }
568
- }
569
-
570
- if ((asset = getAsset(`/index.html`))) {
571
- deconstructedResponse.body = serveAsset(asset);
572
- deconstructedResponse.headers.set(
573
- "Content-Type",
574
- getType(asset) || "application/octet-stream"
575
- );
576
- return deconstructedResponse;
577
- }
578
-
579
- deconstructedResponse.status = 404;
580
- return deconstructedResponse;
581
- };
582
-
583
- let asset;
584
-
585
- if (url.pathname.endsWith("/")) {
586
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
587
- deconstructedResponse.body = serveAsset(asset);
588
- deconstructedResponse.headers.set(
589
- "Content-Type",
590
- getType(asset) || "application/octet-stream"
591
- );
592
- return deconstructedResponse;
593
- } else if (
594
- (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
595
- ) {
596
- deconstructedResponse.status = 301;
597
- deconstructedResponse.headers.set(
598
- "Location",
599
- `${url.pathname.slice(0, -1)}${url.search}`
600
- );
601
- return deconstructedResponse;
602
- }
603
- }
604
-
605
- if (url.pathname.endsWith("/index")) {
606
- deconstructedResponse.status = 301;
607
- deconstructedResponse.headers.set(
608
- "Location",
609
- `${url.pathname.slice(0, -"index".length)}${url.search}`
610
- );
611
- return deconstructedResponse;
612
- }
613
-
614
- if ((asset = getAsset(url.pathname))) {
615
- if (url.pathname.endsWith(".html")) {
616
- const extensionlessPath = url.pathname.slice(0, -".html".length);
617
- if (getAsset(extensionlessPath) || extensionlessPath === "/") {
618
- deconstructedResponse.body = serveAsset(asset);
619
- deconstructedResponse.headers.set(
620
- "Content-Type",
621
- getType(asset) || "application/octet-stream"
622
- );
623
- return deconstructedResponse;
624
- } else {
625
- deconstructedResponse.status = 301;
626
- deconstructedResponse.headers.set(
627
- "Location",
628
- `${extensionlessPath}${url.search}`
629
- );
630
- return deconstructedResponse;
631
- }
632
- } else {
633
- deconstructedResponse.body = serveAsset(asset);
634
- deconstructedResponse.headers.set(
635
- "Content-Type",
636
- getType(asset) || "application/octet-stream"
637
- );
638
- return deconstructedResponse;
639
- }
640
- } else if (hasFileExtension(url.pathname)) {
641
- notFound();
642
- return deconstructedResponse;
643
- }
644
-
645
- if ((asset = getAsset(`${url.pathname}.html`))) {
646
- deconstructedResponse.body = serveAsset(asset);
647
- deconstructedResponse.headers.set(
648
- "Content-Type",
649
- getType(asset) || "application/octet-stream"
650
- );
651
- return deconstructedResponse;
652
- }
653
-
654
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
655
- deconstructedResponse.status = 301;
656
- deconstructedResponse.headers.set(
657
- "Location",
658
- `${url.pathname}/${url.search}`
659
- );
660
- return deconstructedResponse;
661
- } else {
662
- notFound();
663
- return deconstructedResponse;
664
- }
665
- };
666
-
667
- const attachHeaders = (
668
- request: Request,
669
- deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
670
- ) => {
671
- const headers = deconstructedResponse.headers;
672
- const newHeaders = new Headers({});
673
- const matches = headersMatcher(request) || [];
674
-
675
- matches.forEach((match) => {
676
- Object.entries(match).forEach(([name, value]) => {
677
- newHeaders.append(name, `${value}`);
678
- });
679
- });
680
-
681
- const combinedHeaders = {
682
- ...Object.fromEntries(headers.entries()),
683
- ...Object.fromEntries(newHeaders.entries()),
684
- };
685
-
686
- deconstructedResponse.headers = new Headers({});
687
- Object.entries(combinedHeaders).forEach(([name, value]) => {
688
- if (value) deconstructedResponse.headers.set(name, value);
689
- });
690
- };
691
-
692
- return async (input, init) => {
693
- const request = new Request(input, init);
694
- const deconstructedResponse = generateResponse(request);
695
- attachHeaders(request, deconstructedResponse);
696
-
697
- const headers = new Headers();
698
-
699
- [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
700
- if (value) headers.set(name, value);
701
- });
702
-
703
- return new Response(deconstructedResponse.body, {
704
- headers,
705
- status: deconstructedResponse.status,
706
- });
707
- };
708
- }
709
-
710
- const RUNNING_BUILDERS: BuildResult[] = [];
711
-
712
- async function buildFunctions({
713
- outfile,
714
- outputConfigPath,
715
- functionsDirectory,
716
- minify = false,
717
- sourcemap = false,
718
- fallbackService = "ASSETS",
719
- watch = false,
720
- onEnd,
721
- plugin = false,
722
- buildOutputDirectory,
723
- }: {
724
- outfile: string;
725
- outputConfigPath?: string;
726
- functionsDirectory: string;
727
- minify?: boolean;
728
- sourcemap?: boolean;
729
- fallbackService?: string;
730
- watch?: boolean;
731
- onEnd?: () => void;
732
- plugin?: boolean;
733
- buildOutputDirectory?: string;
734
- }) {
735
- RUNNING_BUILDERS.forEach(
736
- (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
737
- );
738
-
739
- const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
740
- const baseURL = toUrlPath("/");
741
-
742
- const config: Config = await generateConfigFromFileTree({
743
- baseDir: functionsDirectory,
744
- baseURL,
745
- });
746
-
747
- if (outputConfigPath) {
748
- writeFileSync(
749
- outputConfigPath,
750
- JSON.stringify({ ...config, baseURL }, null, 2)
751
- );
752
- }
753
-
754
- await writeRoutesModule({
755
- config,
756
- srcDir: functionsDirectory,
757
- outfile: routesModule,
758
- });
759
-
760
- if (plugin) {
761
- RUNNING_BUILDERS.push(
762
- await buildPlugin({
763
- routesModule,
764
- outfile,
765
- minify,
766
- sourcemap,
767
- watch,
768
- onEnd,
769
- })
770
- );
771
- } else {
772
- RUNNING_BUILDERS.push(
773
- await buildWorker({
774
- routesModule,
775
- outfile,
776
- minify,
777
- sourcemap,
778
- fallbackService,
779
- watch,
780
- onEnd,
781
- buildOutputDirectory,
782
- })
783
- );
784
- }
785
- }
786
-
787
- interface CreateDeploymentArgs {
788
- directory: string;
789
- projectName?: string;
790
- branch?: string;
791
- commitHash?: string;
792
- commitMessage?: string;
793
- commitDirty?: boolean;
794
- }
795
-
796
- const createDeployment: CommandModule<
797
- CreateDeploymentArgs,
798
- CreateDeploymentArgs
799
- > = {
800
- describe: "🆙 Publish a directory of static assets as a Pages deployment",
801
- builder: (yargs) => {
802
- return yargs
803
- .positional("directory", {
804
- type: "string",
805
- default: "functions",
806
- description: "The directory of Pages Functions",
807
- })
808
- .options({
809
- "project-name": {
810
- type: "string",
811
- description:
812
- "The name of the project you want to list deployments for",
813
- },
814
- branch: {
815
- type: "string",
816
- description:
817
- "The branch of the project you want to list deployments for",
818
- },
819
- "commit-hash": {
820
- type: "string",
821
- description:
822
- "The branch of the project you want to list deployments for",
823
- },
824
- "commit-message": {
825
- type: "string",
826
- description:
827
- "The branch of the project you want to list deployments for",
828
- },
829
- "commit-dirty": {
830
- type: "boolean",
831
- description:
832
- "The branch of the project you want to list deployments for",
833
- },
834
- })
835
- .epilogue(pagesBetaWarning);
836
- },
837
- handler: async ({
838
- directory,
839
- projectName,
840
- branch,
841
- commitHash,
842
- commitMessage,
843
- commitDirty,
844
- }) => {
845
- const config = getConfigCache<PagesConfigCache>(
846
- PAGES_CONFIG_CACHE_FILENAME
847
- );
848
- const accountId = await requireAuth(config);
849
-
850
- projectName ??= config.project_name;
851
-
852
- const isInteractive = process.stdin.isTTY;
853
- if (!projectName && isInteractive) {
854
- const existingOrNew = await new Promise<"new" | "existing">((resolve) => {
855
- const { unmount } = render(
856
- <>
857
- <Text>
858
- No project selected. Would you like to create one or use an
859
- existing project?
860
- </Text>
861
- <SelectInput
862
- items={[
863
- {
864
- key: "new",
865
- label: "Create a new project",
866
- value: "new",
867
- },
868
- {
869
- key: "existing",
870
- label: "Use an existing project",
871
- value: "existing",
872
- },
873
- ]}
874
- onSelect={async (selected) => {
875
- resolve(selected.value as "new" | "existing");
876
- unmount();
877
- }}
878
- />
879
- </>
880
- );
881
- });
882
-
883
- switch (existingOrNew) {
884
- case "existing": {
885
- const projects = (await listProjects({ accountId })).filter(
886
- (project) => !project.source
887
- );
888
- projectName = await new Promise((resolve) => {
889
- const { unmount } = render(
890
- <>
891
- <Text>Select a project:</Text>
892
- <SelectInput
893
- items={projects.map((project) => ({
894
- key: project.name,
895
- label: project.name,
896
- value: project,
897
- }))}
898
- onSelect={async (selected) => {
899
- resolve(selected.value.name);
900
- unmount();
901
- }}
902
- />
903
- </>
904
- );
905
- });
906
- break;
907
- }
908
- case "new": {
909
- projectName = await prompt("Enter the name of your new project:");
910
-
911
- if (!projectName) {
912
- throw new FatalError("Must specify a project name.", 1);
913
- }
914
-
915
- let isGitDir = true;
916
- try {
917
- execSync(`git rev-parse --is-inside-work-tree`, {
918
- stdio: "ignore",
919
- });
920
- } catch (err) {
921
- isGitDir = false;
922
- }
923
-
924
- const productionBranch = await prompt(
925
- "Enter the production branch name:",
926
- "text",
927
- isGitDir
928
- ? execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim()
929
- : "production"
930
- );
931
-
932
- if (!productionBranch) {
933
- throw new FatalError("Must specify a production branch.", 1);
934
- }
935
-
936
- await fetchResult<Project>(`/accounts/${accountId}/pages/projects`, {
937
- method: "POST",
938
- body: JSON.stringify({
939
- name: projectName,
940
- production_branch: productionBranch,
941
- }),
942
- });
943
-
944
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
945
- account_id: accountId,
946
- project_name: projectName,
947
- });
948
-
949
- logger.log(`✨ Successfully created the '${projectName}' project.`);
950
- break;
951
- }
952
- }
953
- }
954
-
955
- if (!projectName) {
956
- throw new FatalError("Must specify a project name.", 1);
957
- }
958
-
959
- // We infer git info by default is not passed in
960
-
961
- let isGitDir = true;
962
- try {
963
- execSync(`git rev-parse --is-inside-work-tree`, {
964
- stdio: "ignore",
965
- });
966
- } catch (err) {
967
- isGitDir = false;
968
- }
969
-
970
- let isGitDirty = false;
971
-
972
- if (isGitDir) {
973
- try {
974
- isGitDirty = Boolean(
975
- execSync(`git status --porcelain`).toString().length
976
- );
977
-
978
- if (!branch) {
979
- branch = execSync(`git rev-parse --abbrev-ref HEAD`)
980
- .toString()
981
- .trim();
982
- }
983
-
984
- if (!commitHash) {
985
- commitHash = execSync(`git rev-parse HEAD`).toString().trim();
986
- }
987
-
988
- if (!commitMessage) {
989
- commitMessage = execSync(`git show -s --format=%B ${commitHash}`)
990
- .toString()
991
- .trim();
992
- }
993
- } catch (err) {}
994
-
995
- if (isGitDirty && !commitDirty) {
996
- logger.warn(
997
- `Warning: Your working directory is a git repo and has uncommitted changes\nTo silense this warning, pass in --commit-dirty=true`
998
- );
999
- }
1000
-
1001
- if (commitDirty === undefined) {
1002
- commitDirty = isGitDirty;
1003
- }
1004
- }
1005
-
1006
- let builtFunctions: string | undefined = undefined;
1007
- const functionsDirectory = join(cwd(), "functions");
1008
- if (existsSync(functionsDirectory)) {
1009
- const outfile = join(tmpdir(), "./functionsWorker.js");
1010
-
1011
- await new Promise((resolve) =>
1012
- buildFunctions({
1013
- outfile,
1014
- functionsDirectory,
1015
- onEnd: () => resolve(null),
1016
- buildOutputDirectory: dirname(outfile),
1017
- })
1018
- );
1019
-
1020
- builtFunctions = readFileSync(outfile, "utf-8");
1021
- }
1022
-
1023
- type File = {
1024
- content: Buffer;
1025
- metadata: Metadata;
1026
- };
1027
-
1028
- type Metadata = {
1029
- sizeInBytes: number;
1030
- hash: string;
1031
- };
1032
-
1033
- const IGNORE_LIST = [
1034
- "_worker.js",
1035
- "_redirects",
1036
- "_headers",
1037
- ".DS_Store",
1038
- "node_modules",
1039
- ];
1040
-
1041
- const walk = async (
1042
- dir: string,
1043
- fileMap: Map<string, File> = new Map(),
1044
- depth = 0
1045
- ) => {
1046
- const files = await readdir(dir);
1047
-
1048
- await Promise.all(
1049
- files.map(async (file) => {
1050
- const filepath = join(dir, file);
1051
- const filestat = await stat(filepath);
1052
-
1053
- if (IGNORE_LIST.includes(file)) {
1054
- return;
1055
- }
1056
-
1057
- if (filestat.isSymbolicLink()) {
1058
- return;
1059
- }
1060
-
1061
- if (filestat.isDirectory()) {
1062
- fileMap = await walk(filepath, fileMap, depth + 1);
1063
- } else {
1064
- let name;
1065
- if (depth) {
1066
- name = filepath.split(sep).slice(1).join("/");
1067
- } else {
1068
- name = file;
1069
- }
1070
-
1071
- // TODO: Move this to later so we don't hold as much in memory
1072
- const fileContent = await readFile(filepath);
1073
-
1074
- const base64Content = fileContent.toString("base64");
1075
- const extension =
1076
- name.split(".").length > 1 ? name.split(".").at(-1) || "" : "";
1077
-
1078
- const content = base64Content + extension;
1079
-
1080
- if (filestat.size > 25 * 1024 * 1024) {
1081
- throw new Error(
1082
- `Error: Pages only supports files up to ${prettyBytes(
1083
- 25 * 1024 * 1024
1084
- )} in size\n${name} is ${prettyBytes(filestat.size)} in size`
1085
- );
1086
- }
1087
-
1088
- fileMap.set(name, {
1089
- content: fileContent,
1090
- metadata: {
1091
- sizeInBytes: filestat.size,
1092
- hash: hash(content).toString("hex").slice(0, 32),
1093
- },
1094
- });
1095
- }
1096
- })
1097
- );
1098
-
1099
- return fileMap;
1100
- };
1101
-
1102
- const fileMap = await walk(directory);
1103
-
1104
- const start = Date.now();
1105
-
1106
- const files: Array<Promise<void>> = [];
1107
-
1108
- if (fileMap.size > 1000) {
1109
- throw new Error(
1110
- `Error: Pages only supports up to 1,000 files in a deployment at the moment.\nTry a smaller project perhaps?`
1111
- );
1112
- }
1113
-
1114
- let counter = 0;
1115
-
1116
- const { rerender, unmount } = render(
1117
- <Progress done={counter} total={fileMap.size} />
1118
- );
1119
-
1120
- fileMap.forEach((file: File, name: string) => {
1121
- const form = new FormData();
1122
- form.append(
1123
- "file",
1124
- new File([new Uint8Array(file.content.buffer)], name)
1125
- );
1126
-
1127
- // TODO: Consider a retry
1128
-
1129
- const promise = fetchResult<{ id: string }>(
1130
- `/accounts/${accountId}/pages/projects/${projectName}/file`,
1131
- {
1132
- method: "POST",
1133
- body: form,
1134
- }
1135
- ).then((response) => {
1136
- counter++;
1137
- rerender(<Progress done={counter} total={fileMap.size} />);
1138
- if (response.id != file.metadata.hash) {
1139
- throw new Error(
1140
- `Looks like there was an issue uploading '${name}'. Try again perhaps?`
1141
- );
1142
- }
1143
- });
1144
-
1145
- files.push(promise);
1146
- });
1147
-
1148
- await Promise.all(files);
1149
-
1150
- unmount();
1151
-
1152
- const uploadMs = Date.now() - start;
1153
-
1154
- logger.log(
1155
- `✨ Success! Uploaded ${fileMap.size} files ${formatTime(uploadMs)}\n`
1156
- );
1157
-
1158
- const formData = new FormData();
1159
-
1160
- formData.append(
1161
- "manifest",
1162
- JSON.stringify(
1163
- Object.fromEntries(
1164
- [...fileMap.entries()].map(([fileName, file]) => [
1165
- `/${fileName}`,
1166
- file.metadata.hash,
1167
- ])
1168
- )
1169
- )
1170
- );
1171
-
1172
- if (branch) {
1173
- formData.append("branch", branch);
1174
- }
1175
-
1176
- if (commitMessage) {
1177
- formData.append("commit_message", commitMessage);
1178
- }
1179
-
1180
- if (commitHash) {
1181
- formData.append("commit_hash", commitHash);
1182
- }
1183
-
1184
- if (commitDirty !== undefined) {
1185
- formData.append("commit_dirty", commitDirty);
1186
- }
1187
-
1188
- let _headers: string | undefined,
1189
- _redirects: string | undefined,
1190
- _workerJS: string | undefined;
1191
-
1192
- try {
1193
- _headers = readFileSync(join(directory, "_headers"), "utf-8");
1194
- } catch {}
1195
-
1196
- try {
1197
- _redirects = readFileSync(join(directory, "_redirects"), "utf-8");
1198
- } catch {}
1199
-
1200
- try {
1201
- _workerJS = readFileSync(join(directory, "_worker.js"), "utf-8");
1202
- } catch {}
1203
-
1204
- if (_headers) {
1205
- formData.append("_headers", new File([_headers], "_headers"));
1206
- }
1207
-
1208
- if (_redirects) {
1209
- formData.append("_redirects", new File([_redirects], "_redirects"));
1210
- }
1211
-
1212
- if (builtFunctions) {
1213
- formData.append("_worker.js", new File([builtFunctions], "_worker.js"));
1214
- } else if (_workerJS) {
1215
- formData.append("_worker.js", new File([_workerJS], "_worker.js"));
1216
- }
1217
-
1218
- const deploymentResponse = await fetchResult<Deployment>(
1219
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`,
1220
- {
1221
- method: "POST",
1222
- body: formData,
1223
- }
1224
- );
1225
-
1226
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1227
- account_id: accountId,
1228
- project_name: projectName,
1229
- });
1230
-
1231
- logger.log(
1232
- `✨ Deployment complete! Take a peek over at ${deploymentResponse.url}`
1233
- );
1234
- },
1235
- };
1236
-
1237
- export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1238
- return yargs
1239
- .command(
1240
- "dev [directory] [-- command]",
1241
- "🧑‍💻 Develop your full-stack Pages application locally",
1242
- (yargs) => {
1243
- return yargs
1244
- .positional("directory", {
1245
- type: "string",
1246
- demandOption: undefined,
1247
- description: "The directory of static assets to serve",
1248
- })
1249
- .positional("command", {
1250
- type: "string",
1251
- demandOption: undefined,
1252
- description: "The proxy command to run",
1253
- })
1254
- .options({
1255
- local: {
1256
- type: "boolean",
1257
- default: true,
1258
- description: "Run on my machine",
1259
- },
1260
- port: {
1261
- type: "number",
1262
- default: 8788,
1263
- description: "The port to listen on (serve from)",
1264
- },
1265
- proxy: {
1266
- type: "number",
1267
- description:
1268
- "The port to proxy (where the static assets are served)",
1269
- },
1270
- "script-path": {
1271
- type: "string",
1272
- default: "_worker.js",
1273
- description:
1274
- "The location of the single Worker script if not using functions",
1275
- },
1276
- binding: {
1277
- type: "array",
1278
- description: "Bind variable/secret (KEY=VALUE)",
1279
- alias: "b",
1280
- },
1281
- kv: {
1282
- type: "array",
1283
- description: "KV namespace to bind",
1284
- alias: "k",
1285
- },
1286
- do: {
1287
- type: "array",
1288
- description: "Durable Object to bind (NAME=CLASS)",
1289
- alias: "o",
1290
- },
1291
- "live-reload": {
1292
- type: "boolean",
1293
- default: false,
1294
- description: "Auto reload HTML pages when change is detected",
1295
- },
1296
- // TODO: Miniflare user options
1297
- })
1298
- .epilogue(pagesBetaWarning);
1299
- },
1300
- async ({
1301
- local,
1302
- directory,
1303
- port,
1304
- proxy: requestedProxyPort,
1305
- "script-path": singleWorkerScriptPath,
1306
- binding: bindings = [],
1307
- kv: kvs = [],
1308
- do: durableObjects = [],
1309
- "live-reload": liveReload,
1310
- _: [_pages, _dev, ...remaining],
1311
- }) => {
1312
- // Beta message for `wrangler pages <commands>` usage
1313
- logger.log(pagesBetaWarning);
1314
-
1315
- if (!local) {
1316
- logger.error("Only local mode is supported at the moment.");
1317
- return;
1318
- }
1319
-
1320
- const functionsDirectory = "./functions";
1321
- const usingFunctions = existsSync(functionsDirectory);
1322
-
1323
- const command = remaining as (string | number)[];
1324
-
1325
- let proxyPort: number | void;
1326
-
1327
- if (directory === undefined) {
1328
- proxyPort = await spawnProxyProcess({
1329
- port: requestedProxyPort,
1330
- command,
1331
- });
1332
- if (proxyPort === undefined) return undefined;
1333
- }
1334
-
1335
- let miniflareArgs: MiniflareOptions = {};
1336
-
1337
- let scriptReadyResolve: () => void;
1338
- const scriptReadyPromise = new Promise<void>(
1339
- (resolve) => (scriptReadyResolve = resolve)
1340
- );
1341
-
1342
- if (usingFunctions) {
1343
- const outfile = join(tmpdir(), "./functionsWorker.js");
1344
-
1345
- logger.log(`Compiling worker to "${outfile}"...`);
1346
-
1347
- try {
1348
- await buildFunctions({
1349
- outfile,
1350
- functionsDirectory,
1351
- sourcemap: true,
1352
- watch: true,
1353
- onEnd: () => scriptReadyResolve(),
1354
- buildOutputDirectory: directory,
1355
- });
1356
- } catch {}
1357
-
1358
- watch([functionsDirectory], {
1359
- persistent: true,
1360
- ignoreInitial: true,
1361
- }).on("all", async () => {
1362
- await buildFunctions({
1363
- outfile,
1364
- functionsDirectory,
1365
- sourcemap: true,
1366
- watch: true,
1367
- onEnd: () => scriptReadyResolve(),
1368
- buildOutputDirectory: directory,
1369
- });
1370
- });
1371
-
1372
- miniflareArgs = {
1373
- scriptPath: outfile,
1374
- };
1375
- } else {
1376
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1377
- scriptReadyResolve!();
1378
-
1379
- const scriptPath =
1380
- directory !== undefined
1381
- ? join(directory, singleWorkerScriptPath)
1382
- : singleWorkerScriptPath;
1383
-
1384
- if (existsSync(scriptPath)) {
1385
- miniflareArgs = {
1386
- scriptPath,
1387
- };
1388
- } else {
1389
- logger.log("No functions. Shimming...");
1390
- miniflareArgs = {
1391
- // TODO: The fact that these request/response hacks are necessary is ridiculous.
1392
- // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
1393
- script: `
1394
- export default {
1395
- async fetch(request, env, context) {
1396
- const response = await env.ASSETS.fetch(request.url, request)
1397
- return new Response(response.body, response)
1398
- }
1399
- }`,
1400
- };
1401
- }
1402
- }
1403
-
1404
- // Defer importing miniflare until we really need it
1405
- const { Miniflare, Log, LogLevel } = await import("miniflare");
1406
- const { Response, fetch } = await import("@miniflare/core");
1407
-
1408
- // Wait for esbuild to finish building before starting Miniflare.
1409
- // This must be before the call to `new Miniflare`, as that will
1410
- // asynchronously start loading the script. `await startServer()`
1411
- // internally just waits for that promise to resolve.
1412
- await scriptReadyPromise;
1413
-
1414
- // `assetsFetch()` will only be called if there is `proxyPort` defined.
1415
- // We only define `proxyPort`, above, when there is no `directory` defined.
1416
- const assetsFetch =
1417
- directory !== undefined
1418
- ? await generateAssetsFetch(directory)
1419
- : invalidAssetsFetch;
1420
-
1421
- const requestContextCheckOptions =
1422
- await getRequestContextCheckOptions();
1423
-
1424
- const miniflare = new Miniflare({
1425
- port,
1426
- watch: true,
1427
- modules: true,
1428
-
1429
- log: new Log(LogLevel.ERROR, { prefix: "pages" }),
1430
- logUnhandledRejections: true,
1431
- sourceMap: true,
1432
-
1433
- kvNamespaces: kvs.map((kv) => kv.toString()),
1434
-
1435
- durableObjects: Object.fromEntries(
1436
- durableObjects.map((durableObject) =>
1437
- durableObject.toString().split("=")
1438
- )
1439
- ),
1440
-
1441
- // User bindings
1442
- bindings: {
1443
- ...Object.fromEntries(
1444
- bindings
1445
- .map((binding) => binding.toString().split("="))
1446
- .map(([key, ...values]) => [key, values.join("=")])
1447
- ),
1448
- },
1449
-
1450
- // env.ASSETS.fetch
1451
- serviceBindings: {
1452
- async ASSETS(request: Request) {
1453
- if (proxyPort) {
1454
- try {
1455
- const url = new URL(request.url);
1456
- url.host = `localhost:${proxyPort}`;
1457
- return await fetch(url, request);
1458
- } catch (thrown) {
1459
- logger.error(`Could not proxy request: ${thrown}`);
1460
-
1461
- // TODO: Pretty error page
1462
- return new Response(
1463
- `[wrangler] Could not proxy request: ${thrown}`,
1464
- { status: 502 }
1465
- );
1466
- }
1467
- } else {
1468
- try {
1469
- return await assetsFetch(request);
1470
- } catch (thrown) {
1471
- logger.error(`Could not serve static asset: ${thrown}`);
1472
-
1473
- // TODO: Pretty error page
1474
- return new Response(
1475
- `[wrangler] Could not serve static asset: ${thrown}`,
1476
- { status: 502 }
1477
- );
1478
- }
1479
- }
1480
- },
1481
- },
1482
-
1483
- kvPersist: true,
1484
- durableObjectsPersist: true,
1485
- cachePersist: true,
1486
- liveReload,
1487
-
1488
- ...requestContextCheckOptions,
1489
- ...miniflareArgs,
1490
- });
1491
-
1492
- try {
1493
- // `startServer` might throw if user code contains errors
1494
- const server = await miniflare.startServer();
1495
- logger.log(`Serving at http://localhost:${port}/`);
1496
-
1497
- if (process.env.BROWSER !== "none") {
1498
- await openInBrowser(`http://localhost:${port}/`);
1499
- }
1500
-
1501
- if (directory !== undefined && liveReload) {
1502
- watch([directory], {
1503
- persistent: true,
1504
- ignoreInitial: true,
1505
- }).on("all", async () => {
1506
- await miniflare.reload();
1507
- });
1508
- }
1509
-
1510
- CLEANUP_CALLBACKS.push(() => {
1511
- server.close();
1512
- miniflare.dispose().catch((err) => miniflare.log.error(err));
1513
- });
1514
- } catch (e) {
1515
- miniflare.log.error(e as Error);
1516
- CLEANUP();
1517
- throw new FatalError("Could not start Miniflare.", 1);
1518
- }
1519
- }
1520
- )
1521
- .command("functions", false, (yargs) =>
1522
- // we hide this command from help output because
1523
- // it's not meant to be used directly right now
1524
- yargs.command(
1525
- "build [directory]",
1526
- "Compile a folder of Cloudflare Pages Functions into a single Worker",
1527
- (yargs) =>
1528
- yargs
1529
- .positional("directory", {
1530
- type: "string",
1531
- default: "functions",
1532
- description: "The directory of Pages Functions",
1533
- })
1534
- .options({
1535
- outfile: {
1536
- type: "string",
1537
- default: "_worker.js",
1538
- description: "The location of the output Worker script",
1539
- },
1540
- "output-config-path": {
1541
- type: "string",
1542
- description: "The location for the output config file",
1543
- },
1544
- minify: {
1545
- type: "boolean",
1546
- default: false,
1547
- description: "Minify the output Worker script",
1548
- },
1549
- sourcemap: {
1550
- type: "boolean",
1551
- default: false,
1552
- description:
1553
- "Generate a sourcemap for the output Worker script",
1554
- },
1555
- "fallback-service": {
1556
- type: "string",
1557
- default: "ASSETS",
1558
- description:
1559
- "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.",
1560
- },
1561
- watch: {
1562
- type: "boolean",
1563
- default: false,
1564
- description:
1565
- "Watch for changes to the functions and automatically rebuild the Worker script",
1566
- },
1567
- plugin: {
1568
- type: "boolean",
1569
- default: false,
1570
- description: "Build a plugin rather than a Worker script",
1571
- },
1572
- })
1573
- .epilogue(pagesBetaWarning),
1574
- async ({
1575
- directory,
1576
- outfile,
1577
- "output-config-path": outputConfigPath,
1578
- minify,
1579
- sourcemap,
1580
- fallbackService,
1581
- watch,
1582
- plugin,
1583
- }) => {
1584
- // Beta message for `wrangler pages <commands>` usage
1585
- logger.log(pagesBetaWarning);
1586
-
1587
- await buildFunctions({
1588
- outfile,
1589
- outputConfigPath,
1590
- functionsDirectory: directory,
1591
- minify,
1592
- sourcemap,
1593
- fallbackService,
1594
- watch,
1595
- plugin,
1596
- buildOutputDirectory: dirname(outfile),
1597
- });
1598
- }
1599
- )
1600
- )
1601
- .command("project", "⚡️ Interact with your Pages projects", (yargs) =>
1602
- yargs
1603
- .command(
1604
- "list",
1605
- "List your Cloudflare Pages projects",
1606
- (yargs) => yargs.epilogue(pagesBetaWarning),
1607
- async () => {
1608
- const config = getConfigCache<PagesConfigCache>(
1609
- PAGES_CONFIG_CACHE_FILENAME
1610
- );
1611
-
1612
- const accountId = await requireAuth(config);
1613
-
1614
- const projects: Array<Project> = await listProjects({ accountId });
1615
-
1616
- const data = projects.map((project) => {
1617
- return {
1618
- "Project Name": project.name,
1619
- "Project Domains": `${project.domains.join(", ")}`,
1620
- "Git Provider": project.source ? "Yes" : "No",
1621
- "Last Modified": project.latest_deployment
1622
- ? timeagoFormat(project.latest_deployment.modified_on)
1623
- : timeagoFormat(project.created_on),
1624
- };
1625
- });
1626
-
1627
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1628
- account_id: accountId,
1629
- });
1630
-
1631
- render(<Table data={data}></Table>);
1632
- }
1633
- )
1634
- .command(
1635
- "create [project-name]",
1636
- "Create a new Cloudflare Pages project",
1637
- (yargs) =>
1638
- yargs
1639
- .positional("project-name", {
1640
- type: "string",
1641
- demandOption: true,
1642
- description: "The name of your Pages project",
1643
- })
1644
- .options({
1645
- "production-branch": {
1646
- type: "string",
1647
- description:
1648
- "The name of the production branch of your project",
1649
- },
1650
- })
1651
- .epilogue(pagesBetaWarning),
1652
- async ({ productionBranch, projectName }) => {
1653
- const config = getConfigCache<PagesConfigCache>(
1654
- PAGES_CONFIG_CACHE_FILENAME
1655
- );
1656
- const accountId = await requireAuth(config);
1657
-
1658
- const isInteractive = process.stdin.isTTY;
1659
- if (!projectName && isInteractive) {
1660
- projectName = await prompt("Enter the name of your new project:");
1661
- }
1662
-
1663
- if (!projectName) {
1664
- throw new FatalError("Must specify a project name.", 1);
1665
- }
1666
-
1667
- if (!productionBranch && isInteractive) {
1668
- let isGitDir = true;
1669
- try {
1670
- execSync(`git rev-parse --is-inside-work-tree`, {
1671
- stdio: "ignore",
1672
- });
1673
- } catch (err) {
1674
- isGitDir = false;
1675
- }
1676
-
1677
- productionBranch = await prompt(
1678
- "Enter the production branch name:",
1679
- "text",
1680
- isGitDir
1681
- ? execSync(`git rev-parse --abbrev-ref HEAD`)
1682
- .toString()
1683
- .trim()
1684
- : "production"
1685
- );
1686
- }
1687
-
1688
- if (!productionBranch) {
1689
- throw new FatalError("Must specify a production branch.", 1);
1690
- }
1691
-
1692
- const { subdomain } = await fetchResult<Project>(
1693
- `/accounts/${accountId}/pages/projects`,
1694
- {
1695
- method: "POST",
1696
- body: JSON.stringify({
1697
- name: projectName,
1698
- production_branch: productionBranch,
1699
- }),
1700
- }
1701
- );
1702
-
1703
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1704
- account_id: accountId,
1705
- project_name: projectName,
1706
- });
1707
-
1708
- logger.log(
1709
- `✨ Successfully created the '${projectName}' project. It will be available at https://${subdomain}/ once you create your first deployment.`
1710
- );
1711
- logger.log(
1712
- `To deploy a folder of assets, run 'wrangler pages publish [directory]'.`
1713
- );
1714
- }
1715
- )
1716
- .epilogue(pagesBetaWarning)
1717
- )
1718
- .command(
1719
- "deployment",
1720
- "🚀 Interact with the deployments of a project",
1721
- (yargs) =>
1722
- yargs
1723
- .command(
1724
- "list",
1725
- "List deployments in your Cloudflare Pages project",
1726
- (yargs) =>
1727
- yargs
1728
- .options({
1729
- "project-name": {
1730
- type: "string",
1731
- description:
1732
- "The name of the project you would like to list deployments for",
1733
- },
1734
- })
1735
- .epilogue(pagesBetaWarning),
1736
- async ({ projectName }) => {
1737
- const config = getConfigCache<PagesConfigCache>(
1738
- PAGES_CONFIG_CACHE_FILENAME
1739
- );
1740
- const accountId = await requireAuth(config);
1741
-
1742
- projectName ??= config.project_name;
1743
-
1744
- const isInteractive = process.stdin.isTTY;
1745
- if (!projectName && isInteractive) {
1746
- const projects = await listProjects({ accountId });
1747
- projectName = await new Promise((resolve) => {
1748
- const { unmount } = render(
1749
- <>
1750
- <Text>Select a project:</Text>
1751
- <SelectInput
1752
- items={projects.map((project) => ({
1753
- key: project.name,
1754
- label: project.name,
1755
- value: project,
1756
- }))}
1757
- onSelect={async (selected) => {
1758
- resolve(selected.value.name);
1759
- unmount();
1760
- }}
1761
- />
1762
- </>
1763
- );
1764
- });
1765
- }
1766
-
1767
- if (!projectName) {
1768
- throw new FatalError("Must specify a project name.", 1);
1769
- }
1770
-
1771
- const deployments: Array<Deployment> = await fetchResult(
1772
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`
1773
- );
1774
-
1775
- const titleCase = (word: string) =>
1776
- word.charAt(0).toUpperCase() + word.slice(1);
1777
-
1778
- const shortSha = (sha: string) => sha.slice(0, 7);
1779
-
1780
- const getStatus = (deployment: Deployment) => {
1781
- // Return a pretty time since timestamp if successful otherwise the status
1782
- if (deployment.latest_stage.status === `success`) {
1783
- return timeagoFormat(deployment.latest_stage.ended_on);
1784
- }
1785
- return titleCase(deployment.latest_stage.status);
1786
- };
1787
-
1788
- const data = deployments.map((deployment) => {
1789
- return {
1790
- Environment: titleCase(deployment.environment),
1791
- Branch: deployment.deployment_trigger.metadata.branch,
1792
- Source: shortSha(
1793
- deployment.deployment_trigger.metadata.commit_hash
1794
- ),
1795
- Deployment: deployment.url,
1796
- Status: getStatus(deployment),
1797
- // TODO: Use a url shortener
1798
- Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
1799
- };
1800
- });
1801
-
1802
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1803
- account_id: accountId,
1804
- });
1805
-
1806
- render(<Table data={data}></Table>);
1807
- }
1808
- )
1809
- .command({
1810
- command: "create [directory]",
1811
- ...createDeployment,
1812
- } as CommandModule)
1813
- .epilogue(pagesBetaWarning)
1814
- )
1815
- .command({
1816
- command: "publish [directory]",
1817
- ...createDeployment,
1818
- } as CommandModule);
1819
- };
1820
-
1821
- const invalidAssetsFetch: typeof fetch = () => {
1822
- throw new Error(
1823
- "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1824
- );
1825
- };
1826
-
1827
- const listProjects = async ({
1828
- accountId,
1829
- }: {
1830
- accountId: string;
1831
- }): Promise<Array<Project>> => {
1832
- const pageSize = 10;
1833
- let page = 1;
1834
- const results = [];
1835
- while (results.length % pageSize === 0) {
1836
- const json: Array<Project> = await fetchResult(
1837
- `/accounts/${accountId}/pages/projects`,
1838
- {},
1839
- new URLSearchParams({
1840
- per_page: pageSize.toString(),
1841
- page: page.toString(),
1842
- })
1843
- );
1844
- page++;
1845
- results.push(...json);
1846
- if (json.length < pageSize) {
1847
- break;
1848
- }
1849
- }
1850
- return results;
1851
- };
1852
-
1853
- function formatTime(duration: number) {
1854
- return `(${(duration / 1000).toFixed(2)} sec)`;
1855
- }
1856
-
1857
- function Progress({ done, total }: { done: number; total: number }) {
1858
- return (
1859
- <>
1860
- <Text>
1861
- <Spinner type="earth" />
1862
- {` Uploading... (${done}/${total})\n`}
1863
- </Text>
1864
- </>
1865
- );
1866
- }