wrangler 0.0.0-e7a0cd5b → 0.0.0-e7c7235fd

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 (268) hide show
  1. package/README.md +31 -45
  2. package/bin/wrangler.js +24 -93
  3. package/config-schema.json +3324 -0
  4. package/package.json +183 -191
  5. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  6. package/templates/__tests__/tsconfig.json +8 -0
  7. package/templates/checked-fetch.js +19 -6
  8. package/templates/facade.d.ts +19 -0
  9. package/templates/gitignore +2 -3
  10. package/templates/init-tests/test-jest-new-worker.js +3 -5
  11. package/templates/init-tests/test-vitest-new-worker.js +4 -6
  12. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  13. package/templates/middleware/common.ts +9 -4
  14. package/templates/middleware/loader-modules.ts +94 -44
  15. package/templates/middleware/loader-sw.ts +48 -32
  16. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  17. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  18. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  20. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  21. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  22. package/templates/middleware/middleware-scheduled.ts +15 -1
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.ts +4 -1
  28. package/templates/pages-dev-pipeline.ts +6 -2
  29. package/templates/pages-dev-util.ts +4 -1
  30. package/templates/pages-shim.ts +1 -1
  31. package/templates/pages-template-plugin.ts +33 -14
  32. package/templates/pages-template-worker.ts +12 -3
  33. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  34. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  35. package/templates/tsconfig-sanity.ts +11 -0
  36. package/templates/tsconfig.init.json +22 -0
  37. package/templates/tsconfig.json +5 -103
  38. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  39. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  40. package/wrangler-dist/ProxyWorker.js +241 -0
  41. package/wrangler-dist/ProxyWorker.js.map +6 -0
  42. package/wrangler-dist/cli.d.ts +26345 -529
  43. package/wrangler-dist/cli.js +159104 -150579
  44. package/Cloudflare_CA.pem +0 -18
  45. package/import_meta_url.js +0 -3
  46. package/miniflare-config-stubs/.env.empty +0 -0
  47. package/miniflare-config-stubs/package.empty.json +0 -1
  48. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  49. package/miniflare-dist/index.mjs +0 -6316
  50. package/src/__tests__/access.test.ts +0 -25
  51. package/src/__tests__/api-dev.test.ts +0 -209
  52. package/src/__tests__/api-devregistry.test.js +0 -57
  53. package/src/__tests__/api.test.ts +0 -80
  54. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  55. package/src/__tests__/config-cache.test.ts +0 -42
  56. package/src/__tests__/configuration.test.ts +0 -4028
  57. package/src/__tests__/d1.test.ts +0 -72
  58. package/src/__tests__/delete.test.ts +0 -230
  59. package/src/__tests__/deployments.test.ts +0 -95
  60. package/src/__tests__/dev.test.tsx +0 -1509
  61. package/src/__tests__/dialogs.test.tsx +0 -40
  62. package/src/__tests__/generate.test.ts +0 -235
  63. package/src/__tests__/get-host-from-url.test.ts +0 -16
  64. package/src/__tests__/guess-worker-format.test.ts +0 -85
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  68. package/src/__tests__/helpers/mock-bin.ts +0 -36
  69. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  70. package/src/__tests__/helpers/mock-console.ts +0 -106
  71. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  72. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  73. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  74. package/src/__tests__/helpers/mock-istty.ts +0 -74
  75. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  76. package/src/__tests__/helpers/mock-kv.ts +0 -33
  77. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -252
  78. package/src/__tests__/helpers/mock-process.ts +0 -39
  79. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  80. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  81. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  82. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -59
  83. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  84. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -36
  85. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  86. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  87. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  88. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -22
  89. package/src/__tests__/helpers/msw/index.ts +0 -21
  90. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  91. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  92. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  93. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  94. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  95. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  96. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  97. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  98. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  99. package/src/__tests__/https-options.test.ts +0 -163
  100. package/src/__tests__/index.test.ts +0 -262
  101. package/src/__tests__/init.test.ts +0 -2900
  102. package/src/__tests__/jest.setup.ts +0 -202
  103. package/src/__tests__/kv.test.ts +0 -1675
  104. package/src/__tests__/logger.test.ts +0 -141
  105. package/src/__tests__/metrics.test.ts +0 -450
  106. package/src/__tests__/middleware.scheduled.test.ts +0 -135
  107. package/src/__tests__/middleware.test.ts +0 -726
  108. package/src/__tests__/package-manager.test.ts +0 -353
  109. package/src/__tests__/pages.test.ts +0 -2223
  110. package/src/__tests__/parse.test.ts +0 -330
  111. package/src/__tests__/paths.test.ts +0 -39
  112. package/src/__tests__/publish.test.ts +0 -7660
  113. package/src/__tests__/pubsub.test.ts +0 -370
  114. package/src/__tests__/queues.test.ts +0 -371
  115. package/src/__tests__/r2.test.ts +0 -376
  116. package/src/__tests__/route.test.ts +0 -45
  117. package/src/__tests__/secret.test.ts +0 -644
  118. package/src/__tests__/tail.test.ts +0 -800
  119. package/src/__tests__/test-old-node-version.js +0 -31
  120. package/src/__tests__/type-generation.test.ts +0 -217
  121. package/src/__tests__/user.test.ts +0 -155
  122. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  123. package/src/__tests__/validate-dev-props.test.ts +0 -56
  124. package/src/__tests__/version.test.ts +0 -35
  125. package/src/__tests__/whoami.test.tsx +0 -278
  126. package/src/__tests__/worker-namespace.test.ts +0 -326
  127. package/src/abort.d.ts +0 -3
  128. package/src/api/dev.ts +0 -208
  129. package/src/api/index.ts +0 -2
  130. package/src/bundle-reporter.tsx +0 -68
  131. package/src/bundle.ts +0 -785
  132. package/src/cfetch/index.ts +0 -160
  133. package/src/cfetch/internal.ts +0 -263
  134. package/src/cli.ts +0 -28
  135. package/src/config/README.md +0 -107
  136. package/src/config/config.ts +0 -275
  137. package/src/config/diagnostics.ts +0 -80
  138. package/src/config/environment.ts +0 -563
  139. package/src/config/index.ts +0 -342
  140. package/src/config/validation-helpers.ts +0 -597
  141. package/src/config/validation.ts +0 -2113
  142. package/src/config-cache.ts +0 -85
  143. package/src/create-worker-preview.ts +0 -282
  144. package/src/create-worker-upload-form.ts +0 -321
  145. package/src/d1/backups.tsx +0 -218
  146. package/src/d1/create.tsx +0 -54
  147. package/src/d1/delete.tsx +0 -56
  148. package/src/d1/execute.tsx +0 -299
  149. package/src/d1/formatTimeAgo.ts +0 -14
  150. package/src/d1/index.ts +0 -76
  151. package/src/d1/list.tsx +0 -48
  152. package/src/d1/options.ts +0 -12
  153. package/src/d1/types.tsx +0 -14
  154. package/src/d1/utils.ts +0 -39
  155. package/src/delete.ts +0 -108
  156. package/src/deployments.ts +0 -74
  157. package/src/deprecated/index.ts +0 -438
  158. package/src/dev/dev-vars.ts +0 -39
  159. package/src/dev/dev.tsx +0 -587
  160. package/src/dev/get-local-persistence-path.tsx +0 -31
  161. package/src/dev/local.tsx +0 -717
  162. package/src/dev/remote.tsx +0 -603
  163. package/src/dev/start-server.ts +0 -513
  164. package/src/dev/use-esbuild.ts +0 -204
  165. package/src/dev/validate-dev-props.ts +0 -31
  166. package/src/dev-registry.tsx +0 -201
  167. package/src/dev.tsx +0 -869
  168. package/src/dialogs.tsx +0 -163
  169. package/src/dispatch-namespace.ts +0 -207
  170. package/src/durable.ts +0 -102
  171. package/src/entry.ts +0 -329
  172. package/src/environment-variables.ts +0 -50
  173. package/src/errors.ts +0 -11
  174. package/src/git-client.ts +0 -124
  175. package/src/global-wrangler-config-path.ts +0 -26
  176. package/src/https-options.ts +0 -127
  177. package/src/index.tsx +0 -684
  178. package/src/init.ts +0 -970
  179. package/src/inspect.ts +0 -767
  180. package/src/intl-polyfill.d.ts +0 -139
  181. package/src/is-ci.ts +0 -14
  182. package/src/is-interactive.ts +0 -16
  183. package/src/kv/helpers.ts +0 -430
  184. package/src/kv/index.ts +0 -596
  185. package/src/logger.ts +0 -92
  186. package/src/metrics/index.ts +0 -5
  187. package/src/metrics/metrics-config.ts +0 -239
  188. package/src/metrics/metrics-dispatcher.ts +0 -96
  189. package/src/metrics/metrics-usage-headers.ts +0 -24
  190. package/src/metrics/send-event.ts +0 -94
  191. package/src/miniflare-cli/README.md +0 -30
  192. package/src/miniflare-cli/assets.ts +0 -215
  193. package/src/miniflare-cli/index.ts +0 -213
  194. package/src/miniflare-cli/request-context.ts +0 -40
  195. package/src/module-collection.ts +0 -267
  196. package/src/open-in-browser.ts +0 -17
  197. package/src/package-manager.ts +0 -219
  198. package/src/pages/build.tsx +0 -238
  199. package/src/pages/constants.ts +0 -18
  200. package/src/pages/deployments.tsx +0 -106
  201. package/src/pages/dev.tsx +0 -693
  202. package/src/pages/errors.ts +0 -66
  203. package/src/pages/functions/buildPlugin.ts +0 -110
  204. package/src/pages/functions/buildWorker.ts +0 -156
  205. package/src/pages/functions/filepath-routing.test.ts +0 -234
  206. package/src/pages/functions/filepath-routing.ts +0 -189
  207. package/src/pages/functions/identifiers.ts +0 -78
  208. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  209. package/src/pages/functions/routes-consolidation.ts +0 -73
  210. package/src/pages/functions/routes-transformation.test.ts +0 -282
  211. package/src/pages/functions/routes-transformation.ts +0 -115
  212. package/src/pages/functions/routes-validation.test.ts +0 -403
  213. package/src/pages/functions/routes-validation.ts +0 -202
  214. package/src/pages/functions/routes.ts +0 -151
  215. package/src/pages/functions.tsx +0 -82
  216. package/src/pages/hash.tsx +0 -13
  217. package/src/pages/index.tsx +0 -94
  218. package/src/pages/projects.tsx +0 -169
  219. package/src/pages/publish.tsx +0 -436
  220. package/src/pages/types.ts +0 -49
  221. package/src/pages/upload.tsx +0 -425
  222. package/src/pages/utils.ts +0 -12
  223. package/src/parse.ts +0 -286
  224. package/src/paths.ts +0 -71
  225. package/src/proxy.ts +0 -689
  226. package/src/publish/index.ts +0 -270
  227. package/src/publish/publish.ts +0 -1035
  228. package/src/pubsub/index.ts +0 -286
  229. package/src/pubsub/pubsub-commands.tsx +0 -624
  230. package/src/queues/cli/commands/consumer/add.ts +0 -71
  231. package/src/queues/cli/commands/consumer/index.ts +0 -22
  232. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  233. package/src/queues/cli/commands/create.ts +0 -25
  234. package/src/queues/cli/commands/delete.ts +0 -26
  235. package/src/queues/cli/commands/index.ts +0 -33
  236. package/src/queues/cli/commands/list.ts +0 -25
  237. package/src/queues/client.ts +0 -135
  238. package/src/r2/helpers.ts +0 -131
  239. package/src/r2/index.ts +0 -277
  240. package/src/routes.ts +0 -140
  241. package/src/secret/index.ts +0 -379
  242. package/src/selfsigned.d.ts +0 -29
  243. package/src/sites.tsx +0 -372
  244. package/src/tail/createTail.ts +0 -315
  245. package/src/tail/filters.ts +0 -277
  246. package/src/tail/index.ts +0 -214
  247. package/src/tail/printing.ts +0 -107
  248. package/src/type-generation.ts +0 -159
  249. package/src/update-check.ts +0 -19
  250. package/src/user/access.ts +0 -69
  251. package/src/user/choose-account.tsx +0 -69
  252. package/src/user/env-vars.ts +0 -46
  253. package/src/user/generate-auth-url.ts +0 -33
  254. package/src/user/generate-random-state.ts +0 -16
  255. package/src/user/index.ts +0 -3
  256. package/src/user/user.tsx +0 -1192
  257. package/src/utils/collectKeyValues.ts +0 -14
  258. package/src/whoami.tsx +0 -169
  259. package/src/worker.ts +0 -242
  260. package/src/yargs-types.ts +0 -20
  261. package/src/zones.ts +0 -191
  262. package/templates/d1-beta-facade.js +0 -174
  263. package/templates/experimental-local-cache-stubs.js +0 -27
  264. package/templates/first-party-worker-module-facade.ts +0 -18
  265. package/templates/format-dev-errors.ts +0 -32
  266. package/templates/serve-static-assets.ts +0 -63
  267. package/templates/service-bindings-module-facade.js +0 -54
  268. package/templates/service-bindings-sw-facade.js +0 -42
