wrangler 0.0.0-e33bea9b → 0.0.0-e34d19867

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