wrangler 0.0.0-e9a1820 → 0.0.0-e9c2b04a

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