wrangler 0.0.0-e043479 → 0.0.0-e0b9366

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 (51) hide show
  1. package/package.json +10 -4
  2. package/pages/functions/filepath-routing.test.ts +125 -25
  3. package/pages/functions/filepath-routing.ts +6 -3
  4. package/src/__tests__/configuration.test.ts +479 -114
  5. package/src/__tests__/dev.test.tsx +162 -8
  6. package/src/__tests__/dev2.test.tsx +152 -0
  7. package/src/__tests__/guess-worker-format.test.ts +9 -17
  8. package/src/__tests__/helpers/mock-account-id.ts +4 -0
  9. package/src/__tests__/helpers/mock-cfetch.ts +3 -3
  10. package/src/__tests__/helpers/mock-kv.ts +9 -16
  11. package/src/__tests__/helpers/run-in-tmp.ts +3 -0
  12. package/src/__tests__/https-options.test.ts +127 -0
  13. package/src/__tests__/index.test.ts +125 -0
  14. package/src/__tests__/jest.setup.ts +1 -1
  15. package/src/__tests__/kv.test.ts +27 -53
  16. package/src/__tests__/logout.test.ts +15 -13
  17. package/src/__tests__/pages.test.ts +44 -0
  18. package/src/__tests__/publish.test.ts +504 -32
  19. package/src/__tests__/route.test.ts +45 -0
  20. package/src/__tests__/whoami.test.tsx +21 -7
  21. package/src/bundle.ts +20 -11
  22. package/src/cfetch/internal.ts +11 -5
  23. package/src/config/config.ts +53 -44
  24. package/src/config/validation-helpers.ts +110 -12
  25. package/src/config/validation.ts +59 -41
  26. package/src/{api/preview.ts → create-worker-preview.ts} +23 -4
  27. package/src/{api/form_data.ts → create-worker-upload-form.ts} +1 -1
  28. package/src/dev/dev.tsx +357 -0
  29. package/src/dev/local.tsx +241 -0
  30. package/src/dev/remote.tsx +201 -0
  31. package/src/dev/use-esbuild.ts +100 -0
  32. package/src/entry.ts +111 -9
  33. package/src/https-options.ts +122 -0
  34. package/src/index.tsx +171 -109
  35. package/src/inspect.ts +9 -1
  36. package/src/{kv.tsx → kv.ts} +0 -0
  37. package/src/module-collection.ts +85 -2
  38. package/src/open-in-browser.ts +14 -2
  39. package/src/pages.tsx +1 -1
  40. package/src/proxy.ts +102 -40
  41. package/src/publish.ts +41 -50
  42. package/src/reporting.ts +25 -9
  43. package/src/selfsigned.d.ts +29 -0
  44. package/src/sites.tsx +51 -16
  45. package/src/user.tsx +132 -77
  46. package/src/{api/worker.ts → worker.ts} +0 -23
  47. package/wrangler-dist/cli.js +5012 -3107
  48. package/wrangler-dist/cli.js.map +3 -3
  49. package/src/__tests__/helpers/mock-user.ts +0 -27
  50. package/src/dev.tsx +0 -960
  51. package/src/guess-worker-format.ts +0 -68
