wrangler 0.0.0-e3cab74 → 0.0.0-e452a35

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 (102) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +42 -28
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +93 -4
  8. package/pages/functions/filepath-routing.test.ts +136 -25
  9. package/pages/functions/filepath-routing.ts +14 -3
  10. package/pages/functions/routes.ts +6 -1
  11. package/pages/functions/template-plugin.ts +147 -0
  12. package/pages/functions/template-worker.ts +21 -8
  13. package/src/__tests__/config-cache.test.ts +36 -0
  14. package/src/__tests__/configuration.test.ts +1514 -367
  15. package/src/__tests__/dev.test.tsx +870 -84
  16. package/src/__tests__/guess-worker-format.test.ts +37 -18
  17. package/src/__tests__/helpers/mock-account-id.ts +22 -4
  18. package/src/__tests__/helpers/mock-cfetch.ts +8 -4
  19. package/src/__tests__/helpers/mock-console.ts +35 -10
  20. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  21. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  22. package/src/__tests__/helpers/mock-istty.ts +27 -0
  23. package/src/__tests__/helpers/mock-kv.ts +9 -16
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/https-options.test.ts +130 -0
  29. package/src/__tests__/index.test.ts +137 -747
  30. package/src/__tests__/init.test.ts +1557 -0
  31. package/src/__tests__/jest.setup.ts +28 -8
  32. package/src/__tests__/kv.test.ts +598 -258
  33. package/src/__tests__/logger.test.ts +115 -0
  34. package/src/__tests__/pages.test.ts +657 -0
  35. package/src/__tests__/parse.test.ts +8 -0
  36. package/src/__tests__/publish.test.ts +4003 -941
  37. package/src/__tests__/r2.test.ts +69 -34
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +228 -73
  40. package/src/__tests__/tail.test.ts +146 -20
  41. package/src/__tests__/user.test.ts +131 -0
  42. package/src/__tests__/whoami.test.tsx +26 -7
  43. package/src/abort.d.ts +3 -0
  44. package/src/bundle.ts +74 -7
  45. package/src/cfetch/index.ts +21 -4
  46. package/src/cfetch/internal.ts +20 -14
  47. package/src/cli.ts +5 -11
  48. package/src/config/README.md +7 -7
  49. package/src/config/config.ts +69 -100
  50. package/src/config/environment.ts +119 -4
  51. package/src/config/index.ts +177 -4
  52. package/src/config/validation-helpers.ts +228 -23
  53. package/src/config/validation.ts +687 -174
  54. package/src/config-cache.ts +45 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +74 -36
  56. package/src/{api/form_data.ts → create-worker-upload-form.ts} +55 -18
  57. package/src/dev/dev-vars.ts +36 -0
  58. package/src/dev/dev.tsx +422 -0
  59. package/src/dev/local.tsx +318 -0
  60. package/src/dev/remote.tsx +227 -0
  61. package/src/dev/use-esbuild.ts +118 -0
  62. package/src/dialogs.tsx +16 -6
  63. package/src/durable.ts +102 -0
  64. package/src/entry.ts +279 -14
  65. package/src/environment-variables.ts +3 -1
  66. package/src/errors.ts +11 -0
  67. package/src/https-options.ts +123 -0
  68. package/src/index.tsx +1268 -806
  69. package/src/inspect.ts +64 -11
  70. package/src/intl-polyfill.d.ts +139 -0
  71. package/src/{kv.tsx → kv.ts} +195 -62
  72. package/src/logger.ts +66 -0
  73. package/src/miniflare-cli/README.md +30 -0
  74. package/src/miniflare-cli/enum-keys.ts +17 -0
  75. package/src/miniflare-cli/index.ts +41 -0
  76. package/src/miniflare-cli/request-context.ts +40 -0
  77. package/src/module-collection.ts +94 -6
  78. package/src/open-in-browser.ts +9 -3
  79. package/src/package-manager.ts +9 -8
  80. package/src/pages.tsx +1057 -75
  81. package/src/parse.ts +24 -5
  82. package/src/proxy.ts +143 -54
  83. package/src/publish.ts +444 -229
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +98 -44
  86. package/src/tail/index.ts +2 -2
  87. package/src/tail/printing.ts +13 -8
  88. package/src/update-check.ts +19 -0
  89. package/src/user.tsx +263 -109
  90. package/src/whoami.tsx +2 -1
  91. package/src/{api/worker.ts → worker.ts} +24 -30
  92. package/templates/gitignore +171 -0
  93. package/templates/new-worker.ts +16 -1
  94. package/templates/static-asset-facade.js +1 -1
  95. package/wrangler-dist/cli.js +55345 -69246
  96. package/src/__tests__/helpers/mock-user.ts +0 -27
  97. package/src/__tests__/logout.test.ts +0 -50
  98. package/src/__tests__/sentry.test.ts +0 -146
  99. package/src/dev.tsx +0 -961
  100. package/src/guess-worker-format.ts +0 -68
  101. package/src/reporting.ts +0 -115
  102. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,422 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as path from "node:path";
