wrangler 0.0.0-e0d2f35 → 0.0.0-e1b8ac4

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 (160) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +58 -31
  7. package/pages/functions/buildPlugin.ts +105 -0
  8. package/pages/functions/buildWorker.ts +93 -4
  9. package/pages/functions/filepath-routing.test.ts +223 -28
  10. package/pages/functions/filepath-routing.ts +92 -131
  11. package/pages/functions/routes.ts +16 -18
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +24 -17
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3548 -0
  16. package/src/__tests__/dev.test.tsx +1049 -65
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +50 -12
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/{mock-kv.ts → helpers/mock-kv.ts} +9 -16
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-process.ts +24 -0
  31. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  32. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  33. package/src/__tests__/{run-in-tmp.ts → helpers/run-in-tmp.ts} +11 -1
  34. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  35. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  36. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  37. package/src/__tests__/https-options.test.ts +130 -0
  38. package/src/__tests__/index.test.ts +171 -338
  39. package/src/__tests__/init.test.ts +1992 -0
  40. package/src/__tests__/jest.setup.ts +86 -8
  41. package/src/__tests__/kv.test.ts +745 -449
  42. package/src/__tests__/logger.test.ts +141 -0
  43. package/src/__tests__/package-manager.test.ts +353 -0
  44. package/src/__tests__/pages.test.ts +754 -0
  45. package/src/__tests__/parse.test.ts +330 -0
  46. package/src/__tests__/publish.test.ts +5631 -903
  47. package/src/__tests__/r2.test.ts +233 -0
  48. package/src/__tests__/route.test.ts +45 -0
  49. package/src/__tests__/secret.test.ts +370 -95
  50. package/src/__tests__/tail.test.ts +690 -0
  51. package/src/__tests__/user.test.ts +132 -0
  52. package/src/__tests__/whoami.test.tsx +58 -20
  53. package/src/abort.d.ts +3 -0
  54. package/src/bundle.ts +204 -0
  55. package/src/cfetch/index.ts +30 -20
  56. package/src/cfetch/internal.ts +101 -30
  57. package/src/cli.ts +6 -2
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +243 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +420 -0
  62. package/src/config/index.ts +225 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1580 -0
  65. package/src/config-cache.ts +45 -0
  66. package/src/create-worker-preview.ts +185 -0
  67. package/src/create-worker-upload-form.ts +254 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +399 -0
  70. package/src/dev/local.tsx +321 -0
  71. package/src/dev/remote.tsx +242 -0
  72. package/src/dev/use-esbuild.ts +112 -0
  73. package/src/dialogs.tsx +66 -8
  74. package/src/durable.ts +102 -0
  75. package/src/entry.ts +322 -0
  76. package/src/environment-variables.ts +35 -0
  77. package/src/errors.ts +11 -0
  78. package/src/generate-auth-url.ts +33 -0
  79. package/src/generate-random-state.ts +16 -0
  80. package/src/https-options.ts +123 -0
  81. package/src/index.tsx +1848 -1019
  82. package/src/inspect.ts +87 -20
  83. package/src/intl-polyfill.d.ts +139 -0
  84. package/src/{kv.tsx → kv.ts} +199 -67
  85. package/src/logger.ts +73 -0
  86. package/src/miniflare-cli/README.md +30 -0
  87. package/src/miniflare-cli/enum-keys.ts +17 -0
  88. package/src/miniflare-cli/index.ts +41 -0
  89. package/src/miniflare-cli/request-context.ts +40 -0
  90. package/src/module-collection.ts +229 -34
  91. package/src/open-in-browser.ts +17 -0
  92. package/src/package-manager.ts +174 -0
  93. package/src/pages.tsx +1145 -95
  94. package/src/parse.ts +222 -0
  95. package/src/paths.ts +26 -0
  96. package/src/proxy.ts +180 -74
  97. package/src/publish.ts +626 -310
  98. package/src/r2.ts +50 -0
  99. package/src/selfsigned.d.ts +29 -0
  100. package/src/sites.tsx +187 -59
  101. package/src/tail/filters.ts +279 -0
  102. package/src/tail/index.ts +299 -0
  103. package/src/tail/printing.ts +67 -0
  104. package/src/update-check.ts +19 -0
  105. package/src/user.tsx +359 -176
  106. package/src/whoami.tsx +5 -3
  107. package/src/{api/worker.ts → worker.ts} +66 -40
  108. package/src/zones.ts +73 -0
  109. package/templates/gitignore +171 -0
  110. package/templates/new-worker-scheduled.js +17 -0
  111. package/templates/new-worker-scheduled.ts +32 -0
  112. package/templates/new-worker.js +15 -0
  113. package/templates/new-worker.ts +30 -0
  114. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  115. package/templates/tsconfig.json +105 -0
  116. package/wrangler-dist/cli.js +112889 -110835
  117. package/src/__tests__/logout.test.ts +0 -64
  118. package/src/__tests__/mock-console.ts +0 -34
  119. package/src/__tests__/mock-dialogs.ts +0 -65
  120. package/src/__tests__/mock-user.ts +0 -27
  121. package/src/__tests__/run-wrangler.ts +0 -8
  122. package/src/api/form_data.ts +0 -135
  123. package/src/api/preview.ts +0 -128
  124. package/src/config.ts +0 -641
  125. package/src/dev.tsx +0 -830
  126. package/src/tail.tsx +0 -73
  127. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  128. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  129. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  130. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  131. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  132. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  133. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  134. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  138. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  139. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  140. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  141. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  142. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  143. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  144. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  145. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  146. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  147. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  148. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  149. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  150. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  151. package/vendor/wrangler-mime/LICENSE +0 -21
  152. package/vendor/wrangler-mime/Mime.js +0 -97
  153. package/vendor/wrangler-mime/README.md +0 -187
  154. package/vendor/wrangler-mime/cli.js +0 -46
  155. package/vendor/wrangler-mime/index.js +0 -4
  156. package/vendor/wrangler-mime/lite.js +0 -4
  157. package/vendor/wrangler-mime/package.json +0 -52
  158. package/vendor/wrangler-mime/types/other.js +0 -1
  159. package/vendor/wrangler-mime/types/standard.js +0 -1
  160. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx DELETED
