wrangler 0.0.0-e95e5a0 → 0.0.0-e98613f8

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