wrangler 0.0.0-e5d3690 → 0.0.0-e60a675d

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