wrangler 0.0.0-e29a241 → 0.0.0-e2a6fa40

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 (166) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +118 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +138 -83
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +137 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/new-worker-scheduled.js +17 -0
  27. package/templates/new-worker-scheduled.ts +32 -0
  28. package/templates/new-worker.js +3 -3
  29. package/templates/new-worker.ts +22 -4
  30. package/templates/no-op-worker.js +10 -0
  31. package/templates/pages-dev-pipeline.ts +31 -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/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +105 -0
  38. package/templates/tsconfig.json +6 -103
  39. package/wrangler-dist/cli.d.ts +1734 -0
  40. package/wrangler-dist/cli.js +142808 -133914
  41. package/wrangler-dist/wasm-sync.wasm +0 -0
  42. package/import_meta_url.js +0 -3
  43. package/miniflare-config-stubs/.env.empty +0 -0
  44. package/miniflare-config-stubs/package.empty.json +0 -1
  45. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  46. package/miniflare-dist/index.mjs +0 -79
  47. package/miniflare-dist/index.mjs.map +0 -7
  48. package/pages/functions/buildWorker.ts +0 -62
  49. package/pages/functions/filepath-routing.test.ts +0 -223
  50. package/pages/functions/filepath-routing.ts +0 -181
  51. package/pages/functions/identifiers.ts +0 -78
  52. package/pages/functions/routes.ts +0 -151
  53. package/pages/functions/template-worker.ts +0 -130
  54. package/src/__tests__/configuration.test.ts +0 -2754
  55. package/src/__tests__/dev.test.tsx +0 -496
  56. package/src/__tests__/dev2.test.tsx +0 -154
  57. package/src/__tests__/guess-worker-format.test.ts +0 -58
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  61. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  62. package/src/__tests__/helpers/mock-bin.ts +0 -36
  63. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  64. package/src/__tests__/helpers/mock-console.ts +0 -70
  65. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  66. package/src/__tests__/helpers/mock-kv.ts +0 -33
  67. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  68. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  69. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  70. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  71. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  72. package/src/__tests__/https-options.test.ts +0 -127
  73. package/src/__tests__/index.test.ts +0 -991
  74. package/src/__tests__/jest.setup.ts +0 -69
  75. package/src/__tests__/kv.test.ts +0 -1382
  76. package/src/__tests__/logout.test.ts +0 -52
  77. package/src/__tests__/package-manager.test.ts +0 -206
  78. package/src/__tests__/pages.test.ts +0 -44
  79. package/src/__tests__/parse.test.ts +0 -322
  80. package/src/__tests__/publish.test.ts +0 -2704
  81. package/src/__tests__/r2.test.ts +0 -198
  82. package/src/__tests__/route.test.ts +0 -45
  83. package/src/__tests__/secret.test.ts +0 -425
  84. package/src/__tests__/sentry.test.ts +0 -146
  85. package/src/__tests__/tail.test.ts +0 -564
  86. package/src/__tests__/whoami.test.tsx +0 -100
  87. package/src/bundle.ts +0 -142
  88. package/src/cfetch/index.ts +0 -104
  89. package/src/cfetch/internal.ts +0 -139
  90. package/src/cli.ts +0 -19
  91. package/src/config/README.md +0 -107
  92. package/src/config/config.ts +0 -274
  93. package/src/config/diagnostics.ts +0 -80
  94. package/src/config/environment.ts +0 -310
  95. package/src/config/index.ts +0 -56
  96. package/src/config/validation-helpers.ts +0 -486
  97. package/src/config/validation.ts +0 -1096
  98. package/src/create-worker-preview.ts +0 -166
  99. package/src/create-worker-upload-form.ts +0 -217
  100. package/src/dev/dev.tsx +0 -364
  101. package/src/dev/local.tsx +0 -226
  102. package/src/dev/remote.tsx +0 -203
  103. package/src/dev/use-esbuild.ts +0 -100
  104. package/src/dialogs.tsx +0 -77
  105. package/src/entry.ts +0 -208
  106. package/src/environment-variables.ts +0 -33
  107. package/src/https-options.ts +0 -122
  108. package/src/index.tsx +0 -2373
  109. package/src/inspect.ts +0 -617
  110. package/src/kv.ts +0 -319
  111. package/src/miniflare-cli/README.md +0 -30
  112. package/src/miniflare-cli/enum-keys.ts +0 -17
  113. package/src/miniflare-cli/index.ts +0 -37
  114. package/src/module-collection.ts +0 -258
  115. package/src/open-in-browser.ts +0 -25
  116. package/src/package-manager.ts +0 -126
  117. package/src/pages.tsx +0 -1045
  118. package/src/parse.ts +0 -183
  119. package/src/paths.ts +0 -26
  120. package/src/proxy.ts +0 -440
  121. package/src/publish.ts +0 -347
  122. package/src/r2.ts +0 -50
  123. package/src/reporting.ts +0 -131
  124. package/src/selfsigned.d.ts +0 -29
  125. package/src/sites.tsx +0 -280
  126. package/src/tail/filters.ts +0 -279
  127. package/src/tail/index.ts +0 -299
  128. package/src/tail/printing.ts +0 -62
  129. package/src/user.tsx +0 -1118
  130. package/src/whoami.tsx +0 -69
  131. package/src/worker.ts +0 -163
  132. package/templates/static-asset-facade.js +0 -47
  133. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  134. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  135. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  136. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  137. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  138. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  139. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  140. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  141. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  142. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  143. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  147. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  148. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  149. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  150. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  151. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  152. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  153. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  154. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  155. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  156. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  157. package/vendor/wrangler-mime/LICENSE +0 -21
  158. package/vendor/wrangler-mime/Mime.js +0 -97
  159. package/vendor/wrangler-mime/README.md +0 -187
  160. package/vendor/wrangler-mime/cli.js +0 -46
  161. package/vendor/wrangler-mime/index.js +0 -4
  162. package/vendor/wrangler-mime/lite.js +0 -4
  163. package/vendor/wrangler-mime/package.json +0 -52
  164. package/vendor/wrangler-mime/types/other.js +0 -1
  165. package/vendor/wrangler-mime/types/standard.js +0 -1
  166. package/wrangler-dist/cli.js.map +0 -7
