wrangler 0.0.0-e978986 → 0.0.0-e98613f8

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