wrangler 0.0.0-e2f9bb2 → 0.0.0-e30d1013

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