package/src/dev/dev.tsx DELETED
@@ -1,364 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { watch } from "chokidar";
3
- import clipboardy from "clipboardy";
4
- import commandExists from "command-exists";
5
- import { Box, Text, useApp, useInput } from "ink";
6
- import React, { useState, useEffect, useRef } from "react";
7
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
8
- import onExit from "signal-exit";
9
- import tmp from "tmp-promise";
10
- import { fetch } from "undici";
11
- import { runCustomBuild } from "../entry";
12
- import openInBrowser from "../open-in-browser";
13
- import { reportError } from "../reporting";
14
- import { getAPIToken } from "../user";
15
- import { Local } from "./local";
16
- import { Remote } from "./remote";
17
- import { useEsbuild } from "./use-esbuild";
18
- import type { Config } from "../config";
19
- import type { Entry } from "../entry";
20
- import type { AssetPaths } from "../sites";
21
- import type { CfWorkerInit } from "../worker";
22
-
23
- export type DevProps = {
24
- name?: string;
25
- entry: Entry;
26
- port?: number;
27
- ip: string;
28
- inspectorPort: number;
29
- rules: Config["rules"];
30
- accountId: undefined | string;
31
- initialMode: "local" | "remote";
32
- jsxFactory: undefined | string;
33
- jsxFragment: undefined | string;
34
- upstreamProtocol: "https" | "http";
35
- localProtocol: "https" | "http";
36
- enableLocalPersistence: boolean;
37
- bindings: CfWorkerInit["bindings"];
38
- public: undefined | string;
39
- assetPaths: undefined | AssetPaths;
40
- compatibilityDate: undefined | string;
41
- compatibilityFlags: undefined | string[];
42
- usageModel: undefined | "bundled" | "unbound";
43
- buildCommand: {
44
- command?: undefined | string;
45
- cwd?: undefined | string;
46
- watch_dir?: undefined | string;
47
- };
48
- env: string | undefined;
49
- legacyEnv: boolean;
50
- zone:
51
- | {
52
- id: string;
53
- host: string;
54
- }
55
- | undefined;
56
- };
57
-
58
- export function DevImplementation(props: DevProps): JSX.Element {
59
- const port = props.port ?? 8787;
60
- const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
61
- const directory = useTmpDir();
62
-
63
- useCustomBuild(props.entry, props.buildCommand);
64
-
65
- if (props.public && props.entry.format === "service-worker") {
66
- throw new Error(
67
- "You cannot use the service worker format with a `public` directory."
68
- );
69
- }
70
-
71
- if (props.bindings.wasm_modules && props.entry.format === "modules") {
72
- throw new Error(
73
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
74
- );
75
- }
76
-
77
- if (props.bindings.text_blobs && props.entry.format === "modules") {
78
- throw new Error(
79
- "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"
80
- );
81
- }
82
-
83
- const bundle = useEsbuild({
84
- entry: props.entry,
85
- destination: directory,
86
- staticRoot: props.public,
87
- jsxFactory: props.jsxFactory,
88
- rules: props.rules,
89
- jsxFragment: props.jsxFragment,
90
- serveAssetsFromWorker: !!props.public,
91
- });
92
-
93
- const toggles = useHotkeys(
94
- {
95
- local: props.initialMode === "local",
96
- tunnel: false,
97
- },
98
- port,
99
- props.ip,
100
- props.inspectorPort,
101
- props.localProtocol
102
- );
103
-
104
- useTunnel(toggles.tunnel);
105
-
106
- return (
107
- <>
108
- {toggles.local ? (
109
- <Local
110
- name={props.name}
111
- bundle={bundle}
112
- format={props.entry.format}
113
- compatibilityDate={props.compatibilityDate}
114
- compatibilityFlags={props.compatibilityFlags}
115
- bindings={props.bindings}
116
- assetPaths={props.assetPaths}
117
- public={props.public}
118
- port={port}
119
- ip={props.ip}
120
- rules={props.rules}
121
- inspectorPort={props.inspectorPort}
122
- enableLocalPersistence={props.enableLocalPersistence}
123
- />
124
- ) : (
125
- <Remote
126
- name={props.name}
127
- bundle={bundle}
128
- format={props.entry.format}
129
- accountId={props.accountId}
130
- apiToken={apiToken}
131
- bindings={props.bindings}
132
- assetPaths={props.assetPaths}
133
- public={props.public}
134
- port={port}
135
- ip={props.ip}
136
- localProtocol={props.localProtocol}
137
- inspectorPort={props.inspectorPort}
138
- compatibilityDate={props.compatibilityDate}
139
- compatibilityFlags={props.compatibilityFlags}
140
- usageModel={props.usageModel}
141
- env={props.env}
142
- legacyEnv={props.legacyEnv}
143
- zone={props.zone}
144
- />
145
- )}
146
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
147
- <Text>
148
- {`B to open a browser, D to open Devtools, L to ${
149
- toggles.local ? "turn off" : "turn on"
150
- } local mode, X to exit`}
151
- </Text>
152
- </Box>
153
- </>
154
- );
155
- }
156
-
157
- export interface DirectorySyncResult {
158
- name: string;
159
- removeCallback: () => void;
160
- }
161
-
162
- function useTmpDir(): string | undefined {
163
- const [directory, setDirectory] = useState<DirectorySyncResult>();
164
- const handleError = useErrorHandler();
165
- useEffect(() => {
166
- let dir: DirectorySyncResult | undefined;
167
- try {
168
- dir = tmp.dirSync({ unsafeCleanup: true });
169
- setDirectory(dir);
170
- return;
171
- } catch (err) {
172
- console.error("failed to create tmp dir");
173
- handleError(err);
174
- }
175
- return () => {
176
- dir?.removeCallback();
177
- };
178
- }, [handleError]);
179
- return directory?.name;
180
- }
181
-
182
- function useCustomBuild(
183
- expectedEntry: Entry,
184
- build: {
185
- command?: undefined | string;
186
- cwd?: undefined | string;
187
- watch_dir?: undefined | string;
188
- }
189
- ): void {
190
- useEffect(() => {
191
- if (!build.command) return;
192
- let watcher: ReturnType<typeof watch> | undefined;
193
- if (build.watch_dir) {
194
- watcher = watch(build.watch_dir, {
195
- persistent: true,
196
- ignoreInitial: true,
197
- }).on("all", (_event, filePath) => {
198
- //TODO: we should buffer requests to the proxy until this completes
199
- console.log(`The file ${filePath} changed, restarting build...`);
200
- runCustomBuild(expectedEntry.file, build).catch((err) => {
201
- console.error("Custom build failed:", err);
202
- });
203
- });
204
- }
205
-
206
- return () => {
207
- watcher?.close();
208
- };
209
- }, [build, expectedEntry.file]);
210
- }
211
-
212
- function sleep(period: number) {
213
- return new Promise((resolve) => setTimeout(resolve, period));
214
- }
215
- const SLEEP_DURATION = 2000;
216
- // really need a first class api for this
217
- const hostNameRegex = /userHostname="(.*)"/g;
218
- async function findTunnelHostname() {
219
- let hostName: string | undefined;
220
- while (!hostName) {
221
- try {
222
- const resp = await fetch("http://localhost:8789/metrics");
223
- const data = await resp.text();
224
- const matches = Array.from(data.matchAll(hostNameRegex));
225
- hostName = matches[0][1];
226
- } catch (err) {
227
- await sleep(SLEEP_DURATION);
228
- }
229
- }
230
- return hostName;
231
- }
232
-
233
- /**
234
- * Create a tunnel to the remote worker.
235
- * We've disabled this for now until we figure out a better user experience.
236
- */
237
- function useTunnel(toggle: boolean) {
238
- const tunnel = useRef<ReturnType<typeof spawn>>();
239
- const removeSignalExitListener = useRef<() => void>();
240
- // TODO: test if cloudflared is available, if not
241
- // point them to a url where they can get docs to install it
242
- useEffect(() => {
243
- async function startTunnel() {
244
- if (toggle) {
245
- try {
246
- await commandExists("cloudflared");
247
- } catch (e) {
248
- console.error(
249
- "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
250
- );
251
- return;
252
- }
253
- console.log("⎔ Starting a tunnel...");
254
- tunnel.current = spawn("cloudflared", [
255
- "tunnel",
256
- "--url",
257
- "http://localhost:8787",
258
- "--metrics",
259
- "localhost:8789",
260
- ]);
261
-
262
- tunnel.current.on("close", (code) => {
263
- if (code) {
264
- console.log(`Tunnel process exited with code ${code}`);
265
- }
266
- });
267
-
268
- removeSignalExitListener.current = onExit((_code, _signal) => {
269
- console.log("⎔ Shutting down local tunnel.");
270
- tunnel.current?.kill();
271
- tunnel.current = undefined;
272
- });
273
-
274
- const hostName = await findTunnelHostname();
275
- await clipboardy.write(hostName);
276
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
277
- }
278
- }
279
-
280
- startTunnel().catch(async (err) => {
281
- console.error("tunnel:", err);
282
- await reportError(err);
283
- });
284
-
285
- return () => {
286
- if (tunnel.current) {
287
- console.log("⎔ Shutting down tunnel.");
288
- tunnel.current?.kill();
289
- tunnel.current = undefined;
290
- removeSignalExitListener.current && removeSignalExitListener.current();
291
- removeSignalExitListener.current = undefined;
292
- }
293
- };
294
- }, [toggle]);
295
- }
296
-
297
- type useHotkeysInitialState = {
298
- local: boolean;
299
- tunnel: boolean;
300
- };
301
- function useHotkeys(
302
- initial: useHotkeysInitialState,
303
- port: number,
304
- ip: string,
305
- inspectorPort: number,
306
- localProtocol: "http" | "https"
307
- ) {
308
- // UGH, we should put port in context instead
309
- const [toggles, setToggles] = useState(initial);
310
- useInput(
311
- async (
312
- input,
313
- // eslint-disable-next-line unused-imports/no-unused-vars
314
- key
315
- ) => {
316
- switch (input.toLowerCase()) {
317
- // open browser
318
- case "b": {
319
- await openInBrowser(`${localProtocol}://${ip}:${port}`);
320
- break;
321
- }
322
- // toggle inspector
323
- case "d": {
324
- await openInBrowser(
325
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`,
326
- { forceChromium: true }
327
- );
328
- break;
329
- }
330
- // toggle local
331
- case "l":
332
- setToggles((previousToggles) => ({
333
- ...previousToggles,
334
- local: !previousToggles.local,
335
- }));
336
- break;
337
- // shut down
338
- case "q":
339
- case "x":
340
- process.exit(0);
341
- break;
342
- default:
343
- // nothing?
344
- break;
345
- }
346
- }
347
- );
348
- return toggles;
349
- }
350
-
351
- function ErrorFallback(props: { error: Error }) {
352
- const { exit } = useApp();
353
- useEffect(() => exit(props.error));
354
- return (
355
- <>
356
- <Text>Something went wrong:</Text>
357
- <Text>{props.error.stack}</Text>
358
- </>
359
- );
360
- }
361
-
362
- export default withErrorBoundary(DevImplementation, {
363
- FallbackComponent: ErrorFallback,
364
- });
package/src/dev/local.tsx DELETED
@@ -1,226 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { writeFile } from "node:fs/promises";
4
- import path from "node:path";
5
- import { useState, useEffect, useRef } from "react";
6
- import onExit from "signal-exit";
7
- import useInspector from "../inspect";
8
- import { DEFAULT_MODULE_RULES } from "../module-collection";
9
- import { waitForPortToBeAvailable } from "../proxy";
10
- import type { Config } from "../config";
11
- import type { AssetPaths } from "../sites";
12
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
13
- import type { EsbuildBundle } from "./use-esbuild";
14
- import type { MiniflareOptions } from "miniflare";
15
-
16
- interface LocalProps {
17
- name: undefined | string;
18
- bundle: EsbuildBundle | undefined;
19
- format: CfScriptFormat | undefined;
20
- compatibilityDate: string | undefined;
21
- compatibilityFlags: undefined | string[];
22
- bindings: CfWorkerInit["bindings"];
23
- assetPaths: undefined | AssetPaths;
24
- public: undefined | string;
25
- port: number;
26
- ip: string;
27
- rules: Config["rules"];
28
- inspectorPort: number;
29
- enableLocalPersistence: boolean;
30
- }
31
-
32
- export function Local(props: LocalProps) {
33
- const { inspectorUrl } = useLocalWorker(props);
34
- useInspector({
35
- inspectorUrl,
36
- port: props.inspectorPort,
37
- logToTerminal: false,
38
- });
39
- return null;
40
- }
41
-
42
- function useLocalWorker({
43
- name: workerName,
44
- bundle,
45
- format,
46
- compatibilityDate,
47
- compatibilityFlags,
48
- bindings,
49
- assetPaths,
50
- public: publicDirectory,
51
- port,
52
- rules,
53
- enableLocalPersistence,
54
- ip,
55
- }: LocalProps) {
56
- // TODO: pass vars via command line
57
- const local = useRef<ReturnType<typeof spawn>>();
58
- const removeSignalExitListener = useRef<() => void>();
59
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
60
- useEffect(() => {
61
- async function startLocalWorker() {
62
- if (!bundle || !format) return;
63
-
64
- // port for the worker
65
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
66
-
67
- if (publicDirectory) {
68
- throw new Error(
69
- '⎔ A "public" folder is not yet supported in local mode.'
70
- );
71
- }
72
-
73
- // In local mode, we want to copy all referenced modules into
74
- // the output bundle directory before starting up
75
- for (const module of bundle.modules) {
76
- await writeFile(
77
- path.join(path.dirname(bundle.path), module.name),
78
- module.content
79
- );
80
- }
81
-
82
- const scriptPath = realpathSync(bundle.path);
83
-
84
- const wasmBindings = { ...bindings.wasm_modules };
85
- if (format === "service-worker") {
86
- for (const { type, name } of bundle.modules) {
87
- if (type === "compiled-wasm") {
88
- // In service-worker format, .wasm modules are referenced by global identifiers,
89
- // so we convert it here.
90
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
91
- // characters with an underscore.
92
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
93
- wasmBindings[identifier] = name;
94
- }
95
- }
96
- }
97
-
98
- const options: MiniflareOptions = {
99
- name: workerName,
100
- port,
101
- scriptPath,
102
- host: ip,
103
- modules: format === "modules",
104
- modulesRules: (rules || [])
105
- .concat(DEFAULT_MODULE_RULES)
106
- .map(({ type, globs: include, fallthrough }) => ({
107
- type,
108
- include,
109
- fallthrough,
110
- })),
111
- compatibilityDate,
112
- compatibilityFlags,
113
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
114
- kvPersist: enableLocalPersistence,
115
- durableObjects: Object.fromEntries(
116
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
117
- (value) => [value.name, value.class_name]
118
- )
119
- ),
120
- durableObjectsPersist: enableLocalPersistence,
121
- cachePersist: enableLocalPersistence,
122
- sitePath: assetPaths?.assetDirectory
123
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
124
- : undefined,
125
- siteInclude: assetPaths?.includePatterns.length
126
- ? assetPaths?.includePatterns
127
- : undefined,
128
- siteExclude: assetPaths?.excludePatterns.length
129
- ? assetPaths.excludePatterns
130
- : undefined,
131
- bindings: bindings.vars,
132
- wasmBindings,
133
- sourceMap: true,
134
- logUnhandledRejections: true,
135
- };
136
-
137
- // The path to the Miniflare CLI assumes that this file is being run from
138
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
139
- // If either of those paths change this line needs updating.
140
- const miniflareCLIPath = path.resolve(
141
- __dirname,
142
- "../miniflare-dist/index.mjs"
143
- );
144
- const optionsArg = JSON.stringify(options, null);
145
-
146
- console.log("⎔ Starting a local server...");
147
- local.current = spawn("node", [
148
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
149
- "--no-warnings", // hide annoying Node warnings
150
- "--inspect", // start Miniflare listening for a debugger to attach
151
- miniflareCLIPath,
152
- optionsArg,
153
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
154
- ]);
155
-
156
- local.current.on("close", (code) => {
157
- if (code) {
158
- console.log(`Miniflare process exited with code ${code}`);
159
- }
160
- });
161
-
162
- local.current.stdout?.on("data", (data: Buffer) => {
163
- console.log(`${data.toString()}`);
164
- });
165
-
166
- local.current.stderr?.on("data", (data: Buffer) => {
167
- console.error(`${data.toString()}`);
168
- const matches =
169
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
170
- data.toString()
171
- );
172
- if (matches) {
173
- setInspectorUrl(matches[1]);
174
- }
175
- });
176
-
177
- local.current.on("exit", (code) => {
178
- if (code) {
179
- console.error(`Miniflare process exited with code ${code}`);
180
- }
181
- });
182
-
183
- local.current.on("error", (error: Error) => {
184
- console.error(`Miniflare process failed to spawn`);
185
- console.error(error);
186
- });
187
-
188
- removeSignalExitListener.current = onExit((_code, _signal) => {
189
- console.log("⎔ Shutting down local server.");
190
- local.current?.kill();
191
- local.current = undefined;
192
- });
193
- }
194
-
195
- startLocalWorker().catch((err) => {
196
- console.error("local worker:", err);
197
- });
198
-
199
- return () => {
200
- if (local.current) {
201
- console.log("⎔ Shutting down local server.");
202
- local.current?.kill();
203
- local.current = undefined;
204
- removeSignalExitListener.current && removeSignalExitListener.current();
205
- removeSignalExitListener.current = undefined;
206
- }
207
- };
208
- }, [
209
- bundle,
210
- workerName,
211
- format,
212
- port,
213
- ip,
214
- bindings.durable_objects?.bindings,
215
- bindings.kv_namespaces,
216
- bindings.vars,
217
- compatibilityDate,
218
- compatibilityFlags,
219
- enableLocalPersistence,
220
- assetPaths,
221
- publicDirectory,
222
- rules,
223
- bindings.wasm_modules,
224
- ]);
225
- return { inspectorUrl };
226
- }