wrangler 0.0.0-e3ce82b → 0.0.0-e41c7e41

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 (264) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1451 -21
  5. package/package.json +191 -153
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +56 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +3970 -3476
  13. package/src/__tests__/d1.test.ts +80 -0
  14. package/src/__tests__/delete.test.ts +230 -0
  15. package/src/__tests__/deployments.test.ts +91 -0
  16. package/src/__tests__/dev.test.tsx +1508 -955
  17. package/src/__tests__/dialogs.test.tsx +40 -0
  18. package/src/__tests__/generate.test.ts +235 -0
  19. package/src/__tests__/get-host-from-url.test.ts +16 -0
  20. package/src/__tests__/guess-worker-format.test.ts +68 -68
  21. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  22. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  33. package/src/__tests__/helpers/mock-process.ts +39 -0
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +241 -234
  56. package/src/__tests__/init.test.ts +2869 -1606
  57. package/src/__tests__/jest.setup.ts +159 -34
  58. package/src/__tests__/kv.test.ts +1660 -1466
  59. package/src/__tests__/logger.test.ts +100 -74
  60. package/src/__tests__/metrics.test.ts +450 -0
  61. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  62. package/src/__tests__/middleware.test.ts +726 -0
  63. package/src/__tests__/package-manager.test.ts +303 -303
  64. package/src/__tests__/pages-deployment-tail.test.ts +820 -0
  65. package/src/__tests__/pages.test.ts +2423 -735
  66. package/src/__tests__/parse.test.ts +252 -252
  67. package/src/__tests__/paths.test.ts +39 -0
  68. package/src/__tests__/publish.test.ts +7505 -5627
  69. package/src/__tests__/pubsub.test.ts +370 -0
  70. package/src/__tests__/queues.test.ts +371 -0
  71. package/src/__tests__/r2.test.ts +388 -228
  72. package/src/__tests__/route.test.ts +18 -18
  73. package/src/__tests__/secret.test.ts +622 -459
  74. package/src/__tests__/tail.test.ts +677 -567
  75. package/src/__tests__/test-old-node-version.js +31 -0
  76. package/src/__tests__/type-generation.test.ts +226 -0
  77. package/src/__tests__/user.test.ts +140 -116
  78. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  79. package/src/__tests__/validate-dev-props.test.ts +56 -0
  80. package/src/__tests__/version.test.ts +35 -0
  81. package/src/__tests__/whoami.test.tsx +264 -125
  82. package/src/__tests__/worker-namespace.test.ts +326 -0
  83. package/src/abort.d.ts +1 -1
  84. package/src/api/dev.ts +210 -0
  85. package/src/api/index.ts +2 -0
  86. package/src/bundle-reporter.tsx +68 -0
  87. package/src/bundle.ts +785 -159
  88. package/src/cfetch/index.ts +120 -81
  89. package/src/cfetch/internal.ts +207 -86
  90. package/src/cli.ts +23 -8
  91. package/src/config/config.ts +236 -195
  92. package/src/config/diagnostics.ts +61 -61
  93. package/src/config/environment.ts +498 -357
  94. package/src/config/index.ts +302 -193
  95. package/src/config/validation-helpers.ts +379 -366
  96. package/src/config/validation.ts +1931 -1376
  97. package/src/config-cache.ts +81 -41
  98. package/src/create-worker-preview.ts +239 -142
  99. package/src/create-worker-upload-form.ts +300 -238
  100. package/src/d1/backups.tsx +218 -0
  101. package/src/d1/constants.ts +2 -0
  102. package/src/d1/create.tsx +63 -0
  103. package/src/d1/delete.tsx +56 -0
  104. package/src/d1/execute.tsx +352 -0
  105. package/src/d1/formatTimeAgo.ts +14 -0
  106. package/src/d1/index.ts +99 -0
  107. package/src/d1/list.tsx +48 -0
  108. package/src/d1/migrations.tsx +446 -0
  109. package/src/d1/options.ts +22 -0
  110. package/src/d1/types.tsx +24 -0
  111. package/src/d1/utils.ts +48 -0
  112. package/src/delete.ts +108 -0
  113. package/src/deployments.ts +77 -0
  114. package/src/deprecated/index.ts +438 -0
  115. package/src/dev/dev-vars.ts +20 -17
  116. package/src/dev/dev.tsx +522 -333
  117. package/src/dev/get-local-persistence-path.tsx +31 -0
  118. package/src/dev/local.tsx +866 -302
  119. package/src/dev/remote.tsx +591 -225
  120. package/src/dev/start-server.ts +538 -0
  121. package/src/dev/use-esbuild.ts +183 -97
  122. package/src/dev/validate-dev-props.ts +31 -0
  123. package/src/dev-registry.tsx +201 -0
  124. package/src/dev.tsx +905 -0
  125. package/src/dialogs.tsx +132 -99
  126. package/src/dispatch-namespace.ts +207 -0
  127. package/src/durable.ts +87 -87
  128. package/src/entry.ts +235 -228
  129. package/src/environment-variables.ts +38 -23
  130. package/src/errors.ts +6 -6
  131. package/src/git-client.ts +124 -0
  132. package/src/global-wrangler-config-path.ts +26 -0
  133. package/src/https-options.ts +84 -80
  134. package/src/index.tsx +625 -2789
  135. package/src/init.ts +970 -0
  136. package/src/inspect.ts +698 -593
  137. package/src/intl-polyfill.d.ts +123 -123
  138. package/src/is-ci.ts +14 -0
  139. package/src/is-interactive.ts +16 -0
  140. package/src/kv/helpers.ts +430 -0
  141. package/src/kv/index.ts +596 -0
  142. package/src/logger.ts +67 -41
  143. package/src/metrics/index.ts +5 -0
  144. package/src/metrics/metrics-config.ts +239 -0
  145. package/src/metrics/metrics-dispatcher.ts +96 -0
  146. package/src/metrics/metrics-usage-headers.ts +24 -0
  147. package/src/metrics/send-event.ts +96 -0
  148. package/src/miniflare-cli/assets.ts +215 -0
  149. package/src/miniflare-cli/index.ts +205 -33
  150. package/src/miniflare-cli/request-context.ts +18 -18
  151. package/src/module-collection.ts +221 -212
  152. package/src/open-in-browser.ts +4 -6
  153. package/src/package-manager.ts +173 -128
  154. package/src/pages/build.tsx +270 -0
  155. package/src/pages/constants.ts +18 -0
  156. package/src/pages/deployment-tails.tsx +284 -0
  157. package/src/pages/deployments.tsx +84 -0
  158. package/src/pages/dev.tsx +708 -0
  159. package/src/pages/errors.ts +66 -0
  160. package/src/pages/functions/buildPlugin.ts +107 -0
  161. package/src/pages/functions/buildWorker.ts +166 -0
  162. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  163. package/src/pages/functions/filepath-routing.ts +189 -0
  164. package/src/pages/functions/identifiers.ts +78 -0
  165. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  166. package/src/pages/functions/routes-consolidation.ts +73 -0
  167. package/src/pages/functions/routes-transformation.test.ts +282 -0
  168. package/src/pages/functions/routes-transformation.ts +115 -0
  169. package/src/pages/functions/routes-validation.test.ts +403 -0
  170. package/src/pages/functions/routes-validation.ts +202 -0
  171. package/src/pages/functions/routes.ts +151 -0
  172. package/src/pages/functions.tsx +82 -0
  173. package/src/pages/hash.tsx +13 -0
  174. package/src/pages/index.tsx +102 -0
  175. package/src/pages/projects.tsx +169 -0
  176. package/src/pages/prompt-select-project.tsx +31 -0
  177. package/src/pages/publish.tsx +451 -0
  178. package/src/pages/types.ts +41 -0
  179. package/src/pages/upload.tsx +426 -0
  180. package/src/pages/utils.ts +23 -0
  181. package/src/parse.ts +208 -125
  182. package/src/paths.ts +53 -8
  183. package/src/proxy.ts +618 -407
  184. package/src/publish/index.ts +270 -0
  185. package/src/publish/publish.ts +1035 -0
  186. package/src/pubsub/index.ts +286 -0
  187. package/src/pubsub/pubsub-commands.tsx +624 -0
  188. package/src/queues/cli/commands/consumer/add.ts +71 -0
  189. package/src/queues/cli/commands/consumer/index.ts +22 -0
  190. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  191. package/src/queues/cli/commands/create.ts +25 -0
  192. package/src/queues/cli/commands/delete.ts +26 -0
  193. package/src/queues/cli/commands/index.ts +33 -0
  194. package/src/queues/cli/commands/list.ts +25 -0
  195. package/src/queues/client.ts +135 -0
  196. package/src/r2/constants.ts +4 -0
  197. package/src/r2/helpers.ts +131 -0
  198. package/src/r2/index.ts +289 -0
  199. package/src/routes.ts +140 -0
  200. package/src/secret/index.ts +378 -0
  201. package/src/selfsigned.d.ts +23 -23
  202. package/src/sites.tsx +273 -227
  203. package/src/tail/createTail.ts +379 -0
  204. package/src/tail/filters.ts +108 -110
  205. package/src/tail/index.ts +211 -296
  206. package/src/tail/printing.ts +86 -46
  207. package/src/type-generation.ts +173 -0
  208. package/src/update-check.ts +11 -11
  209. package/src/user/access.ts +69 -0
  210. package/src/user/choose-account.tsx +69 -0
  211. package/src/user/env-vars.ts +46 -0
  212. package/src/user/generate-auth-url.ts +33 -0
  213. package/src/user/generate-random-state.ts +16 -0
  214. package/src/user/index.ts +3 -0
  215. package/src/user/user.tsx +1192 -0
  216. package/src/utils/collectKeyValues.ts +14 -0
  217. package/src/whoami.tsx +141 -43
  218. package/src/worker.ts +171 -107
  219. package/src/yargs-types.ts +24 -0
  220. package/src/zones.ts +158 -40
  221. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  222. package/templates/checked-fetch.js +17 -0
  223. package/templates/d1-beta-facade.js +205 -0
  224. package/templates/first-party-worker-module-facade.ts +18 -0
  225. package/templates/format-dev-errors.ts +32 -0
  226. package/templates/init-tests/test-jest-new-worker.js +25 -0
  227. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  228. package/templates/middleware/common.ts +62 -0
  229. package/templates/middleware/loader-modules.ts +84 -0
  230. package/templates/middleware/loader-sw.ts +227 -0
  231. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  232. package/templates/middleware/middleware-pretty-error.ts +40 -0
  233. package/templates/middleware/middleware-scheduled.ts +15 -0
  234. package/templates/new-worker-scheduled.js +3 -3
  235. package/templates/new-worker-scheduled.ts +15 -15
  236. package/templates/new-worker.js +3 -3
  237. package/templates/new-worker.ts +15 -15
  238. package/templates/no-op-worker.js +10 -0
  239. package/templates/pages-dev-pipeline.ts +28 -0
  240. package/templates/pages-dev-util.ts +52 -0
  241. package/templates/pages-shim.ts +9 -0
  242. package/templates/pages-template-plugin.ts +171 -0
  243. package/templates/pages-template-worker.ts +189 -0
  244. package/templates/serve-static-assets.ts +63 -0
  245. package/templates/service-bindings-module-facade.js +54 -0
  246. package/templates/service-bindings-sw-facade.js +42 -0
  247. package/templates/tsconfig.json +96 -95
  248. package/wrangler-dist/cli.d.ts +893 -0
  249. package/wrangler-dist/cli.js +146109 -108690
  250. package/pages/functions/buildPlugin.ts +0 -105
  251. package/pages/functions/buildWorker.ts +0 -151
  252. package/pages/functions/filepath-routing.ts +0 -189
  253. package/pages/functions/identifiers.ts +0 -78
  254. package/pages/functions/routes.ts +0 -156
  255. package/pages/functions/template-plugin.ts +0 -147
  256. package/pages/functions/template-worker.ts +0 -143
  257. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  258. package/src/kv.ts +0 -408
  259. package/src/miniflare-cli/enum-keys.ts +0 -17
  260. package/src/pages.tsx +0 -2093
  261. package/src/publish.ts +0 -721
  262. package/src/r2.ts +0 -50
  263. package/src/user.tsx +0 -1214
  264. package/templates/static-asset-facade.js +0 -43
