wrangler 0.0.0-e928f94 → 0.0.0-e978986

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 (124) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +74 -34
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +151 -0
  8. package/pages/functions/filepath-routing.test.ts +234 -0
  9. package/pages/functions/filepath-routing.ts +189 -0
  10. package/pages/functions/identifiers.ts +78 -0
  11. package/pages/functions/routes.ts +156 -0
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +143 -0
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3374 -0
  16. package/src/__tests__/dev.test.tsx +980 -0
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +130 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/helpers/mock-kv.ts +33 -0
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +233 -130
  38. package/src/__tests__/init.test.ts +1567 -0
  39. package/src/__tests__/jest.setup.ts +77 -0
  40. package/src/__tests__/kv.test.ts +1481 -0
  41. package/src/__tests__/logger.test.ts +115 -0
  42. package/src/__tests__/package-manager.test.ts +353 -0
  43. package/src/__tests__/pages.test.ts +657 -0
  44. package/src/__tests__/parse.test.ts +330 -0
  45. package/src/__tests__/publish.test.ts +5468 -0
  46. package/src/__tests__/r2.test.ts +233 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +481 -0
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +131 -0
  51. package/src/__tests__/whoami.test.tsx +105 -0
  52. package/src/abort.d.ts +3 -0
  53. package/src/bundle.ts +200 -0
  54. package/src/cfetch/index.ts +121 -0
  55. package/src/cfetch/internal.ts +145 -0
  56. package/src/cli.ts +10 -7
  57. package/src/config/README.md +107 -0
  58. package/src/config/config.ts +234 -0
  59. package/src/config/diagnostics.ts +80 -0
  60. package/src/config/environment.ts +420 -0
  61. package/src/config/index.ts +225 -0
  62. package/src/config/validation-helpers.ts +575 -0
  63. package/src/config/validation.ts +1539 -0
  64. package/src/config-cache.ts +45 -0
  65. package/src/create-worker-preview.ts +185 -0
  66. package/src/create-worker-upload-form.ts +254 -0
  67. package/src/dev/dev-vars.ts +36 -0
  68. package/src/dev/dev.tsx +419 -0
  69. package/src/dev/local.tsx +318 -0
  70. package/src/dev/remote.tsx +227 -0
  71. package/src/dev/use-esbuild.ts +118 -0
  72. package/src/dialogs.tsx +67 -17
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +322 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/https-options.ts +123 -0
  78. package/src/index.tsx +2031 -1041
  79. package/src/inspect.ts +662 -0
  80. package/src/intl-polyfill.d.ts +139 -0
  81. package/src/kv.ts +408 -0
  82. package/src/logger.ts +66 -0
  83. package/src/miniflare-cli/README.md +30 -0
  84. package/src/miniflare-cli/enum-keys.ts +17 -0
  85. package/src/miniflare-cli/index.ts +41 -0
  86. package/src/miniflare-cli/request-context.ts +40 -0
  87. package/src/module-collection.ts +229 -35
  88. package/src/open-in-browser.ts +19 -0
  89. package/src/package-manager.ts +174 -0
  90. package/src/pages.tsx +1444 -260
  91. package/src/parse.ts +202 -0
  92. package/src/paths.ts +26 -0
  93. package/src/proxy.ts +465 -0
  94. package/src/publish.ts +498 -261
  95. package/src/r2.ts +50 -0
  96. package/src/selfsigned.d.ts +29 -0
  97. package/src/sites.tsx +240 -60
  98. package/src/tail/filters.ts +279 -0
  99. package/src/tail/index.ts +299 -0
  100. package/src/tail/printing.ts +67 -0
  101. package/src/update-check.ts +19 -0
  102. package/src/user.tsx +395 -221
  103. package/src/whoami.tsx +70 -0
  104. package/src/worker.ts +180 -0
  105. package/templates/gitignore +171 -0
  106. package/templates/new-worker-scheduled.js +17 -0
  107. package/templates/new-worker-scheduled.ts +32 -0
  108. package/templates/new-worker.js +15 -0
  109. package/templates/new-worker.ts +30 -0
  110. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  111. package/templates/tsconfig.json +105 -0
  112. package/wrangler-dist/cli.js +118298 -116056
  113. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  114. package/src/__tests__/mock-cfetch.js +0 -46
  115. package/src/api/form_data.ts +0 -141
  116. package/src/api/inspect.ts +0 -441
  117. package/src/api/preview.ts +0 -128
  118. package/src/api/worker.ts +0 -161
  119. package/src/cfetch.ts +0 -72
  120. package/src/config.ts +0 -122
  121. package/src/dev.tsx +0 -724
  122. package/src/kv.tsx +0 -211
  123. package/src/tail.tsx +0 -71
  124. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx DELETED
