wrangler 0.0.0-e1c2f5b9 → 0.0.0-e1d50407

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 (287) hide show
  1. package/README.md +12 -14
  2. package/bin/wrangler.js +14 -75
  3. package/package.json +213 -194
  4. package/templates/__tests__/tsconfig.json +1 -1
  5. package/templates/checked-fetch.js +19 -6
  6. package/templates/facade.d.ts +4 -1
  7. package/templates/gitignore +1 -0
  8. package/templates/init-tests/test-vitest-new-worker.ts +1 -1
  9. package/templates/middleware/common.ts +9 -4
  10. package/templates/middleware/loader-modules.ts +64 -9
  11. package/templates/middleware/loader-sw.ts +2 -7
  12. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  13. package/templates/middleware/middleware-miniflare3-json-error.ts +18 -5
  14. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  15. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  16. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  17. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  18. package/templates/modules-watch-stub.js +4 -0
  19. package/templates/new-worker-scheduled.ts +1 -1
  20. package/templates/new-worker.ts +4 -1
  21. package/templates/pages-dev-util.ts +4 -1
  22. package/templates/pages-shim.ts +0 -3
  23. package/templates/pages-template-plugin.ts +30 -11
  24. package/templates/pages-template-worker.ts +11 -2
  25. package/templates/startDevWorker/InspectorProxyWorker.ts +652 -0
  26. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  27. package/templates/tsconfig.init.json +1 -2
  28. package/templates/tsconfig.json +1 -1
  29. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  30. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  31. package/wrangler-dist/ProxyWorker.js +186 -0
  32. package/wrangler-dist/ProxyWorker.js.map +6 -0
  33. package/wrangler-dist/cli.d.ts +23110 -509
  34. package/wrangler-dist/cli.js +133619 -137696
  35. package/wrangler-dist/wasm-sync.wasm +0 -0
  36. package/import_meta_url.js +0 -3
  37. package/miniflare-config-stubs/.env.empty +0 -0
  38. package/miniflare-config-stubs/package.empty.json +0 -1
  39. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  40. package/miniflare-dist/index.mjs +0 -6364
  41. package/src/__tests__/access.test.ts +0 -25
  42. package/src/__tests__/api-dev.test.ts +0 -238
  43. package/src/__tests__/api-devregistry.test.js +0 -64
  44. package/src/__tests__/api.test.ts +0 -80
  45. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  46. package/src/__tests__/config-cache.test.ts +0 -42
  47. package/src/__tests__/configuration.test.ts +0 -4163
  48. package/src/__tests__/d1.test.ts +0 -123
  49. package/src/__tests__/delete.test.ts +0 -263
  50. package/src/__tests__/deployments.test.ts +0 -105
  51. package/src/__tests__/dev.test.tsx +0 -1586
  52. package/src/__tests__/dialogs.test.tsx +0 -40
  53. package/src/__tests__/generate.test.ts +0 -235
  54. package/src/__tests__/get-host-from-url.test.ts +0 -16
  55. package/src/__tests__/guess-worker-format.test.ts +0 -85
  56. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  57. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  58. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  59. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  60. package/src/__tests__/helpers/mock-bin.ts +0 -36
  61. package/src/__tests__/helpers/mock-cfetch.ts +0 -277
  62. package/src/__tests__/helpers/mock-console.ts +0 -106
  63. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  64. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  68. package/src/__tests__/helpers/mock-kv.ts +0 -33
  69. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -271
  70. package/src/__tests__/helpers/mock-process.ts +0 -34
  71. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  72. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  73. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  74. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -59
  75. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  76. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  77. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  78. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  79. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  80. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -22
  81. package/src/__tests__/helpers/msw/index.ts +0 -21
  82. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  83. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  84. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  85. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  86. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  87. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  88. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  89. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  90. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  91. package/src/__tests__/https-options.test.ts +0 -163
  92. package/src/__tests__/index.test.ts +0 -268
  93. package/src/__tests__/init.test.ts +0 -3094
  94. package/src/__tests__/jest.setup.ts +0 -203
  95. package/src/__tests__/kv.test.ts +0 -1786
  96. package/src/__tests__/logger.test.ts +0 -141
  97. package/src/__tests__/logout.test.ts +0 -47
  98. package/src/__tests__/metrics.test.ts +0 -495
  99. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  100. package/src/__tests__/middleware.test.ts +0 -750
  101. package/src/__tests__/package-manager.test.ts +0 -353
  102. package/src/__tests__/pages-deployment-tail.test.ts +0 -884
  103. package/src/__tests__/pages.test.ts +0 -2443
  104. package/src/__tests__/parse.test.ts +0 -330
  105. package/src/__tests__/paths.test.ts +0 -39
  106. package/src/__tests__/publish.test.ts +0 -7757
  107. package/src/__tests__/pubsub.test.ts +0 -490
  108. package/src/__tests__/queues.test.ts +0 -522
  109. package/src/__tests__/r2.test.ts +0 -393
  110. package/src/__tests__/route.test.ts +0 -45
  111. package/src/__tests__/secret.test.ts +0 -694
  112. package/src/__tests__/tail.test.ts +0 -899
  113. package/src/__tests__/test-old-node-version.js +0 -31
  114. package/src/__tests__/tsconfig-sanity.ts +0 -12
  115. package/src/__tests__/tsconfig.json +0 -8
  116. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  117. package/src/__tests__/type-generation.test.ts +0 -233
  118. package/src/__tests__/user.test.ts +0 -129
  119. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  120. package/src/__tests__/validate-dev-props.test.ts +0 -56
  121. package/src/__tests__/version.test.ts +0 -35
  122. package/src/__tests__/whoami.test.tsx +0 -278
  123. package/src/__tests__/worker-namespace.test.ts +0 -326
  124. package/src/abort.d.ts +0 -3
  125. package/src/api/dev.ts +0 -218
  126. package/src/api/index.ts +0 -2
  127. package/src/bundle-reporter.tsx +0 -68
  128. package/src/bundle.ts +0 -823
  129. package/src/cfetch/index.ts +0 -158
  130. package/src/cfetch/internal.ts +0 -261
  131. package/src/cli.ts +0 -28
  132. package/src/config/README.md +0 -107
  133. package/src/config/config.ts +0 -275
  134. package/src/config/diagnostics.ts +0 -80
  135. package/src/config/environment.ts +0 -577
  136. package/src/config/index.ts +0 -358
  137. package/src/config/validation-helpers.ts +0 -597
  138. package/src/config/validation.ts +0 -2151
  139. package/src/config-cache.ts +0 -85
  140. package/src/create-worker-preview.ts +0 -282
  141. package/src/create-worker-upload-form.ts +0 -325
  142. package/src/d1/backups.tsx +0 -223
  143. package/src/d1/constants.ts +0 -2
  144. package/src/d1/create.tsx +0 -63
  145. package/src/d1/delete.tsx +0 -56
  146. package/src/d1/execute.tsx +0 -352
  147. package/src/d1/formatTimeAgo.ts +0 -14
  148. package/src/d1/index.ts +0 -101
  149. package/src/d1/list.tsx +0 -48
  150. package/src/d1/migrations/apply.tsx +0 -196
  151. package/src/d1/migrations/create.tsx +0 -77
  152. package/src/d1/migrations/helpers.ts +0 -147
  153. package/src/d1/migrations/index.tsx +0 -3
  154. package/src/d1/migrations/list.tsx +0 -79
  155. package/src/d1/migrations/options.ts +0 -18
  156. package/src/d1/options.ts +0 -22
  157. package/src/d1/types.tsx +0 -24
  158. package/src/d1/utils.ts +0 -48
  159. package/src/delete.ts +0 -108
  160. package/src/deployments.ts +0 -83
  161. package/src/deprecated/index.ts +0 -145
  162. package/src/dev/dev-vars.ts +0 -39
  163. package/src/dev/dev.tsx +0 -614
  164. package/src/dev/get-local-persistence-path.tsx +0 -31
  165. package/src/dev/local.tsx +0 -932
  166. package/src/dev/remote.tsx +0 -603
  167. package/src/dev/start-server.ts +0 -543
  168. package/src/dev/use-esbuild.ts +0 -204
  169. package/src/dev/validate-dev-props.ts +0 -31
  170. package/src/dev-registry.tsx +0 -201
  171. package/src/dev.tsx +0 -949
  172. package/src/dialogs.tsx +0 -168
  173. package/src/dispatch-namespace.ts +0 -207
  174. package/src/docs/index.ts +0 -97
  175. package/src/durable.ts +0 -102
  176. package/src/entry.ts +0 -329
  177. package/src/environment-variables/factory.ts +0 -88
  178. package/src/environment-variables/misc-variables.ts +0 -30
  179. package/src/errors.ts +0 -11
  180. package/src/generate/index.ts +0 -300
  181. package/src/git-client.ts +0 -135
  182. package/src/global-wrangler-config-path.ts +0 -26
  183. package/src/https-options.ts +0 -127
  184. package/src/index.tsx +0 -694
  185. package/src/init.ts +0 -1025
  186. package/src/inspect.ts +0 -767
  187. package/src/intl-polyfill.d.ts +0 -139
  188. package/src/is-ci.ts +0 -14
  189. package/src/is-interactive.ts +0 -16
  190. package/src/jest.d.ts +0 -4
  191. package/src/kv/helpers.ts +0 -430
  192. package/src/kv/index.ts +0 -596
  193. package/src/logger.ts +0 -92
  194. package/src/metrics/index.ts +0 -5
  195. package/src/metrics/metrics-config.ts +0 -239
  196. package/src/metrics/metrics-dispatcher.ts +0 -96
  197. package/src/metrics/metrics-usage-headers.ts +0 -24
  198. package/src/metrics/send-event.ts +0 -97
  199. package/src/miniflare-cli/README.md +0 -30
  200. package/src/miniflare-cli/assets.ts +0 -250
  201. package/src/miniflare-cli/index.ts +0 -210
  202. package/src/miniflare-cli/request-context.ts +0 -40
  203. package/src/miniflare-cli/tsconfig.json +0 -9
  204. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  205. package/src/miniflare-cli/types.ts +0 -11
  206. package/src/module-collection.ts +0 -267
  207. package/src/open-in-browser.ts +0 -17
  208. package/src/package-manager.ts +0 -219
  209. package/src/pages/build.tsx +0 -270
  210. package/src/pages/constants.ts +0 -18
  211. package/src/pages/deployment-tails.tsx +0 -284
  212. package/src/pages/deployments.tsx +0 -84
  213. package/src/pages/dev.tsx +0 -710
  214. package/src/pages/errors.ts +0 -66
  215. package/src/pages/functions/buildPlugin.ts +0 -107
  216. package/src/pages/functions/buildWorker.ts +0 -166
  217. package/src/pages/functions/filepath-routing.test.ts +0 -234
  218. package/src/pages/functions/filepath-routing.ts +0 -189
  219. package/src/pages/functions/identifiers.ts +0 -78
  220. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  221. package/src/pages/functions/routes-consolidation.ts +0 -73
  222. package/src/pages/functions/routes-transformation.test.ts +0 -282
  223. package/src/pages/functions/routes-transformation.ts +0 -115
  224. package/src/pages/functions/routes-validation.test.ts +0 -403
  225. package/src/pages/functions/routes-validation.ts +0 -202
  226. package/src/pages/functions/routes.ts +0 -151
  227. package/src/pages/functions/tsconfig.json +0 -8
  228. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  229. package/src/pages/functions.tsx +0 -82
  230. package/src/pages/hash.tsx +0 -13
  231. package/src/pages/index.tsx +0 -102
  232. package/src/pages/projects.tsx +0 -169
  233. package/src/pages/prompt-select-project.tsx +0 -31
  234. package/src/pages/publish.tsx +0 -461
  235. package/src/pages/types.ts +0 -41
  236. package/src/pages/upload.tsx +0 -447
  237. package/src/pages/utils.ts +0 -23
  238. package/src/parse.ts +0 -286
  239. package/src/paths.ts +0 -71
  240. package/src/proxy.ts +0 -694
  241. package/src/publish/index.ts +0 -270
  242. package/src/publish/publish.ts +0 -1036
  243. package/src/pubsub/index.ts +0 -286
  244. package/src/pubsub/pubsub-commands.tsx +0 -624
  245. package/src/queues/cli/commands/consumer/add.ts +0 -71
  246. package/src/queues/cli/commands/consumer/index.ts +0 -22
  247. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  248. package/src/queues/cli/commands/create.ts +0 -25
  249. package/src/queues/cli/commands/delete.ts +0 -26
  250. package/src/queues/cli/commands/index.ts +0 -36
  251. package/src/queues/cli/commands/list.ts +0 -25
  252. package/src/queues/client.ts +0 -135
  253. package/src/queues/utils.ts +0 -18
  254. package/src/r2/constants.ts +0 -4
  255. package/src/r2/helpers.ts +0 -131
  256. package/src/r2/index.ts +0 -289
  257. package/src/routes.ts +0 -140
  258. package/src/secret/index.ts +0 -379
  259. package/src/selfsigned.d.ts +0 -29
  260. package/src/sites.tsx +0 -372
  261. package/src/tail/createTail.ts +0 -379
  262. package/src/tail/filters.ts +0 -277
  263. package/src/tail/index.ts +0 -214
  264. package/src/tail/printing.ts +0 -107
  265. package/src/tsconfig-sanity.ts +0 -16
  266. package/src/type-generation.ts +0 -181
  267. package/src/update-check.ts +0 -19
  268. package/src/user/access.ts +0 -68
  269. package/src/user/auth-variables.ts +0 -113
  270. package/src/user/choose-account.tsx +0 -69
  271. package/src/user/generate-auth-url.ts +0 -33
  272. package/src/user/generate-random-state.ts +0 -16
  273. package/src/user/index.ts +0 -2
  274. package/src/user/user.tsx +0 -1238
  275. package/src/utils/collectKeyValues.ts +0 -14
  276. package/src/whoami.tsx +0 -169
  277. package/src/worker.ts +0 -251
  278. package/src/yargs-types.ts +0 -24
  279. package/src/zones.ts +0 -191
  280. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  281. package/templates/d1-beta-facade.js +0 -205
  282. package/templates/first-party-worker-module-facade.ts +0 -19
  283. package/templates/format-dev-errors.ts +0 -33
  284. package/templates/serve-static-assets.ts +0 -65
  285. package/templates/service-bindings-module-facade.js +0 -54
  286. package/templates/service-bindings-sw-facade.js +0 -42
  287. package/templates/tsconfig.tsbuildinfo +0 -1
