wrangler 0.0.0-e1c2f5b9 → 0.0.0-e1d2fd668

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