package/src/dev/local.tsx CHANGED
@@ -1,322 +1,886 @@
1
- import { spawn } from "node:child_process";
1
+ import assert from "node:assert";
2
+ import { fork } from "node:child_process";
2
3
  import { realpathSync } from "node:fs";
3
- import { writeFile } from "node:fs/promises";
4
+ import { readFile, writeFile } from "node:fs/promises";
4
5
  import path from "node:path";
6
+ import chalk from "chalk";
7
+ import { npxImport } from "npx-import";
5
8
  import { useState, useEffect, useRef } from "react";
6
9
  import onExit from "signal-exit";
10
+ import { performApiFetch } from "../cfetch/internal";
11
+ import { registerWorker } from "../dev-registry";
7
12
  import useInspector from "../inspect";
8
13
  import { logger } from "../logger";
9
- import { DEFAULT_MODULE_RULES } from "../module-collection";
14
+ import {
15
+ DEFAULT_MODULE_RULES,
16
+ ModuleTypeToRuleType,
17
+ } from "../module-collection";
18
+ import { getBasePath } from "../paths";
10
19
  import { waitForPortToBeAvailable } from "../proxy";
20
+ import { requireAuth } from "../user";
11
21
  import type { Config } from "../config";
22
+ import type { WorkerRegistry } from "../dev-registry";
23
+ import type { LoggerLevel } from "../logger";
24
+ import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli";
12
25
  import type { AssetPaths } from "../sites";