package/src/dev.tsx DELETED
@@ -1,960 +0,0 @@
1
- import assert from "node:assert";
2
- import { spawn } from "node:child_process";
3
- import { existsSync, realpathSync } from "node:fs";
4
- import { readFile, writeFile } from "node:fs/promises";
5
- import path from "node:path";
6
- import { watch } from "chokidar";
7
- import clipboardy from "clipboardy";
8
- import commandExists from "command-exists";
9
- import { execaCommand } from "execa";
10
- import { Box, Text, useApp, useInput } from "ink";
11
- import React, { useState, useEffect, useRef } from "react";
12
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
13
- import onExit from "signal-exit";
14
- import tmp from "tmp-promise";
15
- import { fetch } from "undici";
16
- import { createWorker } from "./api/worker";
17
- import { bundleWorker } from "./bundle";
18
- import guessWorkerFormat from "./guess-worker-format";
19
- import useInspector from "./inspect";
20
- import { DEFAULT_MODULE_RULES } from "./module-collection";
21
- import openInBrowser from "./open-in-browser";
22
- import { usePreviewServer, waitForPortToBeAvailable } from "./proxy";
23
- import { syncAssets } from "./sites";
24
- import { getAPIToken } from "./user";
25
- import type { CfPreviewToken } from "./api/preview";
26
- import type { CfModule, CfWorkerInit, CfScriptFormat } from "./api/worker";
27
- import type { Config } from "./config";
28
- import type { Entry } from "./entry";
29
- import type { AssetPaths } from "./sites";
30
- import type { WatchMode } from "esbuild";
31
- import type { ExecaChildProcess } from "execa";
32
- import type { DirectoryResult } from "tmp-promise";
33
-
34
- export type DevProps = {
35
- name?: string;
36
- entry: Entry;
37
- port?: number;
38
- inspectorPort: number;
39
- format: CfScriptFormat | undefined;
40
- rules: Config["rules"];
41
- accountId: undefined | string;
42
- initialMode: "local" | "remote";
43
- jsxFactory: undefined | string;
44
- jsxFragment: undefined | string;
45
- enableLocalPersistence: boolean;
46
- bindings: CfWorkerInit["bindings"];
47
- public: undefined | string;
48
- assetPaths: undefined | AssetPaths;
49
- compatibilityDate: undefined | string;
50
- compatibilityFlags: undefined | string[];
51
- usageModel: undefined | "bundled" | "unbound";
52
- buildCommand: {
53
- command?: undefined | string;
54
- cwd?: undefined | string;
55
- watch_dir?: undefined | string;
56
- };
57
- env: string | undefined;
58
- legacyEnv: boolean;
59
- zone:
60
- | {
61
- id: string;
62
- host: string;
63
- }
64
- | undefined;
65
- };
66
-
67
- function Dev(props: DevProps): JSX.Element {
68
- const port = props.port ?? 8787;
69
- const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
70
- const directory = useTmpDir();
71
-
72
- // if there isn't a build command, we just return the entry immediately
73
- // ideally there would be a conditional here, but the rules of hooks
74
- // kinda forbid that, so we thread the entry through useCustomBuild
75
- const entry = useCustomBuild(props.entry, props.buildCommand);
76
-
77
- const format = useWorkerFormat({ entry: props.entry, format: props.format });
78
- if (format && props.public && format === "service-worker") {
79
- throw new Error(
80
- "You cannot use the service worker format with a `public` directory."
81
- );
82
- }
83
-
84
- if (props.bindings.wasm_modules && format === "modules") {
85
- throw new Error(
86
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
87
- );
88
- }
89
-
90
- if (props.bindings.text_blobs && format === "modules") {
91
- throw new Error(
92
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
93
- );
94
- }
95
-
96
- const bundle = useEsbuild({
97
- entry,
98
- format,
99
- destination: directory,
100
- staticRoot: props.public,
101
- jsxFactory: props.jsxFactory,
102
- rules: props.rules,
103
- jsxFragment: props.jsxFragment,
104
- serveAssetsFromWorker: !!props.public,
105
- });
106
-
107
- const toggles = useHotkeys(
108
- {
109
- local: props.initialMode === "local",
110
- tunnel: false,
111
- },
112
- port,
113
- props.inspectorPort
114
- );
115
-
116
- useTunnel(toggles.tunnel);
117
-
118
- return (
119
- <>
120
- {toggles.local ? (
121
- <Local
122
- name={props.name}
123
- bundle={bundle}
124
- format={format}
125
- bindings={props.bindings}
126
- assetPaths={props.assetPaths}
127
- public={props.public}
128
- port={port}
129
- rules={props.rules}
130
- inspectorPort={props.inspectorPort}
131
- enableLocalPersistence={props.enableLocalPersistence}
132
- />
133
- ) : (
134
- <Remote
135
- name={props.name}
136
- bundle={bundle}
137
- format={format}
138
- accountId={props.accountId}
139
- apiToken={apiToken}
140
- bindings={props.bindings}
141
- assetPaths={props.assetPaths}
142
- public={props.public}
143
- port={port}
144
- inspectorPort={props.inspectorPort}
145
- compatibilityDate={props.compatibilityDate}
146
- compatibilityFlags={props.compatibilityFlags}
147
- usageModel={props.usageModel}
148
- env={props.env}
149
- legacyEnv={props.legacyEnv}
150
- zone={props.zone}
151
- />
152
- )}
153
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
154
- <Text>
155
- {`B to open a browser, D to open Devtools, L to ${
156
- toggles.local ? "turn off" : "turn on"
157
- } local mode, X to exit`}
158
- </Text>
159
- </Box>
160
- </>
161
- );
162
- }
163
-
164
- function useWorkerFormat(props: {
165
- entry: Entry | undefined;
166
- format: undefined | CfScriptFormat;
167
- }): CfScriptFormat | undefined {
168
- const [format, setFormat] = useState<CfScriptFormat | undefined>();
169
- useEffect(() => {
170
- async function validateFormat() {
171
- if (!props.entry || format) {
172
- return;
173
- }
174
- setFormat(await guessWorkerFormat(props.entry, props.format));
175
- }
176
- validateFormat().catch((err) => {
177
- console.error("Failed to validate worker format:", err);
178
- });
179
- }, [props.entry, props.format, format]);
180
- return format;
181
- }
182
-
183
- function Remote(props: {
184
- name: string | undefined;
185
- bundle: EsbuildBundle | undefined;
186
- format: CfScriptFormat | undefined;
187
- public: undefined | string;
188
- assetPaths: undefined | AssetPaths;
189
- port: number;
190
- inspectorPort: number;
191
- accountId: undefined | string;
192
- apiToken: undefined | string;
193
- bindings: CfWorkerInit["bindings"];
194
- compatibilityDate: string | undefined;
195
- compatibilityFlags: undefined | string[];
196
- usageModel: undefined | "bundled" | "unbound";
197
- env: string | undefined;
198
- legacyEnv: boolean | undefined;
199
- zone: { id: string; host: string } | undefined;
200
- }) {
201
- assert(props.accountId, "accountId is required");
202
- assert(props.apiToken, "apiToken is required");
203
- const previewToken = useWorker({
204
- name: props.name,
205
- bundle: props.bundle,
206
- format: props.format,
207
- modules: props.bundle ? props.bundle.modules : [],
208
- accountId: props.accountId,
209
- apiToken: props.apiToken,
210
- bindings: props.bindings,
211
- assetPaths: props.assetPaths,
212
- port: props.port,
213
- compatibilityDate: props.compatibilityDate,
214
- compatibilityFlags: props.compatibilityFlags,
215
- usageModel: props.usageModel,
216
- env: props.env,
217
- legacyEnv: props.legacyEnv,
218
- zone: props.zone,
219
- });
220
-
221
- usePreviewServer({
222
- previewToken,
223
- publicRoot: props.public,
224
- port: props.port,
225
- });
226
-
227
- useInspector({
228
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
229
- port: props.inspectorPort,
230
- logToTerminal: true,
231
- });
232
- return null;
233
- }
234
- function Local(props: {
235
- name: undefined | string;
236
- bundle: EsbuildBundle | undefined;
237
- format: CfScriptFormat | undefined;
238
- bindings: CfWorkerInit["bindings"];
239
- assetPaths: undefined | AssetPaths;
240
- public: undefined | string;
241
- port: number;
242
- rules: Config["rules"];
243
- inspectorPort: number;
244
- enableLocalPersistence: boolean;
245
- }) {
246
- const { inspectorUrl } = useLocalWorker({
247
- name: props.name,
248
- bundle: props.bundle,
249
- format: props.format,
250
- bindings: props.bindings,
251
- assetPaths: props.assetPaths,
252
- public: props.public,
253
- port: props.port,
254
- rules: props.rules,
255
- inspectorPort: props.port,
256
- enableLocalPersistence: props.enableLocalPersistence,
257
- });
258
- useInspector({
259
- inspectorUrl,
260
- port: props.inspectorPort,
261
- logToTerminal: false,
262
- });
263
- return null;
264
- }
265
-
266
- function useLocalWorker(props: {
267
- name: undefined | string;
268
- bundle: EsbuildBundle | undefined;
269
- rules: Config["rules"];
270
- format: CfScriptFormat | undefined;
271
- bindings: CfWorkerInit["bindings"];
272
- assetPaths: undefined | AssetPaths;
273
- public: undefined | string;
274
- port: number;
275
- inspectorPort: number;
276
- enableLocalPersistence: boolean;
277
- }) {
278
- // TODO: pass vars via command line
279
- const { bundle, format, bindings, port, assetPaths, inspectorPort } = props;
280
- const local = useRef<ReturnType<typeof spawn>>();
281
- const removeSignalExitListener = useRef<() => void>();
282
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
283
- useEffect(() => {
284
- async function startLocalWorker() {
285
- if (!bundle || !format) return;
286
-
287
- // port for the worker
288
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
289
- // port for inspector
290
- await waitForPortToBeAvailable(inspectorPort, {
291
- retryPeriod: 200,
292
- timeout: 2000,
293
- });
294
-
295
- if (props.public) {
296
- throw new Error(
297
- '⎔ A "public" folder is not yet supported in local mode.'
298
- );
299
- }
300
-
301
- // In local mode, we want to copy all referenced modules into
302
- // the output bundle directory before starting up
303
- for (const module of bundle.modules) {
304
- await writeFile(
305
- path.join(path.dirname(bundle.path), module.name),
306
- module.content
307
- );
308
- }
309
-
310
- console.log("⎔ Starting a local server...");
311
- // TODO: just use execa for this
312
- local.current = spawn(
313
- "node",
314
- [
315
- "--experimental-vm-modules",
316
- "--inspect",
317
- require.resolve("miniflare/cli"),
318
- realpathSync(bundle.path),
319
- "--watch",
320
- "--wrangler-config",
321
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
322
- "--env",
323
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
324
- "--package",
325
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
326
- "--port",
327
- port.toString(),
328
- ...(assetPaths
329
- ? [
330
- "--site",
331
- path.join(process.cwd(), assetPaths.baseDirectory),
332
- ...assetPaths.includePatterns.map((pattern) => [
333
- "--site-include",
334
- pattern,
335
- ]),
336
- ...assetPaths.excludePatterns.map((pattern) => [
337
- "--site-exclude",
338
- pattern,
339
- ]),
340
- ].flatMap((x) => x)
341
- : []),
342
- ...(props.enableLocalPersistence
343
- ? ["--kv-persist", "--cache-persist", "--do-persist"]
344
- : []),
345
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
346
- return ["--binding", `${key}=${value}`];
347
- }),
348
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
349
- return ["--kv", binding];
350
- }),
351
- ...(bindings.durable_objects?.bindings || []).flatMap(
352
- ({ name, class_name }) => {
353
- return ["--do", `${name}=${class_name}`];
354
- }
355
- ),
356
- ...Object.entries(bindings.wasm_modules || {}).flatMap(
357
- ([name, filePath]) => {
358
- return [
359
- "--wasm",
360
- `${name}=${path.join(process.cwd(), filePath)}`,
361
- ];
362
- }
363
- ),
364
- ...bundle.modules.reduce<string[]>((cmd, { name, type }) => {
365
- if (format === "service-worker") {
366
- if (type === "compiled-wasm") {
367
- // In service-worker format, .wasm modules are referenced
368
- // by global identifiers, so we convert it here.
369
- // This identifier has to be a valid JS identifier,
370
- // so we replace all non alphanumeric characters
371
- // with an underscore.
372
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
373
- return cmd.concat([`--wasm`, `${identifier}=${name}`]);
374
- } else {
375
- // TODO: we should actually support this
376
- throw new Error(
377
- `⎔ Unsupported module type ${type} for file ${name} in service-worker format`
378
- );
379
- }
380
- }
381
- return cmd;
382
- }, []),
383
- "--modules",
384
- String(format === "modules"),
385
- ...(props.rules || [])
386
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
387
- .concat(DEFAULT_MODULE_RULES!)
388
- .flatMap((rule) =>
389
- rule.globs.flatMap((glob) => [
390
- "--modules-rule",
391
- `${rule.type}=${glob}`,
392
- ])
393
- ),
394
- ],
395
- {
396
- cwd: path.dirname(realpathSync(bundle.path)),
397
- }
398
- );
399
- console.log(`⬣ Listening at http://localhost:${port}`);
400
-
401
- local.current.on("close", (code) => {
402
- if (code !== null) {
403
- console.log(`miniflare process exited with code ${code}`);
404
- }
405
- });
406
-
407
- local.current.stdout?.on("data", (data: Buffer) => {
408
- console.log(`${data.toString()}`);
409
- });
410
-
411
- local.current.stderr?.on("data", (data: Buffer) => {
412
- console.error(`${data.toString()}`);
413
- const matches =
414
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
415
- data.toString()
416
- );
417
- if (matches) {
418
- setInspectorUrl(matches[1]);
419
- }
420
- });
421
-
422
- local.current.on("exit", (code) => {
423
- if (code !== 0) {
424
- console.error(`miniflare process exited with code ${code}`);
425
- }
426
- });
427
-
428
- local.current.on("error", (error: Error) => {
429
- console.error(`miniflare process failed to spawn`);
430
- console.error(error);
431
- });
432
-
433
- removeSignalExitListener.current = onExit((_code, _signal) => {
434
- console.log("⎔ Shutting down local server.");
435
- local.current?.kill();
436
- local.current = undefined;
437
- });
438
- }
439
-
440
- startLocalWorker().catch((err) => {
441
- console.error("local worker:", err);
442
- });
443
-
444
- return () => {
445
- if (local.current) {
446
- console.log("⎔ Shutting down local server.");
447
- local.current?.kill();
448
- local.current = undefined;
449
- removeSignalExitListener.current && removeSignalExitListener.current();
450
- removeSignalExitListener.current = undefined;
451
- }
452
- };
453
- }, [
454
- bundle,
455
- format,
456
- port,
457
- inspectorPort,
458
- bindings.durable_objects?.bindings,
459
- bindings.kv_namespaces,
460
- bindings.vars,
461
- props.enableLocalPersistence,
462
- assetPaths,
463
- props.public,
464
- props.rules,
465
- bindings.wasm_modules,
466
- ]);
467
- return { inspectorUrl };
468
- }
469
-
470
- function useTmpDir(): string | undefined {
471
- const [directory, setDirectory] = useState<DirectoryResult>();
472
- const handleError = useErrorHandler();
473
- useEffect(() => {
474
- let dir: DirectoryResult;
475
- async function create() {
476
- try {
477
- dir = await tmp.dir({ unsafeCleanup: true });
478
- setDirectory(dir);
479
- return;
480
- } catch (err) {
481
- console.error("failed to create tmp dir");
482
- throw err;
483
- }
484
- }
485
- create().catch((err) => {
486
- // we want to break here
487
- // we can't do much without a temp dir anyway
488
- handleError(err);
489
- });
490
- return () => {
491
- dir.cleanup().catch(() => {
492
- // extremely unlikely,
493
- // but it's 2022 after all
494
- console.error("failed to cleanup tmp dir");
495
- });
496
- };
497
- }, [handleError]);
498
- return directory?.path;
499
- }
500
-
501
- function useCustomBuild(
502
- expectedEntry: Entry,
503
- props: {
504
- command?: undefined | string;
505
- cwd?: undefined | string;
506
- watch_dir?: undefined | string;
507
- }
508
- ): undefined | Entry {
509
- const [entry, setEntry] = useState<Entry | undefined>(
510
- // if there's no build command, just return the expected entry
511
- !props.command ? expectedEntry : undefined
512
- );
513
- const { command, cwd, watch_dir } = props;
514
- useEffect(() => {
515
- if (!command) return;
516
- let cmd: ExecaChildProcess<string> | undefined,
517
- interval: NodeJS.Timeout | undefined;
518
- console.log("running:", command);
519
- cmd = execaCommand(command, {
520
- ...(cwd && { cwd }),
521
- shell: true,
522
- stderr: "inherit",
523
- stdout: "inherit",
524
- });
525
- if (watch_dir) {
526
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
527
- "all",
528
- (_event, filePath) => {
529
- console.log(`The file ${filePath} changed, restarting build...`);
530
- cmd?.kill();
531
- cmd = execaCommand(command, {
532
- ...(cwd && { cwd }),
533
- shell: true,
534
- stderr: "inherit",
535
- stdout: "inherit",
536
- });
537
- }
538
- );
539
- }
540
-
541
- // check every so often whether `expectedEntry` exists
542
- // if it does, we're done
543
- const startedAt = Date.now();
544
- interval = setInterval(() => {
545
- let fileExists = false;
546
- try {
547
- // Use require.resolve to use node's resolution algorithm,
548
- // this lets us use paths without explicit .js extension
549
- // TODO: we should probably remove this, because it doesn't
550
- // take into consideration other extensions like .tsx, .ts, .jsx, etc
551
- fileExists = existsSync(require.resolve(expectedEntry.file));
552
- } catch (e) {
553
- // fail silently, usually means require.resolve threw MODULE_NOT_FOUND
554
- }
555
-
556
- if (fileExists === true) {
557
- interval && clearInterval(interval);
558
- setEntry(expectedEntry);
559
- } else {
560
- const elapsed = Date.now() - startedAt;
561
- // timeout after 30 seconds of waiting
562
- if (elapsed > 1000 * 30) {
563
- console.error(
564
- `⎔ Build timed out, Could not resolve ${expectedEntry.file}`
565
- );
566
- interval && clearInterval(interval);
567
- cmd?.kill();
568
- }
569
- }
570
- }, 200);
571
-
572
- return () => {
573
- if (cmd) {
574
- cmd.kill();
575
- cmd = undefined;
576
- }
577
- interval && clearInterval(interval);
578
- interval = undefined;
579
- };
580
- }, [command, cwd, expectedEntry, watch_dir]);
581
- return entry;
582
- }
583
-
584
- type EsbuildBundle = {
585
- id: number;
586
- path: string;
587
- entry: Entry;
588
- type: "esm" | "commonjs";
589
- modules: CfModule[];
590
- serveAssetsFromWorker: boolean;
591
- };
592
-
593
- function useEsbuild({
594
- entry,
595
- destination,
596
- staticRoot,
597
- jsxFactory,
598
- jsxFragment,
599
- format,
600
- rules,
601
- serveAssetsFromWorker,
602
- }: {
603
- entry: undefined | Entry;
604
- destination: string | undefined;
605
- format: CfScriptFormat | undefined;
606
- staticRoot: undefined | string;
607
- jsxFactory: string | undefined;
608
- jsxFragment: string | undefined;
609
- rules: Config["rules"];
610
- serveAssetsFromWorker: boolean;
611
- }): EsbuildBundle | undefined {
612
- const [bundle, setBundle] = useState<EsbuildBundle>();
613
- useEffect(() => {
614
- let stopWatching: (() => void) | undefined = undefined;
615
-
616
- const watchMode: WatchMode = {
617
- async onRebuild(error) {
618
- if (error) console.error("watch build failed:", error);
619
- else {
620
- // nothing really changes here, so let's increment the id
621
- // to change the return object's identity
622
- setBundle((previousBundle) => {
623
- assert(
624
- previousBundle,
625
- "Rebuild triggered with no previous build available"
626
- );
627
- return { ...previousBundle, id: previousBundle.id + 1 };
628
- });
629
- }
630
- },
631
- };
632
-
633
- async function build() {
634
- if (!destination || !entry || !format) return;
635
-
636
- const { resolvedEntryPointPath, bundleType, modules, stop } =
637
- await bundleWorker(entry, destination, {
638
- // In dev, we serve assets from the local proxy before we send the request to the worker.
639
- serveAssetsFromWorker: false,
640
- jsxFactory,
641
- jsxFragment,
642
- format,
643
- rules,
644
- watch: watchMode,
645
- });
646
-
647
- // Capture the `stop()` method to use as the `useEffect()` destructor.
648
- stopWatching = stop;
649
-
650
- setBundle({
651
- id: 0,
652
- entry,
653
- path: resolvedEntryPointPath,
654
- type: bundleType,
655
- modules,
656
- serveAssetsFromWorker,
657
- });
658
- }
659
-
660
- build().catch(() => {
661
- // esbuild already logs errors to stderr and we don't want to end the process
662
- // on build errors anyway so this is a no-op error handler
663
- });
664
-
665
- return stopWatching;
666
- }, [
667
- entry,
668
- destination,
669
- staticRoot,
670
- jsxFactory,
671
- jsxFragment,
672
- format,
673
- serveAssetsFromWorker,
674
- rules,
675
- ]);
676
- return bundle;
677
- }
678
-
679
- function useWorker(props: {
680
- name: string | undefined;
681
- bundle: EsbuildBundle | undefined;
682
- format: CfScriptFormat | undefined;
683
- modules: CfModule[];
684
- accountId: string;
685
- apiToken: string;
686
- bindings: CfWorkerInit["bindings"];
687
- assetPaths: undefined | AssetPaths;
688
- port: number;
689
- compatibilityDate: string | undefined;
690
- compatibilityFlags: string[] | undefined;
691
- usageModel: undefined | "bundled" | "unbound";
692
- env: string | undefined;
693
- legacyEnv: boolean | undefined;
694
- zone: { id: string; host: string } | undefined;
695
- }): CfPreviewToken | undefined {
696
- const {
697
- name,
698
- bundle,
699
- format,
700
- modules,
701
- accountId,
702
- apiToken,
703
- bindings,
704
- assetPaths,
705
- compatibilityDate,
706
- compatibilityFlags,
707
- usageModel,
708
- port,
709
- } = props;
710
- const [token, setToken] = useState<CfPreviewToken | undefined>();
711
-
712
- // This is the most reliable way to detect whether
713
- // something's "happened" in our system; We make a ref and
714
- // mark it once we log our initial message. Refs are vars!
715
- const startedRef = useRef(false);
716
-
717
- useEffect(() => {
718
- async function start() {
719
- setToken(undefined); // reset token in case we're re-running
720
-
721
- if (!bundle || !format) return;
722
-
723
- if (!startedRef.current) {
724
- startedRef.current = true;
725
- } else {
726
- console.log("⎔ Detected changes, restarted server.");
727
- }
728
-
729
- const assets = await syncAssets(
730
- accountId,
731
- // When we're using the newer service environments, we wouldn't
732
- // have added the env name on to the script name. However, we must
733
- // include it in the kv namespace name regardless (since there's no
734
- // concept of service environments for kv namespaces yet).
735
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
736
- assetPaths,
737
- true
738
- ); // TODO: cancellable?
739
-
740
- const content = await readFile(bundle.path, "utf-8");
741
-
742
- const init: CfWorkerInit = {
743
- name,
744
- main: {
745
- name: path.basename(bundle.path),
746
- type: format === "modules" ? "esm" : "commonjs",
747
- content,
748
- },
749
- modules: modules.concat(
750
- assets.manifest
751
- ? {
752
- name: "__STATIC_CONTENT_MANIFEST",
753
- content: JSON.stringify(assets.manifest),
754
- type: "text",
755
- }
756
- : []
757
- ),
758
- bindings: {
759
- ...bindings,
760
- kv_namespaces: (bindings.kv_namespaces || []).concat(
761
- assets.namespace
762
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
763
- : []
764
- ),
765
- text_blobs: {
766
- ...bindings.text_blobs,
767
- ...(assets.manifest &&
768
- format === "service-worker" && {
769
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
770
- }),
771
- },
772
- },
773
- migrations: undefined, // no migrations in dev
774
- compatibility_date: compatibilityDate,
775
- compatibility_flags: compatibilityFlags,
776
- usage_model: usageModel,
777
- };
778
- setToken(
779
- await createWorker(
780
- init,
781
- {
782
- accountId,
783
- apiToken,
784
- },
785
- { env: props.env, legacyEnv: props.legacyEnv, zone: props.zone }
786
- )
787
- );
788
- }
789
- start().catch((err) => {
790
- // we want to log the error, but not end the process
791
- // since it could recover after the developer fixes whatever's wrong
792
- console.error("remote worker:", err);
793
- });
794
- }, [
795
- name,
796
- bundle,
797
- format,
798
- accountId,
799
- apiToken,
800
- port,
801
- assetPaths,
802
- compatibilityDate,
803
- compatibilityFlags,
804
- usageModel,
805
- bindings,
806
- modules,
807
- props.env,
808
- props.legacyEnv,
809
- props.zone,
810
- ]);
811
- return token;
812
- }
813
-
814
- function sleep(period: number) {
815
- return new Promise((resolve) => setTimeout(resolve, period));
816
- }
817
- const SLEEP_DURATION = 2000;
818
- // really need a first class api for this
819
- const hostNameRegex = /userHostname="(.*)"/g;
820
- async function findTunnelHostname() {
821
- let hostName: string | undefined;
822
- while (!hostName) {
823
- try {
824
- const resp = await fetch("http://localhost:8789/metrics");
825
- const data = await resp.text();
826
- const matches = Array.from(data.matchAll(hostNameRegex));
827
- hostName = matches[0][1];
828
- } catch (err) {
829
- await sleep(SLEEP_DURATION);
830
- }
831
- }
832
- return hostName;
833
- }
834
-
835
- /**
836
- * Create a tunnel to the remote worker.
837
- * We've disabled this for now until we figure out a better user experience.
838
- */
839
- function useTunnel(toggle: boolean) {
840
- const tunnel = useRef<ReturnType<typeof spawn>>();
841
- const removeSignalExitListener = useRef<() => void>();
842
- // TODO: test if cloudflared is available, if not
843
- // point them to a url where they can get docs to install it
844
- useEffect(() => {
845
- async function startTunnel() {
846
- if (toggle) {
847
- try {
848
- await commandExists("cloudflared");
849
- } catch (e) {
850
- console.error(
851
- "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
852
- );
853
- return;
854
- }
855
- console.log("⎔ Starting a tunnel...");
856
- tunnel.current = spawn("cloudflared", [
857
- "tunnel",
858
- "--url",
859
- "http://localhost:8787",
860
- "--metrics",
861
- "localhost:8789",
862
- ]);
863
-
864
- tunnel.current.on("close", (code) => {
865
- if (code !== 0) {
866
- console.log(`Tunnel process exited with code ${code}`);
867
- }
868
- });
869
-
870
- removeSignalExitListener.current = onExit((_code, _signal) => {
871
- console.log("⎔ Shutting down local tunnel.");
872
- tunnel.current?.kill();
873
- tunnel.current = undefined;
874
- });
875
-
876
- const hostName = await findTunnelHostname();
877
- await clipboardy.write(hostName);
878
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
879
- }
880
- }
881
-
882
- startTunnel().catch((err) => {
883
- console.error("tunnel:", err);
884
- });
885
-
886
- return () => {
887
- if (tunnel.current) {
888
- console.log("⎔ Shutting down tunnel.");
889
- tunnel.current?.kill();
890
- tunnel.current = undefined;
891
- removeSignalExitListener.current && removeSignalExitListener.current();
892
- removeSignalExitListener.current = undefined;
893
- }
894
- };
895
- }, [toggle]);
896
- }
897
-
898
- type useHotkeysInitialState = {
899
- local: boolean;
900
- tunnel: boolean;
901
- };
902
- function useHotkeys(
903
- initial: useHotkeysInitialState,
904
- port: number,
905
- inspectorPort: number
906
- ) {
907
- // UGH, we should put port in context instead
908
- const [toggles, setToggles] = useState(initial);
909
- useInput(
910
- async (
911
- input,
912
- // eslint-disable-next-line unused-imports/no-unused-vars
913
- key
914
- ) => {
915
- switch (input.toLowerCase()) {
916
- // open browser
917
- case "b": {
918
- await openInBrowser(`http://localhost:${port}`);
919
- break;
920
- }
921
- // toggle inspector
922
- case "d": {
923
- await openInBrowser(
924
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`
925
- );
926
- break;
927
- }
928
- // toggle local
929
- case "l":
930
- setToggles((previousToggles) => ({
931
- ...previousToggles,
932
- local: !previousToggles.local,
933
- }));
934
- break;
935
- // shut down
936
- case "q":
937
- case "x":
938
- process.exit(0);
939
- break;
940
- default:
941
- // nothing?
942
- break;
943
- }
944
- }
945
- );
946
- return toggles;
947
- }
948
-
949
- function ErrorFallback(props: { error: Error }) {
950
- const { exit } = useApp();
951
- useEffect(() => exit(new Error()));
952
- return (
953
- <>
954
- <Text>Something went wrong:</Text>
955
- <Text>{props.error.stack}</Text>
956
- </>
957
- );
958
- }
959
-
960
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });