wrangler 0.0.0-e64812e → 0.0.0-e6c9c5c0

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