@@ -1,1036 +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, 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
- analytics_engine_datasets: config.analytics_engine_datasets,
544
- dispatch_namespaces: config.dispatch_namespaces,
545
- logfwdr: config.logfwdr,
546
- unsafe: config.unsafe?.bindings,
547
- };
548
-
549
- if (assets.manifest) {
550
- modules.push({
551
- name: "__STATIC_CONTENT_MANIFEST",
552
- content: JSON.stringify(assets.manifest),
553
- type: "text",
554
- });
555
- }
556
-
557
- const worker: CfWorkerInit = {
558
- name: scriptName,
559
- main: {
560
- name: path.basename(resolvedEntryPointPath),
561
- content: content,
562
- type: bundleType,
563
- },
564
- bindings,
565
- migrations,
566
- modules,
567
- compatibility_date: props.compatibilityDate ?? config.compatibility_date,
568
- compatibility_flags:
569
- props.compatibilityFlags ?? config.compatibility_flags,
570
- usage_model: config.usage_model,
571
- keepVars,
572
- logpush: props.logpush !== undefined ? props.logpush : config.logpush,
573
- };
574
-
575
- // As this is not deterministic for testing, we detect if in a jest environment and run asynchronously
576
- // We do not care about the timing outside of testing
577
- const bundleSizePromise = printBundleSize(
578
- { name: path.basename(resolvedEntryPointPath), content: content },
579
- modules
580
- );
581
- if (process.env.JEST_WORKER_ID !== undefined) await bundleSizePromise;
582
- else void bundleSizePromise;
583
-
584
- const withoutStaticAssets = {
585
- ...bindings,
586
- kv_namespaces: config.kv_namespaces,
587
- text_blobs: config.text_blobs,
588
- };
589
-
590
- // mask anything that was overridden in cli args
591
- // so that we don't log potential secrets into the terminal
592
- const maskedVars = { ...withoutStaticAssets.vars };
593
- for (const key of Object.keys(maskedVars)) {
594
- if (maskedVars[key] !== config.vars[key]) {
595
- // This means it was overridden in cli args
596
- // so let's mask it
597
- maskedVars[key] = "(hidden)";
598
- }
599
- }
600
-
601
- printBindings({ ...withoutStaticAssets, vars: maskedVars });
602
-
603
- await ensureQueuesExist(config);
604
-
605
- if (!props.dryRun) {
606
- // Upload the script so it has time to propagate.
607
- // We can also now tell whether available_on_subdomain is set
608
- try {
609
- const result = await fetchResult<{
610
- available_on_subdomain: boolean;
611
- id: string | null;
612
- etag: string | null;
613
- pipeline_hash: string | null;
614
- tag: string | null;
615
- }>(
616
- workerUrl,
617
- {
618
- method: "PUT",
619
- body: createWorkerUploadForm(worker),
620
- headers: await getMetricsUsageHeaders(config.send_metrics),
621
- },
622
- new URLSearchParams({
623
- include_subdomain_availability: "true",
624
- // pass excludeScript so the whole body of the
625
- // script doesn't get included in the response
626
- excludeScript: "true",
627
- })
628
- );
629
-
630
- available_on_subdomain = result.available_on_subdomain;
631
- scriptTag = result.tag;
632
-
633
- if (config.first_party_worker) {
634
- // Print some useful information returned after publishing
635
- // Not all fields will be populated for every worker
636
- // These fields are likely to be scraped by tools, so do not rename
637
- if (result.id) logger.log("Worker ID: ", result.id);
638
- if (result.etag) logger.log("Worker ETag: ", result.etag);
639
- if (result.pipeline_hash)
640
- logger.log("Worker PipelineHash: ", result.pipeline_hash);
641
- }
642
- } catch (err) {
643
- if (errIsScriptSizeOrStartupErr(err)) {
644
- printOffendingDependencies(dependencies);
645
- }
646
- throw err;
647
- }
648
- }
649
- } finally {
650
- if (typeof destination !== "string") {
651
- // this means we're using a temp dir,
652
- // so let's clean up before we proceed
653
- await destination.cleanup();
654
- }
655
- }
656
-
657
- if (props.dryRun) {
658
- logger.log(`--dry-run: exiting now.`);
659
- return;
660
- }
661
- assert(accountId, "Missing accountId");
662
-
663
- const uploadMs = Date.now() - start;
664
- const deployments: Promise<string[]>[] = [];
665
-
666
- if (deployToWorkersDev) {
667
- // Deploy to a subdomain of `workers.dev`
668
- const userSubdomain = await getWorkersDevSubdomain(accountId);
669
- const scriptURL =
670
- props.legacyEnv || !props.env
671
- ? `${scriptName}.${userSubdomain}.workers.dev`
672
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
673
- if (!available_on_subdomain) {
674
- // Enable the `workers.dev` subdomain.
675
- deployments.push(
676
- fetchResult(`${workerUrl}/subdomain`, {
677
- method: "POST",
678
- body: JSON.stringify({ enabled: true }),
679
- headers: {
680
- "Content-Type": "application/json",
681
- },
682
- })
683
- .then(() => [scriptURL])
684
- // Add a delay when the subdomain is first created.
685
- // This is to prevent an issue where a negative cache-hit
686
- // causes the subdomain to be unavailable for 30 seconds.
687
- // This is a temporary measure until we fix this on the edge.
688
- .then(async (url) => {
689
- await sleep(3000);
690
- return url;
691
- })
692
- );
693
- } else {
694
- deployments.push(Promise.resolve([scriptURL]));
695
- }
696
- } else {
697
- if (available_on_subdomain) {
698
- // Disable the workers.dev deployment
699
- await fetchResult(`${workerUrl}/subdomain`, {
700
- method: "POST",
701
- body: JSON.stringify({ enabled: false }),
702
- headers: {
703
- "Content-Type": "application/json",
704
- },
705
- });
706
- } else if (routes.length !== 0) {
707
- // if you get to this point it's because
708
- // you're trying to deploy a worker to a custom
709
- // domain that's already bound to another worker.
710
- // so this thing is about finding workers that have
711
- // bindings to the routes you're trying to deploy to.
712
- //
713
- // the logic is kinda similar (read: duplicated) from publishRoutesFallback,
714
- // except here we know we have a good API token or whatever so we don't need
715
- // to bother with all the error handling tomfoolery.
716
- const routesWithOtherBindings: Record<string, string[]> = {};
717
- for (const route of routes) {
718
- const zone = await getZoneForRoute(route);
719
- if (!zone) {
720
- continue;
721
- }
722
-
723
- const routePattern = typeof route === "string" ? route : route.pattern;
724
- const routesInZone = await fetchListResult<{
725
- pattern: string;
726
- script: string;
727
- }>(`/zones/${zone.id}/workers/routes`);
728
-
729
- routesInZone.forEach(({ script, pattern }) => {
730
- if (pattern === routePattern && script !== scriptName) {
731
- if (!(script in routesWithOtherBindings)) {
732
- routesWithOtherBindings[script] = [];
733
- }
734
-
735
- routesWithOtherBindings[script].push(pattern);
736
- }
737
- });
738
- }
739
-
740
- if (Object.keys(routesWithOtherBindings).length > 0) {
741
- let errorMessage =
742
- "Can't publish a worker to routes that are assigned to another worker.\n";
743
-
744
- for (const worker in routesWithOtherBindings) {
745
- const assignedRoutes = routesWithOtherBindings[worker];
746
- errorMessage += `"${worker}" is already assigned to routes:\n${assignedRoutes.map(
747
- (r) => ` - ${chalk.underline(r)}\n`
748
- )}`;
749
- }
750
-
751
- const resolution =
752
- "Unassign other workers from the routes you want to publish to, and then try again.";
753
- const dashLink = `Visit ${chalk.blue(
754
- chalk.underline(
755
- `https://dash.cloudflare.com/${accountId}/workers/overview`
756
- )
757
- )} to unassign a worker from a route.`;
758
-
759
- throw new Error(`${errorMessage}\n${resolution}\n${dashLink}`);
760
- }
761
- }
762
- }
763
-
764
- logger.log("Uploaded", workerName, formatTime(uploadMs));
765
-
766
- // Update routing table for the script.
767
- if (routesOnly.length > 0) {
768
- deployments.push(
769
- publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
770
- if (routesOnly.length > 10) {
771
- return routesOnly
772
- .slice(0, 9)
773
- .map((route) => renderRoute(route))
774
- .concat([`...and ${routesOnly.length - 10} more routes`]);
775
- }
776
- return routesOnly.map((route) => renderRoute(route));
777
- })
778
- );
779
- }
780
-
781
- // Update custom domains for the script
782
- if (customDomainsOnly.length > 0) {
783
- deployments.push(
784
- publishCustomDomains(workerUrl, accountId, customDomainsOnly)
785
- );
786
- }
787
-
788
- // Configure any schedules for the script.
789
- // TODO: rename this to `schedules`?
790
- if (triggers && triggers.length) {
791
- deployments.push(
792
- fetchResult(`${workerUrl}/schedules`, {
793
- // Note: PUT will override previous schedules on this script.
794
- method: "PUT",
795
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
796
- headers: {
797
- "Content-Type": "application/json",
798
- },
799
- }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
800
- );
801
- }
802
-
803
- if (config.queues.consumers && config.queues.consumers.length) {
804
- deployments.push(...updateQueueConsumers(config));
805
- }
806
-
807
- const targets = await Promise.all(deployments);
808
- const deployMs = Date.now() - start - uploadMs;
809
-
810
- if (deployments.length > 0) {
811
- logger.log("Published", workerName, formatTime(deployMs));
812
- for (const target of targets.flat()) {
813
- // Append protocol only on workers.dev domains
814
- logger.log(
815
- " ",
816
- (target.endsWith("workers.dev") ? "https://" : "") + target
817
- );
818
- }
819
- } else {
820
- logger.log("No publish targets for", workerName, formatTime(deployMs));
821
- }
822
-
823
- try {
824
- const deploymentsList = await fetchResult<DeploymentListRes>(
825
- `/accounts/${accountId}/workers/deployments/by-script/${scriptTag}`
826
- );
827
-
828
- logger.log("Current Deployment ID:", deploymentsList.latest.id);
829
- } catch (e) {
830
- if ((e as { code: number }).code === 10023) {
831
- // TODO: remove this try/catch once deployments is completely rolled out
832
- } else {
833
- throw e;
834
- }
835
- }
836
- }
837
-
838
- function formatTime(duration: number) {
839
- return `(${(duration / 1000).toFixed(2)} sec)`;
840
- }
841
-
842
- /**
843
- * Associate the newly deployed Worker with the given routes.
844
- */
845
- async function publishRoutes(
846
- routes: Route[],
847
- {
848
- workerUrl,
849
- scriptName,
850
- notProd,
851
- }: { workerUrl: string; scriptName: string; notProd: boolean }
852
- ): Promise<string[]> {
853
- try {
854
- return await fetchResult(`${workerUrl}/routes`, {
855
- // Note: PUT will delete previous routes on this script.
856
- method: "PUT",
857
- body: JSON.stringify(
858
- routes.map((route) =>
859
- typeof route !== "object" ? { pattern: route } : route
860
- )
861
- ),
862
- headers: {
863
- "Content-Type": "application/json",
864
- },
865
- });
866
- } catch (e) {
867
- if (isAuthenticationError(e)) {
868
- // An authentication error is probably due to a known issue,
869
- // where the user is logged in via an API token that does not have "All Zones".
870
- return await publishRoutesFallback(routes, { scriptName, notProd });
871
- } else {
872
- throw e;
873
- }
874
- }
875
- }
876
-
877
- /**
878
- * Try updating routes for the Worker using a less optimal zone-based API.
879
- *
880
- * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
881
- */
882
- async function publishRoutesFallback(
883
- routes: Route[],
884
- { scriptName, notProd }: { scriptName: string; notProd: boolean }
885
- ) {
886
- if (notProd) {
887
- throw new Error(
888
- "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
889
- "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
890
- );
891
- }
892
- logger.warn(
893
- "The current authentication token does not have 'All Zones' permissions.\n" +
894
- "Falling back to using the zone-based API endpoint to update each route individually.\n" +
895
- "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
896
- "Existing routes for this Worker in such zones will not be deleted."
897
- );
898
-
899
- const deployedRoutes: string[] = [];
900
-
901
- // Collect the routes (and their zones) that will be deployed.
902
- const activeZones = new Map<string, string>();
903
- const routesToDeploy = new Map<string, string>();
904
- for (const route of routes) {
905
- const zone = await getZoneForRoute(route);
906
- if (zone) {
907
- activeZones.set(zone.id, zone.host);
908
- routesToDeploy.set(
909
- typeof route === "string" ? route : route.pattern,
910
- zone.id
911
- );
912
- }
913
- }
914
-
915
- // Collect the routes that are already deployed.
916
- const allRoutes = new Map<string, string>();
917
- const alreadyDeployedRoutes = new Set<string>();
918
- for (const [zone, host] of activeZones) {
919
- try {
920
- for (const { pattern, script } of await fetchListResult<{
921
- pattern: string;
922
- script: string;
923
- }>(`/zones/${zone}/workers/routes`)) {
924
- allRoutes.set(pattern, script);
925
- if (script === scriptName) {
926
- alreadyDeployedRoutes.add(pattern);
927
- }
928
- }
929
- } catch (e) {
930
- if (isAuthenticationError(e)) {
931
- e.notes.push({
932
- text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
933
- });
934
- }
935
- throw e;
936
- }
937
- }
938
-
939
- // Deploy each route that is not already deployed.
940
- for (const [routePattern, zoneId] of routesToDeploy.entries()) {
941
- if (allRoutes.has(routePattern)) {
942
- const knownScript = allRoutes.get(routePattern);
943
- if (knownScript === scriptName) {
944
- // This route is already associated with this worker, so no need to hit the API.
945
- alreadyDeployedRoutes.delete(routePattern);
946
- continue;
947
- } else {
948
- throw new Error(
949
- `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
950
- );
951
- }
952
- }
953
-
954
- const { pattern } = await fetchResult<{ pattern: string }>(
955
- `/zones/${zoneId}/workers/routes`,
956
- {
957
- method: "POST",
958
- body: JSON.stringify({
959
- pattern: routePattern,
960
- script: scriptName,
961
- }),
962
- headers: {
963
- "Content-Type": "application/json",
964
- },
965
- }
966
- );
967
-
968
- deployedRoutes.push(pattern);
969
- }
970
-
971
- if (alreadyDeployedRoutes.size) {
972
- logger.warn(
973
- "Previously deployed routes:\n" +
974
- "The following routes were already associated with this worker, and have not been deleted:\n" +
975
- [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
976
- "If these routes are not wanted then you can remove them in the dashboard."
977
- );
978
- }
979
-
980
- return deployedRoutes;
981
- }
982
-
983
- function isAuthenticationError(e: unknown): e is ParseError {
984
- return e instanceof ParseError && (e as { code?: number }).code === 10000;
985
- }
986
-
987
- async function ensureQueuesExist(config: Config) {
988
- const producers = (config.queues.producers || []).map(
989
- (producer) => producer.queue
990
- );
991
- const consumers = (config.queues.consumers || []).map(
992
- (consumer) => consumer.queue
993
- );
994
-
995
- const queueNames = producers.concat(consumers);
996
- for (const queue of queueNames) {
997
- try {
998
- await getQueue(config, queue);
999
- } catch (err) {
1000
- const queueErr = err as FetchError;
1001
- if (queueErr.code === 11000) {
1002
- // queue_not_found
1003
- throw new Error(
1004
- `Queue "${queue}" does not exist. To create it, run: wrangler queues create ${queue}`
1005
- );
1006
- }
1007
- throw err;
1008
- }
1009
- }
1010
- }
1011
-
1012
- function updateQueueConsumers(config: Config): Promise<string[]>[] {
1013
- const consumers = config.queues.consumers || [];
1014
- return consumers.map((consumer) => {
1015
- const body: PutConsumerBody = {
1016
- dead_letter_queue: consumer.dead_letter_queue,
1017
- settings: {
1018
- batch_size: consumer.max_batch_size,
1019
- max_retries: consumer.max_retries,
1020
- max_wait_time_ms: consumer.max_batch_timeout
1021
- ? 1000 * consumer.max_batch_timeout
1022
- : undefined,
1023
- },
1024
- };
1025
-
1026
- if (config.name === undefined) {
1027
- // TODO: how can we reliably get the current script name?
1028
- throw new Error("Script name is required to update queue consumers");
1029
- }
1030
- const scriptName = config.name;
1031
- const envName = undefined; // TODO: script environment for wrangler publish?
1032
- return putConsumer(config, consumer.queue, scriptName, envName, body).then(
1033
- () => [`Consumer for ${consumer.queue}`]
1034
- );
1035
- });
1036
- }