wrangler 0.0.0-e928f94 → 0.0.0-e93063e9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -14
  3. package/bin/wrangler.js +180 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +6364 -0
  6. package/package.json +194 -113
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +238 -0
  9. package/src/__tests__/api-devregistry.test.js +64 -0
  10. package/src/__tests__/api.test.ts +80 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +42 -0
  13. package/src/__tests__/configuration.test.ts +4163 -0
  14. package/src/__tests__/d1/d1.test.ts +123 -0
  15. package/src/__tests__/d1/splitter.test.ts +255 -0
  16. package/src/__tests__/delete.test.ts +266 -0
  17. package/src/__tests__/deployments.test.ts +105 -0
  18. package/src/__tests__/dev.test.tsx +1586 -0
  19. package/src/__tests__/generate.test.ts +238 -0
  20. package/src/__tests__/get-host-from-url.test.ts +16 -0
  21. package/src/__tests__/guess-worker-format.test.ts +85 -0
  22. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  23. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  24. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  25. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  26. package/src/__tests__/helpers/mock-bin.ts +36 -0
  27. package/src/__tests__/helpers/mock-cfetch.ts +278 -0
  28. package/src/__tests__/helpers/mock-console.ts +106 -0
  29. package/src/__tests__/helpers/mock-dialogs.ts +137 -0
  30. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  31. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  32. package/src/__tests__/helpers/mock-istty.ts +74 -0
  33. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  34. package/src/__tests__/helpers/mock-kv.ts +33 -0
  35. package/src/__tests__/helpers/mock-oauth-flow.ts +271 -0
  36. package/src/__tests__/helpers/mock-process.ts +34 -0
  37. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  38. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  39. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  40. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  41. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  42. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  43. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  44. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  45. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  46. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  47. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  48. package/src/__tests__/helpers/msw/index.ts +21 -0
  49. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  50. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  51. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  52. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  53. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  54. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  55. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  56. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  57. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  58. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  59. package/src/__tests__/https-options.test.ts +163 -0
  60. package/src/__tests__/index.test.ts +264 -149
  61. package/src/__tests__/init.test.ts +3147 -0
  62. package/src/__tests__/jest.setup.ts +198 -0
  63. package/src/__tests__/kv.test.ts +1788 -0
  64. package/src/__tests__/logger.test.ts +141 -0
  65. package/src/__tests__/logout.test.ts +47 -0
  66. package/src/__tests__/metrics.test.ts +493 -0
  67. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  68. package/src/__tests__/middleware.test.ts +750 -0
  69. package/src/__tests__/package-manager.test.ts +353 -0
  70. package/src/__tests__/pages-deployment-tail.test.ts +884 -0
  71. package/src/__tests__/pages.test.ts +2899 -0
  72. package/src/__tests__/parse.test.ts +330 -0
  73. package/src/__tests__/paths.test.ts +39 -0
  74. package/src/__tests__/publish.test.ts +7769 -0
  75. package/src/__tests__/pubsub.test.ts +490 -0
  76. package/src/__tests__/queues.test.ts +522 -0
  77. package/src/__tests__/r2.test.ts +393 -0
  78. package/src/__tests__/route.test.ts +45 -0
  79. package/src/__tests__/secret.test.ts +701 -0
  80. package/src/__tests__/tail.test.ts +905 -0
  81. package/src/__tests__/test-old-node-version.js +31 -0
  82. package/src/__tests__/tsconfig-sanity.ts +12 -0
  83. package/src/__tests__/tsconfig.json +8 -0
  84. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  85. package/src/__tests__/type-generation.test.ts +233 -0
  86. package/src/__tests__/user.test.ts +129 -0
  87. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  88. package/src/__tests__/validate-dev-props.test.ts +56 -0
  89. package/src/__tests__/version.test.ts +35 -0
  90. package/src/__tests__/whoami.test.tsx +183 -0
  91. package/src/__tests__/worker-namespace.test.ts +326 -0
  92. package/src/abort.d.ts +3 -0
  93. package/src/api/dev.ts +247 -0
  94. package/src/api/index.ts +2 -0
  95. package/src/bundle-reporter.ts +68 -0
  96. package/src/bundle.ts +823 -0
  97. package/src/cfetch/index.ts +158 -0
  98. package/src/cfetch/internal.ts +261 -0
  99. package/src/cli.ts +26 -8
  100. package/src/config/README.md +107 -0
  101. package/src/config/config.ts +275 -0
  102. package/src/config/diagnostics.ts +80 -0
  103. package/src/config/environment.ts +577 -0
  104. package/src/config/index.ts +358 -0
  105. package/src/config/validation-helpers.ts +597 -0
  106. package/src/config/validation.ts +2151 -0
  107. package/src/config-cache.ts +85 -0
  108. package/src/create-worker-preview.ts +282 -0
  109. package/src/create-worker-upload-form.ts +325 -0
  110. package/src/d1/backups.tsx +223 -0
  111. package/src/d1/constants.ts +2 -0
  112. package/src/d1/create.tsx +63 -0
  113. package/src/d1/delete.ts +56 -0
  114. package/src/d1/execute.tsx +323 -0
  115. package/src/d1/formatTimeAgo.ts +14 -0
  116. package/src/d1/index.ts +101 -0
  117. package/src/d1/list.tsx +48 -0
  118. package/src/d1/migrations/apply.tsx +197 -0
  119. package/src/d1/migrations/create.tsx +77 -0
  120. package/src/d1/migrations/helpers.ts +147 -0
  121. package/src/d1/migrations/index.ts +3 -0
  122. package/src/d1/migrations/list.tsx +79 -0
  123. package/src/d1/migrations/options.ts +18 -0
  124. package/src/d1/options.ts +22 -0
  125. package/src/d1/splitter.ts +161 -0
  126. package/src/d1/types.ts +24 -0
  127. package/src/d1/utils.ts +48 -0
  128. package/src/delete.ts +103 -0
  129. package/src/deployments.ts +83 -0
  130. package/src/deprecated/index.ts +145 -0
  131. package/src/dev/dev-vars.ts +39 -0
  132. package/src/dev/dev.tsx +614 -0
  133. package/src/dev/get-local-persistence-path.ts +31 -0
  134. package/src/dev/local.tsx +932 -0
  135. package/src/dev/remote.tsx +630 -0
  136. package/src/dev/start-server.ts +543 -0
  137. package/src/dev/use-esbuild.ts +204 -0
  138. package/src/dev/validate-dev-props.ts +31 -0
  139. package/src/dev-registry.ts +201 -0
  140. package/src/dev.tsx +929 -704
  141. package/src/dialogs.ts +136 -0
  142. package/src/dispatch-namespace.ts +207 -0
  143. package/src/docs/index.ts +97 -0
  144. package/src/durable.ts +102 -0
  145. package/src/entry.ts +329 -0
  146. package/src/environment-variables/factory.ts +88 -0
  147. package/src/environment-variables/misc-variables.ts +30 -0
  148. package/src/errors.ts +11 -0
  149. package/src/generate/index.ts +300 -0
  150. package/src/git-client.ts +135 -0
  151. package/src/global-wrangler-config-path.ts +26 -0
  152. package/src/https-options.ts +127 -0
  153. package/src/index.ts +694 -0
  154. package/src/init.ts +1023 -0
  155. package/src/inspect.ts +767 -0
  156. package/src/intl-polyfill.d.ts +139 -0
  157. package/src/is-ci.ts +14 -0
  158. package/src/is-interactive.ts +16 -0
  159. package/src/jest.d.ts +4 -0
  160. package/src/kv/helpers.ts +430 -0
  161. package/src/kv/index.ts +596 -0
  162. package/src/logger.ts +104 -0
  163. package/src/metrics/index.ts +5 -0
  164. package/src/metrics/metrics-config.ts +239 -0
  165. package/src/metrics/metrics-dispatcher.ts +96 -0
  166. package/src/metrics/metrics-usage-headers.ts +24 -0
  167. package/src/metrics/send-event.ts +97 -0
  168. package/src/miniflare-cli/README.md +30 -0
  169. package/src/miniflare-cli/assets.ts +250 -0
  170. package/src/miniflare-cli/index.ts +210 -0
  171. package/src/miniflare-cli/request-context.ts +40 -0
  172. package/src/miniflare-cli/tsconfig.json +9 -0
  173. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  174. package/src/miniflare-cli/types.ts +11 -0
  175. package/src/module-collection.ts +256 -53
  176. package/src/open-in-browser.ts +17 -0
  177. package/src/package-manager.ts +219 -0
  178. package/src/pages/build.ts +270 -0
  179. package/src/pages/constants.ts +18 -0
  180. package/src/pages/deployment-tails.ts +284 -0
  181. package/src/pages/deployments.tsx +84 -0
  182. package/src/pages/dev.ts +711 -0
  183. package/src/pages/errors.ts +66 -0
  184. package/src/pages/functions/buildPlugin.ts +107 -0
  185. package/src/pages/functions/buildWorker.ts +166 -0
  186. package/src/pages/functions/filepath-routing.test.ts +234 -0
  187. package/src/pages/functions/filepath-routing.ts +189 -0
  188. package/src/pages/functions/identifiers.ts +78 -0
  189. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  190. package/src/pages/functions/routes-consolidation.ts +73 -0
  191. package/src/pages/functions/routes-transformation.test.ts +282 -0
  192. package/src/pages/functions/routes-transformation.ts +115 -0
  193. package/src/pages/functions/routes-validation.test.ts +403 -0
  194. package/src/pages/functions/routes-validation.ts +202 -0
  195. package/src/pages/functions/routes.ts +151 -0
  196. package/src/pages/functions/tsconfig.json +8 -0
  197. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  198. package/src/pages/functions.ts +82 -0
  199. package/src/pages/hash.ts +13 -0
  200. package/src/pages/index.ts +102 -0
  201. package/src/pages/projects.tsx +167 -0
  202. package/src/pages/prompt-select-project.tsx +31 -0
  203. package/src/pages/publish.tsx +462 -0
  204. package/src/pages/types.ts +41 -0
  205. package/src/pages/upload.tsx +447 -0
  206. package/src/pages/utils.ts +23 -0
  207. package/src/parse.ts +286 -0
  208. package/src/paths.ts +71 -0
  209. package/src/proxy.ts +694 -0
  210. package/src/publish/index.ts +270 -0
  211. package/src/publish/publish.ts +1038 -0
  212. package/src/pubsub/index.ts +286 -0
  213. package/src/pubsub/pubsub-commands.ts +624 -0
  214. package/src/queues/cli/commands/consumer/add.ts +71 -0
  215. package/src/queues/cli/commands/consumer/index.ts +22 -0
  216. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  217. package/src/queues/cli/commands/create.ts +25 -0
  218. package/src/queues/cli/commands/delete.ts +26 -0
  219. package/src/queues/cli/commands/index.ts +36 -0
  220. package/src/queues/cli/commands/list.ts +25 -0
  221. package/src/queues/client.ts +135 -0
  222. package/src/queues/utils.ts +18 -0
  223. package/src/r2/constants.ts +4 -0
  224. package/src/r2/helpers.ts +131 -0
  225. package/src/r2/index.ts +289 -0
  226. package/src/routes.ts +140 -0
  227. package/src/secret/index.ts +379 -0
  228. package/src/selfsigned.d.ts +29 -0
  229. package/src/sites.ts +372 -0
  230. package/src/tail/createTail.ts +379 -0
  231. package/src/tail/filters.ts +277 -0
  232. package/src/tail/index.ts +213 -0
  233. package/src/tail/printing.ts +107 -0
  234. package/src/tsconfig-sanity.ts +16 -0
  235. package/src/type-generation.ts +181 -0
  236. package/src/update-check.ts +19 -0
  237. package/src/user/access.ts +68 -0
  238. package/src/user/auth-variables.ts +113 -0
  239. package/src/user/choose-account.tsx +39 -0
  240. package/src/user/generate-auth-url.ts +33 -0
  241. package/src/user/generate-random-state.ts +16 -0
  242. package/src/user/index.ts +2 -0
  243. package/src/user/user.ts +1232 -0
  244. package/src/utils/collectKeyValues.ts +14 -0
  245. package/src/whoami.ts +135 -0
  246. package/src/worker.ts +251 -0
  247. package/src/yargs-types.ts +24 -0
  248. package/src/zones.ts +191 -0
  249. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  250. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  251. package/templates/__tests__/tsconfig.json +8 -0
  252. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  253. package/templates/checked-fetch.js +17 -0
  254. package/templates/d1-beta-facade.js +241 -0
  255. package/templates/facade.d.ts +14 -0
  256. package/templates/first-party-worker-module-facade.ts +19 -0
  257. package/templates/format-dev-errors.ts +33 -0
  258. package/templates/gitignore +171 -0
  259. package/templates/init-tests/test-jest-new-worker.js +23 -0
  260. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  261. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  262. package/templates/middleware/common.ts +62 -0
  263. package/templates/middleware/loader-modules.ts +82 -0
  264. package/templates/middleware/loader-sw.ts +233 -0
  265. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  266. package/templates/middleware/middleware-pretty-error.ts +40 -0
  267. package/templates/middleware/middleware-scheduled.ts +15 -0
  268. package/templates/new-worker-scheduled.js +17 -0
  269. package/templates/new-worker-scheduled.ts +32 -0
  270. package/templates/new-worker.js +15 -0
  271. package/templates/new-worker.ts +30 -0
  272. package/templates/no-op-worker.js +10 -0
  273. package/templates/pages-dev-pipeline.ts +31 -0
  274. package/templates/pages-dev-util.ts +52 -0
  275. package/templates/pages-shim.ts +12 -0
  276. package/templates/pages-template-plugin.ts +176 -0
  277. package/templates/pages-template-worker.ts +189 -0
  278. package/templates/serve-static-assets.ts +65 -0
  279. package/templates/service-bindings-module-facade.js +54 -0
  280. package/templates/service-bindings-sw-facade.js +42 -0
  281. package/templates/tsconfig-sanity.ts +11 -0
  282. package/templates/tsconfig.init.json +106 -0
  283. package/templates/tsconfig.json +8 -0
  284. package/templates/tsconfig.tsbuildinfo +1 -0
  285. package/wrangler-dist/cli.d.ts +906 -0
  286. package/wrangler-dist/cli.js +133533 -113146
  287. package/wrangler-dist/wasm-sync.wasm +0 -0
  288. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  289. package/src/__tests__/mock-cfetch.js +0 -46
  290. package/src/api/form_data.ts +0 -141
  291. package/src/api/inspect.ts +0 -441
  292. package/src/api/preview.ts +0 -128
  293. package/src/api/worker.ts +0 -161
  294. package/src/cfetch.ts +0 -72
  295. package/src/config.ts +0 -122
  296. package/src/dialogs.tsx +0 -85
  297. package/src/index.tsx +0 -1858
  298. package/src/kv.tsx +0 -211
  299. package/src/pages.tsx +0 -843
  300. package/src/publish.ts +0 -346
  301. package/src/sites.tsx +0 -115
  302. package/src/tail.tsx +0 -71
  303. package/src/user.tsx +0 -1029
  304. package/static-asset-facade.js +0 -47
  305. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  306. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  307. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  308. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  309. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  310. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  311. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  312. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  313. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  314. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  315. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  316. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  317. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  318. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  319. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  320. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  321. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  322. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  323. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  324. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  325. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  326. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  327. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  328. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  329. package/vendor/wrangler-mime/LICENSE +0 -21
  330. package/vendor/wrangler-mime/Mime.js +0 -97
  331. package/vendor/wrangler-mime/README.md +0 -187
  332. package/vendor/wrangler-mime/cli.js +0 -46
  333. package/vendor/wrangler-mime/index.js +0 -4
  334. package/vendor/wrangler-mime/lite.js +0 -4
  335. package/vendor/wrangler-mime/package.json +0 -52
  336. package/vendor/wrangler-mime/types/other.js +0 -1
  337. package/vendor/wrangler-mime/types/standard.js +0 -1
  338. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,1038 @@