3
+ import { watch } from "chokidar";
4
+ import clipboardy from "clipboardy";
5
+ import commandExists from "command-exists";
6
+ import { Box, Text, useApp, useInput, useStdin } from "ink";
7
+ import React, { useState, useEffect, useRef } from "react";
8
+ import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
9
+ import onExit from "signal-exit";
10
+ import tmp from "tmp-promise";
11
+ import { fetch } from "undici";
12
+ import { printBindings } from "../config";
13
+ import { runCustomBuild } from "../entry";
14
+ import { openInspector } from "../inspect";
15
+ import { logger } from "../logger";
16
+ import openInBrowser from "../open-in-browser";
17
+ import { getAPIToken } from "../user";
18
+ import { Local } from "./local";
19
+ import { Remote } from "./remote";
20
+ import { useEsbuild } from "./use-esbuild";
21
+ import type { Config } from "../config";
22
+ import type { Entry } from "../entry";
23
+ import type { AssetPaths } from "../sites";
24
+ import type { CfWorkerInit } from "../worker";
25
+ import type { EsbuildBundle } from "./use-esbuild";
26
+
27
+ export type DevProps = {
28
+ name?: string;
29
+ entry: Entry;
30
+ port: number;
31
+ ip: string;
32
+ inspectorPort: number;
33
+ rules: Config["rules"];
34
+ accountId: string | undefined;
35
+ initialMode: "local" | "remote";
36
+ jsxFactory: string | undefined;
37
+ jsxFragment: string | undefined;
38
+ tsconfig: string | undefined;
39
+ upstreamProtocol: "https" | "http";
40
+ localProtocol: "https" | "http";
41
+ enableLocalPersistence: boolean;
42
+ bindings: CfWorkerInit["bindings"];
43
+ crons: Config["triggers"]["crons"];
44
+ public: string | undefined;
45
+ assetPaths: AssetPaths | undefined;
46
+ compatibilityDate: string;
47
+ compatibilityFlags: string[] | undefined;
48
+ usageModel: "bundled" | "unbound" | undefined;
49
+ minify: boolean | undefined;
50
+ nodeCompat: boolean | undefined;
51
+ build: {
52
+ command?: string | undefined;
53
+ cwd?: string | undefined;
54
+ watch_dir?: string | undefined;
55
+ };
56
+ env: string | undefined;
57
+ legacyEnv: boolean;
58
+ zone:
59
+ | {
60
+ id: string;
61
+ host: string;
62
+ }
63
+ | undefined;
64
+ };
65
+
66
+ export function DevImplementation(props: DevProps): JSX.Element {
67
+ const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
68
+ const directory = useTmpDir();
69
+
70
+ useCustomBuild(props.entry, props.build);
71
+
72
+ if (props.public && props.entry.format === "service-worker") {
73
+ throw new Error(
74
+ "You cannot use the service-worker format with a `public` directory."
75
+ );
76
+ }
77
+
78
+ if (props.bindings.wasm_modules && props.entry.format === "modules") {
79
+ throw new Error(
80
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
81
+ );
82
+ }
83
+
84
+ if (props.bindings.text_blobs && props.entry.format === "modules") {
85
+ throw new Error(
86
+ "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
87
+ );
88
+ }
89
+
90
+ if (props.bindings.data_blobs && props.entry.format === "modules") {
91
+ throw new Error(
92
+ "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
93
+ );
94
+ }
95
+
96
+ const bundle = useEsbuild({
97
+ entry: props.entry,
98
+ destination: directory,
99
+ staticRoot: props.public,
100
+ jsxFactory: props.jsxFactory,
101
+ rules: props.rules,
102
+ jsxFragment: props.jsxFragment,
103
+ serveAssetsFromWorker: !!props.public,
104
+ tsconfig: props.tsconfig,
105
+ minify: props.minify,
106
+ nodeCompat: props.nodeCompat,
107
+ });
108
+
109
+ printBindings(props.bindings);
110
+
111
+ // only load the UI if we're running in a supported environment
112
+ const { isRawModeSupported } = useStdin();
113
+ return isRawModeSupported ? (
114
+ <InteractiveDevSession {...props} bundle={bundle} apiToken={apiToken} />
115
+ ) : (
116
+ <DevSession
117
+ {...props}
118
+ bundle={bundle}
119
+ apiToken={apiToken}
120
+ local={props.initialMode === "local"}
121
+ />
122
+ );
123
+ }
124
+
125
+ type InteractiveDevSessionProps = DevProps & {
126
+ apiToken: string | undefined;
127
+ bundle: EsbuildBundle | undefined;
128
+ };
129
+
130
+ function InteractiveDevSession(props: InteractiveDevSessionProps) {
131
+ const toggles = useHotkeys(
132
+ {
133
+ local: props.initialMode === "local",
134
+ tunnel: false,
135
+ },
136
+ props.port,
137
+ props.ip,
138
+ props.inspectorPort,
139
+ props.localProtocol
140
+ );
141
+
142
+ useTunnel(toggles.tunnel);
143
+
144
+ return (
145
+ <>
146
+ <DevSession {...props} local={toggles.local} />
147
+ <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
148
+ <Text bold={true}>[b]</Text>
149
+ <Text> open a browser, </Text>
150
+ <Text bold={true}>[d]</Text>
151
+ <Text> open Devtools, </Text>
152
+ <Text bold={true}>[l]</Text>
153
+ <Text> {toggles.local ? "turn off" : "turn on"} local mode, </Text>
154
+ <Text bold={true}>[c]</Text>
155
+ <Text> clear console, </Text>
156
+ <Text bold={true}>[x]</Text>
157
+ <Text> to exit</Text>
158
+ </Box>
159
+ </>
160
+ );
161
+ }
162
+
163
+ type DevSessionProps = InteractiveDevSessionProps & { local: boolean };
164
+
165
+ function DevSession(props: DevSessionProps) {
166
+ return props.local ? (
167
+ <Local
168
+ name={props.name}
169
+ bundle={props.bundle}
170
+ format={props.entry.format}
171
+ compatibilityDate={props.compatibilityDate}
172
+ compatibilityFlags={props.compatibilityFlags}
173
+ bindings={props.bindings}
174
+ assetPaths={props.assetPaths}
175
+ public={props.public}
176
+ port={props.port}
177
+ ip={props.ip}
178
+ rules={props.rules}
179
+ inspectorPort={props.inspectorPort}
180
+ enableLocalPersistence={props.enableLocalPersistence}
181
+ crons={props.crons}
182
+ />
183
+ ) : (
184
+ <Remote
185
+ name={props.name}
186
+ bundle={props.bundle}
187
+ format={props.entry.format}
188
+ accountId={props.accountId}
189
+ apiToken={props.apiToken}
190
+ bindings={props.bindings}
191
+ assetPaths={props.assetPaths}
192
+ public={props.public}
193
+ port={props.port}
194
+ ip={props.ip}
195
+ localProtocol={props.localProtocol}
196
+ inspectorPort={props.inspectorPort}
197
+ compatibilityDate={props.compatibilityDate}
198
+ compatibilityFlags={props.compatibilityFlags}
199
+ usageModel={props.usageModel}
200
+ env={props.env}
201
+ legacyEnv={props.legacyEnv}
202
+ zone={props.zone}
203
+ />
204
+ );
205
+ }
206
+
207
+ export interface DirectorySyncResult {
208
+ name: string;
209
+ removeCallback: () => void;
210
+ }
211
+
212
+ function useTmpDir(): string | undefined {
213
+ const [directory, setDirectory] = useState<DirectorySyncResult>();
214
+ const handleError = useErrorHandler();
215
+ useEffect(() => {
216
+ let dir: DirectorySyncResult | undefined;
217
+ try {
218
+ dir = tmp.dirSync({ unsafeCleanup: true });
219
+ setDirectory(dir);
220
+ return;
221
+ } catch (err) {
222
+ logger.error(
223
+ "Failed to create temporary directory to store built files."
224
+ );
225
+ handleError(err);
226
+ }
227
+ return () => {
228
+ dir?.removeCallback();
229
+ };
230
+ }, [handleError]);
231
+ return directory?.name;
232
+ }
233
+
234
+ function useCustomBuild(
235
+ expectedEntry: Entry,
236
+ build: {
237
+ command?: string | undefined;
238
+ cwd?: string | undefined;
239
+ watch_dir?: string | undefined;
240
+ }
241
+ ): void {
242
+ useEffect(() => {
243
+ if (!build.command) return;
244
+ let watcher: ReturnType<typeof watch> | undefined;
245
+ if (build.watch_dir) {
246
+ watcher = watch(build.watch_dir, {
247
+ persistent: true,
248
+ ignoreInitial: true,
249
+ }).on("all", (_event, filePath) => {
250
+ const relativeFile =
251
+ path.relative(expectedEntry.directory, expectedEntry.file) || ".";
252
+ //TODO: we should buffer requests to the proxy until this completes
253
+ logger.log(`The file ${filePath} changed, restarting build...`);
254
+ runCustomBuild(expectedEntry.file, relativeFile, build).catch((err) => {
255
+ logger.error("Custom build failed:", err);
256
+ });
257
+ });
258
+ }
259
+
260
+ return () => {
261
+ watcher?.close();
262
+ };
263
+ }, [build, expectedEntry]);
264
+ }
265
+
266
+ function sleep(period: number) {
267
+ return new Promise((resolve) => setTimeout(resolve, period));
268
+ }
269
+ const SLEEP_DURATION = 2000;
270
+ // really need a first class api for this
271
+ const hostNameRegex = /userHostname="(.*)"/g;
272
+ async function findTunnelHostname() {
273
+ let hostName: string | undefined;
274
+ while (!hostName) {
275
+ try {
276
+ const resp = await fetch("http://localhost:8789/metrics");
277
+ const data = await resp.text();
278
+ const matches = Array.from(data.matchAll(hostNameRegex));
279
+ hostName = matches[0][1];
280
+ } catch (err) {
281
+ await sleep(SLEEP_DURATION);
282
+ }
283
+ }
284
+ return hostName;
285
+ }
286
+
287
+ /**
288
+ * Create a tunnel to the remote worker.
289
+ * We've disabled this for now until we figure out a better user experience.
290
+ */
291
+ function useTunnel(toggle: boolean) {
292
+ const tunnel = useRef<ReturnType<typeof spawn>>();
293
+ const removeSignalExitListener = useRef<() => void>();
294
+ // TODO: test if cloudflared is available, if not
295
+ // point them to a url where they can get docs to install it
296
+ useEffect(() => {
297
+ async function startTunnel() {
298
+ if (toggle) {
299
+ try {
300
+ await commandExists("cloudflared");
301
+ } catch (e) {
302
+ logger.warn(
303
+ "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
304
+ );
305
+ return;
306
+ }
307
+ logger.log("⎔ Starting a tunnel...");
308
+ tunnel.current = spawn("cloudflared", [
309
+ "tunnel",
310
+ "--url",
311
+ "http://localhost:8787",
312
+ "--metrics",
313
+ "localhost:8789",
314
+ ]);
315
+
316
+ tunnel.current.on("close", (code) => {
317
+ if (code) {
318
+ logger.log(`Tunnel process exited with code ${code}`);
319
+ }
320
+ });
321
+
322
+ removeSignalExitListener.current = onExit((_code, _signal) => {
323
+ logger.log("⎔ Shutting down local tunnel.");
324
+ tunnel.current?.kill();
325
+ tunnel.current = undefined;
326
+ });
327
+
328
+ const hostName = await findTunnelHostname();
329
+ await clipboardy.write(hostName);
330
+ logger.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
331
+ }
332
+ }
333
+
334
+ startTunnel().catch(async (err) => {
335
+ logger.error("tunnel:", err);
336
+ });
337
+
338
+ return () => {
339
+ if (tunnel.current) {
340
+ logger.log("⎔ Shutting down tunnel.");
341
+ tunnel.current?.kill();
342
+ tunnel.current = undefined;
343
+ removeSignalExitListener.current && removeSignalExitListener.current();
344
+ removeSignalExitListener.current = undefined;
345
+ }
346
+ };
347
+ }, [toggle]);
348
+ }
349
+
350
+ type useHotkeysInitialState = {
351
+ local: boolean;
352
+ tunnel: boolean;
353
+ };
354
+ function useHotkeys(
355
+ initial: useHotkeysInitialState,
356
+ port: number,
357
+ ip: string,
358
+ inspectorPort: number,
359
+ localProtocol: "http" | "https"
360
+ ) {
361
+ // UGH, we should put port in context instead
362
+ const [toggles, setToggles] = useState(initial);
363
+ const { exit } = useApp();
364
+ useInput(
365
+ async (
366
+ input,
367
+ // eslint-disable-next-line unused-imports/no-unused-vars
368
+ key
369
+ ) => {
370
+ switch (input.toLowerCase()) {
371
+ // clear console
372
+ case "c":
373
+ console.clear();
374
+ // This console.log causes Ink to re-render the `DevSession` component.
375
+ // Couldn't find a better way to tell it to do so...
376
+ console.log();
377
+ break;
378
+ // open browser
379
+ case "b": {
380
+ await openInBrowser(`${localProtocol}://${ip}:${port}`);
381
+ break;
382
+ }
383
+ // toggle inspector
384
+ case "d": {
385
+ await openInspector(inspectorPort);
386
+ break;
387
+ }
388
+ // toggle local
389
+ case "l":
390
+ setToggles((previousToggles) => ({
391
+ ...previousToggles,
392
+ local: !previousToggles.local,
393
+ }));
394
+ break;
395
+ // shut down
396
+ case "q":
397
+ case "x":
398
+ exit();
399
+ break;
400
+ default:
401
+ // nothing?
402
+ break;
403
+ }
404
+ }
405
+ );
406
+ return toggles;
407
+ }
408
+
409
+ function ErrorFallback(props: { error: Error }) {
410
+ const { exit } = useApp();
411
+ useEffect(() => exit(props.error));
412
+ return (
413
+ <>
414
+ <Text>Something went wrong:</Text>
415
+ <Text>{props.error.stack}</Text>
416
+ </>
417
+ );
418
+ }
419
+
420
+ export default withErrorBoundary(DevImplementation, {
421
+ FallbackComponent: ErrorFallback,
422
+ });