wrangler 0.0.0-eebdb6c → 0.0.0-eec88346

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