@@ -1,830 +0,0 @@
1
- import * as esbuild from "esbuild";
2
- import assert from "node:assert";
3
- import { spawn } from "node:child_process";
4
- import { readFile } from "node:fs/promises";
5
- import { existsSync } from "node:fs";
6
- import path from "node:path";
7
- import { Box, Text, useApp, useInput } from "ink";
8
- import { watch } from "chokidar";
9
- import clipboardy from "clipboardy";
10
- import commandExists from "command-exists";
11
- import { execaCommand } from "execa";
12
- import fetch from "node-fetch";
13
- import open from "open";
14
- import React, { useState, useEffect, useRef } from "react";
15
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
16
- import onExit from "signal-exit";
17
- import tmp from "tmp-promise";
18
- import type { DirectoryResult } from "tmp-promise";
19
-
20
- import type { CfPreviewToken } from "./api/preview";
21
- import type { CfModule } from "./api/worker";
22
- import { createWorker } from "./api/worker";
23
- import type { CfWorkerInit } from "./api/worker";
24
-
25
- import useInspector from "./inspect";
26
- import makeModuleCollector from "./module-collection";
27
- import { usePreviewServer, waitForPortToBeAvailable } from "./proxy";
28
- import type { AssetPaths } from "./sites";
29
- import { syncAssets } from "./sites";
30
- import { getAPIToken } from "./user";
31
-
32
- type CfScriptFormat = undefined | "modules" | "service-worker";
33
-
34
- export type DevProps = {
35
- name?: string;
36
- entry: string;
37
- port?: number;
38
- format: CfScriptFormat;
39
- accountId: undefined | string;
40
- initialMode: "local" | "remote";
41
- jsxFactory: undefined | string;
42
- jsxFragment: undefined | string;
43
- enableLocalPersistence: boolean;
44
- bindings: CfWorkerInit["bindings"];
45
- public: undefined | string;
46
- assetPaths: undefined | AssetPaths;
47
- compatibilityDate: undefined | string;
48
- compatibilityFlags: undefined | string[];
49
- usageModel: undefined | "bundled" | "unbound";
50
- buildCommand: {
51
- command?: undefined | string;
52
- cwd?: undefined | string;
53
- watch_dir?: undefined | string;
54
- };
55
- env: string | undefined;
56
- };
57
-
58
- function Dev(props: DevProps): JSX.Element {
59
- if (props.public && props.format === "service-worker") {
60
- throw new Error(
61
- "You cannot use the service worker format with a `public` directory."
62
- );
63
- }
64
- const port = props.port ?? 8787;
65
- const apiToken = getAPIToken();
66
- const directory = useTmpDir();
67
-
68
- // if there isn't a build command, we just return the entry immediately
69
- // ideally there would be a conditional here, but the rules of hooks
70
- // kinda forbid that, so we thread the entry through useCustomBuild
71
- const entry = useCustomBuild(props.entry, props.buildCommand);
72
-
73
- const bundle = useEsbuild({
74
- entry,
75
- destination: directory,
76
- staticRoot: props.public,
77
- jsxFactory: props.jsxFactory,
78
- jsxFragment: props.jsxFragment,
79
- });
80
- if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
81
- throw new Error(
82
- "You cannot use the service worker format with a `public` directory."
83
- );
84
- }
85
-
86
- const toggles = useHotkeys(
87
- {
88
- local: props.initialMode === "local",
89
- tunnel: false,
90
- },
91
- port
92
- );
93
-
94
- useTunnel(toggles.tunnel);
95
-
96
- return (
97
- <>
98
- {toggles.local ? (
99
- <Local
100
- name={props.name}
101
- bundle={bundle}
102
- format={props.format}
103
- bindings={props.bindings}
104
- assetPaths={props.assetPaths}
105
- public={props.public}
106
- port={port}
107
- enableLocalPersistence={props.enableLocalPersistence}
108
- />
109
- ) : (
110
- <Remote
111
- name={props.name}
112
- bundle={bundle}
113
- format={props.format}
114
- accountId={props.accountId}
115
- apiToken={apiToken}
116
- bindings={props.bindings}
117
- assetPaths={props.assetPaths}
118
- public={props.public}
119
- port={port}
120
- compatibilityDate={props.compatibilityDate}
121
- compatibilityFlags={props.compatibilityFlags}
122
- usageModel={props.usageModel}
123
- env={props.env}
124
- />
125
- )}
126
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
127
- <Text>
128
- {`B to open a browser, D to open Devtools, S to ${
129
- toggles.tunnel ? "turn off" : "turn on"
130
- } (experimental) sharing, L to ${
131
- toggles.local ? "turn off" : "turn on"
132
- } local mode, X to exit`}
133
- </Text>
134
- </Box>
135
- </>
136
- );
137
- }
138
-
139
- function Remote(props: {
140
- name: undefined | string;
141
- bundle: EsbuildBundle | undefined;
142
- format: CfScriptFormat;
143
- public: undefined | string;
144
- assetPaths: undefined | AssetPaths;
145
- port: number;
146
- accountId: undefined | string;
147
- apiToken: undefined | string;
148
- bindings: CfWorkerInit["bindings"];
149
- compatibilityDate: string | undefined;
150
- compatibilityFlags: undefined | string[];
151
- usageModel: undefined | "bundled" | "unbound";
152
- env: string | undefined;
153
- }) {
154
- assert(props.accountId, "accountId is required");
155
- assert(props.apiToken, "apiToken is required");
156
- const previewToken = useWorker({
157
- name: props.name,
158
- bundle: props.bundle,
159
- format: props.format,
160
- modules: props.bundle ? props.bundle.modules : [],
161
- accountId: props.accountId,
162
- apiToken: props.apiToken,
163
- bindings: props.bindings,
164
- assetPaths: props.assetPaths,
165
- port: props.port,
166
- compatibilityDate: props.compatibilityDate,
167
- compatibilityFlags: props.compatibilityFlags,
168
- usageModel: props.usageModel,
169
- env: props.env,
170
- });
171
-
172
- usePreviewServer({
173
- previewToken,
174
- publicRoot: props.public,
175
- port: props.port,
176
- });
177
-
178
- useInspector({
179
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
180
- port: 9229,
181
- logToTerminal: true,
182
- });
183
- return null;
184
- }
185
- function Local(props: {
186
- name: undefined | string;
187
- bundle: EsbuildBundle | undefined;
188
- format: CfScriptFormat;
189
- bindings: CfWorkerInit["bindings"];
190
- assetPaths: undefined | AssetPaths;
191
- public: undefined | string;
192
- port: number;
193
- enableLocalPersistence: boolean;
194
- }) {
195
- const { inspectorUrl } = useLocalWorker({
196
- name: props.name,
197
- bundle: props.bundle,
198
- format: props.format,
199
- bindings: props.bindings,
200
- assetPaths: props.assetPaths,
201
- public: props.public,
202
- port: props.port,
203
- enableLocalPersistence: props.enableLocalPersistence,
204
- });
205
- useInspector({ inspectorUrl, port: 9229, logToTerminal: false });
206
- return null;
207
- }
208
-
209
- function useLocalWorker(props: {
210
- name: undefined | string;
211
- bundle: EsbuildBundle | undefined;
212
- format: CfScriptFormat;
213
- bindings: CfWorkerInit["bindings"];
214
- assetPaths: undefined | AssetPaths;
215
- public: undefined | string;
216
- port: number;
217
- enableLocalPersistence: boolean;
218
- }) {
219
- // TODO: pass vars via command line
220
- const { bundle, format, bindings, port, assetPaths } = props;
221
- const local = useRef<ReturnType<typeof spawn>>();
222
- const removeSignalExitListener = useRef<() => void>();
223
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
224
- useEffect(() => {
225
- async function startLocalWorker() {
226
- if (!bundle) return;
227
- if (format === "modules" && bundle.type === "commonjs") {
228
- console.error("⎔ Cannot use modules with a commonjs bundle.");
229
- // TODO: a much better error message here, with what to do next
230
- return;
231
- }
232
- if (format === "service-worker" && bundle.type !== "esm") {
233
- console.error("⎔ Cannot use service-worker with a esm bundle.");
234
- // TODO: a much better error message here, with what to do next
235
- return;
236
- }
237
-
238
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
239
- if (props.public) {
240
- throw new Error(
241
- '⎔ A "public" folder is not yet supported in local mode.'
242
- );
243
- }
244
-
245
- console.log("⎔ Starting a local server...");
246
- // TODO: just use execa for this
247
- local.current = spawn("node", [
248
- "--experimental-vm-modules",
249
- "--inspect",
250
- require.resolve("miniflare/cli"),
251
- bundle.path,
252
- "--watch",
253
- "--wrangler-config",
254
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
255
- "--env",
256
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
257
- "--package",
258
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
259
- "--port",
260
- port.toString(),
261
- ...(assetPaths
262
- ? [
263
- "--site",
264
- assetPaths.baseDirectory,
265
- ...assetPaths.includePatterns.map((pattern) => [
266
- "--site-include",
267
- pattern,
268
- ]),
269
- ...assetPaths.excludePatterns.map((pattern) => [
270
- "--site-exclude",
271
- pattern,
272
- ]),
273
- ].flatMap((x) => x)
274
- : []),
275
- ...(props.enableLocalPersistence
276
- ? ["--kv-persist", "--cache-persist", "--do-persist"]
277
- : []),
278
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
279
- return ["--binding", `${key}=${value}`];
280
- }),
281
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
282
- return ["--kv", binding];
283
- }),
284
- ...(bindings.durable_objects?.bindings || []).flatMap(
285
- ({ name, class_name }) => {
286
- return ["--do", `${name}=${class_name}`];
287
- }
288
- ),
289
- "--modules",
290
- format ||
291
- (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
292
- ? "true"
293
- : "false",
294
- ]);
295
- console.log(`⬣ Listening at http://localhost:${port}`);
296
-
297
- local.current.on("close", (code) => {
298
- if (code !== null) {
299
- console.log(`miniflare process exited with code ${code}`);
300
- }
301
- });
302
-
303
- local.current.stdout?.on("data", (data: Buffer) => {
304
- console.log(`${data.toString()}`);
305
- });
306
-
307
- local.current.stderr?.on("data", (data: Buffer) => {
308
- console.error(`${data.toString()}`);
309
- const matches =
310
- /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
311
- data.toString()
312
- );
313
- if (matches) {
314
- setInspectorUrl(matches[1]);
315
- }
316
- });
317
-
318
- local.current.on("exit", (code) => {
319
- if (code !== 0) {
320
- console.error(`miniflare process exited with code ${code}`);
321
- }
322
- });
323
-
324
- local.current.on("error", (error: Error) => {
325
- console.error(`miniflare process failed to spawn`);
326
- console.error(error);
327
- });
328
-
329
- removeSignalExitListener.current = onExit((_code, _signal) => {
330
- console.log("⎔ Shutting down local server.");
331
- local.current?.kill();
332
- local.current = undefined;
333
- });
334
- }
335
-
336
- startLocalWorker().catch((err) => {
337
- console.error("local worker:", err);
338
- });
339
-
340
- return () => {
341
- if (local.current) {
342
- console.log("⎔ Shutting down local server.");
343
- local.current?.kill();
344
- local.current = undefined;
345
- removeSignalExitListener.current && removeSignalExitListener.current();
346
- removeSignalExitListener.current = undefined;
347
- }
348
- };
349
- }, [
350
- bundle,
351
- format,
352
- port,
353
- bindings.durable_objects?.bindings,
354
- bindings.kv_namespaces,
355
- bindings.vars,
356
- props.enableLocalPersistence,
357
- assetPaths,
358
- props.public,
359
- ]);
360
- return { inspectorUrl };
361
- }
362
-
363
- function useTmpDir(): string | undefined {
364
- const [directory, setDirectory] = useState<DirectoryResult>();
365
- const handleError = useErrorHandler();
366
- useEffect(() => {
367
- let dir: DirectoryResult;
368
- async function create() {
369
- try {
370
- dir = await tmp.dir({ unsafeCleanup: true });
371
- setDirectory(dir);
372
- return;
373
- } catch (err) {
374
- console.error("failed to create tmp dir");
375
- throw err;
376
- }
377
- }
378
- create().catch((err) => {
379
- // we want to break here
380
- // we can't do much without a temp dir anyway
381
- handleError(err);
382
- });
383
- return () => {
384
- dir.cleanup().catch(() => {
385
- // extremely unlikely,
386
- // but it's 2022 after all
387
- console.error("failed to cleanup tmp dir");
388
- });
389
- };
390
- }, [handleError]);
391
- return directory?.path;
392
- }
393
-
394
- function useCustomBuild(
395
- expectedEntry: string,
396
- props: {
397
- command?: undefined | string;
398
- cwd?: undefined | string;
399
- watch_dir?: undefined | string;
400
- }
401
- ): undefined | string {
402
- const [entry, setEntry] = useState<string | undefined>(
403
- // if there's no build command, just return the expected entry
404
- props.command || expectedEntry
405
- );
406
- const { command, cwd, watch_dir } = props;
407
- useEffect(() => {
408
- if (!command) return;
409
- let cmd, interval;
410
- console.log("running:", command);
411
- cmd = execaCommand(command, {
412
- ...(cwd && { cwd }),
413
- shell: true,
414
- stderr: "inherit",
415
- stdout: "inherit",
416
- });
417
- if (watch_dir) {
418
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
419
- "all",
420
- (_event, filePath) => {
421
- console.log(`The file ${filePath} changed, restarting build...`);
422
- cmd.kill();
423
- cmd = execaCommand(command, {
424
- ...(cwd && { cwd }),
425
- shell: true,
426
- stderr: "inherit",
427
- stdout: "inherit",
428
- });
429
- }
430
- );
431
- }
432
-
433
- // check every so often whether `expectedEntry` exists
434
- // if it does, we're done
435
- const startedAt = Date.now();
436
- interval = setInterval(() => {
437
- if (existsSync(expectedEntry)) {
438
- clearInterval(interval);
439
- setEntry(expectedEntry);
440
- } else {
441
- const elapsed = Date.now() - startedAt;
442
- // timeout after 30 seconds of waiting
443
- if (elapsed > 1000 * 60 * 30) {
444
- console.error("⎔ Build timed out.");
445
- clearInterval(interval);
446
- cmd.kill();
447
- }
448
- }
449
- }, 200);
450
- // TODO: we could probably timeout here after a while
451
-
452
- return () => {
453
- if (cmd) {
454
- cmd.kill();
455
- cmd = undefined;
456
- }
457
- clearInterval(interval);
458
- interval = undefined;
459
- };
460
- }, [command, cwd, expectedEntry, watch_dir]);
461
- return entry;
462
- }
463
-
464
- type EsbuildBundle = {
465
- id: number;
466
- path: string;
467
- entry: string;
468
- type: "esm" | "commonjs";
469
- exports: string[];
470
- modules: CfModule[];
471
- };
472
-
473
- function useEsbuild(props: {
474
- entry: undefined | string;
475
- destination: string | undefined;
476
- staticRoot: undefined | string;
477
- jsxFactory: string | undefined;
478
- jsxFragment: string | undefined;
479
- }): EsbuildBundle | undefined {
480
- const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
481
- const [bundle, setBundle] = useState<EsbuildBundle>();
482
- useEffect(() => {
483
- let result: esbuild.BuildResult | undefined;
484
- async function build() {
485
- if (!destination || !entry) return;
486
- const moduleCollector = makeModuleCollector();
487
- result = await esbuild.build({
488
- entryPoints: [entry],
489
- bundle: true,
490
- outdir: destination,
491
- metafile: true,
492
- format: "esm",
493
- sourcemap: true,
494
- loader: {
495
- ".js": "jsx",
496
- ".html": "text",
497
- ".pem": "text",
498
- ".txt": "text",
499
- },
500
- ...(jsxFactory && { jsxFactory }),
501
- ...(jsxFragment && { jsxFragment }),
502
- external: ["__STATIC_CONTENT_MANIFEST"],
503
- conditions: ["worker", "browser"],
504
- plugins: [moduleCollector.plugin],
505
- // TODO: import.meta.url
506
- watch: {
507
- async onRebuild(error) {
508
- if (error) console.error("watch build failed:", error);
509
- else {
510
- // nothing really changes here, so let's increment the id
511
- // to change the return object's identity
512
- setBundle((previousBundle) => {
513
- if (previousBundle === undefined) {
514
- assert.fail(
515
- "Rebuild triggered with no previous build available"
516
- );
517
- }
518
- return { ...previousBundle, id: previousBundle.id + 1 };
519
- });
520
- }
521
- },
522
- },
523
- });
524
-
525
- // result.metafile is defined because of the `metafile: true` option above.
526
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
527
- const metafile = result.metafile!;
528
- const outputEntry = Object.entries(metafile.outputs).find(
529
- ([_path, { entryPoint }]) => entryPoint === entry
530
- ); // assumedly only one entry point
531
-
532
- if (outputEntry === undefined) {
533
- throw new Error(
534
- `Cannot find entry-point "${entry}" in generated bundle.`
535
- );
536
- }
537
- setBundle({
538
- id: 0,
539
- entry,
540
- path: outputEntry[0],
541
- type: outputEntry[1].exports.length > 0 ? "esm" : "commonjs",
542
- exports: outputEntry[1].exports,
543
- modules: moduleCollector.modules,
544
- });
545
- }
546
- build().catch((_err) => {
547
- // esbuild already logs errors to stderr
548
- // and we don't want to end the process
549
- // on build errors anyway
550
- // so this is a no-op error handler
551
- });
552
- return () => {
553
- result?.stop?.();
554
- };
555
- }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
556
- return bundle;
557
- }
558
-
559
- function useWorker(props: {
560
- name: undefined | string;
561
- bundle: EsbuildBundle | undefined;
562
- format: CfScriptFormat;
563
- modules: CfModule[];
564
- accountId: string;
565
- apiToken: string;
566
- bindings: CfWorkerInit["bindings"];
567
- assetPaths: undefined | AssetPaths;
568
- port: number;
569
- compatibilityDate: string | undefined;
570
- compatibilityFlags: string[] | undefined;
571
- usageModel: undefined | "bundled" | "unbound";
572
- env: string | undefined;
573
- }): CfPreviewToken | undefined {
574
- const {
575
- name,
576
- bundle,
577
- format,
578
- modules,
579
- accountId,
580
- apiToken,
581
- bindings,
582
- assetPaths,
583
- compatibilityDate,
584
- compatibilityFlags,
585
- usageModel,
586
- port,
587
- } = props;
588
- const [token, setToken] = useState<CfPreviewToken | undefined>();
589
-
590
- // This is the most reliable way to detect whether
591
- // something's "happened" in our system; We make a ref and
592
- // mark it once we log our initial message. Refs are vars!
593
- const startedRef = useRef(false);
594
-
595
- useEffect(() => {
596
- async function start() {
597
- setToken(undefined); // reset token in case we're re-running
598
-
599
- if (!bundle) return;
600
- if (format === "modules" && bundle.type === "commonjs") {
601
- console.error("⎔ Cannot use modules with a commonjs bundle.");
602
- // TODO: a much better error message here, with what to do next
603
- return;
604
- }
605
- if (format === "service-worker" && bundle.type !== "esm") {
606
- console.error("⎔ Cannot use service-worker with a esm bundle.");
607
- // TODO: a much better error message here, with what to do next
608
- return;
609
- }
610
-
611
- if (!startedRef.current) {
612
- startedRef.current = true;
613
- } else {
614
- console.log("⎔ Detected changes, restarted server.");
615
- }
616
-
617
- const assets = await syncAssets(
618
- accountId,
619
- name || path.basename(bundle.path),
620
- assetPaths,
621
- true,
622
- props.env
623
- ); // TODO: cancellable?
624
-
625
- const workerType = format || bundle.type === "esm" ? "esm" : "commonjs";
626
- let content = await readFile(bundle.path, "utf-8");
627
- if (workerType !== "esm" && assets.manifest) {
628
- content = `const __STATIC_CONTENT_MANIFEST = ${JSON.stringify(
629
- assets.manifest
630
- )};\n${content}`;
631
- }
632
-
633
- const init: CfWorkerInit = {
634
- name,
635
- main: {
636
- name: path.basename(bundle.path),
637
- type: workerType,
638
- content,
639
- },
640
- modules: modules.concat(
641
- assets.manifest && workerType === "esm"
642
- ? {
643
- name: "__STATIC_CONTENT_MANIFEST",
644
- content: JSON.stringify(assets.manifest),
645
- type: "text",
646
- }
647
- : []
648
- ),
649
- bindings: {
650
- ...bindings,
651
- kv_namespaces: (bindings.kv_namespaces || []).concat(
652
- assets.namespace
653
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
654
- : []
655
- ),
656
- },
657
- migrations: undefined, // no migrations in dev
658
- compatibility_date: compatibilityDate,
659
- compatibility_flags: compatibilityFlags,
660
- usage_model: usageModel,
661
- };
662
- setToken(
663
- await createWorker(init, {
664
- accountId,
665
- apiToken,
666
- })
667
- );
668
- }
669
- start().catch((err) => {
670
- // we want to log the error, but not end the process
671
- // since it could recover after the developer fixes whatever's wrong
672
- console.error("remote worker:", err);
673
- });
674
- }, [
675
- name,
676
- bundle,
677
- format,
678
- accountId,
679
- apiToken,
680
- port,
681
- assetPaths,
682
- compatibilityDate,
683
- compatibilityFlags,
684
- usageModel,
685
- bindings,
686
- modules,
687
- props.env,
688
- ]);
689
- return token;
690
- }
691
-
692
- function sleep(period: number) {
693
- return new Promise((resolve) => setTimeout(resolve, period));
694
- }
695
- const SLEEP_DURATION = 2000;
696
- // really need a first class api for this
697
- const hostNameRegex = /userHostname="(.*)"/g;
698
- async function findTunnelHostname() {
699
- let hostName: string | undefined;
700
- while (!hostName) {
701
- try {
702
- const resp = await fetch("http://localhost:8789/metrics");
703
- const data = await resp.text();
704
- const matches = Array.from(data.matchAll(hostNameRegex));
705
- hostName = matches[0][1];
706
- } catch (err) {
707
- await sleep(SLEEP_DURATION);
708
- }
709
- }
710
- return hostName;
711
- }
712
-
713
- function useTunnel(toggle: boolean) {
714
- const tunnel = useRef<ReturnType<typeof spawn>>();
715
- const removeSignalExitListener = useRef<() => void>();
716
- // TODO: test if cloudflared is available, if not
717
- // point them to a url where they can get docs to install it
718
- useEffect(() => {
719
- async function startTunnel() {
720
- if (toggle) {
721
- try {
722
- await commandExists("cloudflared");
723
- } catch (e) {
724
- console.error(
725
- "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
726
- );
727
- return;
728
- }
729
- console.log("⎔ Starting a tunnel...");
730
- tunnel.current = spawn("cloudflared", [
731
- "tunnel",
732
- "--url",
733
- "http://localhost:8787",
734
- "--metrics",
735
- "localhost:8789",
736
- ]);
737
-
738
- tunnel.current.on("close", (code) => {
739
- if (code !== 0) {
740
- console.log(`Tunnel process exited with code ${code}`);
741
- }
742
- });
743
-
744
- removeSignalExitListener.current = onExit((_code, _signal) => {
745
- console.log("⎔ Shutting down local tunnel.");
746
- tunnel.current?.kill();
747
- tunnel.current = undefined;
748
- });
749
-
750
- const hostName = await findTunnelHostname();
751
- await clipboardy.write(hostName);
752
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
753
- }
754
- }
755
-
756
- startTunnel().catch((err) => {
757
- console.error("tunnel:", err);
758
- });
759
-
760
- return () => {
761
- if (tunnel.current) {
762
- console.log("⎔ Shutting down tunnel.");
763
- tunnel.current?.kill();
764
- tunnel.current = undefined;
765
- removeSignalExitListener.current && removeSignalExitListener.current();
766
- removeSignalExitListener.current = undefined;
767
- }
768
- };
769
- }, [toggle]);
770
- }
771
-
772
- type useHotkeysInitialState = {
773
- local: boolean;
774
- tunnel: boolean;
775
- };
776
- function useHotkeys(initial: useHotkeysInitialState, port: number) {
777
- // UGH, we should put port in context instead
778
- const [toggles, setToggles] = useState(initial);
779
- useInput(
780
- async (
781
- input,
782
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
783
- key
784
- ) => {
785
- switch (input) {
786
- case "b": // open browser
787
- await open(`http://localhost:${port}/`);
788
- break;
789
- case "d": // toggle inspector
790
- await open(
791
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
792
- );
793
- break;
794
- case "s": // toggle tunnel
795
- setToggles((previousToggles) => ({
796
- ...previousToggles,
797
- tunnel: !previousToggles.tunnel,
798
- }));
799
- break;
800
- case "l": // toggle local
801
- setToggles((previousToggles) => ({
802
- ...previousToggles,
803
- local: !previousToggles.local,
804
- }));
805
- break;
806
- case "q": // shut down
807
- case "x": // shut down
808
- process.exit(0);
809
- break;
810
- default:
811
- // nothing?
812
- break;
813
- }
814
- }
815
- );
816
- return toggles;
817
- }
818
-
819
- function ErrorFallback(props: { error: Error }) {
820
- const { exit } = useApp();
821
- useEffect(() => exit(new Error()));
822
- return (
823
- <>
824
- <Text>Something went wrong:</Text>
825
- <Text>{props.error.stack}</Text>
826
- </>
827
- );
828
- }
829
-
830
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });