wrangler 0.0.0-e464fcdb → 0.0.0-e4bb5f36

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