13
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
26
+ import type {
27
+ CfWorkerInit,
28
+ CfScriptFormat,
29
+ CfWasmModuleBindings,
30
+ CfTextBlobBindings,
31
+ CfDataBlobBindings,
32
+ CfDurableObject,
33
+ CfKvNamespace,
34
+ CfR2Bucket,
35
+ CfVars,
36
+ CfQueue,
37
+ CfD1Database,
38
+ } from "../worker";
14
39
  import type { EsbuildBundle } from "./use-esbuild";
40
+ import type {
41
+ Miniflare as Miniflare3Type,
42
+ MiniflareOptions as Miniflare3Options,
43
+ Log as Miniflare3LogType,
44
+ CloudflareFetch,
45
+ } from "@miniflare/tre";
15
46
  import type { MiniflareOptions } from "miniflare";
47
+ import type { ChildProcess } from "node:child_process";
48
+ import type { RequestInit } from "undici";
16
49
 
17
- interface LocalProps {
18
- name: string | undefined;
19
- bundle: EsbuildBundle | undefined;
20
- format: CfScriptFormat | undefined;
21
- compatibilityDate: string;
22
- compatibilityFlags: string[] | undefined;
23
- bindings: CfWorkerInit["bindings"];
24
- localProtocol: "http" | "https";
25
- assetPaths: AssetPaths | undefined;
26
- public: string | undefined;
27
- port: number;
28
- ip: string;
29
- rules: Config["rules"];
30
- inspectorPort: number;
31
- enableLocalPersistence: boolean;
32
- crons: Config["triggers"]["crons"];
50
+ export interface LocalProps {
51
+ name: string | undefined;
52
+ bundle: EsbuildBundle | undefined;
53
+ format: CfScriptFormat | undefined;
54
+ compatibilityDate: string;
55
+ compatibilityFlags: string[] | undefined;
56
+ usageModel: "bundled" | "unbound" | undefined;
57
+ bindings: CfWorkerInit["bindings"];
58
+ workerDefinitions: WorkerRegistry | undefined;
59
+ assetPaths: AssetPaths | undefined;
60
+ port: number;
61
+ ip: string;
62
+ rules: Config["rules"];
63
+ inspectorPort: number;
64
+ localPersistencePath: string | null;
65
+ liveReload: boolean;
66
+ crons: Config["triggers"]["crons"];
67
+ queueConsumers: Config["queues"]["consumers"];
68
+ localProtocol: "http" | "https";
69
+ localUpstream: string | undefined;
70
+ inspect: boolean;
71
+ onReady: ((ip: string, port: number) => void) | undefined;
72
+ logPrefix?: string;
73
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
74
+ testScheduled?: boolean;
75
+ experimentalLocal: boolean | undefined;
76
+ accountId: string | undefined; // Account ID? In local mode??? :exploding_head:
77
+ experimentalLocalRemoteKv: boolean | undefined;
33
78
  }
34
79
 
80
+ type InspectorJSON = {
81
+ id: string;
82
+ title: string;
83
+ type: "node";
84
+ description: string;
85
+ webSocketDebuggerUrl: string;
86
+ devtoolsFrontendUrl: string;
87
+ devtoolsFrontendUrlCompat: string;
88
+ faviconUrl: string;
89
+ url: string;
90
+ }[];
91
+
35
92
  export function Local(props: LocalProps) {
36
- const { inspectorUrl } = useLocalWorker(props);
37
- useInspector({
38
- inspectorUrl,
39
- port: props.inspectorPort,
40
- logToTerminal: false,
41
- });
42
- return null;
93
+ const { inspectorUrl } = useLocalWorker(props);
94
+ useInspector({
95
+ inspectorUrl,
96
+ port: props.inspectorPort,
97
+ logToTerminal: props.experimentalLocal ?? false,
98
+ });
99
+ return null;
43
100
  }
44
101
 
45
102
  function useLocalWorker({
46
- name: workerName,
47
- bundle,
48
- format,
49
- compatibilityDate,
50
- compatibilityFlags,
51
- bindings,
52
- assetPaths,
53
- public: publicDirectory,
54
- port,
55
- rules,
56
- enableLocalPersistence,
57
- ip,
58
- localProtocol,
59
- crons,
103
+ name: workerName,
104
+ bundle,
105
+ format,
106
+ compatibilityDate,
107
+ compatibilityFlags,
108
+ usageModel,
109
+ bindings,
110
+ workerDefinitions,
111
+ assetPaths,
112
+ port,
113
+ inspectorPort,
114
+ rules,
115
+ localPersistencePath,
116
+ liveReload,
117
+ ip,
118
+ crons,
119
+ queueConsumers,
120
+ localProtocol,
121
+ localUpstream,
122
+ inspect,
123
+ onReady,
124
+ logPrefix,
125
+ enablePagesAssetsServiceBinding,
126
+ experimentalLocal,
127
+ accountId,
128
+ experimentalLocalRemoteKv,
60
129
  }: LocalProps) {
61
- // TODO: pass vars via command line
62
- const local = useRef<ReturnType<typeof spawn>>();
63
- const removeSignalExitListener = useRef<() => void>();
64
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
65
- // if we're using local persistence for data, we should use the cwd
66
- // as an explicit path, or else it'll use the temp dir
67
- // which disappears when dev ends
68
- const localPersistencePath = enableLocalPersistence
69
- ? // Maybe we could make the path configurable as well?
70
- path.join(process.cwd(), "wrangler-local-state")
71
- : // We otherwise choose null, but choose true later
72
- // so that it's persisted in the temp dir across a dev session
73
- // even when we change source and reload
74
- null;
75
- useEffect(() => {
76
- const abortController = new AbortController();
77
- async function startLocalWorker() {
78
- if (!bundle || !format) return;
79
-
80
- // port for the worker
81
- await waitForPortToBeAvailable(port, {
82
- retryPeriod: 200,
83
- timeout: 2000,
84
- abortSignal: abortController.signal,
85
- });
86
-
87
- if (publicDirectory) {
88
- throw new Error(
89
- '⎔ A "public" folder is not yet supported in local mode.'
90
- );
91
- }
92
- if (bindings.services && bindings.services.length > 0) {
93
- throw new Error(
94
- "⎔ Service bindings are not yet supported in local mode."
95
- );
96
- }
97
-
98
- // In local mode, we want to copy all referenced modules into
99
- // the output bundle directory before starting up
100
- for (const module of bundle.modules) {
101
- await writeFile(
102
- path.join(path.dirname(bundle.path), module.name),
103
- module.content
104
- );
105
- }
106
-
107
- const scriptPath = realpathSync(bundle.path);
108
-
109
- // the wasm_modules/text_blobs/data_blobs bindings are
110
- // relative to process.cwd(), but the actual worker bundle
111
- // is in the temp output directory; so we rewrite the paths to be absolute,
112
- // letting miniflare resolve them correctly
113
-
114
- // wasm
115
- const wasmBindings: Record<string, string> = {};
116
- for (const [name, filePath] of Object.entries(
117
- bindings.wasm_modules || {}
118
- )) {
119
- wasmBindings[name] = path.join(process.cwd(), filePath);
120
- }
121
-
122
- // text
123
- const textBlobBindings: Record<string, string> = {};
124
- for (const [name, filePath] of Object.entries(
125
- bindings.text_blobs || {}
126
- )) {
127
- textBlobBindings[name] = path.join(process.cwd(), filePath);
128
- }
129
-
130
- // data
131
- const dataBlobBindings: Record<string, string> = {};
132
- for (const [name, filePath] of Object.entries(
133
- bindings.data_blobs || {}
134
- )) {
135
- dataBlobBindings[name] = path.join(process.cwd(), filePath);
136
- }
137
-
138
- if (format === "service-worker") {
139
- for (const { type, name } of bundle.modules) {
140
- if (type === "compiled-wasm") {
141
- // In service-worker format, .wasm modules are referenced by global identifiers,
142
- // so we convert it here.
143
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
144
- // characters with an underscore.
145
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
146
- wasmBindings[identifier] = name;
147
- } else if (type === "text") {
148
- // In service-worker format, text modules are referenced by global identifiers,
149
- // so we convert it here.
150
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
151
- // characters with an underscore.
152
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
153
- textBlobBindings[identifier] = name;
154
- } else if (type === "buffer") {
155
- // In service-worker format, data blobs are referenced by global identifiers,
156
- // so we convert it here.
157
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
158
- // characters with an underscore.
159
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
160
- dataBlobBindings[identifier] = name;
161
- }
162
- }
163
- }
164
-
165
- const options: MiniflareOptions = {
166
- name: workerName,
167
- port,
168
- scriptPath,
169
- https: localProtocol === "https",
170
- host: ip,
171
- modules: format === "modules",
172
- modulesRules: (rules || [])
173
- .concat(DEFAULT_MODULE_RULES)
174
- .map(({ type, globs: include, fallthrough }) => ({
175
- type,
176
- include,
177
- fallthrough,
178
- })),
179
- compatibilityDate,
180
- compatibilityFlags,
181
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
182
- durableObjects: Object.fromEntries(
183
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
184
- (value) => [value.name, value.class_name]
185
- )
186
- ),
187
- ...(localPersistencePath
188
- ? {
189
- kvPersist: path.join(localPersistencePath, "kv"),
190
- durableObjectsPersist: path.join(localPersistencePath, "do"),
191
- cachePersist: path.join(localPersistencePath, "cache"),
192
- }
193
- : {
194
- // We mark these as true, so that they'll
195
- // persist in the temp directory.
196
- // This means they'll persist across a dev session,
197
- // even if we change source and reload,
198
- // and be deleted when the dev session ends
199
- durableObjectsPersist: true,
200
- cachePersist: true,
201
- kvPersist: true,
202
- }),
203
-
204
- sitePath: assetPaths?.assetDirectory
205
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
206
- : undefined,
207
- siteInclude: assetPaths?.includePatterns.length
208
- ? assetPaths?.includePatterns
209
- : undefined,
210
- siteExclude: assetPaths?.excludePatterns.length
211
- ? assetPaths.excludePatterns
212
- : undefined,
213
- bindings: bindings.vars,
214
- wasmBindings,
215
- textBlobBindings,
216
- dataBlobBindings,
217
- sourceMap: true,
218
- logUnhandledRejections: true,
219
- crons,
220
- };
221
-
222
- // The path to the Miniflare CLI assumes that this file is being run from
223
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
224
- // If either of those paths change this line needs updating.
225
- const miniflareCLIPath = path.resolve(
226
- __dirname,
227
- "../miniflare-dist/index.mjs"
228
- );
229
- const optionsArg = JSON.stringify(options, null);
230
-
231
- logger.log("⎔ Starting a local server...");
232
- local.current = spawn(
233
- "node",
234
- [
235
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
236
- "--no-warnings", // hide annoying Node warnings
237
- "--inspect", // start Miniflare listening for a debugger to attach
238
- miniflareCLIPath,
239
- optionsArg,
240
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
241
- ],
242
- {
243
- cwd: path.dirname(scriptPath),
244
- }
245
- );
246
-
247
- local.current.on("close", (code) => {
248
- if (code) {
249
- logger.log(`Miniflare process exited with code ${code}`);
250
- }
251
- });
252
-
253
- local.current.stdout?.on("data", (data: Buffer) => {
254
- process.stdout.write(data);
255
- });
256
-
257
- local.current.stderr?.on("data", (data: Buffer) => {
258
- const matches =
259
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
260
- data.toString()
261
- );
262
- if (matches) {
263
- setInspectorUrl(matches[1]);
264
- }
265
- });
266
-
267
- local.current.on("exit", (code) => {
268
- if (code) {
269
- logger.error(`Miniflare process exited with code ${code}`);
270
- }
271
- });
272
-
273
- local.current.on("error", (error: Error) => {
274
- logger.error(`Miniflare process failed to spawn`);
275
- logger.error(error);
276
- });
277
-
278
- removeSignalExitListener.current = onExit((_code, _signal) => {
279
- logger.log("⎔ Shutting down local server.");
280
- local.current?.kill();
281
- local.current = undefined;
282
- });
283
- }
284
-
285
- startLocalWorker().catch((err) => {
286
- logger.error("local worker:", err);
287
- });
288
-
289
- return () => {
290
- abortController.abort();
291
- if (local.current) {
292
- logger.log("⎔ Shutting down local server.");
293
- local.current?.kill();
294
- local.current = undefined;
295
- removeSignalExitListener.current && removeSignalExitListener.current();
296
- removeSignalExitListener.current = undefined;
297
- }
298
- };
299
- }, [
300
- bundle,
301
- workerName,
302
- format,
303
- port,
304
- localProtocol,
305
- ip,
306
- bindings.durable_objects?.bindings,
307
- bindings.kv_namespaces,
308
- bindings.vars,
309
- bindings.services,
310
- compatibilityDate,
311
- compatibilityFlags,
312
- localPersistencePath,
313
- assetPaths,
314
- publicDirectory,
315
- rules,
316
- bindings.wasm_modules,
317
- bindings.text_blobs,
318
- bindings.data_blobs,
319
- crons,
320
- ]);
321
- return { inspectorUrl };
130
+ // TODO: pass vars via command line
131
+ const local = useRef<ChildProcess>();
132
+ const experimentalLocalRef = useRef<Miniflare3Type>();
133
+ const removeSignalExitListener = useRef<() => void>();
134
+ const removeExperimentalLocalSignalExitListener = useRef<() => void>();
135
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
136
+
137
+ useEffect(() => {
138
+ if (bindings.services && bindings.services.length > 0) {
139
+ logger.warn(
140
+ "⎔ Support for service bindings in local mode is experimental and may change."
141
+ );
142
+ }
143
+ }, [bindings.services]);
144
+
145
+ useEffect(() => {
146
+ const externalDurableObjects = (
147
+ bindings.durable_objects?.bindings || []
148
+ ).filter((binding) => binding.script_name);
149
+
150
+ if (externalDurableObjects.length > 0) {
151
+ logger.warn(
152
+ "⎔ Support for external Durable Objects in local mode is experimental and may change."
153
+ );
154
+ }
155
+ }, [bindings.durable_objects?.bindings]);
156
+
157
+ useEffect(() => {
158
+ const abortController = new AbortController();
159
+ async function startLocalWorker() {
160
+ if (!bundle || !format) return;
161
+
162
+ // port for the worker
163
+ await waitForPortToBeAvailable(port, {
164
+ retryPeriod: 200,
165
+ timeout: 2000,
166
+ abortSignal: abortController.signal,
167
+ });
168
+
169
+ // In local mode, we want to copy all referenced modules into
170
+ // the output bundle directory before starting up
171
+ for (const module of bundle.modules) {
172
+ await writeFile(
173
+ path.join(path.dirname(bundle.path), module.name),
174
+ module.content
175
+ );
176
+ }
177
+
178
+ const scriptPath = realpathSync(bundle.path);
179
+
180
+ const upstream =
181
+ typeof localUpstream === "string"
182
+ ? `${localProtocol}://${localUpstream}`
183
+ : undefined;
184
+
185
+ const {
186
+ externalDurableObjects,
187
+ internalDurableObjects,
188
+ wasmBindings,
189
+ textBlobBindings,
190
+ dataBlobBindings,
191
+ } = setupBindings({
192
+ wasm_modules: bindings.wasm_modules,
193
+ text_blobs: bindings.text_blobs,
194
+ data_blobs: bindings.data_blobs,
195
+ durable_objects: bindings.durable_objects,
196
+ format,
197
+ bundle,
198
+ });
199
+
200
+ const { forkOptions, miniflareCLIPath, options } = setupMiniflareOptions({
201
+ workerName,
202
+ port,
203
+ scriptPath,
204
+ localProtocol,
205
+ ip,
206
+ format,
207
+ rules,
208
+ compatibilityDate,
209
+ compatibilityFlags,
210
+ usageModel,
211
+ kv_namespaces: bindings?.kv_namespaces,
212
+ r2_buckets: bindings?.r2_buckets,
213
+ queueBindings: bindings?.queues,
214
+ queueConsumers: queueConsumers,
215
+ d1_databases: bindings?.d1_databases,
216
+ internalDurableObjects,
217
+ externalDurableObjects,
218
+ localPersistencePath,
219
+ liveReload,
220
+ assetPaths,
221
+ vars: bindings?.vars,
222
+ wasmBindings,
223
+ textBlobBindings,
224
+ dataBlobBindings,
225
+ crons,
226
+ upstream,
227
+ logPrefix,
228
+ workerDefinitions,
229
+ enablePagesAssetsServiceBinding,
230
+ });
231
+
232
+ if (experimentalLocal) {
233
+ const log = await buildMiniflare3Logger(logPrefix);
234
+ const mf3Options = await transformMf2OptionsToMf3Options({
235
+ miniflare2Options: options,
236
+ format,
237
+ bundle,
238
+ log,
239
+ kvNamespaces: bindings?.kv_namespaces,
240
+ r2Buckets: bindings?.r2_buckets,
241
+ authenticatedAccountId: accountId,
242
+ kvRemote: experimentalLocalRemoteKv,
243
+ inspectorPort,
244
+ });
245
+
246
+ const current = experimentalLocalRef.current;
247
+
248
+ if (current === undefined) {
249
+ // If we don't have an active Miniflare instance, create a new one
250
+ const { Miniflare } = await getMiniflare3();
251
+ if (abortController.signal.aborted) return;
252
+ const mf = new Miniflare(mf3Options);
253
+ experimentalLocalRef.current = mf;
254
+ removeExperimentalLocalSignalExitListener.current = onExit(() => {
255
+ logger.log("⎔ Shutting down experimental local server.");
256
+ mf.dispose();
257
+ experimentalLocalRef.current = undefined;
258
+ });
259
+ await mf.ready;
260
+ } else {
261
+ // Otherwise, reuse the existing instance with its loopback server
262
+ // and just update the options
263
+ if (abortController.signal.aborted) return;
264
+ logger.log("⎔ Reloading experimental local server.");
265
+ await current.setOptions(mf3Options);
266
+ }
267
+
268
+ try {
269
+ // fetch the inspector JSON response from the DevTools Inspector protocol
270
+ const inspectorJSONArr = (await (
271
+ await fetch(`http://127.0.0.1:${inspectorPort}/json`)
272
+ ).json()) as InspectorJSON;
273
+
274
+ const foundInspectorURL = inspectorJSONArr?.find((inspectorJSON) =>
275
+ inspectorJSON.id.startsWith("core:user")
276
+ )?.webSocketDebuggerUrl;
277
+ if (foundInspectorURL === undefined) {
278
+ setInspectorUrl(undefined);
279
+ } else {
280
+ const url = new URL(foundInspectorURL);
281
+ // Force inspector URL to be different on each reload so `useEffect`
282
+ // in `useInspector` is re-run to connect to newly restarted
283
+ // `workerd` server when updating options. Can't use a query param
284
+ // here as that seems to cause an infinite connection loop, can't
285
+ // use a hash as those are forbidden by `ws`, so username it is.
286
+ url.username = `${Date.now()}-${Math.floor(
287
+ Math.random() * Number.MAX_SAFE_INTEGER
288
+ )}`;
289
+ setInspectorUrl(url.toString());
290
+ }
291
+ } catch (error: unknown) {
292
+ logger.error("Error attempting to retrieve Debugger URL:", error);
293
+ }
294
+
295
+ return;
296
+ }
297
+
298
+ const nodeOptions = setupNodeOptions({ inspect, ip, inspectorPort });
299
+ logger.log("⎔ Starting a local server...");
300
+
301
+ const child = (local.current = fork(miniflareCLIPath, forkOptions, {
302
+ cwd: path.dirname(scriptPath),
303
+ execArgv: nodeOptions,
304
+ stdio: "pipe",
305
+ env: {
306
+ ...process.env,
307
+ FORCE_COLOR: chalk.supportsColor.hasBasic ? "1" : undefined,
308
+ },
309
+ }));
310
+
311
+ child.on("message", async (messageString) => {
312
+ const message = JSON.parse(messageString as string);
313
+ if (message.ready) {
314
+ // Let's register our presence in the dev registry
315
+ if (workerName) {
316
+ await registerWorker(workerName, {
317
+ protocol: localProtocol,
318
+ mode: "local",
319
+ port,
320
+ host: ip,
321
+ durableObjects: internalDurableObjects.map((binding) => ({
322
+ name: binding.name,
323
+ className: binding.class_name,
324
+ })),
325
+ ...(message.durableObjectsPort
326
+ ? {
327
+ durableObjectsHost: ip,
328
+ durableObjectsPort: message.durableObjectsPort,
329
+ }
330
+ : {}),
331
+ });
332
+ }
333
+ onReady?.(ip, message.mfPort);
334
+ }
335
+ });
336
+
337
+ child.on("close", (code) => {
338
+ if (code) {
339
+ logger.log(`Miniflare process exited with code ${code}`);
340
+ }
341
+ });
342
+
343
+ child.stdout?.on("data", (data: Buffer) => {
344
+ process.stdout.write(data);
345
+ });
346
+
347
+ // parse the node inspector url (which may be received in chunks) from stderr
348
+ let stderrData = "";
349
+ let inspectorUrlFound = false;
350
+ child.stderr?.on("data", (data: Buffer) => {
351
+ if (!inspectorUrlFound) {
352
+ stderrData += data.toString();
353
+ const matches =
354
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
355
+ stderrData
356
+ );
357
+ if (matches) {
358
+ inspectorUrlFound = true;
359
+ setInspectorUrl(matches[1]);
360
+ }
361
+ }
362
+
363
+ process.stderr.write(data);
364
+ });
365
+
366
+ child.on("exit", (code) => {
367
+ if (code) {
368
+ logger.error(`Miniflare process exited with code ${code}`);
369
+ }
370
+ });
371
+
372
+ child.on("error", (error: Error) => {
373
+ logger.error(`Miniflare process failed to spawn`);
374
+ logger.error(error);
375
+ });
376
+
377
+ removeSignalExitListener.current = onExit((_code, _signal) => {
378
+ logger.log("⎔ Shutting down local server.");
379
+ child.kill();
380
+ local.current = undefined;
381
+ });
382
+ }
383
+
384
+ startLocalWorker().catch((err) => {
385
+ logger.error("local worker:", err);
386
+ });
387
+
388
+ return () => {
389
+ abortController.abort();
390
+ if (local.current) {
391
+ logger.log("⎔ Shutting down local server.");
392
+ local.current?.kill();
393
+ local.current = undefined;
394
+ }
395
+ removeSignalExitListener.current?.();
396
+ removeSignalExitListener.current = undefined;
397
+ };
398
+ }, [
399
+ bundle,
400
+ workerName,
401
+ format,
402
+ port,
403
+ inspectorPort,
404
+ ip,
405
+ queueConsumers,
406
+ bindings.queues,
407
+ bindings.durable_objects,
408
+ bindings.kv_namespaces,
409
+ bindings.r2_buckets,
410
+ bindings.d1_databases,
411
+ bindings.vars,
412
+ bindings.services,
413
+ workerDefinitions,
414
+ compatibilityDate,
415
+ compatibilityFlags,
416
+ usageModel,
417
+ localPersistencePath,
418
+ liveReload,
419
+ assetPaths,
420
+ rules,
421
+ bindings.wasm_modules,
422
+ bindings.text_blobs,
423
+ bindings.data_blobs,
424
+ crons,
425
+ localProtocol,
426
+ localUpstream,
427
+ inspect,
428
+ logPrefix,
429
+ onReady,
430
+ enablePagesAssetsServiceBinding,
431
+ experimentalLocal,
432
+ accountId,
433
+ experimentalLocalRemoteKv,
434
+ ]);
435
+
436
+ // Rather than disposing the Miniflare instance on every reload, only dispose
437
+ // it if local mode is disabled and the `Local` component is unmounted. This
438
+ // allows us to use the more efficient `Miniflare#setOptions` on reload which
439
+ // retains internal state (e.g. the Miniflare loopback server).
440
+ useEffect(
441
+ () => () => {
442
+ if (experimentalLocalRef.current) {
443
+ logger.log("⎔ Shutting down experimental local server.");
444
+ // Initialisation errors are also thrown asynchronously by dispose().
445
+ // The catch() above should've caught them though.
446
+ experimentalLocalRef.current?.dispose().catch(() => {});
447
+ experimentalLocalRef.current = undefined;
448
+ }
449
+ removeExperimentalLocalSignalExitListener.current?.();
450
+ removeExperimentalLocalSignalExitListener.current = undefined;
451
+ },
452
+ []
453
+ );
454
+
455
+ return { inspectorUrl };
456
+ }
457
+
458
+ interface SetupBindingsProps {
459
+ wasm_modules: CfWasmModuleBindings | undefined;
460
+ text_blobs: CfTextBlobBindings | undefined;
461
+ data_blobs: CfDataBlobBindings | undefined;
462
+ durable_objects: { bindings: CfDurableObject[] } | undefined;
463
+ bundle: EsbuildBundle;
464
+ format: CfScriptFormat;
465
+ }
466
+
467
+ export function setupBindings({
468
+ wasm_modules,
469
+ text_blobs,
470
+ data_blobs,
471
+ durable_objects,
472
+ format,
473
+ bundle,
474
+ }: SetupBindingsProps) {
475
+ // the wasm_modules/text_blobs/data_blobs bindings are
476
+ // relative to process.cwd(), but the actual worker bundle
477
+ // is in the temp output directory; so we rewrite the paths to be absolute,
478
+ // letting miniflare resolve them correctly
479
+
480
+ // wasm
481
+ const wasmBindings: Record<string, string> = {};
482
+ for (const [name, filePath] of Object.entries(wasm_modules || {})) {
483
+ wasmBindings[name] = path.join(process.cwd(), filePath);
484
+ }
485
+
486
+ // text
487
+ const textBlobBindings: Record<string, string> = {};
488
+ for (const [name, filePath] of Object.entries(text_blobs || {})) {
489
+ textBlobBindings[name] = path.join(process.cwd(), filePath);
490
+ }
491
+
492
+ // data
493
+ const dataBlobBindings: Record<string, string> = {};
494
+ for (const [name, filePath] of Object.entries(data_blobs || {})) {
495
+ dataBlobBindings[name] = path.join(process.cwd(), filePath);
496
+ }
497
+
498
+ if (format === "service-worker") {
499
+ for (const { type, name } of bundle.modules) {
500
+ if (type === "compiled-wasm") {
501
+ // In service-worker format, .wasm modules are referenced by global identifiers,
502
+ // so we convert it here.
503
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
504
+ // characters with an underscore.
505
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
506
+ wasmBindings[identifier] = name;
507
+ } else if (type === "text") {
508
+ // In service-worker format, text modules are referenced by global identifiers,
509
+ // so we convert it here.
510
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
511
+ // characters with an underscore.
512
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
513
+ textBlobBindings[identifier] = name;
514
+ } else if (type === "buffer") {
515
+ // In service-worker format, data blobs are referenced by global identifiers,
516
+ // so we convert it here.
517
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
518
+ // characters with an underscore.
519
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
520
+ dataBlobBindings[identifier] = name;
521
+ }
522
+ }
523
+ }
524
+
525
+ const internalDurableObjects = (durable_objects?.bindings || []).filter(
526
+ (binding) => !binding.script_name
527
+ );
528
+ const externalDurableObjects = (durable_objects?.bindings || []).filter(
529
+ (binding) => binding.script_name
530
+ );
531
+ return {
532
+ internalDurableObjects,
533
+ externalDurableObjects,
534
+ wasmBindings,
535
+ textBlobBindings,
536
+ dataBlobBindings,
537
+ };
538
+ }
539
+
540
+ interface SetupMiniflareOptionsProps {
541
+ workerName: string | undefined;
542
+ port: number;
543
+ scriptPath: string;
544
+ localProtocol: "http" | "https";
545
+ ip: string;
546
+ format: CfScriptFormat;
547
+ rules: Config["rules"];
548
+ compatibilityDate: string;
549
+ compatibilityFlags: string[] | undefined;
550
+ usageModel: "bundled" | "unbound" | undefined;
551
+ kv_namespaces: CfKvNamespace[] | undefined;
552
+ queueBindings: CfQueue[] | undefined;
553
+ queueConsumers: Config["queues"]["consumers"];
554
+ r2_buckets: CfR2Bucket[] | undefined;
555
+ d1_databases: CfD1Database[] | undefined;
556
+ internalDurableObjects: CfDurableObject[];
557
+ externalDurableObjects: CfDurableObject[];
558
+ localPersistencePath: string | null;
559
+ liveReload: boolean;
560
+ assetPaths: AssetPaths | undefined;
561
+ vars: CfVars | undefined;
562
+ wasmBindings: Record<string, string>;
563
+ textBlobBindings: Record<string, string>;
564
+ dataBlobBindings: Record<string, string>;
565
+ crons: Config["triggers"]["crons"];
566
+ upstream: string | undefined;
567
+ logPrefix: string | undefined;
568
+ workerDefinitions: WorkerRegistry | undefined;
569
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
570
+ }
571
+
572
+ export function setupMiniflareOptions({
573
+ workerName,
574
+ port,
575
+ scriptPath,
576
+ localProtocol,
577
+ ip,
578
+ format,
579
+ rules,
580
+ compatibilityDate,
581
+ compatibilityFlags,
582
+ usageModel,
583
+ kv_namespaces,
584
+ queueBindings,
585
+ queueConsumers,
586
+ r2_buckets,
587
+ d1_databases,
588
+ internalDurableObjects,
589
+ externalDurableObjects,
590
+ localPersistencePath,
591
+ liveReload,
592
+ assetPaths,
593
+ vars,
594
+ wasmBindings,
595
+ textBlobBindings,
596
+ dataBlobBindings,
597
+ crons,
598
+ upstream,
599
+ logPrefix,
600
+ workerDefinitions,
601
+ enablePagesAssetsServiceBinding,
602
+ }: SetupMiniflareOptionsProps): {
603
+ miniflareCLIPath: string;
604
+ forkOptions: string[];
605
+ options: MiniflareOptions;
606
+ } {
607
+ // It's now getting _really_ messy now with Pages ASSETS binding outside and the external Durable Objects inside.
608
+ const options: MiniflareOptions = {
609
+ name: workerName,
610
+ port,
611
+ scriptPath,
612
+ https: localProtocol === "https",
613
+ host: ip,
614
+ modules: format === "modules",
615
+ modulesRules: (rules || [])
616
+ .concat(DEFAULT_MODULE_RULES)
617
+ .map(({ type, globs: include, fallthrough }) => ({
618
+ type,
619
+ include,
620
+ fallthrough,
621
+ })),
622
+ compatibilityDate,
623
+ compatibilityFlags,
624
+ usageModel,
625
+ kvNamespaces: kv_namespaces?.map((kv) => kv.binding),
626
+ queueBindings: queueBindings?.map((queue) => {
627
+ return { name: queue.binding, queueName: queue.queue_name };
628
+ }),
629
+ queueConsumers: queueConsumers?.map((consumer) => {
630
+ const waitMs = consumer.max_batch_timeout
631
+ ? 1000 * consumer.max_batch_timeout
632
+ : undefined;
633
+ return {
634
+ queueName: consumer.queue,
635
+ maxBatchSize: consumer.max_batch_size,
636
+ maxWaitMs: waitMs,
637
+ maxRetries: consumer.max_retries,
638
+ deadLetterQueue: consumer.dead_letter_queue,
639
+ };
640
+ }),
641
+ r2Buckets: r2_buckets?.map((r2) => r2.binding),
642
+ durableObjects: Object.fromEntries(
643
+ internalDurableObjects.map((binding) => [
644
+ binding.name,
645
+ binding.class_name,
646
+ ])
647
+ ),
648
+ externalDurableObjects: Object.fromEntries(
649
+ externalDurableObjects
650
+ .map((binding) => {
651
+ const service =
652
+ workerDefinitions &&
653
+ workerDefinitions[binding.script_name as string];
654
+ if (!service) return [binding.name, undefined];
655
+
656
+ const name = service.durableObjects.find(
657
+ (durableObject) => durableObject.className === binding.class_name
658
+ )?.name;
659
+ if (!name) return [binding.name, undefined];
660
+
661
+ return [
662
+ binding.name,
663
+ {
664
+ name,
665
+ host: service.durableObjectsHost,
666
+ port: service.durableObjectsPort,
667
+ },
668
+ ];
669
+ })
670
+ .filter(([_, details]) => !!details)
671
+ ),
672
+ d1Databases: d1_databases?.map((db) => db.binding),
673
+ ...(localPersistencePath
674
+ ? {
675
+ cachePersist: path.join(localPersistencePath, "cache"),
676
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
677
+ kvPersist: path.join(localPersistencePath, "kv"),
678
+ r2Persist: path.join(localPersistencePath, "r2"),
679
+ d1Persist: path.join(localPersistencePath, "d1"),
680
+ }
681
+ : {
682
+ // We mark these as true, so that they'll
683
+ // persist in the temp directory.
684
+ // This means they'll persist across a dev session,
685
+ // even if we change source and reload,
686
+ // and be deleted when the dev session ends
687
+ cachePersist: true,
688
+ durableObjectsPersist: true,
689
+ kvPersist: true,
690
+ r2Persist: true,
691
+ }),
692
+
693
+ liveReload,
694
+ sitePath: assetPaths?.assetDirectory
695
+ ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
696
+ : undefined,
697
+ siteInclude: assetPaths?.includePatterns.length
698
+ ? assetPaths?.includePatterns
699
+ : undefined,
700
+ siteExclude: assetPaths?.excludePatterns.length
701
+ ? assetPaths.excludePatterns
702
+ : undefined,
703
+ bindings: vars,
704
+ wasmBindings,
705
+ textBlobBindings,
706
+ dataBlobBindings,
707
+ sourceMap: true,
708
+ logUnhandledRejections: true,
709
+ crons,
710
+ upstream,
711
+ logLevel: logger.loggerLevel,
712
+ logOptions: logPrefix ? { prefix: logPrefix } : undefined,
713
+ enablePagesAssetsServiceBinding,
714
+ };
715
+ // The path to the Miniflare CLI assumes that this file is being run from
716
+ // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
717
+ // If either of those paths change this line needs updating.
718
+ const miniflareCLIPath = path.resolve(
719
+ getBasePath(),
720
+ "miniflare-dist/index.mjs"
721
+ );
722
+ const miniflareOptions = JSON.stringify(options, null);
723
+ const forkOptions = [miniflareOptions];
724
+ if (enablePagesAssetsServiceBinding) {
725
+ forkOptions.push(JSON.stringify(enablePagesAssetsServiceBinding));
726
+ }
727
+ return { miniflareCLIPath, forkOptions, options };
728
+ }
729
+
730
+ export function setupNodeOptions({
731
+ inspect,
732
+ ip,
733
+ inspectorPort,
734
+ }: {
735
+ inspect: boolean;
736
+ ip: string;
737
+ inspectorPort: number;
738
+ }) {
739
+ const nodeOptions = [
740
+ "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
741
+ "--no-warnings", // hide annoying Node warnings
742
+ // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
743
+ ];
744
+ if (inspect) {
745
+ nodeOptions.push("--inspect=" + `${ip}:${inspectorPort}`); // start Miniflare listening for a debugger to attach
746
+ }
747
+ return nodeOptions;
748
+ }
749
+
750
+ export interface SetupMiniflare3Options {
751
+ // Regular Miniflare 2 options to transform
752
+ miniflare2Options: MiniflareOptions;
753
+ // Miniflare 3 requires all modules to be manually specified
754
+ format: CfScriptFormat;
755
+ bundle: EsbuildBundle;
756
+
757
+ // Miniflare's logger
758
+ log: Miniflare3LogType;
759
+
760
+ // Miniflare 3 accepts namespace/bucket names in addition to binding names.
761
+ // This means multiple workers persisting to the same location can have
762
+ // different binding names for the same namespace/bucket. Therefore, we need
763
+ // the full KV/R2 arrays. This is also required for remote KV storage, as
764
+ // we need actual namespace IDs to connect to.
765
+ kvNamespaces: CfKvNamespace[] | undefined;
766
+ r2Buckets: CfR2Bucket[] | undefined;
767
+
768
+ // Account ID to use for authenticated Cloudflare fetch. If true, prompt
769
+ // user for ID if multiple available.
770
+ authenticatedAccountId: string | true | undefined;
771
+ // Whether to read/write from/to real KV namespaces
772
+ kvRemote: boolean | undefined;
773
+
774
+ // Port to start DevTools inspector server on
775
+ inspectorPort: number;
776
+ }
777
+
778
+ export async function buildMiniflare3Logger(
779
+ logPrefix?: string
780
+ ): Promise<Miniflare3LogType> {
781
+ const { Log, NoOpLog, LogLevel } = await getMiniflare3();
782
+
783
+ let level = logger.loggerLevel.toUpperCase() as Uppercase<LoggerLevel>;
784
+ if (level === "LOG") level = "INFO";
785
+ const logLevel = LogLevel[level];
786
+
787
+ return logLevel === LogLevel.NONE
788
+ ? new NoOpLog()
789
+ : new Log(logLevel, { prefix: logPrefix });
790
+ }
791
+
792
+ export async function transformMf2OptionsToMf3Options({
793
+ miniflare2Options,
794
+ format,
795
+ bundle,
796
+ log,
797
+ kvNamespaces,
798
+ r2Buckets,
799
+ authenticatedAccountId,
800
+ kvRemote,
801
+ inspectorPort,
802
+ }: SetupMiniflare3Options): Promise<Miniflare3Options> {
803
+ // Build authenticated Cloudflare API fetch function if required
804
+ let cloudflareFetch: CloudflareFetch | undefined;
805
+ if (kvRemote && authenticatedAccountId !== undefined) {
806
+ const preferredAccountId =
807
+ authenticatedAccountId === true ? undefined : authenticatedAccountId;
808
+ const accountId = await requireAuth({ account_id: preferredAccountId });
809
+ cloudflareFetch = (resource, searchParams, init) => {
810
+ resource = `/accounts/${accountId}/${resource}`;
811
+ // Miniflare and Wrangler's `undici` versions may be slightly different,
812
+ // but their `RequestInit` types *should* be compatible
813
+ return performApiFetch(resource, init as RequestInit, searchParams);
814
+ };
815
+ }
816
+
817
+ const options: Miniflare3Options = {
818
+ ...miniflare2Options,
819
+ // Miniflare 3 distinguishes between binding name and namespace/bucket IDs.
820
+ kvNamespaces: Object.fromEntries(
821
+ kvNamespaces?.map(({ binding, id }) => [binding, id]) ?? []
822
+ ),
823
+ r2Buckets: Object.fromEntries(
824
+ r2Buckets?.map(({ binding, bucket_name }) => [binding, bucket_name]) ?? []
825
+ ),
826
+ inspectorPort,
827
+ verbose: true,
828
+ cloudflareFetch,
829
+ log,
830
+ };
831
+
832
+ if (format === "modules") {
833
+ // Manually specify all modules from the bundle. If we didn't do this,
834
+ // Miniflare 3 would try collect them automatically again itself.
835
+
836
+ // Resolve entrypoint relative to the temporary directory, ensuring
837
+ // path doesn't start with `..`, which causes issues in `workerd`.
838
+ // Also ensures other modules with relative names can be resolved.
839
+ const root = path.dirname(bundle.path);
840
+
841
+ assert.strictEqual(bundle.type, "esm");
842
+ // Required for source mapped paths to resolve correctly
843
+ options.modulesRoot = root;
844
+ options.modules = [
845
+ // Entrypoint
846
+ {
847
+ type: "ESModule",
848
+ path: bundle.path,
849
+ contents: await readFile(bundle.path, "utf-8"),
850
+ },
851
+ // Misc (WebAssembly, etc, ...)
852
+ ...bundle.modules.map((module) => ({
853
+ type: ModuleTypeToRuleType[module.type ?? "esm"],
854
+ path: path.resolve(root, module.name),
855
+ contents: module.content,
856
+ })),
857
+ ];
858
+ }
859
+
860
+ if (kvRemote) {
861
+ // `kvPersist` is always assigned a truthy value in `setupMiniflareOptions`
862
+ assert(options.kvPersist);
863
+ const kvRemoteCache =
864
+ options.kvPersist === true
865
+ ? // If storing in temporary directory, find this path from the bundle
866
+ // output path
867
+ path.join(path.dirname(bundle.path), ".mf", "kv-remote")
868
+ : // Otherwise, `kvPersist` looks like `.../kv`, so rewrite it to
869
+ // `kv-remote` since the expected metadata format for remote storage
870
+ // is different to local
871
+ path.join(path.dirname(options.kvPersist), "kv-remote");
872
+ options.kvPersist = `remote:?cache=${encodeURIComponent(kvRemoteCache)}`;
873
+ }
874
+
875
+ return options;
876
+ }
877
+
878
+ // Caching of the `npx-import`ed `@miniflare/tre` package
879
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
880
+ let miniflare3Module: typeof import("@miniflare/tre");
881
+ export async function getMiniflare3(): Promise<
882
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
883
+ typeof import("@miniflare/tre")
884
+ > {
885
+ return (miniflare3Module ??= await npxImport("@miniflare/tre@3.0.0-next.7"));
322
886
  }