wrangler 0.0.0-e6e1daba → 0.0.0-e70806f1

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