1
+ import assert from "node:assert";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { URLSearchParams } from "node:url";
5
+ import chalk from "chalk";
6
+ import tmp from "tmp-promise";
7
+ import { bundleWorker } from "../bundle";
8
+ import {
9
+ printBundleSize,
10
+ printOffendingDependencies,
11
+ } from "../bundle-reporter";
12
+ import { fetchListResult, fetchResult } from "../cfetch";
13
+ import { printBindings } from "../config";
14
+ import { createWorkerUploadForm } from "../create-worker-upload-form";
15
+ import { confirm } from "../dialogs";
16
+ import { getMigrationsToUpload } from "../durable";
17
+ import { logger } from "../logger";
18
+ import { getMetricsUsageHeaders } from "../metrics";
19
+ import { ParseError } from "../parse";
20
+ import { getQueue, putConsumer } from "../queues/client";
21
+ import { getWorkersDevSubdomain } from "../routes";
22
+ import { syncAssets } from "../sites";
23
+ import { identifyD1BindingsAsBeta } from "../worker";
24
+ import { getZoneForRoute } from "../zones";
25
+ import type { FetchError } from "../cfetch";
26
+ import type { Config } from "../config";
27
+ import type {
28
+ Route,
29
+ ZoneIdRoute,
30
+ ZoneNameRoute,
31
+ CustomDomainRoute,
32
+ } from "../config/environment";
33
+ import type { DeploymentListRes } from "../deployments";
34
+ import type { Entry } from "../entry";
35
+ import type { PutConsumerBody } from "../queues/client";
36
+ import type { AssetPaths } from "../sites";
37
+ import type { CfWorkerInit } from "../worker";
38
+
39
+ type Props = {
40
+ config: Config;
41
+ accountId: string | undefined;
42
+ entry: Entry;
43
+ rules: Config["rules"];
44
+ name: string | undefined;
45
+ env: string | undefined;
46
+ compatibilityDate: string | undefined;
47
+ compatibilityFlags: string[] | undefined;
48
+ assetPaths: AssetPaths | undefined;
49
+ vars: Record<string, string> | undefined;
50
+ defines: Record<string, string> | undefined;
51
+ triggers: string[] | undefined;
52
+ routes: string[] | undefined;
53
+ legacyEnv: boolean | undefined;
54
+ jsxFactory: string | undefined;
55
+ jsxFragment: string | undefined;
56
+ tsconfig: string | undefined;
57
+ isWorkersSite: boolean;
58
+ minify: boolean | undefined;
59
+ nodeCompat: boolean | undefined;
60
+ outDir: string | undefined;
61
+ dryRun: boolean | undefined;
62
+ noBundle: boolean | undefined;
63
+ keepVars: boolean | undefined;
64
+ logpush: boolean | undefined;
65
+ };
66
+
67
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
68
+
69
+ export type CustomDomain = {
70
+ id: string;
71
+ zone_id: string;
72
+ zone_name: string;
73
+ hostname: string;
74
+ service: string;
75
+ environment: string;
76
+ };
77
+ type UpdatedCustomDomain = CustomDomain & { modified: boolean };
78
+ type ConflictingCustomDomain = CustomDomain & {
79
+ external_dns_record_id?: string;
80
+ external_cert_id?: string;
81
+ };
82
+
83
+ export type CustomDomainChangeset = {
84
+ added: CustomDomain[];
85
+ removed: CustomDomain[];
86
+ updated: UpdatedCustomDomain[];
87
+ conflicting: ConflictingCustomDomain[];
88
+ };
89
+
90
+ function sleep(ms: number) {
91
+ return new Promise((resolve) => setTimeout(resolve, ms));
92
+ }
93
+
94
+ const scriptStartupErrorRegex = /startup/i;
95
+
96
+ function errIsScriptSizeOrStartupErr(err: unknown) {
97
+ if (!err) return false;
98
+
99
+ // 10027 = workers.api.error.script_too_large
100
+ if ((err as { code: number }).code === 10027) {
101
+ return true;
102
+ }
103
+
104
+ // 10021 = validation error
105
+ // no explicit error code for more granular errors than "invalid script"
106
+ // but the error will contain a string error message directly from the
107
+ // validator.
108
+ // the error always SHOULD look like "Script startup exceeded CPU limit."
109
+ // (or the less likely "Script startup exceeded memory limits.")
110
+ if (
111
+ (err as { code: number }).code === 10021 &&
112
+ err instanceof ParseError &&
113
+ scriptStartupErrorRegex.test(err.notes[0]?.text)
114
+ ) {
115
+ return true;
116
+ }
117
+
118
+ return false;
119
+ }
120
+
121
+ function renderRoute(route: Route): string {
122
+ let result = "";
123
+ if (typeof route === "string") {
124
+ result = route;
125
+ } else {
126
+ result = route.pattern;
127
+ const isCustomDomain = Boolean(
128
+ "custom_domain" in route && route.custom_domain
129
+ );
130
+ if (isCustomDomain && "zone_id" in route) {
131
+ result += ` (custom domain - zone id: ${route.zone_id})`;
132
+ } else if (isCustomDomain && "zone_name" in route) {
133
+ result += ` (custom domain - zone name: ${route.zone_name})`;
134
+ } else if (isCustomDomain) {
135
+ result += ` (custom domain)`;
136
+ } else if ("zone_id" in route) {
137
+ result += ` (zone id: ${route.zone_id})`;
138
+ } else if ("zone_name" in route) {
139
+ result += ` (zone name: ${route.zone_name})`;
140
+ }
141
+ }
142
+ return result;
143
+ }
144
+
145
+ // publishing to custom domains involves a few more steps than just updating
146
+ // the routing table, and thus the api implementing it is fairly defensive -
147
+ // it will error eagerly on conflicts against existing domains or existing
148
+ // managed DNS records
149
+
150
+ // however, you can pass params to override the errors. to know if we should
151
+ // override the current state, we generate a "changeset" of required actions
152
+ // to get to the state we want (specified by the list of custom domains). the
153
+ // changeset returns an "updated" collection (existing custom domains
154
+ // connected to other scripts) and a "conflicting" collection (the requested
155
+ // custom domains that have a managed, conflicting DNS record preventing the
156
+ // host's use as a custom domain). with this information, we can prompt to
157
+ // the user what will occur if we create the custom domains requested, and
158
+ // add the override param if they confirm the action
159
+ //
160
+ // if a user does not confirm that they want to override, we skip publishing
161
+ // to these custom domains, but continue on through the rest of the
162
+ // publish stage
163
+ async function publishCustomDomains(
164
+ workerUrl: string,
165
+ accountId: string,
166
+ domains: Array<RouteObject>
167
+ ): Promise<string[]> {
168
+ const config = {
169
+ override_scope: true,
170
+ override_existing_origin: false,
171
+ override_existing_dns_record: false,
172
+ };
173
+ const origins = domains.map((domainRoute) => {
174
+ return {
175
+ hostname: domainRoute.pattern,
176
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
177
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
178
+ };
179
+ });
180
+
181
+ const fail = () => {
182
+ return [
183
+ domains.length > 1
184
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
185
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
186
+ ];
187
+ };
188
+
189
+ if (!process.stdout.isTTY) {
190
+ // running in non-interactive mode.
191
+ // existing origins / dns records are not indicative of errors,
192
+ // so we aggressively update rather than aggressively fail
193
+ config.override_existing_origin = true;
194
+ config.override_existing_dns_record = true;
195
+ } else {
196
+ // get a changeset for operations required to achieve a state with the requested domains
197
+ const changeset = await fetchResult<CustomDomainChangeset>(
198
+ `${workerUrl}/domains/changeset?replace_state=true`,
199
+ {
200
+ method: "POST",
201
+ body: JSON.stringify(origins),
202
+ headers: {
203
+ "Content-Type": "application/json",
204
+ },
205
+ }
206
+ );
207
+
208
+ const updatesRequired = changeset.updated.filter(
209
+ (domain) => domain.modified
210
+ );
211
+ if (updatesRequired.length > 0) {
212
+ // find out which scripts the conflict domains are already attached to
213
+ // so we can provide that in the confirmation prompt
214
+ const existing = await Promise.all(
215
+ updatesRequired.map((domain) =>
216
+ fetchResult<CustomDomain>(
217
+ `/accounts/${accountId}/workers/domains/records/${domain.id}`
218
+ )
219
+ )
220
+ );
221
+ const existingRendered = existing
222
+ .map(
223
+ (domain) =>
224
+ `\t• ${domain.hostname} (used as a domain for "${domain.service}")`
225
+ )
226
+ .join("\n");
227
+ const message = `Custom Domains already exist for these domains:
228
+ ${existingRendered}
229
+ Update them to point to this script instead?`;
230
+ if (!(await confirm(message))) return fail();
231
+ config.override_existing_origin = true;
232
+ }
233
+
234
+ if (changeset.conflicting.length > 0) {
235
+ const conflicitingRendered = changeset.conflicting
236
+ .map((domain) => `\t• ${domain.hostname}`)
237
+ .join("\n");
238
+ const message = `You already have DNS records that conflict for these Custom Domains:
239
+ ${conflicitingRendered}
240
+ Update them to point to this script instead?`;
241
+ if (!(await confirm(message))) return fail();
242
+ config.override_existing_dns_record = true;
243
+ }
244
+ }
245
+
246
+ // publish to domains
247
+ await fetchResult(`${workerUrl}/domains/records`, {
248
+ method: "PUT",
249
+ body: JSON.stringify({ ...config, origins }),
250
+ headers: {
251
+ "Content-Type": "application/json",
252
+ },
253
+ });
254
+
255
+ return domains.map((domain) => renderRoute(domain));
256
+ }
257
+
258
+ export default async function publish(props: Props): Promise<void> {
259
+ // TODO: warn if git/hg has uncommitted changes
260
+ const { config, accountId, name } = props;
261
+ if (accountId && name) {
262
+ try {
263
+ const serviceMetaData = await fetchResult(
264
+ `/accounts/${accountId}/workers/services/${name}`
265
+ );
266
+ const { default_environment } = serviceMetaData as {
267
+ default_environment: {
268
+ script: { last_deployed_from: "dash" | "wrangler" | "api" };
269
+ };
270
+ };
271
+
272
+ if (default_environment.script.last_deployed_from === "dash") {
273
+ logger.warn(
274
+ `You are about to publish a Workers Service that was last published via the Cloudflare Dashboard.\nEdits that have been made via the dashboard will be overridden by your local code and config.`
275
+ );
276
+ if (!(await confirm("Would you like to continue?"))) {
277
+ return;
278
+ }
279
+ }
280
+ } catch (e) {
281
+ // code: 10090, message: workers.api.error.service_not_found
282
+ // is thrown from the above fetchResult on the first publish of a Worker
283
+ if ((e as { code?: number }).code !== 10090) {
284
+ logger.error(e);
285
+ }
286
+ }
287
+ }
288
+
289
+ if (!(props.compatibilityDate || config.compatibility_date)) {
290
+ const compatibilityDateStr = `${new Date().getFullYear()}-${(
291
+ new Date().getMonth() +
292
+ 1 +
293
+ ""
294
+ ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
295
+
296
+ throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
297
+ \`\`\`
298
+ compatibility_date = "${compatibilityDateStr}"
299
+ \`\`\`
300
+ Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
301
+ See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
302
+ }
303
+
304
+ const triggers = props.triggers || config.triggers?.crons;
305
+ const routes =
306
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
307
+ const routesOnly: Array<Route> = [];
308
+ const customDomainsOnly: Array<RouteObject> = [];
309
+ for (const route of routes) {
310
+ if (typeof route !== "string" && route.custom_domain) {
311
+ if (route.pattern.includes("*")) {
312
+ throw new Error(
313
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
314
+ );
315
+ }
316
+ if (route.pattern.includes("/")) {
317
+ throw new Error(
318
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
319
+ );
320
+ }
321
+ customDomainsOnly.push(route);
322
+ } else {
323
+ routesOnly.push(route);
324
+ }
325
+ }
326
+
327
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
328
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
329
+
330
+ const jsxFactory = props.jsxFactory || config.jsx_factory;
331
+ const jsxFragment = props.jsxFragment || config.jsx_fragment;
332
+ const keepVars = props.keepVars ?? config.keep_vars;
333
+
334
+ const minify = props.minify ?? config.minify;
335
+
336
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
337
+ if (nodeCompat) {
338
+ logger.warn(
339
+ "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
340
+ );
341
+ }
342
+
343
+ // Warn if user tries minify or node-compat with no-bundle
344
+ if (props.noBundle && minify) {
345
+ logger.warn(
346
+ "`--minify` and `--no-bundle` can't be used together. If you want to minify your Worker and disable Wrangler's bundling, please minify as part of your own bundling process."
347
+ );
348
+ }
349
+
350
+ if (props.noBundle && nodeCompat) {
351
+ logger.warn(
352
+ "`--node-compat` and `--no-bundle` can't be used together. If you want to polyfill Node.js built-ins and disable Wrangler's bundling, please polyfill as part of your own bundling process."
353
+ );
354
+ }
355
+
356
+ const scriptName = props.name;
357
+ assert(
358
+ scriptName,
359
+ 'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`'
360
+ );
361
+
362
+ assert(
363
+ !config.site || config.site.bucket,
364
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
365
+ );
366
+
367
+ if (props.outDir) {
368
+ // we're using a custom output directory,
369
+ // so let's first ensure it exists
370
+ mkdirSync(props.outDir, { recursive: true });
371
+ // add a README
372
+ const readmePath = path.join(props.outDir, "README.md");
373
+ writeFileSync(
374
+ readmePath,
375
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
376
+ );
377
+ }
378
+
379
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
380
+ const envName = props.env ?? "production";
381
+
382
+ const start = Date.now();
383
+ const notProd = Boolean(!props.legacyEnv && props.env);
384
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
385
+ const workerUrl = notProd
386
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
387
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
388
+
389
+ let available_on_subdomain: boolean | undefined = undefined; // we'll set this later
390
+ let scriptTag: string | null = null;
391
+
392
+ const { format } = props.entry;
393
+
394
+ if (
395
+ !props.isWorkersSite &&
396
+ Boolean(props.assetPaths) &&
397
+ format === "service-worker"
398
+ ) {
399
+ throw new Error(
400
+ "You cannot use the service-worker format with an `assets` directory yet. For information on how to migrate to the module-worker format, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
401
+ );
402
+ }
403
+
404
+ if (config.wasm_modules && format === "modules") {
405
+ throw new Error(
406
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
407
+ );
408
+ }
409
+
410
+ if (config.text_blobs && format === "modules") {
411
+ throw new Error(
412
+ "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
413
+ );
414
+ }
415
+
416
+ if (config.data_blobs && format === "modules") {
417
+ throw new Error(
418
+ "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
419
+ );
420
+ }
421
+ try {
422
+ if (props.noBundle) {
423
+ // if we're not building, let's just copy the entry to the destination directory
424
+ const destinationDir =
425
+ typeof destination === "string" ? destination : destination.path;
426
+ mkdirSync(destinationDir, { recursive: true });
427
+ writeFileSync(
428
+ path.join(destinationDir, path.basename(props.entry.file)),
429
+ readFileSync(props.entry.file, "utf-8")
430
+ );
431
+ }
432
+
433
+ // If we are using d1 bindings, and are not bundling the worker
434
+ // we should error here as the d1 shim won't be added
435
+ const betaD1Shims = identifyD1BindingsAsBeta(config.d1_databases);
436
+ if (
437
+ Array.isArray(betaD1Shims) &&
438
+ betaD1Shims.length > 0 &&
439
+ props.noBundle
440
+ ) {
441
+ throw new Error(
442
+ "While in beta, you cannot use D1 bindings without bundling your worker. Please remove `no_bundle` from your wrangler.toml file or remove the `--no-bundle` flag to access D1 bindings."
443
+ );
444
+ }
445
+
446
+ const {
447
+ modules,
448
+ dependencies,
449
+ resolvedEntryPointPath,
450
+ bundleType,
451
+ }: Awaited<ReturnType<typeof bundleWorker>> = props.noBundle
452
+ ? // we can skip the whole bundling step and mock a bundle here
453
+ {
454
+ modules: [],
455
+ dependencies: {},
456
+ resolvedEntryPointPath: props.entry.file,
457
+ bundleType: props.entry.format === "modules" ? "esm" : "commonjs",
458
+ stop: undefined,
459
+ }
460
+ : await bundleWorker(
461
+ props.entry,
462
+ typeof destination === "string" ? destination : destination.path,
463
+ {
464
+ serveAssetsFromWorker:
465
+ !props.isWorkersSite && Boolean(props.assetPaths),
466
+ betaD1Shims: identifyD1BindingsAsBeta(config.d1_databases)?.map(
467
+ (db) => db.binding
468
+ ),
469
+ jsxFactory,
470
+ jsxFragment,
471
+ rules: props.rules,
472
+ tsconfig: props.tsconfig ?? config.tsconfig,
473
+ minify,
474
+ nodeCompat,
475
+ define: { ...config.define, ...props.defines },
476
+ checkFetch: false,
477
+ assets: config.assets && {
478
+ ...config.assets,
479
+ // enable the cache when publishing
480
+ bypassCache: false,
481
+ },
482
+ services: config.services,
483
+ // We don't set workerDefinitions here,
484
+ // because we don't want to apply the dev-time
485
+ // facades on top of it
486
+ workerDefinitions: undefined,
487
+ firstPartyWorkerDevFacade: false,
488
+ // We want to know if the build is for development or publishing
489
+ // This could potentially cause issues as we no longer have identical behaviour between dev and publish?
490
+ targetConsumer: "publish",
491
+ local: false,
492
+ experimentalLocal: false,
493
+ }
494
+ );
495
+
496
+ const content = readFileSync(resolvedEntryPointPath, {
497
+ encoding: "utf-8",
498
+ });
499
+
500
+ // durable object migrations
501
+ const migrations = !props.dryRun
502
+ ? await getMigrationsToUpload(scriptName, {
503
+ accountId,
504
+ config,
505
+ legacyEnv: props.legacyEnv,
506
+ env: props.env,
507
+ })
508
+ : undefined;
509
+
510
+ const assets = await syncAssets(
511
+ accountId,
512
+ // When we're using the newer service environments, we wouldn't
513
+ // have added the env name on to the script name. However, we must
514
+ // include it in the kv namespace name regardless (since there's no
515
+ // concept of service environments for kv namespaces yet).
516
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
517
+ props.assetPaths,
518
+ false,
519
+ props.dryRun
520
+ );
521
+
522
+ const bindings: CfWorkerInit["bindings"] = {
523
+ kv_namespaces: (config.kv_namespaces || []).concat(
524
+ assets.namespace
525
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
526
+ : []
527
+ ),
528
+ vars: { ...config.vars, ...props.vars },
529
+ wasm_modules: config.wasm_modules,
530
+ text_blobs: {
531
+ ...config.text_blobs,
532
+ ...(assets.manifest &&
533
+ format === "service-worker" && {
534
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
535
+ }),
536
+ },
537
+ data_blobs: config.data_blobs,
538
+ durable_objects: config.durable_objects,
539
+ queues: config.queues.producers?.map((producer) => {
540
+ return { binding: producer.binding, queue_name: producer.queue };
541
+ }),
542
+ r2_buckets: config.r2_buckets,
543
+ d1_databases: identifyD1BindingsAsBeta(config.d1_databases),
544
+ services: config.services,
545
+ analytics_engine_datasets: config.analytics_engine_datasets,
546
+ dispatch_namespaces: config.dispatch_namespaces,
547
+ logfwdr: config.logfwdr,
548
+ unsafe: config.unsafe?.bindings,
549
+ };
550
+
551
+ if (assets.manifest) {
552
+ modules.push({
553
+ name: "__STATIC_CONTENT_MANIFEST",
554
+ content: JSON.stringify(assets.manifest),
555
+ type: "text",
556
+ });
557
+ }
558
+
559
+ const worker: CfWorkerInit = {
560
+ name: scriptName,
561
+ main: {
562
+ name: path.basename(resolvedEntryPointPath),
563
+ content: content,
564
+ type: bundleType,
565
+ },
566
+ bindings,
567
+ migrations,
568
+ modules,
569
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
570
+ compatibility_flags:
571
+ props.compatibilityFlags ?? config.compatibility_flags,
572
+ usage_model: config.usage_model,
573
+ keepVars,
574
+ logpush: props.logpush !== undefined ? props.logpush : config.logpush,
575
+ };
576
+
577
+ // As this is not deterministic for testing, we detect if in a jest environment and run asynchronously
578
+ // We do not care about the timing outside of testing
579
+ const bundleSizePromise = printBundleSize(
580
+ { name: path.basename(resolvedEntryPointPath), content: content },
581
+ modules
582
+ );
583
+ if (process.env.JEST_WORKER_ID !== undefined) await bundleSizePromise;
584
+ else void bundleSizePromise;
585
+
586
+ const withoutStaticAssets = {
587
+ ...bindings,
588
+ kv_namespaces: config.kv_namespaces,
589
+ text_blobs: config.text_blobs,
590
+ };
591
+
592
+ // mask anything that was overridden in cli args
593
+ // so that we don't log potential secrets into the terminal
594
+ const maskedVars = { ...withoutStaticAssets.vars };
595
+ for (const key of Object.keys(maskedVars)) {
596
+ if (maskedVars[key] !== config.vars[key]) {
597
+ // This means it was overridden in cli args
598
+ // so let's mask it
599
+ maskedVars[key] = "(hidden)";
600
+ }
601
+ }
602
+
603
+ printBindings({ ...withoutStaticAssets, vars: maskedVars });
604
+
605
+ await ensureQueuesExist(config);
606
+
607
+ if (!props.dryRun) {
608
+ // Upload the script so it has time to propagate.
609
+ // We can also now tell whether available_on_subdomain is set
610
+ try {
611
+ const result = await fetchResult<{
612
+ available_on_subdomain: boolean;
613
+ id: string | null;
614
+ etag: string | null;
615
+ pipeline_hash: string | null;
616
+ tag: string | null;
617
+ }>(
618
+ workerUrl,
619
+ {
620
+ method: "PUT",
621
+ body: createWorkerUploadForm(worker),
622
+ headers: await getMetricsUsageHeaders(config.send_metrics),
623
+ },
624
+ new URLSearchParams({
625
+ include_subdomain_availability: "true",
626
+ // pass excludeScript so the whole body of the
627
+ // script doesn't get included in the response
628
+ excludeScript: "true",
629
+ })
630
+ );
631
+
632
+ available_on_subdomain = result.available_on_subdomain;
633
+ scriptTag = result.tag;
634
+
635
+ if (config.first_party_worker) {
636
+ // Print some useful information returned after publishing
637
+ // Not all fields will be populated for every worker
638
+ // These fields are likely to be scraped by tools, so do not rename
639
+ if (result.id) logger.log("Worker ID: ", result.id);
640
+ if (result.etag) logger.log("Worker ETag: ", result.etag);
641
+ if (result.pipeline_hash)
642
+ logger.log("Worker PipelineHash: ", result.pipeline_hash);
643
+ }
644
+ } catch (err) {
645
+ if (errIsScriptSizeOrStartupErr(err)) {
646
+ printOffendingDependencies(dependencies);
647
+ }
648
+ throw err;
649
+ }
650
+ }
651
+ } finally {
652
+ if (typeof destination !== "string") {
653
+ // this means we're using a temp dir,
654
+ // so let's clean up before we proceed
655
+ await destination.cleanup();
656
+ }
657
+ }
658
+
659
+ if (props.dryRun) {
660
+ logger.log(`--dry-run: exiting now.`);
661
+ return;
662
+ }
663
+ assert(accountId, "Missing accountId");
664
+
665
+ const uploadMs = Date.now() - start;
666
+ const deployments: Promise<string[]>[] = [];
667
+
668
+ if (deployToWorkersDev) {
669
+ // Deploy to a subdomain of `workers.dev`
670
+ const userSubdomain = await getWorkersDevSubdomain(accountId);
671
+ const scriptURL =
672
+ props.legacyEnv || !props.env
673
+ ? `${scriptName}.${userSubdomain}.workers.dev`
674
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
675
+ if (!available_on_subdomain) {
676
+ // Enable the `workers.dev` subdomain.
677
+ deployments.push(
678
+ fetchResult(`${workerUrl}/subdomain`, {
679
+ method: "POST",
680
+ body: JSON.stringify({ enabled: true }),
681
+ headers: {
682
+ "Content-Type": "application/json",
683
+ },
684
+ })
685
+ .then(() => [scriptURL])
686
+ // Add a delay when the subdomain is first created.
687
+ // This is to prevent an issue where a negative cache-hit
688
+ // causes the subdomain to be unavailable for 30 seconds.
689
+ // This is a temporary measure until we fix this on the edge.
690
+ .then(async (url) => {
691
+ await sleep(3000);
692
+ return url;
693
+ })
694
+ );
695
+ } else {
696
+ deployments.push(Promise.resolve([scriptURL]));
697
+ }
698
+ } else {
699
+ if (available_on_subdomain) {
700
+ // Disable the workers.dev deployment
701
+ await fetchResult(`${workerUrl}/subdomain`, {
702
+ method: "POST",
703
+ body: JSON.stringify({ enabled: false }),
704
+ headers: {
705
+ "Content-Type": "application/json",
706
+ },
707
+ });
708
+ } else if (routes.length !== 0) {
709
+ // if you get to this point it's because
710
+ // you're trying to deploy a worker to a custom
711
+ // domain that's already bound to another worker.
712
+ // so this thing is about finding workers that have
713
+ // bindings to the routes you're trying to deploy to.
714
+ //
715
+ // the logic is kinda similar (read: duplicated) from publishRoutesFallback,
716
+ // except here we know we have a good API token or whatever so we don't need
717
+ // to bother with all the error handling tomfoolery.
718
+ const routesWithOtherBindings: Record<string, string[]> = {};
719
+ for (const route of routes) {
720
+ const zone = await getZoneForRoute(route);
721
+ if (!zone) {
722
+ continue;
723
+ }
724
+
725
+ const routePattern = typeof route === "string" ? route : route.pattern;
726
+ const routesInZone = await fetchListResult<{
727
+ pattern: string;
728
+ script: string;
729
+ }>(`/zones/${zone.id}/workers/routes`);
730
+
731
+ routesInZone.forEach(({ script, pattern }) => {
732
+ if (pattern === routePattern && script !== scriptName) {
733
+ if (!(script in routesWithOtherBindings)) {
734
+ routesWithOtherBindings[script] = [];
735
+ }
736
+
737
+ routesWithOtherBindings[script].push(pattern);
738
+ }
739
+ });
740
+ }
741
+
742
+ if (Object.keys(routesWithOtherBindings).length > 0) {
743
+ let errorMessage =
744
+ "Can't publish a worker to routes that are assigned to another worker.\n";
745
+
746
+ for (const worker in routesWithOtherBindings) {
747
+ const assignedRoutes = routesWithOtherBindings[worker];
748
+ errorMessage += `"${worker}" is already assigned to routes:\n${assignedRoutes.map(
749
+ (r) => ` - ${chalk.underline(r)}\n`
750
+ )}`;
751
+ }
752
+
753
+ const resolution =
754
+ "Unassign other workers from the routes you want to publish to, and then try again.";
755
+ const dashLink = `Visit ${chalk.blue(
756
+ chalk.underline(
757
+ `https://dash.cloudflare.com/${accountId}/workers/overview`
758
+ )
759
+ )} to unassign a worker from a route.`;
760
+
761
+ throw new Error(`${errorMessage}\n${resolution}\n${dashLink}`);
762
+ }
763
+ }
764
+ }
765
+
766
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
767
+
768
+ // Update routing table for the script.
769
+ if (routesOnly.length > 0) {
770
+ deployments.push(
771
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
772
+ if (routesOnly.length > 10) {
773
+ return routesOnly
774
+ .slice(0, 9)
775
+ .map((route) => renderRoute(route))
776
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
777
+ }
778
+ return routesOnly.map((route) => renderRoute(route));
779
+ })
780
+ );
781
+ }
782
+
783
+ // Update custom domains for the script
784
+ if (customDomainsOnly.length > 0) {
785
+ deployments.push(
786
+ publishCustomDomains(workerUrl, accountId, customDomainsOnly)
787
+ );
788
+ }
789
+
790
+ // Configure any schedules for the script.
791
+ // TODO: rename this to `schedules`?
792
+ if (triggers && triggers.length) {
793
+ deployments.push(
794
+ fetchResult(`${workerUrl}/schedules`, {
795
+ // Note: PUT will override previous schedules on this script.
796
+ method: "PUT",
797
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
798
+ headers: {
799
+ "Content-Type": "application/json",
800
+ },
801
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
802
+ );
803
+ }
804
+
805
+ if (config.queues.consumers && config.queues.consumers.length) {
806
+ deployments.push(...updateQueueConsumers(config));
807
+ }
808
+
809
+ const targets = await Promise.all(deployments);
810
+ const deployMs = Date.now() - start - uploadMs;
811
+
812
+ if (deployments.length > 0) {
813
+ logger.log("Published", workerName, formatTime(deployMs));
814
+ for (const target of targets.flat()) {
815
+ // Append protocol only on workers.dev domains
816
+ logger.log(
817
+ " ",
818
+ (target.endsWith("workers.dev") ? "https://" : "") + target
819
+ );
820
+ }
821
+ } else {
822
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
823
+ }
824
+
825
+ try {
826
+ const deploymentsList = await fetchResult<DeploymentListRes>(
827
+ `/accounts/${accountId}/workers/deployments/by-script/${scriptTag}`
828
+ );
829
+
830
+ logger.log("Current Deployment ID:", deploymentsList.latest.id);
831
+ } catch (e) {
832
+ if ((e as { code: number }).code === 10023) {
833
+ // TODO: remove this try/catch once deployments is completely rolled out
834
+ } else {
835
+ throw e;
836
+ }
837
+ }
838
+ }
839
+
840
+ function formatTime(duration: number) {
841
+ return `(${(duration / 1000).toFixed(2)} sec)`;
842
+ }
843
+
844
+ /**
845
+ * Associate the newly deployed Worker with the given routes.
846
+ */
847
+ async function publishRoutes(
848
+ routes: Route[],
849
+ {
850
+ workerUrl,
851
+ scriptName,
852
+ notProd,
853
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
854
+ ): Promise<string[]> {
855
+ try {
856
+ return await fetchResult(`${workerUrl}/routes`, {
857
+ // Note: PUT will delete previous routes on this script.
858
+ method: "PUT",
859
+ body: JSON.stringify(
860
+ routes.map((route) =>
861
+ typeof route !== "object" ? { pattern: route } : route
862
+ )
863
+ ),
864
+ headers: {
865
+ "Content-Type": "application/json",
866
+ },
867
+ });
868
+ } catch (e) {
869
+ if (isAuthenticationError(e)) {
870
+ // An authentication error is probably due to a known issue,
871
+ // where the user is logged in via an API token that does not have "All Zones".
872
+ return await publishRoutesFallback(routes, { scriptName, notProd });
873
+ } else {
874
+ throw e;
875
+ }
876
+ }
877
+ }
878
+
879
+ /**
880
+ * Try updating routes for the Worker using a less optimal zone-based API.
881
+ *
882
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
883
+ */
884
+ async function publishRoutesFallback(
885
+ routes: Route[],
886
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
887
+ ) {
888
+ if (notProd) {
889
+ throw new Error(
890
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
891
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
892
+ );
893
+ }
894
+ logger.warn(
895
+ "The current authentication token does not have 'All Zones' permissions.\n" +
896
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
897
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
898
+ "Existing routes for this Worker in such zones will not be deleted."
899
+ );
900
+
901
+ const deployedRoutes: string[] = [];
902
+
903
+ // Collect the routes (and their zones) that will be deployed.
904
+ const activeZones = new Map<string, string>();
905
+ const routesToDeploy = new Map<string, string>();
906
+ for (const route of routes) {
907
+ const zone = await getZoneForRoute(route);
908
+ if (zone) {
909
+ activeZones.set(zone.id, zone.host);
910
+ routesToDeploy.set(
911
+ typeof route === "string" ? route : route.pattern,
912
+ zone.id
913
+ );
914
+ }
915
+ }
916
+
917
+ // Collect the routes that are already deployed.
918
+ const allRoutes = new Map<string, string>();
919
+ const alreadyDeployedRoutes = new Set<string>();
920
+ for (const [zone, host] of activeZones) {
921
+ try {
922
+ for (const { pattern, script } of await fetchListResult<{
923
+ pattern: string;
924
+ script: string;
925
+ }>(`/zones/${zone}/workers/routes`)) {
926
+ allRoutes.set(pattern, script);
927
+ if (script === scriptName) {
928
+ alreadyDeployedRoutes.add(pattern);
929
+ }
930
+ }
931
+ } catch (e) {
932
+ if (isAuthenticationError(e)) {
933
+ e.notes.push({
934
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
935
+ });
936
+ }
937
+ throw e;
938
+ }
939
+ }
940
+
941
+ // Deploy each route that is not already deployed.
942
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
943
+ if (allRoutes.has(routePattern)) {
944
+ const knownScript = allRoutes.get(routePattern);
945
+ if (knownScript === scriptName) {
946
+ // This route is already associated with this worker, so no need to hit the API.
947
+ alreadyDeployedRoutes.delete(routePattern);
948
+ continue;
949
+ } else {
950
+ throw new Error(
951
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
952
+ );
953
+ }
954
+ }
955
+
956
+ const { pattern } = await fetchResult<{ pattern: string }>(
957
+ `/zones/${zoneId}/workers/routes`,
958
+ {
959
+ method: "POST",
960
+ body: JSON.stringify({
961
+ pattern: routePattern,
962
+ script: scriptName,
963
+ }),
964
+ headers: {
965
+ "Content-Type": "application/json",
966
+ },
967
+ }
968
+ );
969
+
970
+ deployedRoutes.push(pattern);
971
+ }
972
+
973
+ if (alreadyDeployedRoutes.size) {
974
+ logger.warn(
975
+ "Previously deployed routes:\n" +
976
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
977
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
978
+ "If these routes are not wanted then you can remove them in the dashboard."
979
+ );
980
+ }
981
+
982
+ return deployedRoutes;
983
+ }
984
+
985
+ function isAuthenticationError(e: unknown): e is ParseError {
986
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
987
+ }
988
+
989
+ async function ensureQueuesExist(config: Config) {
990
+ const producers = (config.queues.producers || []).map(
991
+ (producer) => producer.queue
992
+ );
993
+ const consumers = (config.queues.consumers || []).map(
994
+ (consumer) => consumer.queue
995
+ );
996
+
997
+ const queueNames = producers.concat(consumers);
998
+ for (const queue of queueNames) {
999
+ try {
1000
+ await getQueue(config, queue);
1001
+ } catch (err) {
1002
+ const queueErr = err as FetchError;
1003
+ if (queueErr.code === 11000) {
1004
+ // queue_not_found
1005
+ throw new Error(
1006
+ `Queue "${queue}" does not exist. To create it, run: wrangler queues create ${queue}`
1007
+ );
1008
+ }
1009
+ throw err;
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ function updateQueueConsumers(config: Config): Promise<string[]>[] {
1015
+ const consumers = config.queues.consumers || [];
1016
+ return consumers.map((consumer) => {
1017
+ const body: PutConsumerBody = {
1018
+ dead_letter_queue: consumer.dead_letter_queue,
1019
+ settings: {
1020
+ batch_size: consumer.max_batch_size,
1021
+ max_retries: consumer.max_retries,
1022
+ max_wait_time_ms: consumer.max_batch_timeout
1023
+ ? 1000 * consumer.max_batch_timeout
1024
+ : undefined,
1025
+ },
1026
+ };
1027
+
1028
+ if (config.name === undefined) {
1029
+ // TODO: how can we reliably get the current script name?
1030
+ throw new Error("Script name is required to update queue consumers");
1031
+ }
1032
+ const scriptName = config.name;
1033
+ const envName = undefined; // TODO: script environment for wrangler publish?
1034
+ return putConsumer(config, consumer.queue, scriptName, envName, body).then(
1035
+ () => [`Consumer for ${consumer.queue}`]
1036
+ );
1037
+ });
1038
+ }