package/src/bundle.ts DELETED
@@ -1,785 +0,0 @@
1
- import assert from "node:assert";
2
- import * as fs from "node:fs";
3
- import { builtinModules } from "node:module";
4
- import * as path from "node:path";
5
- import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
6
- import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
7
- import * as esbuild from "esbuild";
8
- import tmp from "tmp-promise";
9
- import createModuleCollector from "./module-collection";
10
- import { getBasePath, toUrlPath } from "./paths";
11
- import type { Config } from "./config";
12
- import type { WorkerRegistry } from "./dev-registry";
13
- import type { Entry } from "./entry";
14
- import type { CfModule } from "./worker";
15
-
16
- 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;
23
- };
24
-
25
- type StaticAssetsConfig =
26
- | (Config["assets"] & {
27
- bypassCache: boolean | undefined;
28
- })
29
- | undefined;
30
-
31
- /**
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.
35
- */
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
- }
74
-
75
- /**
76
- * Generate a bundle for the worker identified by the arguments passed in.
77
- */
78
- export async function bundleWorker(
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
- }
102
- ): Promise<BundleResult> {
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;
431
- }
432
-
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
- }
596
-
597
- /**
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.
740
- *
741
- * This code be removed from here when the API is in Workers core,
742
- * but moved inside Miniflare for simulating D1.
743
- */
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
- };
774
- }
775
-
776
- /**
777
- * Generate a string that describes the entry-points that were identified by esbuild.
778
- */
779
- function listEntryPoints(
780
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
781
- ): string {
782
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
783
- }
784
-
785
- type ValueOf<T> = T[keyof T];