wrangler 0.0.0-e64812e → 0.0.0-e6c9c5c0

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