wrangler 0.0.0-e351afcf → 0.0.0-e39e9ff4

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 (324) hide show
  1. package/README.md +10 -12
  2. package/bin/wrangler.js +13 -74
  3. package/config-schema.json +2900 -0
  4. package/package.json +224 -199
  5. package/templates/__tests__/tsconfig.json +1 -1
  6. package/templates/checked-fetch.js +10 -3
  7. package/templates/facade.d.ts +7 -2
  8. package/templates/gitignore +0 -5
  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 +93 -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-serve-static-assets.d.ts +6 -0
  16. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  17. package/templates/modules-watch-stub.js +4 -0
  18. package/templates/new-worker-scheduled.ts +1 -1
  19. package/templates/new-worker.ts +1 -1
  20. package/templates/pages-dev-pipeline.ts +2 -1
  21. package/templates/pages-dev-util.ts +4 -1
  22. package/templates/pages-shim.ts +0 -3
  23. package/templates/pages-template-plugin.ts +12 -2
  24. package/templates/pages-template-worker.ts +11 -2
  25. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  26. package/templates/startDevWorker/ProxyWorker.ts +331 -0
  27. package/templates/tsconfig.json +1 -1
  28. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  29. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  30. package/wrangler-dist/ProxyWorker.js +240 -0
  31. package/wrangler-dist/ProxyWorker.js.map +6 -0
  32. package/wrangler-dist/cli.d.ts +22636 -297
  33. package/wrangler-dist/cli.js +136177 -115703
  34. package/wrangler-dist/wasm-sync.wasm +0 -0
  35. package/import_meta_url.js +0 -3
  36. package/miniflare-config-stubs/.env.empty +0 -0
  37. package/miniflare-config-stubs/package.empty.json +0 -1
  38. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  39. package/miniflare-dist/index.mjs +0 -6442
  40. package/src/__tests__/access.test.ts +0 -25
  41. package/src/__tests__/api-dev.test.ts +0 -238
  42. package/src/__tests__/api-devregistry.test.ts +0 -121
  43. package/src/__tests__/api.test.ts +0 -102
  44. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  45. package/src/__tests__/config-cache.test.ts +0 -42
  46. package/src/__tests__/configuration.test.ts +0 -4509
  47. package/src/__tests__/constellation.test.ts +0 -371
  48. package/src/__tests__/d1/d1.test.ts +0 -82
  49. package/src/__tests__/d1/execute.test.ts +0 -66
  50. package/src/__tests__/d1/migrate.test.ts +0 -257
  51. package/src/__tests__/d1/splitter.test.ts +0 -255
  52. package/src/__tests__/delete.test.ts +0 -272
  53. package/src/__tests__/deployments.test.ts +0 -369
  54. package/src/__tests__/dev.test.tsx +0 -1617
  55. package/src/__tests__/generate.test.ts +0 -237
  56. package/src/__tests__/get-host-from-url.test.ts +0 -16
  57. package/src/__tests__/guess-worker-format.test.ts +0 -120
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/end-event-loop.ts +0 -6
  61. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  62. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  63. package/src/__tests__/helpers/mock-bin.ts +0 -36
  64. package/src/__tests__/helpers/mock-console.ts +0 -112
  65. package/src/__tests__/helpers/mock-dialogs.ts +0 -139
  66. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +0 -25
  67. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -11
  68. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  69. package/src/__tests__/helpers/mock-istty.ts +0 -74
  70. package/src/__tests__/helpers/mock-known-routes.ts +0 -12
  71. package/src/__tests__/helpers/mock-kv.ts +0 -46
  72. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -263
  73. package/src/__tests__/helpers/mock-process.ts +0 -34
  74. package/src/__tests__/helpers/mock-set-timeout.ts +0 -16
  75. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  76. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  77. package/src/__tests__/helpers/msw/blob-worker.cjs +0 -19
  78. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  79. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -160
  80. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -81
  81. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  82. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -60
  83. package/src/__tests__/helpers/msw/handlers/script.ts +0 -56
  84. package/src/__tests__/helpers/msw/handlers/user.ts +0 -52
  85. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -20
  86. package/src/__tests__/helpers/msw/index.ts +0 -52
  87. package/src/__tests__/helpers/msw/read-file-sync.js +0 -61
  88. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  89. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  90. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +0 -28
  91. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  92. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  93. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  94. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -11
  95. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  96. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  97. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  98. package/src/__tests__/https-options.test.ts +0 -163
  99. package/src/__tests__/index.test.ts +0 -282
  100. package/src/__tests__/init.test.ts +0 -3196
  101. package/src/__tests__/jest.setup.ts +0 -179
  102. package/src/__tests__/kv.test.ts +0 -1799
  103. package/src/__tests__/logger.test.ts +0 -207
  104. package/src/__tests__/logout.test.ts +0 -47
  105. package/src/__tests__/metrics.test.ts +0 -493
  106. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  107. package/src/__tests__/middleware.test.ts +0 -816
  108. package/src/__tests__/mtls-certificates.test.ts +0 -589
  109. package/src/__tests__/package-manager.test.ts +0 -353
  110. package/src/__tests__/pages/deployment-list.test.ts +0 -80
  111. package/src/__tests__/pages/functions-build.test.ts +0 -522
  112. package/src/__tests__/pages/pages.test.ts +0 -81
  113. package/src/__tests__/pages/project-create.test.ts +0 -63
  114. package/src/__tests__/pages/project-list.test.ts +0 -110
  115. package/src/__tests__/pages/project-upload.test.ts +0 -500
  116. package/src/__tests__/pages/publish.test.ts +0 -2864
  117. package/src/__tests__/pages-deployment-tail.test.ts +0 -955
  118. package/src/__tests__/parse.test.ts +0 -436
  119. package/src/__tests__/paths.test.ts +0 -39
  120. package/src/__tests__/publish.test.ts +0 -8849
  121. package/src/__tests__/pubsub.test.ts +0 -496
  122. package/src/__tests__/queues.test.ts +0 -532
  123. package/src/__tests__/r2.test.ts +0 -374
  124. package/src/__tests__/route.test.ts +0 -45
  125. package/src/__tests__/secret.test.ts +0 -693
  126. package/src/__tests__/tail.test.ts +0 -958
  127. package/src/__tests__/test-old-node-version.js +0 -31
  128. package/src/__tests__/traverse-module-graph.test.ts +0 -220
  129. package/src/__tests__/tsconfig-sanity.ts +0 -12
  130. package/src/__tests__/tsconfig.json +0 -8
  131. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  132. package/src/__tests__/type-generation.test.ts +0 -234
  133. package/src/__tests__/user.test.ts +0 -118
  134. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  135. package/src/__tests__/validate-dev-props.test.ts +0 -56
  136. package/src/__tests__/version.test.ts +0 -35
  137. package/src/__tests__/whoami.test.tsx +0 -172
  138. package/src/__tests__/worker-namespace.test.ts +0 -340
  139. package/src/abort.d.ts +0 -3
  140. package/src/api/dev.ts +0 -321
  141. package/src/api/index.ts +0 -11
  142. package/src/api/mtls-certificate.ts +0 -148
  143. package/src/api/pages/create-worker-bundle-contents.ts +0 -76
  144. package/src/api/pages/index.ts +0 -5
  145. package/src/api/pages/publish.tsx +0 -371
  146. package/src/bundle-reporter.ts +0 -68
  147. package/src/bundle.ts +0 -911
  148. package/src/cfetch/index.ts +0 -158
  149. package/src/cfetch/internal.ts +0 -258
  150. package/src/cli.ts +0 -28
  151. package/src/config/README.md +0 -107
  152. package/src/config/config.ts +0 -282
  153. package/src/config/diagnostics.ts +0 -80
  154. package/src/config/environment.ts +0 -618
  155. package/src/config/index.ts +0 -403
  156. package/src/config/validation-helpers.ts +0 -597
  157. package/src/config/validation.ts +0 -2342
  158. package/src/config-cache.ts +0 -85
  159. package/src/constellation/createProject.tsx +0 -51
  160. package/src/constellation/deleteProject.ts +0 -51
  161. package/src/constellation/deleteProjectModel.ts +0 -68
  162. package/src/constellation/index.ts +0 -75
  163. package/src/constellation/listCatalog.tsx +0 -35
  164. package/src/constellation/listModel.tsx +0 -41
  165. package/src/constellation/listProject.tsx +0 -28
  166. package/src/constellation/listRuntime.tsx +0 -28
  167. package/src/constellation/options.ts +0 -17
  168. package/src/constellation/types.ts +0 -17
  169. package/src/constellation/uploadModel.tsx +0 -64
  170. package/src/constellation/utils.ts +0 -90
  171. package/src/create-worker-preview.ts +0 -293
  172. package/src/create-worker-upload-form.ts +0 -359
  173. package/src/d1/backups.tsx +0 -219
  174. package/src/d1/constants.ts +0 -2
  175. package/src/d1/create.tsx +0 -70
  176. package/src/d1/delete.ts +0 -53
  177. package/src/d1/execute.tsx +0 -357
  178. package/src/d1/formatTimeAgo.ts +0 -14
  179. package/src/d1/index.ts +0 -100
  180. package/src/d1/list.tsx +0 -62
  181. package/src/d1/migrations/apply.tsx +0 -212
  182. package/src/d1/migrations/create.tsx +0 -79
  183. package/src/d1/migrations/helpers.ts +0 -169
  184. package/src/d1/migrations/index.ts +0 -3
  185. package/src/d1/migrations/list.tsx +0 -95
  186. package/src/d1/migrations/options.ts +0 -23
  187. package/src/d1/options.ts +0 -22
  188. package/src/d1/splitter.ts +0 -161
  189. package/src/d1/types.ts +0 -25
  190. package/src/d1/utils.ts +0 -49
  191. package/src/delete.ts +0 -100
  192. package/src/deployments.ts +0 -368
  193. package/src/deprecated/index.ts +0 -144
  194. package/src/dev/dev-vars.ts +0 -39
  195. package/src/dev/dev.tsx +0 -602
  196. package/src/dev/get-local-persistence-path.ts +0 -31
  197. package/src/dev/local.tsx +0 -948
  198. package/src/dev/remote.tsx +0 -632
  199. package/src/dev/start-server.ts +0 -543
  200. package/src/dev/use-esbuild.ts +0 -212
  201. package/src/dev/validate-dev-props.ts +0 -40
  202. package/src/dev-registry.ts +0 -202
  203. package/src/dev.tsx +0 -934
  204. package/src/dialogs.ts +0 -136
  205. package/src/dispatch-namespace.ts +0 -211
  206. package/src/docs/helpers.ts +0 -50
  207. package/src/docs/index.ts +0 -54
  208. package/src/durable.ts +0 -102
  209. package/src/entry.ts +0 -338
  210. package/src/environment-variables/factory.ts +0 -89
  211. package/src/environment-variables/misc-variables.ts +0 -30
  212. package/src/errors.ts +0 -11
  213. package/src/generate/index.ts +0 -298
  214. package/src/git-client.ts +0 -135
  215. package/src/global-wrangler-config-path.ts +0 -26
  216. package/src/https-options.ts +0 -127
  217. package/src/index.ts +0 -768
  218. package/src/init.ts +0 -1032
  219. package/src/inspect.ts +0 -782
  220. package/src/intl-polyfill.d.ts +0 -139
  221. package/src/is-ci.ts +0 -14
  222. package/src/is-interactive.ts +0 -16
  223. package/src/jest.d.ts +0 -4
  224. package/src/kv/helpers.ts +0 -433
  225. package/src/kv/index.ts +0 -594
  226. package/src/logger.ts +0 -123
  227. package/src/metrics/index.ts +0 -5
  228. package/src/metrics/metrics-config.ts +0 -239
  229. package/src/metrics/metrics-dispatcher.ts +0 -96
  230. package/src/metrics/metrics-usage-headers.ts +0 -24
  231. package/src/metrics/send-event.ts +0 -99
  232. package/src/miniflare-cli/README.md +0 -30
  233. package/src/miniflare-cli/assets.ts +0 -251
  234. package/src/miniflare-cli/index.ts +0 -210
  235. package/src/miniflare-cli/request-context.ts +0 -40
  236. package/src/miniflare-cli/tsconfig.json +0 -9
  237. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  238. package/src/miniflare-cli/types.ts +0 -11
  239. package/src/module-collection.ts +0 -333
  240. package/src/mtls-certificate/cli.ts +0 -155
  241. package/src/open-in-browser.ts +0 -17
  242. package/src/package-manager.ts +0 -219
  243. package/src/pages/build.ts +0 -422
  244. package/src/pages/buildFunctions.ts +0 -140
  245. package/src/pages/constants.ts +0 -18
  246. package/src/pages/deployment-tails.ts +0 -281
  247. package/src/pages/deployments.tsx +0 -84
  248. package/src/pages/dev.ts +0 -734
  249. package/src/pages/errors.ts +0 -67
  250. package/src/pages/functions/buildPlugin.ts +0 -113
  251. package/src/pages/functions/buildWorker.ts +0 -348
  252. package/src/pages/functions/filepath-routing.test.ts +0 -234
  253. package/src/pages/functions/filepath-routing.ts +0 -189
  254. package/src/pages/functions/identifiers.ts +0 -78
  255. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  256. package/src/pages/functions/routes-consolidation.ts +0 -73
  257. package/src/pages/functions/routes-transformation.test.ts +0 -282
  258. package/src/pages/functions/routes-transformation.ts +0 -115
  259. package/src/pages/functions/routes-validation.test.ts +0 -403
  260. package/src/pages/functions/routes-validation.ts +0 -202
  261. package/src/pages/functions/routes.ts +0 -151
  262. package/src/pages/functions/tsconfig.json +0 -8
  263. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  264. package/src/pages/functions.ts +0 -86
  265. package/src/pages/hash.ts +0 -13
  266. package/src/pages/index.ts +0 -102
  267. package/src/pages/projects.tsx +0 -159
  268. package/src/pages/prompt-select-project.tsx +0 -31
  269. package/src/pages/publish.tsx +0 -267
  270. package/src/pages/types.ts +0 -46
  271. package/src/pages/upload.tsx +0 -469
  272. package/src/pages/utils.ts +0 -23
  273. package/src/parse.ts +0 -308
  274. package/src/paths.ts +0 -71
  275. package/src/proxy.ts +0 -694
  276. package/src/publish/index.ts +0 -274
  277. package/src/publish/publish.ts +0 -1060
  278. package/src/pubsub/index.ts +0 -286
  279. package/src/pubsub/pubsub-commands.ts +0 -623
  280. package/src/queues/cli/commands/consumer/add.ts +0 -71
  281. package/src/queues/cli/commands/consumer/index.ts +0 -19
  282. package/src/queues/cli/commands/consumer/remove.ts +0 -31
  283. package/src/queues/cli/commands/create.ts +0 -25
  284. package/src/queues/cli/commands/delete.ts +0 -26
  285. package/src/queues/cli/commands/index.ts +0 -35
  286. package/src/queues/cli/commands/list.ts +0 -25
  287. package/src/queues/client.ts +0 -136
  288. package/src/queues/utils.ts +0 -18
  289. package/src/r2/constants.ts +0 -4
  290. package/src/r2/helpers.ts +0 -132
  291. package/src/r2/index.ts +0 -289
  292. package/src/routes.ts +0 -140
  293. package/src/secret/index.ts +0 -376
  294. package/src/selfsigned.d.ts +0 -29
  295. package/src/sites.ts +0 -484
  296. package/src/tail/createTail.ts +0 -406
  297. package/src/tail/filters.ts +0 -277
  298. package/src/tail/index.ts +0 -211
  299. package/src/tail/printing.ts +0 -122
  300. package/src/traverse-module-graph.ts +0 -53
  301. package/src/tsconfig-sanity.ts +0 -16
  302. package/src/type-generation.ts +0 -181
  303. package/src/update-check.ts +0 -19
  304. package/src/user/access.ts +0 -68
  305. package/src/user/auth-variables.ts +0 -113
  306. package/src/user/choose-account.tsx +0 -39
  307. package/src/user/generate-auth-url.ts +0 -33
  308. package/src/user/generate-random-state.ts +0 -16
  309. package/src/user/index.ts +0 -2
  310. package/src/user/user.ts +0 -1234
  311. package/src/utils/collectKeyValues.ts +0 -14
  312. package/src/utils/render.ts +0 -93
  313. package/src/whoami.ts +0 -135
  314. package/src/worker.ts +0 -274
  315. package/src/yargs-types.ts +0 -37
  316. package/src/zones.ts +0 -191
  317. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  318. package/templates/d1-beta-facade.js +0 -244
  319. package/templates/first-party-worker-module-facade.ts +0 -19
  320. package/templates/format-dev-errors.ts +0 -34
  321. package/templates/serve-static-assets.ts +0 -66
  322. package/templates/service-bindings-module-facade.js +0 -55
  323. package/templates/service-bindings-sw-facade.js +0 -42
  324. package/templates/tsconfig.tsbuildinfo +0 -1
