wrangler 0.0.0-e64812e → 0.0.0-e7a0cd5b

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