wrangler 0.0.0-e30d1013 → 0.0.0-e3136f935

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