@@ -1,724 +0,0 @@
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
- conditions: ["worker", "browser"],
378
- plugins: [moduleCollector.plugin],
379
- // TODO: import.meta.url
380
- watch: {
381
- async onRebuild(error) {
382
- if (error) console.error("watch build failed:", error);
383
- else {
384
- // nothing really changes here, so let's increment the id
385
- // to change the return object's identity
386
- setBundle((bundle) => ({ ...bundle, id: bundle.id + 1 }));
387
- }
388
- },
389
- },
390
- });
391
-
392
- const chunks = Object.entries(result.metafile.outputs).find(
393
- ([_path, { entryPoint }]) => entryPoint === entry
394
- ); // assumedly only one entry point
395
-
396
- setBundle({
397
- id: 0,
398
- entry,
399
- path: chunks[0],
400
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
401
- exports: chunks[1].exports,
402
- modules: moduleCollector.modules,
403
- });
404
- }
405
- build();
406
- return () => {
407
- result?.stop();
408
- };
409
- }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
410
- return bundle;
411
- }
412
-
413
- function useWorker(props: {
414
- name: void | string;
415
- bundle: EsbuildBundle | void;
416
- format: CfScriptFormat;
417
- modules: CfModule[];
418
- accountId: string;
419
- apiToken: string;
420
- variables: { [name: string]: CfVariable };
421
- sitesFolder: void | string;
422
- port: number;
423
- compatibilityDate: string | void;
424
- compatibilityFlags: string[] | void;
425
- usageModel: void | "bundled" | "unbound";
426
- }): CfPreviewToken | void {
427
- const {
428
- name,
429
- bundle,
430
- format,
431
- modules,
432
- accountId,
433
- apiToken,
434
- variables,
435
- sitesFolder,
436
- compatibilityDate,
437
- compatibilityFlags,
438
- usageModel,
439
- port,
440
- } = props;
441
- const [token, setToken] = useState<CfPreviewToken>();
442
- useEffect(() => {
443
- async function start() {
444
- if (!bundle) return;
445
- if (format === "modules" && bundle.type === "commonjs") {
446
- console.error("⎔ Cannot use modules with a commonjs bundle.");
447
- // TODO: a much better error message here, with what to do next
448
- return;
449
- }
450
- if (format === "service-worker" && bundle.type !== "esm") {
451
- console.error("⎔ Cannot use service-worker with a esm bundle.");
452
- // TODO: a much better error message here, with what to do next
453
- return;
454
- }
455
-
456
- if (token) {
457
- console.log("⎔ Detected changes, restarting server...");
458
- } else {
459
- console.log("⎔ Starting server...");
460
- }
461
-
462
- const assets = sitesFolder
463
- ? await syncAssets(
464
- accountId,
465
- path.basename(bundle.path),
466
- sitesFolder,
467
- true,
468
- undefined // TODO: env
469
- )
470
- : {
471
- manifest: undefined,
472
- namespace: undefined,
473
- }; // TODO: cancellable?
474
-
475
- const content = await readFile(bundle.path, "utf-8");
476
- const init: CfWorkerInit = {
477
- name,
478
- main: {
479
- name: path.basename(bundle.path),
480
- type: format || bundle.type === "esm" ? "esm" : "commonjs",
481
- content,
482
- },
483
- modules: assets.manifest
484
- ? modules.concat({
485
- name: "__STATIC_CONTENT_MANIFEST",
486
- content: JSON.stringify(assets.manifest),
487
- type: "text",
488
- })
489
- : modules,
490
- variables: assets.namespace
491
- ? {
492
- ...variables,
493
- __STATIC_CONTENT: { namespaceId: assets.namespace },
494
- }
495
- : variables,
496
- migrations: undefined, // no migrations in dev
497
- compatibility_date: compatibilityDate,
498
- compatibility_flags: compatibilityFlags,
499
- usage_model: usageModel,
500
- };
501
- setToken(
502
- await createWorker(init, {
503
- accountId,
504
- apiToken,
505
- })
506
- );
507
- console.log(`⬣ Listening at http://localhost:${port}`);
508
- }
509
- start();
510
- }, [
511
- name,
512
- bundle,
513
- format,
514
- accountId,
515
- apiToken,
516
- port,
517
- sitesFolder,
518
- compatibilityDate,
519
- compatibilityFlags,
520
- usageModel,
521
- ]);
522
- return token;
523
- }
524
-
525
- function useProxy({
526
- token,
527
- publicRoot,
528
- port,
529
- }: {
530
- token: CfPreviewToken | void;
531
- publicRoot: void | string;
532
- port: number;
533
- }) {
534
- useEffect(() => {
535
- if (!token) return;
536
- const proxy = httpProxy.createProxyServer({
537
- secure: false,
538
- changeOrigin: true,
539
- headers: {
540
- "cf-workers-preview-token": token.value,
541
- },
542
- target: `https://${token.host}`,
543
- // TODO: log websockets too? validate durables, etc
544
- });
545
-
546
- const servePublic =
547
- publicRoot &&
548
- serveStatic(publicRoot, {
549
- cacheControl: false,
550
- });
551
- const server = http
552
- .createServer((req, res) => {
553
- if (publicRoot) {
554
- servePublic(req, res, () => {
555
- proxy.web(req, res);
556
- });
557
- } else {
558
- proxy.web(req, res);
559
- }
560
- })
561
- .listen(port); // TODO: custom port
562
-
563
- proxy.on("proxyRes", function (proxyRes, req, res) {
564
- // log all requests
565
- console.log(
566
- new Date().toLocaleTimeString(),
567
- req.method,
568
- req.url,
569
- res.statusCode // TODO add a status message like Ok etc?
570
- );
571
- });
572
- // TODO: log errors?
573
-
574
- return () => {
575
- proxy.close();
576
- server.close();
577
- };
578
- }, [token, publicRoot, port]);
579
- }
580
-
581
- function useInspector(inspectorUrl: string | void) {
582
- useEffect(() => {
583
- if (!inspectorUrl) return;
584
-
585
- const inspector = new DtInspector(inspectorUrl);
586
- const abortController = inspector.proxyTo(9229);
587
- return () => {
588
- inspector.close();
589
- abortController.abort();
590
- };
591
- }, [inspectorUrl]);
592
- }
593
-
594
- function sleep(period: number) {
595
- return new Promise((resolve) => setTimeout(resolve, period));
596
- }
597
- const SLEEP_DURATION = 2000;
598
- // really need a first class api for this
599
- const hostNameRegex = /userHostname="(.*)"/g;
600
- async function findTunnelHostname() {
601
- let hostName: string;
602
- while (!hostName) {
603
- try {
604
- const resp = await fetch("http://localhost:8789/metrics");
605
- const data = await resp.text();
606
- const matches = Array.from(data.matchAll(hostNameRegex));
607
- hostName = matches[0][1];
608
- } catch (err) {
609
- await sleep(SLEEP_DURATION);
610
- }
611
- }
612
- return hostName;
613
- }
614
-
615
- function useTunnel(toggle: boolean) {
616
- const tunnel = useRef<ReturnType<typeof spawn>>();
617
- const removeSignalExitListener = useRef<() => void>();
618
- // TODO: test if cloudflared is available, if not
619
- // point them to a url where they can get docs to install it
620
- useEffect(() => {
621
- async function startTunnel() {
622
- if (toggle) {
623
- try {
624
- await commandExists("cloudflared");
625
- } catch (e) {
626
- console.error(
627
- "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
628
- );
629
- return;
630
- }
631
- console.log("⎔ Starting a tunnel...");
632
- tunnel.current = spawn("cloudflared", [
633
- "tunnel",
634
- "--url",
635
- "http://localhost:8787",
636
- "--metrics",
637
- "localhost:8789",
638
- ]);
639
-
640
- tunnel.current.on("close", (code) => {
641
- if (code !== 0) {
642
- console.log(`Tunnel process exited with code ${code}`);
643
- }
644
- });
645
-
646
- removeSignalExitListener.current = onExit((_code, _signal) => {
647
- console.log("⎔ Shutting down local tunnel.");
648
- tunnel.current?.kill();
649
- tunnel.current = undefined;
650
- });
651
-
652
- const hostName = await findTunnelHostname();
653
- clipboardy.write(hostName);
654
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
655
- }
656
- }
657
-
658
- startTunnel();
659
-
660
- return () => {
661
- if (tunnel.current) {
662
- console.log("⎔ Shutting down tunnel.");
663
- tunnel.current?.kill();
664
- tunnel.current = undefined;
665
- removeSignalExitListener.current && removeSignalExitListener.current();
666
- removeSignalExitListener.current = undefined;
667
- }
668
- };
669
- }, [toggle]);
670
- }
671
-
672
- type useHotkeysInitialState = {
673
- local: boolean;
674
- tunnel: boolean;
675
- };
676
- function useHotkeys(initial: useHotkeysInitialState, port: number) {
677
- // UGH, we should put port in context instead
678
- const [toggles, setToggles] = useState(initial);
679
- useInput(
680
- (
681
- input,
682
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
683
- key
684
- ) => {
685
- switch (input) {
686
- case "b": // open browser
687
- open(
688
- `http://localhost:${port}/`
689
- // {
690
- // app: {
691
- // name: open.apps.chrome, // TODO: fallback on other browsers
692
- // },
693
- // }
694
- );
695
- break;
696
- case "d": // toggle inspector
697
- open(
698
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
699
- // {
700
- // app: {
701
- // name: open.apps.chrome,
702
- // // todo - add firefox and edge fallbacks
703
- // },
704
- // }
705
- );
706
- break;
707
- case "s": // toggle tunnel
708
- setToggles((toggles) => ({ ...toggles, tunnel: !toggles.tunnel }));
709
- break;
710
- case "l": // toggle local
711
- setToggles((toggles) => ({ ...toggles, local: !toggles.local }));
712
- break;
713
- case "q": // shut down
714
- case "x": // shut down
715
- process.exit(0);
716
- break;
717
- default:
718
- // nothing?
719
- break;
720
- }
721
- }
722
- );
723
- return toggles;
724
- }