package/src/bundle.ts DELETED
@@ -1,911 +0,0 @@
1
- import assert from "node:assert";
2
- import * as fs from "node:fs";
3
- import { builtinModules } from "node:module";
4
- import * as path from "node:path";
5
- import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
6
- import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
7
- import * as esbuild from "esbuild";
8
- import tmp from "tmp-promise";
9
- import createModuleCollector from "./module-collection";
10
- import { getBasePath } from "./paths";
11
- import type { Config } from "./config";
12
- import type { DurableObjectBindings } from "./config/environment";
13
- import type { WorkerRegistry } from "./dev-registry";
14
- import type { Entry } from "./entry";
15
- import type { CfModule } from "./worker";
16
-
17
- export const COMMON_ESBUILD_OPTIONS = {
18
- // Our workerd runtime uses the same V8 version as recent Chrome, which is highly ES2022 compliant: https://kangax.github.io/compat-table/es2016plus/
19
- target: "es2022",
20
- loader: { ".js": "jsx", ".mjs": "jsx", ".cjs": "jsx" },
21
- } as const;
22
-
23
- export type BundleResult = {
24
- modules: CfModule[];
25
- dependencies: esbuild.Metafile["outputs"][string]["inputs"];
26
- resolvedEntryPointPath: string;
27
- bundleType: "esm" | "commonjs";
28
- stop: (() => void) | undefined;
29
- sourceMapPath?: string | undefined;
30
- };
31
-
32
- type StaticAssetsConfig =
33
- | (Config["assets"] & {
34
- bypassCache: boolean | undefined;
35
- })
36
- | undefined;
37
-
38
- /**
39
- * When applying the middleware facade for service workers, we need to inject
40
- * some code at the top of the final output bundle. Applying an inject too early
41
- * will allow esbuild to reorder the code. Additionally, we need to make sure
42
- * user code is bundled in the final esbuild step with `watch` correctly
43
- * configured, so code changes are detected.
44
- *
45
- * This type is used as the return type for the `MiddlewareFn` type representing
46
- * a facade-applying function. Returned injects should be injected with the
47
- * final esbuild step.
48
- */
49
- type EntryWithInject = Entry & { inject?: string[] };
50
-
51
- /**
52
- * RegExp matching against esbuild's error text when it is unable to resolve
53
- * a Node built-in module. If we detect this when node_compat is disabled,
54
- * we'll rewrite the error to suggest enabling it.
55
- */
56
- const nodeBuiltinResolveErrorText = new RegExp(
57
- '^Could not resolve "(' +
58
- builtinModules.join("|") +
59
- "|" +
60
- builtinModules.map((module) => "node:" + module).join("|") +
61
- ')"$'
62
- );
63
-
64
- /**
65
- * Returns true if the passed value looks like an esbuild BuildFailure object
66
- */
67
- export function isBuildFailure(err: unknown): err is esbuild.BuildFailure {
68
- return (
69
- typeof err === "object" &&
70
- err !== null &&
71
- "errors" in err &&
72
- "warnings" in err
73
- );
74
- }
75
-
76
- /**
77
- * Rewrites esbuild BuildFailures for failing to resolve Node built-in modules
78
- * to suggest enabling Node compat as opposed to `platform: "node"`.
79
- */
80
- export function rewriteNodeCompatBuildFailure(err: esbuild.BuildFailure) {
81
- for (const error of err.errors) {
82
- const match = nodeBuiltinResolveErrorText.exec(error.text);
83
- if (match !== null) {
84
- error.notes = [
85
- {
86
- location: null,
87
- text: `The package "${match[1]}" wasn't found on the file system but is built into node.
88
- Add "node_compat = true" to your wrangler.toml file to enable Node compatibility.`,
89
- },
90
- ];
91
- }
92
- }
93
- }
94
-
95
- const nodejsCompatPlugin: esbuild.Plugin = {
96
- name: "nodejs_compat Plugin",
97
- setup(pluginBuild) {
98
- pluginBuild.onResolve({ filter: /node:.*/ }, () => {
99
- return { external: true };
100
- });
101
- },
102
- };
103
-
104
- const cloudflareJsPlugin: esbuild.Plugin = {
105
- name: "cloudflare javascript Plugin",
106
- setup(pluginBuild) {
107
- pluginBuild.onResolve({ filter: /^cloudflare:.*/ }, () => {
108
- return { external: true };
109
- });
110
- },
111
- };
112
-
113
- /**
114
- * Generate a bundle for the worker identified by the arguments passed in.
115
- */
116
- export async function bundleWorker(
117
- entry: Entry,
118
- destination: string,
119
- options: {
120
- // When `bundle` is set to false, we apply shims to the Worker, but won't pull in any imports
121
- bundle?: boolean;
122
- serveAssetsFromWorker: boolean;
123
- assets?: StaticAssetsConfig;
124
- betaD1Shims?: string[];
125
- doBindings: DurableObjectBindings;
126
- jsxFactory?: string;
127
- jsxFragment?: string;
128
- entryName?: string;
129
- rules: Config["rules"];
130
- watch?: esbuild.WatchMode | boolean;
131
- tsconfig?: string;
132
- minify?: boolean;
133
- legacyNodeCompat?: boolean;
134
- nodejsCompat?: boolean;
135
- define: Config["define"];
136
- checkFetch: boolean;
137
- services?: Config["services"];
138
- workerDefinitions?: WorkerRegistry;
139
- firstPartyWorkerDevFacade?: boolean;
140
- targetConsumer: "dev" | "publish";
141
- local: boolean;
142
- testScheduled?: boolean;
143
- experimentalLocal?: boolean;
144
- inject?: string[];
145
- loader?: Record<string, string>;
146
- sourcemap?: esbuild.CommonOptions["sourcemap"];
147
- plugins?: esbuild.Plugin[];
148
- // TODO: Rip these out https://github.com/cloudflare/workers-sdk/issues/2153
149
- disableModuleCollection?: boolean;
150
- isOutfile?: boolean;
151
- }
152
- ): Promise<BundleResult> {
153
- const {
154
- bundle = true,
155
- serveAssetsFromWorker,
156
- betaD1Shims,
157
- doBindings,
158
- jsxFactory,
159
- jsxFragment,
160
- entryName,
161
- rules,
162
- watch,
163
- tsconfig,
164
- minify,
165
- legacyNodeCompat,
166
- nodejsCompat,
167
- checkFetch,
168
- local,
169
- assets,
170
- workerDefinitions,
171
- services,
172
- firstPartyWorkerDevFacade,
173
- targetConsumer,
174
- testScheduled,
175
- experimentalLocal,
176
- inject: injectOption,
177
- loader,
178
- sourcemap,
179
- plugins,
180
- disableModuleCollection,
181
- isOutfile,
182
- } = options;
183
-
184
- // We create a temporary directory for any oneoff files we
185
- // need to create. This is separate from the main build
186
- // directory (`destination`).
187
- const tmpDir = await tmp.dir({ unsafeCleanup: true });
188
-
189
- const entryDirectory = path.dirname(entry.file);
190
- let moduleCollector = createModuleCollector({
191
- wrangler1xlegacyModuleReferences: {
192
- rootDirectory: entryDirectory,
193
- fileNames: new Set(
194
- fs
195
- .readdirSync(entryDirectory, { withFileTypes: true })
196
- .filter(
197
- (dirEntry) =>
198
- dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
199
- )
200
- .map((dirEnt) => dirEnt.name)
201
- ),
202
- },
203
- format: entry.format,
204
- rules,
205
- });
206
- if (disableModuleCollection) {
207
- moduleCollector = {
208
- modules: [],
209
- plugin: {
210
- name: moduleCollector.plugin.name,
211
- setup: () => {},
212
- },
213
- };
214
- }
215
-
216
- // In dev, we want to patch `fetch()` with a special version that looks
217
- // for bad usages and can warn the user about them; so we inject
218
- // `checked-fetch.js` to do so. However, with yarn 3 style pnp,
219
- // we need to extract that file to an accessible place before injecting
220
- // it in, hence this code here.
221
-
222
- const checkedFetchFileToInject = path.join(tmpDir.path, "checked-fetch.js");
223
-
224
- if (checkFetch && !fs.existsSync(checkedFetchFileToInject)) {
225
- fs.mkdirSync(tmpDir.path, {
226
- recursive: true,
227
- });
228
- fs.writeFileSync(
229
- checkedFetchFileToInject,
230
- fs.readFileSync(path.resolve(getBasePath(), "templates/checked-fetch.js"))
231
- );
232
- }
233
-
234
- // At this point, we take the opportunity to "wrap" any input workers
235
- // with any extra functionality we may want to add. This is done by
236
- // passing the entry point through a pipeline of functions that return
237
- // a new entry point, that we call "middleware" or "facades".
238
- // Look at implementations of these functions to learn more.
239
-
240
- // We also have middleware that uses a more "traditional" middleware stack,
241
- // which is all loaded as one in a stack.
242
- const middlewareToLoad: MiddlewareLoader[] = [];
243
-
244
- if (testScheduled) {
245
- middlewareToLoad.push({
246
- path: "templates/middleware/middleware-scheduled.ts",
247
- });
248
- }
249
- if (experimentalLocal) {
250
- // In Miniflare 3, we bind the user's worker as a service binding in a
251
- // special entry worker that handles things like injecting `Request.cf`,
252
- // live-reload, and the pretty-error page.
253
- //
254
- // Unfortunately, due to a bug in `workerd`, errors thrown asynchronously by
255
- // native APIs don't have `stack`s. This means Miniflare can't extract the
256
- // `stack` trace from dispatching to the user worker service binding by
257
- // `try/catch`.
258
- //
259
- // As a stop-gap solution, if the `MF-Experimental-Error-Stack` header is
260
- // truthy on responses, the body will be interpreted as a JSON-error of the
261
- // form `{ message?: string, name?: string, stack?: string }`.
262
- //
263
- // This middleware wraps the user's worker in a `try/catch`, and rewrites
264
- // errors in this format so a pretty-error page can be shown.
265
- middlewareToLoad.push({
266
- path: "templates/middleware/middleware-miniflare3-json-error.ts",
267
- dev: true,
268
- });
269
- }
270
-
271
- type MiddlewareFn = (currentEntry: Entry) => Promise<EntryWithInject>;
272
- const middleware: (false | undefined | MiddlewareFn)[] = [
273
- // serve static assets
274
- serveAssetsFromWorker &&
275
- ((currentEntry: Entry) => {
276
- return applyStaticAssetFacade(currentEntry, tmpDir.path, assets);
277
- }),
278
- // format errors nicely
279
- // We use an env var here because we don't actually
280
- // want to expose this to the user. It's only used internally to
281
- // experiment with middleware as a teaching exercise.
282
- process.env.FORMAT_WRANGLER_ERRORS === "true" &&
283
- ((currentEntry: Entry) => {
284
- return applyFormatDevErrorsFacade(currentEntry, tmpDir.path);
285
- }),
286
- // bind to other dev instances/service bindings
287
- workerDefinitions &&
288
- Object.keys(workerDefinitions).length > 0 &&
289
- services &&
290
- services.length > 0 &&
291
- ((currentEntry: Entry) => {
292
- return applyMultiWorkerDevFacade(
293
- currentEntry,
294
- tmpDir.path,
295
- services,
296
- workerDefinitions
297
- );
298
- }),
299
- // Simulate internal environment when using first party workers in dev
300
- firstPartyWorkerDevFacade === true &&
301
- ((currentEntry: Entry) => {
302
- return applyFirstPartyWorkerDevFacade(currentEntry, tmpDir.path);
303
- }),
304
-
305
- Array.isArray(betaD1Shims) &&
306
- betaD1Shims.length > 0 &&
307
- ((currentEntry: Entry) => {
308
- return applyD1BetaFacade(
309
- currentEntry,
310
- tmpDir.path,
311
- betaD1Shims,
312
- local && !experimentalLocal,
313
- doBindings
314
- );
315
- }),
316
-
317
- // Middleware loader: to add middleware, we add the path to the middleware
318
- // Currently for demonstration purposes we have two example middlewares
319
- // Middlewares are togglable by changing the `publish` (default=false) and `dev` (default=true) options
320
- // As we are not yet supporting user created middlewares yet, if no wrangler applied middleware
321
- // are found, we will not load any middleware. We also need to check if there are middlewares compatible with
322
- // the target consumer (dev / publish).
323
- (middlewareToLoad.filter(
324
- (m) =>
325
- (m.publish && targetConsumer === "publish") ||
326
- (m.dev !== false && targetConsumer === "dev")
327
- ).length > 0 ||
328
- process.env.EXPERIMENTAL_MIDDLEWARE === "true") &&
329
- ((currentEntry: Entry) => {
330
- return applyMiddlewareLoaderFacade(
331
- currentEntry,
332
- tmpDir.path,
333
- middlewareToLoad.filter(
334
- // We dynamically filter the middleware depending on where we are bundling for
335
- (m) =>
336
- (targetConsumer === "dev" && m.dev !== false) ||
337
- (m.publish && targetConsumer === "publish")
338
- )
339
- );
340
- }),
341
- ].filter(Boolean);
342
-
343
- const inject: string[] = injectOption ?? [];
344
- if (checkFetch) inject.push(checkedFetchFileToInject);
345
-
346
- let inputEntry: EntryWithInject = entry;
347
- for (const middlewareFn of middleware as MiddlewareFn[]) {
348
- inputEntry = await middlewareFn(inputEntry);
349
- if (inputEntry.inject !== undefined) inject.push(...inputEntry.inject);
350
- }
351
-
352
- // At this point, inputEntry points to the entry point we want to build.
353
-
354
- const buildOptions: esbuild.BuildOptions & { metafile: true } = {
355
- entryPoints: [inputEntry.file],
356
- bundle,
357
- absWorkingDir: entry.directory,
358
- outdir: destination,
359
- entryNames: entryName || path.parse(entry.file).name,
360
- ...(isOutfile
361
- ? {
362
- outdir: undefined,
363
- outfile: destination,
364
- entryNames: undefined,
365
- }
366
- : {}),
367
- inject,
368
- external: bundle ? ["__STATIC_CONTENT_MANIFEST"] : undefined,
369
- format: entry.format === "modules" ? "esm" : "iife",
370
- target: COMMON_ESBUILD_OPTIONS.target,
371
- sourcemap: sourcemap ?? true, // this needs to use ?? to accept false
372
- // Include a reference to the output folder in the sourcemap.
373
- // This is omitted by default, but we need it to properly resolve source paths in error output.
374
- sourceRoot: destination,
375
- minify,
376
- metafile: true,
377
- conditions: ["workerd", "worker", "browser"],
378
- ...(process.env.NODE_ENV && {
379
- define: {
380
- // use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
381
- // when we do a build of wrangler. (re: https://github.com/cloudflare/workers-sdk/issues/1477)
382
- "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
383
- ...(legacyNodeCompat ? { global: "globalThis" } : {}),
384
- ...(checkFetch ? { fetch: "checkedFetch" } : {}),
385
- ...options.define,
386
- },
387
- }),
388
- loader: {
389
- ...COMMON_ESBUILD_OPTIONS.loader,
390
- ...(loader || {}),
391
- },
392
- plugins: [
393
- moduleCollector.plugin,
394
- ...(legacyNodeCompat
395
- ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
396
- : []),
397
- ...(nodejsCompat ? [nodejsCompatPlugin] : []),
398
- ...[cloudflareJsPlugin],
399
- ...(plugins || []),
400
- ],
401
- ...(jsxFactory && { jsxFactory }),
402
- ...(jsxFragment && { jsxFragment }),
403
- ...(tsconfig && { tsconfig }),
404
- watch,
405
- // The default logLevel is "warning". So that we can rewrite errors before
406
- // logging, we disable esbuild's default logging, and log build failures
407
- // ourselves.
408
- logLevel: "silent",
409
- };
410
- let result;
411
- try {
412
- result = await esbuild.build(buildOptions);
413
- } catch (e) {
414
- if (!legacyNodeCompat && isBuildFailure(e))
415
- rewriteNodeCompatBuildFailure(e);
416
- throw e;
417
- }
418
-
419
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
420
- ([_path, output]) => output.entryPoint !== undefined
421
- );
422
- assert(
423
- entryPointOutputs.length > 0,
424
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
425
- listEntryPoints(entryPointOutputs)
426
- );
427
- assert(
428
- entryPointOutputs.length < 2,
429
- "More than one entry-point found for generated bundle." +
430
- listEntryPoints(entryPointOutputs)
431
- );
432
-
433
- const { exports: entryPointExports, inputs: dependencies } =
434
- entryPointOutputs[0][1];
435
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
436
-
437
- const sourceMapPath = Object.keys(result.metafile.outputs).filter((_path) =>
438
- _path.includes(".map")
439
- )[0];
440
-
441
- const resolvedEntryPointPath = path.resolve(
442
- entry.directory,
443
- entryPointOutputs[0][0]
444
- );
445
-
446
- // copy all referenced modules into the output bundle directory
447
- for (const module of moduleCollector.modules) {
448
- fs.writeFileSync(
449
- path.join(path.dirname(resolvedEntryPointPath), module.name),
450
- module.content
451
- );
452
- }
453
-
454
- return {
455
- modules: moduleCollector.modules,
456
- dependencies,
457
- resolvedEntryPointPath,
458
- bundleType,
459
- stop: result.stop,
460
- sourceMapPath,
461
- };
462
- }
463
-
464
- /**
465
- * A simple plugin to alias modules and mark them as external
466
- */
467
- export function esbuildAliasExternalPlugin(
468
- aliases: Record<string, string>
469
- ): esbuild.Plugin {
470
- return {
471
- name: "alias",
472
- setup(build) {
473
- build.onResolve({ filter: /.*/g }, (args) => {
474
- // If it's the entrypoint, let it be as is
475
- if (args.kind === "entry-point") {
476
- return {
477
- path: args.path,
478
- };
479
- }
480
- // If it's not a recognised alias, then throw an error
481
- if (!Object.keys(aliases).includes(args.path)) {
482
- throw new Error("unrecognized module: " + args.path);
483
- }
484
-
485
- // Otherwise, return the alias
486
- return {
487
- path: aliases[args.path as keyof typeof aliases],
488
- external: true,
489
- };
490
- });
491
- },
492
- };
493
- }
494
-
495
- /**
496
- * A middleware that catches any thrown errors, and instead formats
497
- * them to be rendered in a browser. This middleware is for demonstration
498
- * purposes only, and is not intended to be used in production (or even dev!)
499
- */
500
- async function applyFormatDevErrorsFacade(
501
- entry: Entry,
502
- tmpDirPath: string
503
- ): Promise<Entry> {
504
- const targetPath = path.join(tmpDirPath, "format-dev-errors.entry.js");
505
- await esbuild.build({
506
- entryPoints: [
507
- path.resolve(getBasePath(), "templates/format-dev-errors.ts"),
508
- ],
509
- bundle: true,
510
- sourcemap: true,
511
- format: "esm",
512
- plugins: [
513
- esbuildAliasExternalPlugin({
514
- __ENTRY_POINT__: entry.file,
515
- }),
516
- ],
517
- outfile: targetPath,
518
- });
519
-
520
- return {
521
- ...entry,
522
- file: targetPath,
523
- };
524
- }
525
-
526
- /**
527
- * A facade that acts as a "middleware loader".
528
- * Instead of needing to apply a facade for each individual middleware, this allows
529
- * middleware to be written in a more traditional manner and then be applied all
530
- * at once, requiring just two esbuild steps, rather than 1 per middleware.
531
- */
532
-
533
- interface MiddlewareLoader {
534
- path: string;
535
- // By default all middleware will run on dev, but will not be run when published
536
- publish?: boolean;
537
- dev?: boolean;
538
- }
539
-
540
- async function applyMiddlewareLoaderFacade(
541
- entry: Entry,
542
- tmpDirPath: string,
543
- middleware: MiddlewareLoader[] // a list of paths to middleware files
544
- ): Promise<EntryWithInject> {
545
- // Firstly we need to insert the middleware array into the project,
546
- // and then we load the middleware - this insertion and loading is
547
- // different for each format.
548
-
549
- // Make sure we resolve all files relative to the actual temporary directory,
550
- // otherwise we'll have issues with source maps
551
- tmpDirPath = fs.realpathSync(tmpDirPath);
552
-
553
- const targetPathInsertion = path.join(
554
- tmpDirPath,
555
- "middleware-insertion.entry.js"
556
- );
557
-
558
- // We need to import each of the middlewares, so we need to generate a
559
- // random, unique identifier that we can use for the import.
560
- // Middlewares are required to be default exports so we can import to any name.
561
- const middlewareIdentifiers = middleware.map(
562
- (_, index) => `__MIDDLEWARE_${index}__`
563
- );
564
-
565
- const dynamicFacadePath = path.join(
566
- tmpDirPath,
567
- "middleware-insertion-facade.js"
568
- );
569
-
570
- if (entry.format === "modules") {
571
- // We use a facade to expose the required middleware alongside any user defined
572
- // middleware on the worker object
573
-
574
- const imports = middlewareIdentifiers
575
- .map((m) => `import ${m} from "${m}";`)
576
- .join("\n");
577
-
578
- // write a file with all of the imports required
579
- fs.writeFileSync(
580
- dynamicFacadePath,
581
- `import worker from "__ENTRY_POINT__";
582
- ${imports}
583
- const facade = {
584
- ...worker,
585
- middleware: [
586
- ${middlewareIdentifiers.join(",")}${middlewareIdentifiers.length > 0 ? "," : ""}
587
- ...(worker.middleware ? worker.middleware : []),
588
- ]
589
- }
590
- export * from "__ENTRY_POINT__";
591
- export default facade;`
592
- );
593
-
594
- await esbuild.build({
595
- entryPoints: [dynamicFacadePath],
596
- bundle: true,
597
- sourcemap: true,
598
- format: "esm",
599
- plugins: [
600
- esbuildAliasExternalPlugin({
601
- __ENTRY_POINT__: entry.file,
602
- ...Object.fromEntries(
603
- middleware.map((val, index) => [
604
- middlewareIdentifiers[index],
605
- path.resolve(getBasePath(), val.path),
606
- ])
607
- ),
608
- }),
609
- ],
610
- outfile: targetPathInsertion,
611
- });
612
- const targetPathLoader = path.join(
613
- tmpDirPath,
614
- "middleware-loader.entry.js"
615
- );
616
- const loaderPath = path.resolve(
617
- getBasePath(),
618
- "templates/middleware/loader-modules.ts"
619
- );
620
- await esbuild.build({
621
- entryPoints: [loaderPath],
622
- bundle: true,
623
- sourcemap: true,
624
- format: "esm",
625
- plugins: [
626
- esbuildAliasExternalPlugin({
627
- __ENTRY_POINT__: targetPathInsertion,
628
- "./common": path.resolve(
629
- getBasePath(),
630
- "templates/middleware/common.ts"
631
- ),
632
- }),
633
- ],
634
- outfile: targetPathLoader,
635
- });
636
- return {
637
- ...entry,
638
- file: targetPathLoader,
639
- };
640
- } else {
641
- const imports = middlewareIdentifiers
642
- .map((m) => `import ${m} from "${m}";`)
643
- .join("\n");
644
- const contents = `import { __facade_registerInternal__ } from "__LOADER__";
645
- ${imports}
646
- __facade_registerInternal__([${middlewareIdentifiers.join(",")}]);`;
647
- fs.writeFileSync(dynamicFacadePath, contents);
648
-
649
- await esbuild.build({
650
- entryPoints: [dynamicFacadePath],
651
- bundle: true,
652
- sourcemap: true,
653
- format: "iife",
654
- plugins: [
655
- {
656
- name: "dynamic-facade-imports",
657
- setup(build) {
658
- build.onResolve({ filter: /^__LOADER__$/ }, () => {
659
- const loaderPath = path.resolve(
660
- getBasePath(),
661
- "templates/middleware/loader-sw.ts"
662
- );
663
- return { path: loaderPath };
664
- });
665
- const middlewareFilter = /^__MIDDLEWARE_(\d+)__$/;
666
- build.onResolve({ filter: middlewareFilter }, (args) => {
667
- const match = middlewareFilter.exec(args.path);
668
- assert(match !== null);
669
- const middlewareIndex = parseInt(match[1]);
670
- return {
671
- path: path.resolve(
672
- getBasePath(),
673
- middleware[middlewareIndex].path
674
- ),
675
- };
676
- });
677
- },
678
- },
679
- ],
680
- outfile: targetPathInsertion,
681
- });
682
- return {
683
- ...entry,
684
- inject: [targetPathInsertion],
685
- };
686
- }
687
- }
688
-
689
- /**
690
- * A middleware that serves static assets from a worker.
691
- * This powers --assets / config.assets
692
- */
693
-
694
- async function applyStaticAssetFacade(
695
- entry: Entry,
696
- tmpDirPath: string,
697
- assets: StaticAssetsConfig
698
- ): Promise<Entry> {
699
- const targetPath = path.join(tmpDirPath, "serve-static-assets.entry.js");
700
-
701
- await esbuild.build({
702
- entryPoints: [
703
- path.resolve(getBasePath(), "templates/serve-static-assets.ts"),
704
- ],
705
- bundle: true,
706
- format: "esm",
707
- sourcemap: true,
708
- plugins: [
709
- esbuildAliasExternalPlugin({
710
- __ENTRY_POINT__: entry.file,
711
- __KV_ASSET_HANDLER__: path.join(getBasePath(), "kv-asset-handler.js"),
712
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
713
- }),
714
- ],
715
- define: {
716
- __CACHE_CONTROL_OPTIONS__: JSON.stringify(
717
- typeof assets === "object"
718
- ? {
719
- browserTTL:
720
- assets.browser_TTL || 172800 /* 2 days: 2* 60 * 60 * 24 */,
721
- bypassCache: assets.bypassCache,
722
- }
723
- : {}
724
- ),
725
- __SERVE_SINGLE_PAGE_APP__: JSON.stringify(
726
- typeof assets === "object" ? assets.serve_single_page_app : false
727
- ),
728
- },
729
- outfile: targetPath,
730
- });
731
-
732
- return {
733
- ...entry,
734
- file: targetPath,
735
- };
736
- }
737
-
738
- /**
739
- * A middleware that enables service bindings to be used in dev,
740
- * binding to other love wrangler dev instances
741
- */
742
-
743
- async function applyMultiWorkerDevFacade(
744
- entry: Entry,
745
- tmpDirPath: string,
746
- services: Config["services"],
747
- workerDefinitions: WorkerRegistry
748
- ) {
749
- const targetPath = path.join(tmpDirPath, "multiworker-dev-facade.entry.js");
750
- const serviceMap = Object.fromEntries(
751
- (services || []).map((serviceBinding) => [
752
- serviceBinding.binding,
753
- workerDefinitions[serviceBinding.service] || null,
754
- ])
755
- );
756
-
757
- await esbuild.build({
758
- entryPoints: [
759
- path.join(
760
- getBasePath(),
761
- entry.format === "modules"
762
- ? "templates/service-bindings-module-facade.js"
763
- : "templates/service-bindings-sw-facade.js"
764
- ),
765
- ],
766
- bundle: true,
767
- sourcemap: true,
768
- format: "esm",
769
- plugins: [
770
- esbuildAliasExternalPlugin({
771
- __ENTRY_POINT__: entry.file,
772
- }),
773
- ],
774
- define: {
775
- __WORKERS__: JSON.stringify(serviceMap),
776
- },
777
- outfile: targetPath,
778
- });
779
-
780
- return {
781
- ...entry,
782
- file: targetPath,
783
- };
784
- }
785
-
786
- /**
787
- * A middleware that makes first party workers "work" in
788
- * our dev environments. Is applied during wrangler dev
789
- * when config.first_party_worker is true
790
- */
791
- async function applyFirstPartyWorkerDevFacade(
792
- entry: Entry,
793
- tmpDirPath: string
794
- ) {
795
- if (entry.format !== "modules") {
796
- throw new Error(
797
- "First party workers must be in the modules format. See https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
798
- );
799
- }
800
-
801
- const targetPath = path.join(
802
- tmpDirPath,
803
- "first-party-worker-module-facade.entry.js"
804
- );
805
-
806
- await esbuild.build({
807
- entryPoints: [
808
- path.resolve(
809
- getBasePath(),
810
- "templates/first-party-worker-module-facade.ts"
811
- ),
812
- ],
813
- bundle: true,
814
- format: "esm",
815
- sourcemap: true,
816
- plugins: [
817
- esbuildAliasExternalPlugin({
818
- __ENTRY_POINT__: entry.file,
819
- }),
820
- ],
821
- outfile: targetPath,
822
- });
823
-
824
- return {
825
- ...entry,
826
- file: targetPath,
827
- };
828
- }
829
-
830
- /**
831
- * A middleware that injects the beta D1 API in JS.
832
- *
833
- * This code be removed from here when the API is in Workers core,
834
- * but moved inside Miniflare for simulating D1.
835
- */
836
- async function applyD1BetaFacade(
837
- entry: Entry,
838
- tmpDirPath: string,
839
- betaD1Shims: string[],
840
- miniflare2: boolean,
841
- doBindings: DurableObjectBindings
842
- ): Promise<Entry> {
843
- let entrypointPath = path.resolve(
844
- getBasePath(),
845
- "templates/d1-beta-facade.js"
846
- );
847
- if (Array.isArray(doBindings) && doBindings.length > 0) {
848
- //we have DO bindings, so we need to shim them
849
- const maskedDoBindings = doBindings
850
- // Don't shim anything not local to this worker
851
- .filter((b) => !b.script_name)
852
- // Reexport the DO classnames
853
- .map(
854
- (b) =>
855
- `export const ${b.class_name} = maskDurableObjectDefinition(OTHER_EXPORTS.${b.class_name});`
856
- )
857
- .join("\n");
858
- const baseFile = fs.readFileSync(
859
- path.resolve(getBasePath(), "templates/d1-beta-facade.js"),
860
- "utf8"
861
- );
862
- //getMaskedEnv is already used to shim regular Workers
863
- const contents = `
864
- ${baseFile}
865
-
866
- var maskDurableObjectDefinition = (cls) =>
867
- class extends cls {
868
- constructor(state, env) {
869
- super(state, getMaskedEnv(env));
870
- }
871
- };
872
- ${maskedDoBindings}`;
873
- const doD1FacadePath = path.join(tmpDirPath, "d1-do-facade.js");
874
- //write our shim so we can build it
875
- fs.writeFileSync(doD1FacadePath, contents);
876
- entrypointPath = doD1FacadePath;
877
- }
878
- const targetPath = path.join(tmpDirPath, "d1-beta-facade.entry.js");
879
- await esbuild.build({
880
- entryPoints: [entrypointPath],
881
- bundle: true,
882
- format: "esm",
883
- sourcemap: true,
884
- plugins: [
885
- esbuildAliasExternalPlugin({
886
- __ENTRY_POINT__: entry.file,
887
- }),
888
- ],
889
- define: {
890
- __D1_IMPORTS__: JSON.stringify(betaD1Shims),
891
- __LOCAL_MODE__: JSON.stringify(miniflare2),
892
- },
893
- outfile: targetPath,
894
- });
895
-
896
- return {
897
- ...entry,
898
- file: targetPath,
899
- };
900
- }
901
-
902
- /**
903
- * Generate a string that describes the entry-points that were identified by esbuild.
904
- */
905
- function listEntryPoints(
906
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
907
- ): string {
908
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
909
- }
910
-
911
- type ValueOf<T> = T[keyof T];