wrangler 0.0.0-e61907d → 0.0.0-fb0eae7

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.
package/src/dev.tsx ADDED
@@ -0,0 +1,723 @@
1
+ import esbuild from "esbuild";
2
+ import httpProxy from "http-proxy";
3
+ import { readFile } from "fs/promises";
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, CfVariable } 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 serveStatic from "serve-static";
21
+ import commandExists from "command-exists";
22
+ import assert from "assert";
23
+ import { getAPIToken } from "./user";
24
+ import fetch from "node-fetch";
25
+ import makeModuleCollector from "./module-collection";
26
+
27
+ type CfScriptFormat = void | "modules" | "service-worker";
28
+
29
+ type Props = {
30
+ name?: string;
31
+ entry: string;
32
+ port?: number;
33
+ format: CfScriptFormat;
34
+ accountId: void | string;
35
+ initialMode: "local" | "remote";
36
+ jsxFactory: void | string;
37
+ jsxFragment: void | string;
38
+ variables: { [name: string]: CfVariable };
39
+ public: void | string;
40
+ site: void | string;
41
+ compatibilityDate: void | string;
42
+ compatibilityFlags: void | string[];
43
+ usageModel: void | "bundled" | "unbound";
44
+ };
45
+
46
+ export function Dev(props: Props): JSX.Element {
47
+ if (props.public && props.format === "service-worker") {
48
+ throw new Error(
49
+ "You cannot use the service worker format with a `public` directory."
50
+ );
51
+ }
52
+ const port = props.port || 8787;
53
+ const apiToken = getAPIToken();
54
+ const directory = useTmpDir();
55
+
56
+ const bundle = useEsbuild({
57
+ entry: props.entry,
58
+ destination: directory,
59
+ staticRoot: props.public,
60
+ jsxFactory: props.jsxFactory,
61
+ jsxFragment: props.jsxFragment,
62
+ });
63
+ if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
64
+ throw new Error(
65
+ "You cannot use the service worker format with a `public` directory."
66
+ );
67
+ }
68
+
69
+ // @ts-expect-error whack
70
+ useDevtoolsRefresh(bundle?.id ?? 0);
71
+
72
+ const toggles = useHotkeys(
73
+ {
74
+ local: props.initialMode === "local",
75
+ tunnel: false,
76
+ },
77
+ port
78
+ );
79
+
80
+ useTunnel(toggles.tunnel);
81
+
82
+ return (
83
+ <>
84
+ {toggles.local ? (
85
+ <Local
86
+ name={props.name}
87
+ bundle={bundle}
88
+ format={props.format}
89
+ variables={props.variables}
90
+ site={props.site}
91
+ public={props.public}
92
+ port={props.port}
93
+ />
94
+ ) : (
95
+ <Remote
96
+ name={props.name}
97
+ bundle={bundle}
98
+ format={props.format}
99
+ accountId={props.accountId}
100
+ apiToken={apiToken}
101
+ variables={props.variables}
102
+ site={props.site}
103
+ public={props.public}
104
+ port={props.port}
105
+ compatibilityDate={props.compatibilityDate}
106
+ compatibilityFlags={props.compatibilityFlags}
107
+ usageModel={props.usageModel}
108
+ />
109
+ )}
110
+ <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
111
+ <Text>
112
+ {`B to open a browser, D to open Devtools, S to ${
113
+ toggles.tunnel ? "turn off" : "turn on"
114
+ } (experimental) sharing, L to ${
115
+ toggles.local ? "turn off" : "turn on"
116
+ } local mode, X to exit`}
117
+ </Text>
118
+ </Box>
119
+ </>
120
+ );
121
+ }
122
+
123
+ function useDevtoolsRefresh(bundleId: number) {
124
+ // TODO: this is a hack while we figure out
125
+ // a better cleaner solution to get devtools to reconnect
126
+ // without having to do a full refresh
127
+ const ref = useRef();
128
+ // @ts-expect-error whack
129
+ ref.current = bundleId;
130
+
131
+ useEffect(() => {
132
+ const server = http.createServer((req, res) => {
133
+ res.setHeader("Access-Control-Allow-Origin", "*");
134
+ res.setHeader("Access-Control-Request-Method", "*");
135
+ res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET");
136
+ res.setHeader("Access-Control-Allow-Headers", "*");
137
+ if (req.method === "OPTIONS") {
138
+ res.writeHead(200);
139
+ res.end();
140
+ return;
141
+ }
142
+ res.writeHead(200, { "Content-Type": "application/json" });
143
+ res.end(JSON.stringify({ value: ref.current }));
144
+ });
145
+
146
+ server.listen(3142);
147
+ return () => {
148
+ server.close();
149
+ };
150
+ }, []);
151
+ }
152
+
153
+ function Remote(props: {
154
+ name: void | string;
155
+ bundle: EsbuildBundle | void;
156
+ format: CfScriptFormat;
157
+ public: void | string;
158
+ site: void | string;
159
+ port: number;
160
+ accountId: void | string;
161
+ apiToken: void | string;
162
+ variables: { [name: string]: CfVariable };
163
+ compatibilityDate: string | void;
164
+ compatibilityFlags: void | string[];
165
+ usageModel: void | "bundled" | "unbound";
166
+ }) {
167
+ assert(props.accountId, "accountId is required");
168
+ assert(props.apiToken, "apiToken is required");
169
+ const token = useWorker({
170
+ name: props.name,
171
+ bundle: props.bundle,
172
+ format: props.format,
173
+ modules: props.bundle ? props.bundle.modules : [],
174
+ accountId: props.accountId,
175
+ apiToken: props.apiToken,
176
+ variables: props.variables,
177
+ sitesFolder: props.site,
178
+ port: props.port,
179
+ compatibilityDate: props.compatibilityDate,
180
+ compatibilityFlags: props.compatibilityFlags,
181
+ usageModel: props.usageModel,
182
+ });
183
+
184
+ useProxy({ token, publicRoot: props.public, port: props.port });
185
+
186
+ useInspector(token ? token.inspectorUrl.href : undefined);
187
+ return null;
188
+ }
189
+ function Local(props: {
190
+ name: void | string;
191
+ bundle: EsbuildBundle | void;
192
+ format: CfScriptFormat;
193
+ variables: { [name: string]: CfVariable };
194
+ public: void | string;
195
+ site: void | string;
196
+ port: number;
197
+ }) {
198
+ const { inspectorUrl } = useLocalWorker({
199
+ name: props.name,
200
+ bundle: props.bundle,
201
+ format: props.format,
202
+ variables: props.variables,
203
+ port: props.port,
204
+ });
205
+ useInspector(inspectorUrl);
206
+ return null;
207
+ }
208
+
209
+ function useLocalWorker(props: {
210
+ name: void | string;
211
+ bundle: EsbuildBundle | void;
212
+ format: CfScriptFormat;
213
+ variables: { [name: string]: CfVariable };
214
+ port: number;
215
+ }) {
216
+ // TODO: pass vars via command line
217
+ const { bundle, format, variables, port } = props;
218
+ const local = useRef<ReturnType<typeof spawn>>();
219
+ const removeSignalExitListener = useRef<() => void>();
220
+ const [inspectorUrl, setInspectorUrl] = useState<string | void>();
221
+ useEffect(() => {
222
+ async function startLocalWorker() {
223
+ if (!bundle) return;
224
+ if (format === "modules" && bundle.type === "commonjs") {
225
+ console.error("⎔ Cannot use modules with a commonjs bundle.");
226
+ // TODO: a much better error message here, with what to do next
227
+ return;
228
+ }
229
+ if (format === "service-worker" && bundle.type !== "esm") {
230
+ console.error("⎔ Cannot use service-worker with a esm bundle.");
231
+ // TODO: a much better error message here, with what to do next
232
+ return;
233
+ }
234
+
235
+ console.log("⎔ Starting a local server...");
236
+ local.current = spawn("node", [
237
+ "--experimental-vm-modules",
238
+ "--inspect",
239
+ require.resolve("miniflare/cli"),
240
+ bundle.path,
241
+ "--watch",
242
+ "--wrangler-config",
243
+ path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
244
+ "--env",
245
+ path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
246
+ "--package",
247
+ path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
248
+ "--port",
249
+ port.toString(),
250
+ "--kv-persist",
251
+ "--cache-persist",
252
+ "--do-persist",
253
+ ...Object.entries(variables)
254
+ .map(([varKey, varVal]) => {
255
+ if (typeof varVal === "string") {
256
+ return `--binding ${varKey}=${varVal}`;
257
+ } else if (
258
+ "namespaceId" in varVal &&
259
+ typeof varVal.namespaceId === "string"
260
+ ) {
261
+ return `--kv ${varKey}`;
262
+ } else if ("class_name" in varVal) {
263
+ return `--do ${varKey}=${varVal.class_name}`;
264
+ }
265
+ })
266
+ .filter(Boolean),
267
+ "--modules",
268
+ format ||
269
+ (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
270
+ ? "true"
271
+ : "false",
272
+ ]);
273
+ console.log(`⬣ Listening at http://localhost:${port}`);
274
+
275
+ local.current.on("close", (code) => {
276
+ if (code !== null) {
277
+ console.log(`miniflare process exited with code ${code}`);
278
+ }
279
+ });
280
+
281
+ local.current.stdout.on("data", (_data: string) => {
282
+ // console.log(`stdout: ${data}`);
283
+ });
284
+
285
+ local.current.stderr.on("data", (data: string) => {
286
+ // console.error(`stderr: ${data}`);
287
+ const matches =
288
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
289
+ data
290
+ );
291
+ if (matches) {
292
+ setInspectorUrl(matches[1]);
293
+ }
294
+ });
295
+
296
+ removeSignalExitListener.current = onExit((_code, _signal) => {
297
+ console.log("⎔ Shutting down local server.");
298
+ local.current?.kill();
299
+ local.current = undefined;
300
+ });
301
+ }
302
+
303
+ startLocalWorker();
304
+
305
+ return () => {
306
+ if (local.current) {
307
+ console.log("⎔ Shutting down local server.");
308
+ local.current?.kill();
309
+ local.current = undefined;
310
+ removeSignalExitListener.current && removeSignalExitListener.current();
311
+ removeSignalExitListener.current = undefined;
312
+ }
313
+ };
314
+ }, [bundle, format, port]);
315
+ return { inspectorUrl };
316
+ }
317
+
318
+ function useTmpDir(): string | void {
319
+ const [directory, setDirectory] = useState<DirectoryResult>();
320
+ useEffect(() => {
321
+ let dir: DirectoryResult;
322
+ async function create() {
323
+ try {
324
+ dir = await tmp.dir({ unsafeCleanup: true });
325
+ setDirectory(dir);
326
+ return;
327
+ } catch (err) {
328
+ console.error("failed to create tmp dir");
329
+ console.error(err);
330
+ throw err;
331
+ }
332
+ }
333
+ create();
334
+ return () => {
335
+ dir.cleanup();
336
+ };
337
+ }, []);
338
+ return directory?.path;
339
+ }
340
+
341
+ type EsbuildBundle = {
342
+ id: number;
343
+ path: string;
344
+ entry: string;
345
+ type: "esm" | "commonjs";
346
+ exports: string[];
347
+ modules: CfModule[];
348
+ };
349
+
350
+ function useEsbuild(props: {
351
+ entry: string;
352
+ destination: string | void;
353
+ staticRoot: void | string;
354
+ jsxFactory: string | void;
355
+ jsxFragment: string | void;
356
+ }): EsbuildBundle | void {
357
+ const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
358
+ const [bundle, setBundle] = useState<EsbuildBundle>();
359
+ useEffect(() => {
360
+ let result: esbuild.BuildResult;
361
+ async function build() {
362
+ if (!destination) return;
363
+ const moduleCollector = makeModuleCollector();
364
+ result = await esbuild.build({
365
+ entryPoints: [entry],
366
+ bundle: true,
367
+ outdir: destination,
368
+ metafile: true,
369
+ format: "esm",
370
+ sourcemap: true,
371
+ loader: {
372
+ ".js": "jsx",
373
+ },
374
+ ...(jsxFactory && { jsxFactory }),
375
+ ...(jsxFragment && { jsxFragment }),
376
+ external: ["__STATIC_CONTENT_MANIFEST"],
377
+ plugins: [moduleCollector.plugin],
378
+ // TODO: import.meta.url
379
+ watch: {
380
+ async onRebuild(error) {
381
+ if (error) console.error("watch build failed:", error);
382
+ else {
383
+ // nothing really changes here, so let's increment the id
384
+ // to change the return object's identity
385
+ setBundle((bundle) => ({ ...bundle, id: bundle.id + 1 }));
386
+ }
387
+ },
388
+ },
389
+ });
390
+
391
+ const chunks = Object.entries(result.metafile.outputs).find(
392
+ ([_path, { entryPoint }]) => entryPoint === entry
393
+ ); // assumedly only one entry point
394
+
395
+ setBundle({
396
+ id: 0,
397
+ entry,
398
+ path: chunks[0],
399
+ type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
400
+ exports: chunks[1].exports,
401
+ modules: moduleCollector.modules,
402
+ });
403
+ }
404
+ build();
405
+ return () => {
406
+ result?.stop();
407
+ };
408
+ }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
409
+ return bundle;
410
+ }
411
+
412
+ function useWorker(props: {
413
+ name: void | string;
414
+ bundle: EsbuildBundle | void;
415
+ format: CfScriptFormat;
416
+ modules: CfModule[];
417
+ accountId: string;
418
+ apiToken: string;
419
+ variables: { [name: string]: CfVariable };
420
+ sitesFolder: void | string;
421
+ port: number;
422
+ compatibilityDate: string | void;
423
+ compatibilityFlags: string[] | void;
424
+ usageModel: void | "bundled" | "unbound";
425
+ }): CfPreviewToken | void {
426
+ const {
427
+ name,
428
+ bundle,
429
+ format,
430
+ modules,
431
+ accountId,
432
+ apiToken,
433
+ variables,
434
+ sitesFolder,
435
+ compatibilityDate,
436
+ compatibilityFlags,
437
+ usageModel,
438
+ port,
439
+ } = props;
440
+ const [token, setToken] = useState<CfPreviewToken>();
441
+ useEffect(() => {
442
+ async function start() {
443
+ if (!bundle) return;
444
+ if (format === "modules" && bundle.type === "commonjs") {
445
+ console.error("⎔ Cannot use modules with a commonjs bundle.");
446
+ // TODO: a much better error message here, with what to do next
447
+ return;
448
+ }
449
+ if (format === "service-worker" && bundle.type !== "esm") {
450
+ console.error("⎔ Cannot use service-worker with a esm bundle.");
451
+ // TODO: a much better error message here, with what to do next
452
+ return;
453
+ }
454
+
455
+ if (token) {
456
+ console.log("⎔ Detected changes, restarting server...");
457
+ } else {
458
+ console.log("⎔ Starting server...");
459
+ }
460
+
461
+ const assets = sitesFolder
462
+ ? await syncAssets(
463
+ accountId,
464
+ path.basename(bundle.path),
465
+ sitesFolder,
466
+ true,
467
+ undefined // TODO: env
468
+ )
469
+ : {
470
+ manifest: undefined,
471
+ namespace: undefined,
472
+ }; // TODO: cancellable?
473
+
474
+ const content = await readFile(bundle.path, "utf-8");
475
+ const init: CfWorkerInit = {
476
+ name,
477
+ main: {
478
+ name: path.basename(bundle.path),
479
+ type: format || bundle.type === "esm" ? "esm" : "commonjs",
480
+ content,
481
+ },
482
+ modules: assets.manifest
483
+ ? modules.concat({
484
+ name: "__STATIC_CONTENT_MANIFEST",
485
+ content: JSON.stringify(assets.manifest),
486
+ type: "text",
487
+ })
488
+ : modules,
489
+ variables: assets.namespace
490
+ ? {
491
+ ...variables,
492
+ __STATIC_CONTENT: { namespaceId: assets.namespace },
493
+ }
494
+ : variables,
495
+ migrations: undefined, // no migrations in dev
496
+ compatibility_date: compatibilityDate,
497
+ compatibility_flags: compatibilityFlags,
498
+ usage_model: usageModel,
499
+ };
500
+ setToken(
501
+ await createWorker(init, {
502
+ accountId,
503
+ apiToken,
504
+ })
505
+ );
506
+ console.log(`⬣ Listening at http://localhost:${port}`);
507
+ }
508
+ start();
509
+ }, [
510
+ name,
511
+ bundle,
512
+ format,
513
+ accountId,
514
+ apiToken,
515
+ port,
516
+ sitesFolder,
517
+ compatibilityDate,
518
+ compatibilityFlags,
519
+ usageModel,
520
+ ]);
521
+ return token;
522
+ }
523
+
524
+ function useProxy({
525
+ token,
526
+ publicRoot,
527
+ port,
528
+ }: {
529
+ token: CfPreviewToken | void;
530
+ publicRoot: void | string;
531
+ port: number;
532
+ }) {
533
+ useEffect(() => {
534
+ if (!token) return;
535
+ const proxy = httpProxy.createProxyServer({
536
+ secure: false,
537
+ changeOrigin: true,
538
+ headers: {
539
+ "cf-workers-preview-token": token.value,
540
+ },
541
+ target: `https://${token.host}`,
542
+ // TODO: log websockets too? validate durables, etc
543
+ });
544
+
545
+ const servePublic =
546
+ publicRoot &&
547
+ serveStatic(publicRoot, {
548
+ cacheControl: false,
549
+ });
550
+ const server = http
551
+ .createServer((req, res) => {
552
+ if (publicRoot) {
553
+ servePublic(req, res, () => {
554
+ proxy.web(req, res);
555
+ });
556
+ } else {
557
+ proxy.web(req, res);
558
+ }
559
+ })
560
+ .listen(port); // TODO: custom port
561
+
562
+ proxy.on("proxyRes", function (proxyRes, req, res) {
563
+ // log all requests
564
+ console.log(
565
+ new Date().toLocaleTimeString(),
566
+ req.method,
567
+ req.url,
568
+ res.statusCode // TODO add a status message like Ok etc?
569
+ );
570
+ });
571
+ // TODO: log errors?
572
+
573
+ return () => {
574
+ proxy.close();
575
+ server.close();
576
+ };
577
+ }, [token, publicRoot, port]);
578
+ }
579
+
580
+ function useInspector(inspectorUrl: string | void) {
581
+ useEffect(() => {
582
+ if (!inspectorUrl) return;
583
+
584
+ const inspector = new DtInspector(inspectorUrl);
585
+ const abortController = inspector.proxyTo(9229);
586
+ return () => {
587
+ inspector.close();
588
+ abortController.abort();
589
+ };
590
+ }, [inspectorUrl]);
591
+ }
592
+
593
+ function sleep(period: number) {
594
+ return new Promise((resolve) => setTimeout(resolve, period));
595
+ }
596
+ const SLEEP_DURATION = 2000;
597
+ // really need a first class api for this
598
+ const hostNameRegex = /userHostname="(.*)"/g;
599
+ async function findTunnelHostname() {
600
+ let hostName: string;
601
+ while (!hostName) {
602
+ try {
603
+ const resp = await fetch("http://localhost:8789/metrics");
604
+ const data = await resp.text();
605
+ const matches = Array.from(data.matchAll(hostNameRegex));
606
+ hostName = matches[0][1];
607
+ } catch (err) {
608
+ await sleep(SLEEP_DURATION);
609
+ }
610
+ }
611
+ return hostName;
612
+ }
613
+
614
+ function useTunnel(toggle: boolean) {
615
+ const tunnel = useRef<ReturnType<typeof spawn>>();
616
+ const removeSignalExitListener = useRef<() => void>();
617
+ // TODO: test if cloudflared is available, if not
618
+ // point them to a url where they can get docs to install it
619
+ useEffect(() => {
620
+ async function startTunnel() {
621
+ if (toggle) {
622
+ try {
623
+ await commandExists("cloudflared");
624
+ } catch (e) {
625
+ console.error(
626
+ "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
627
+ );
628
+ return;
629
+ }
630
+ console.log("⎔ Starting a tunnel...");
631
+ tunnel.current = spawn("cloudflared", [
632
+ "tunnel",
633
+ "--url",
634
+ "http://localhost:8787",
635
+ "--metrics",
636
+ "localhost:8789",
637
+ ]);
638
+
639
+ tunnel.current.on("close", (code) => {
640
+ if (code !== 0) {
641
+ console.log(`Tunnel process exited with code ${code}`);
642
+ }
643
+ });
644
+
645
+ removeSignalExitListener.current = onExit((_code, _signal) => {
646
+ console.log("⎔ Shutting down local tunnel.");
647
+ tunnel.current?.kill();
648
+ tunnel.current = undefined;
649
+ });
650
+
651
+ const hostName = await findTunnelHostname();
652
+ clipboardy.write(hostName);
653
+ console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
654
+ }
655
+ }
656
+
657
+ startTunnel();
658
+
659
+ return () => {
660
+ if (tunnel.current) {
661
+ console.log("⎔ Shutting down tunnel.");
662
+ tunnel.current?.kill();
663
+ tunnel.current = undefined;
664
+ removeSignalExitListener.current && removeSignalExitListener.current();
665
+ removeSignalExitListener.current = undefined;
666
+ }
667
+ };
668
+ }, [toggle]);
669
+ }
670
+
671
+ type useHotkeysInitialState = {
672
+ local: boolean;
673
+ tunnel: boolean;
674
+ };
675
+ function useHotkeys(initial: useHotkeysInitialState, port: number) {
676
+ // UGH, we should put port in context instead
677
+ const [toggles, setToggles] = useState(initial);
678
+ useInput(
679
+ (
680
+ input,
681
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
682
+ key
683
+ ) => {
684
+ switch (input) {
685
+ case "b": // open browser
686
+ open(
687
+ `http://localhost:${port}/`
688
+ // {
689
+ // app: {
690
+ // name: open.apps.chrome, // TODO: fallback on other browsers
691
+ // },
692
+ // }
693
+ );
694
+ break;
695
+ case "d": // toggle inspector
696
+ open(
697
+ `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
698
+ // {
699
+ // app: {
700
+ // name: open.apps.chrome,
701
+ // // todo - add firefox and edge fallbacks
702
+ // },
703
+ // }
704
+ );
705
+ break;
706
+ case "s": // toggle tunnel
707
+ setToggles((toggles) => ({ ...toggles, tunnel: !toggles.tunnel }));
708
+ break;
709
+ case "l": // toggle local
710
+ setToggles((toggles) => ({ ...toggles, local: !toggles.local }));
711
+ break;
712
+ case "q": // shut down
713
+ case "x": // shut down
714
+ process.exit(0);
715
+ break;
716
+ default:
717
+ // nothing?
718
+ break;
719
+ }
720
+ }
721
+ );
722
+ return toggles;
723
+ }