wrangler 0.0.0-e7a0cd5b → 0.0.0-e7c06d78

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 (264) hide show
  1. package/README.md +13 -15
  2. package/bin/wrangler.js +24 -93
  3. package/config-schema.json +3059 -0
  4. package/package.json +196 -191
  5. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  6. package/templates/__tests__/tsconfig.json +8 -0
  7. package/templates/checked-fetch.js +19 -6
  8. package/templates/facade.d.ts +19 -0
  9. package/templates/gitignore +2 -3
  10. package/templates/init-tests/test-jest-new-worker.js +3 -5
  11. package/templates/init-tests/test-vitest-new-worker.js +4 -6
  12. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  13. package/templates/middleware/common.ts +9 -4
  14. package/templates/middleware/loader-modules.ts +94 -44
  15. package/templates/middleware/loader-sw.ts +48 -32
  16. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  17. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  18. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  19. package/templates/middleware/middleware-serve-static-assets.ts +56 -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 +4 -1
  23. package/templates/pages-dev-pipeline.ts +6 -2
  24. package/templates/pages-dev-util.ts +4 -1
  25. package/templates/pages-shim.ts +1 -1
  26. package/templates/pages-template-plugin.ts +33 -14
  27. package/templates/pages-template-worker.ts +12 -3
  28. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  29. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  30. package/templates/tsconfig-sanity.ts +11 -0
  31. package/templates/tsconfig.init.json +22 -0
  32. package/templates/tsconfig.json +5 -103
  33. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  34. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  35. package/wrangler-dist/ProxyWorker.js +240 -0
  36. package/wrangler-dist/ProxyWorker.js.map +6 -0
  37. package/wrangler-dist/cli.d.ts +26010 -512
  38. package/wrangler-dist/cli.js +164971 -116798
  39. package/wrangler-dist/wasm-sync.wasm +0 -0
  40. package/Cloudflare_CA.pem +0 -18
  41. package/import_meta_url.js +0 -3
  42. package/miniflare-config-stubs/.env.empty +0 -0
  43. package/miniflare-config-stubs/package.empty.json +0 -1
  44. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  45. package/miniflare-dist/index.mjs +0 -6316
  46. package/src/__tests__/access.test.ts +0 -25
  47. package/src/__tests__/api-dev.test.ts +0 -209
  48. package/src/__tests__/api-devregistry.test.js +0 -57
  49. package/src/__tests__/api.test.ts +0 -80
  50. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  51. package/src/__tests__/config-cache.test.ts +0 -42
  52. package/src/__tests__/configuration.test.ts +0 -4028
  53. package/src/__tests__/d1.test.ts +0 -72
  54. package/src/__tests__/delete.test.ts +0 -230
  55. package/src/__tests__/deployments.test.ts +0 -95
  56. package/src/__tests__/dev.test.tsx +0 -1509
  57. package/src/__tests__/dialogs.test.tsx +0 -40
  58. package/src/__tests__/generate.test.ts +0 -235
  59. package/src/__tests__/get-host-from-url.test.ts +0 -16
  60. package/src/__tests__/guess-worker-format.test.ts +0 -85
  61. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  62. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  63. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  64. package/src/__tests__/helpers/mock-bin.ts +0 -36
  65. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  66. package/src/__tests__/helpers/mock-console.ts +0 -106
  67. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  68. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  69. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  70. package/src/__tests__/helpers/mock-istty.ts +0 -74
  71. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  72. package/src/__tests__/helpers/mock-kv.ts +0 -33
  73. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -252
  74. package/src/__tests__/helpers/mock-process.ts +0 -39
  75. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  76. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  77. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  78. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -59
  79. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  80. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -36
  81. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  82. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  83. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  84. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -22
  85. package/src/__tests__/helpers/msw/index.ts +0 -21
  86. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  87. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  88. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  89. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  90. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  91. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  92. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  93. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  94. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  95. package/src/__tests__/https-options.test.ts +0 -163
  96. package/src/__tests__/index.test.ts +0 -262
  97. package/src/__tests__/init.test.ts +0 -2900
  98. package/src/__tests__/jest.setup.ts +0 -202
  99. package/src/__tests__/kv.test.ts +0 -1675
  100. package/src/__tests__/logger.test.ts +0 -141
  101. package/src/__tests__/metrics.test.ts +0 -450
  102. package/src/__tests__/middleware.scheduled.test.ts +0 -135
  103. package/src/__tests__/middleware.test.ts +0 -726
  104. package/src/__tests__/package-manager.test.ts +0 -353
  105. package/src/__tests__/pages.test.ts +0 -2223
  106. package/src/__tests__/parse.test.ts +0 -330
  107. package/src/__tests__/paths.test.ts +0 -39
  108. package/src/__tests__/publish.test.ts +0 -7660
  109. package/src/__tests__/pubsub.test.ts +0 -370
  110. package/src/__tests__/queues.test.ts +0 -371
  111. package/src/__tests__/r2.test.ts +0 -376
  112. package/src/__tests__/route.test.ts +0 -45
  113. package/src/__tests__/secret.test.ts +0 -644
  114. package/src/__tests__/tail.test.ts +0 -800
  115. package/src/__tests__/test-old-node-version.js +0 -31
  116. package/src/__tests__/type-generation.test.ts +0 -217
  117. package/src/__tests__/user.test.ts +0 -155
  118. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  119. package/src/__tests__/validate-dev-props.test.ts +0 -56
  120. package/src/__tests__/version.test.ts +0 -35
  121. package/src/__tests__/whoami.test.tsx +0 -278
  122. package/src/__tests__/worker-namespace.test.ts +0 -326
  123. package/src/abort.d.ts +0 -3
  124. package/src/api/dev.ts +0 -208
  125. package/src/api/index.ts +0 -2
  126. package/src/bundle-reporter.tsx +0 -68
  127. package/src/bundle.ts +0 -785
  128. package/src/cfetch/index.ts +0 -160
  129. package/src/cfetch/internal.ts +0 -263
  130. package/src/cli.ts +0 -28
  131. package/src/config/README.md +0 -107
  132. package/src/config/config.ts +0 -275
  133. package/src/config/diagnostics.ts +0 -80
  134. package/src/config/environment.ts +0 -563
  135. package/src/config/index.ts +0 -342
  136. package/src/config/validation-helpers.ts +0 -597
  137. package/src/config/validation.ts +0 -2113
  138. package/src/config-cache.ts +0 -85
  139. package/src/create-worker-preview.ts +0 -282
  140. package/src/create-worker-upload-form.ts +0 -321
  141. package/src/d1/backups.tsx +0 -218
  142. package/src/d1/create.tsx +0 -54
  143. package/src/d1/delete.tsx +0 -56
  144. package/src/d1/execute.tsx +0 -299
  145. package/src/d1/formatTimeAgo.ts +0 -14
  146. package/src/d1/index.ts +0 -76
  147. package/src/d1/list.tsx +0 -48
  148. package/src/d1/options.ts +0 -12
  149. package/src/d1/types.tsx +0 -14
  150. package/src/d1/utils.ts +0 -39
  151. package/src/delete.ts +0 -108
  152. package/src/deployments.ts +0 -74
  153. package/src/deprecated/index.ts +0 -438
  154. package/src/dev/dev-vars.ts +0 -39
  155. package/src/dev/dev.tsx +0 -587
  156. package/src/dev/get-local-persistence-path.tsx +0 -31
  157. package/src/dev/local.tsx +0 -717
  158. package/src/dev/remote.tsx +0 -603
  159. package/src/dev/start-server.ts +0 -513
  160. package/src/dev/use-esbuild.ts +0 -204
  161. package/src/dev/validate-dev-props.ts +0 -31
  162. package/src/dev-registry.tsx +0 -201
  163. package/src/dev.tsx +0 -869
  164. package/src/dialogs.tsx +0 -163
  165. package/src/dispatch-namespace.ts +0 -207
  166. package/src/durable.ts +0 -102
  167. package/src/entry.ts +0 -329
  168. package/src/environment-variables.ts +0 -50
  169. package/src/errors.ts +0 -11
  170. package/src/git-client.ts +0 -124
  171. package/src/global-wrangler-config-path.ts +0 -26
  172. package/src/https-options.ts +0 -127
  173. package/src/index.tsx +0 -684
  174. package/src/init.ts +0 -970
  175. package/src/inspect.ts +0 -767
  176. package/src/intl-polyfill.d.ts +0 -139
  177. package/src/is-ci.ts +0 -14
  178. package/src/is-interactive.ts +0 -16
  179. package/src/kv/helpers.ts +0 -430
  180. package/src/kv/index.ts +0 -596
  181. package/src/logger.ts +0 -92
  182. package/src/metrics/index.ts +0 -5
  183. package/src/metrics/metrics-config.ts +0 -239
  184. package/src/metrics/metrics-dispatcher.ts +0 -96
  185. package/src/metrics/metrics-usage-headers.ts +0 -24
  186. package/src/metrics/send-event.ts +0 -94
  187. package/src/miniflare-cli/README.md +0 -30
  188. package/src/miniflare-cli/assets.ts +0 -215
  189. package/src/miniflare-cli/index.ts +0 -213
  190. package/src/miniflare-cli/request-context.ts +0 -40
  191. package/src/module-collection.ts +0 -267
  192. package/src/open-in-browser.ts +0 -17
  193. package/src/package-manager.ts +0 -219
  194. package/src/pages/build.tsx +0 -238
  195. package/src/pages/constants.ts +0 -18
  196. package/src/pages/deployments.tsx +0 -106
  197. package/src/pages/dev.tsx +0 -693
  198. package/src/pages/errors.ts +0 -66
  199. package/src/pages/functions/buildPlugin.ts +0 -110
  200. package/src/pages/functions/buildWorker.ts +0 -156
  201. package/src/pages/functions/filepath-routing.test.ts +0 -234
  202. package/src/pages/functions/filepath-routing.ts +0 -189
  203. package/src/pages/functions/identifiers.ts +0 -78
  204. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  205. package/src/pages/functions/routes-consolidation.ts +0 -73
  206. package/src/pages/functions/routes-transformation.test.ts +0 -282
  207. package/src/pages/functions/routes-transformation.ts +0 -115
  208. package/src/pages/functions/routes-validation.test.ts +0 -403
  209. package/src/pages/functions/routes-validation.ts +0 -202
  210. package/src/pages/functions/routes.ts +0 -151
  211. package/src/pages/functions.tsx +0 -82
  212. package/src/pages/hash.tsx +0 -13
  213. package/src/pages/index.tsx +0 -94
  214. package/src/pages/projects.tsx +0 -169
  215. package/src/pages/publish.tsx +0 -436
  216. package/src/pages/types.ts +0 -49
  217. package/src/pages/upload.tsx +0 -425
  218. package/src/pages/utils.ts +0 -12
  219. package/src/parse.ts +0 -286
  220. package/src/paths.ts +0 -71
  221. package/src/proxy.ts +0 -689
  222. package/src/publish/index.ts +0 -270
  223. package/src/publish/publish.ts +0 -1035
  224. package/src/pubsub/index.ts +0 -286
  225. package/src/pubsub/pubsub-commands.tsx +0 -624
  226. package/src/queues/cli/commands/consumer/add.ts +0 -71
  227. package/src/queues/cli/commands/consumer/index.ts +0 -22
  228. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  229. package/src/queues/cli/commands/create.ts +0 -25
  230. package/src/queues/cli/commands/delete.ts +0 -26
  231. package/src/queues/cli/commands/index.ts +0 -33
  232. package/src/queues/cli/commands/list.ts +0 -25
  233. package/src/queues/client.ts +0 -135
  234. package/src/r2/helpers.ts +0 -131
  235. package/src/r2/index.ts +0 -277
  236. package/src/routes.ts +0 -140
  237. package/src/secret/index.ts +0 -379
  238. package/src/selfsigned.d.ts +0 -29
  239. package/src/sites.tsx +0 -372
  240. package/src/tail/createTail.ts +0 -315
  241. package/src/tail/filters.ts +0 -277
  242. package/src/tail/index.ts +0 -214
  243. package/src/tail/printing.ts +0 -107
  244. package/src/type-generation.ts +0 -159
  245. package/src/update-check.ts +0 -19
  246. package/src/user/access.ts +0 -69
  247. package/src/user/choose-account.tsx +0 -69
  248. package/src/user/env-vars.ts +0 -46
  249. package/src/user/generate-auth-url.ts +0 -33
  250. package/src/user/generate-random-state.ts +0 -16
  251. package/src/user/index.ts +0 -3
  252. package/src/user/user.tsx +0 -1192
  253. package/src/utils/collectKeyValues.ts +0 -14
  254. package/src/whoami.tsx +0 -169
  255. package/src/worker.ts +0 -242
  256. package/src/yargs-types.ts +0 -20
  257. package/src/zones.ts +0 -191
  258. package/templates/d1-beta-facade.js +0 -174
  259. package/templates/experimental-local-cache-stubs.js +0 -27
  260. package/templates/first-party-worker-module-facade.ts +0 -18
  261. package/templates/format-dev-errors.ts +0 -32
  262. package/templates/serve-static-assets.ts +0 -63
  263. package/templates/service-bindings-module-facade.js +0 -54
  264. package/templates/service-bindings-sw-facade.js +0 -42
@@ -1,1035 +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
- experimentalLocalStubCache: 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
- metadata_binding: config.metadata_binding,
528
- wasm_modules: config.wasm_modules,
529
- text_blobs: {
530
- ...config.text_blobs,
531
- ...(assets.manifest &&
532
- format === "service-worker" && {
533
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
534
- }),
535
- },
536
- data_blobs: config.data_blobs,
537
- durable_objects: config.durable_objects,
538
- queues: config.queues.producers?.map((producer) => {
539
- return { binding: producer.binding, queue_name: producer.queue };
540
- }),
541
- r2_buckets: config.r2_buckets,
542
- d1_databases: identifyD1BindingsAsBeta(config.d1_databases),
543
- services: config.services,
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/versions/by-script/${scriptTag}`
826
- );
827
-
828
- logger.log("Current Deployment:", deploymentsList.latest.number);
829
- } catch (e) {
830
- if ((e as { code: number }).code === 10023) {
831
- // TODO: remove this try/catch once versions is completely rolled out
832
- }
833
- throw e;
834
- }
835
- }
836
-
837
- function formatTime(duration: number) {
838
- return `(${(duration / 1000).toFixed(2)} sec)`;
839
- }
840
-
841
- /**
842
- * Associate the newly deployed Worker with the given routes.
843
- */
844
- async function publishRoutes(
845
- routes: Route[],
846
- {
847
- workerUrl,
848
- scriptName,
849
- notProd,
850
- }: { workerUrl: string; scriptName: string; notProd: boolean }
851
- ): Promise<string[]> {
852
- try {
853
- return await fetchResult(`${workerUrl}/routes`, {
854
- // Note: PUT will delete previous routes on this script.
855
- method: "PUT",
856
- body: JSON.stringify(
857
- routes.map((route) =>
858
- typeof route !== "object" ? { pattern: route } : route
859
- )
860
- ),
861
- headers: {
862
- "Content-Type": "application/json",
863
- },
864
- });
865
- } catch (e) {
866
- if (isAuthenticationError(e)) {
867
- // An authentication error is probably due to a known issue,
868
- // where the user is logged in via an API token that does not have "All Zones".
869
- return await publishRoutesFallback(routes, { scriptName, notProd });
870
- } else {
871
- throw e;
872
- }
873
- }
874
- }
875
-
876
- /**
877
- * Try updating routes for the Worker using a less optimal zone-based API.
878
- *
879
- * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
880
- */
881
- async function publishRoutesFallback(
882
- routes: Route[],
883
- { scriptName, notProd }: { scriptName: string; notProd: boolean }
884
- ) {
885
- if (notProd) {
886
- throw new Error(
887
- "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
888
- "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
889
- );
890
- }
891
- logger.warn(
892
- "The current authentication token does not have 'All Zones' permissions.\n" +
893
- "Falling back to using the zone-based API endpoint to update each route individually.\n" +
894
- "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
895
- "Existing routes for this Worker in such zones will not be deleted."
896
- );
897
-
898
- const deployedRoutes: string[] = [];
899
-
900
- // Collect the routes (and their zones) that will be deployed.
901
- const activeZones = new Map<string, string>();
902
- const routesToDeploy = new Map<string, string>();
903
- for (const route of routes) {
904
- const zone = await getZoneForRoute(route);
905
- if (zone) {
906
- activeZones.set(zone.id, zone.host);
907
- routesToDeploy.set(
908
- typeof route === "string" ? route : route.pattern,
909
- zone.id
910
- );
911
- }
912
- }
913
-
914
- // Collect the routes that are already deployed.
915
- const allRoutes = new Map<string, string>();
916
- const alreadyDeployedRoutes = new Set<string>();
917
- for (const [zone, host] of activeZones) {
918
- try {
919
- for (const { pattern, script } of await fetchListResult<{
920
- pattern: string;
921
- script: string;
922
- }>(`/zones/${zone}/workers/routes`)) {
923
- allRoutes.set(pattern, script);
924
- if (script === scriptName) {
925
- alreadyDeployedRoutes.add(pattern);
926
- }
927
- }
928
- } catch (e) {
929
- if (isAuthenticationError(e)) {
930
- e.notes.push({
931
- text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
932
- });
933
- }
934
- throw e;
935
- }
936
- }
937
-
938
- // Deploy each route that is not already deployed.
939
- for (const [routePattern, zoneId] of routesToDeploy.entries()) {
940
- if (allRoutes.has(routePattern)) {
941
- const knownScript = allRoutes.get(routePattern);
942
- if (knownScript === scriptName) {
943
- // This route is already associated with this worker, so no need to hit the API.
944
- alreadyDeployedRoutes.delete(routePattern);
945
- continue;
946
- } else {
947
- throw new Error(
948
- `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
949
- );
950
- }
951
- }
952
-
953
- const { pattern } = await fetchResult<{ pattern: string }>(
954
- `/zones/${zoneId}/workers/routes`,
955
- {
956
- method: "POST",
957
- body: JSON.stringify({
958
- pattern: routePattern,
959
- script: scriptName,
960
- }),
961
- headers: {
962
- "Content-Type": "application/json",
963
- },
964
- }
965
- );
966
-
967
- deployedRoutes.push(pattern);
968
- }
969
-
970
- if (alreadyDeployedRoutes.size) {
971
- logger.warn(
972
- "Previously deployed routes:\n" +
973
- "The following routes were already associated with this worker, and have not been deleted:\n" +
974
- [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
975
- "If these routes are not wanted then you can remove them in the dashboard."
976
- );
977
- }
978
-
979
- return deployedRoutes;
980
- }
981
-
982
- function isAuthenticationError(e: unknown): e is ParseError {
983
- return e instanceof ParseError && (e as { code?: number }).code === 10000;
984
- }
985
-
986
- async function ensureQueuesExist(config: Config) {
987
- const producers = (config.queues.producers || []).map(
988
- (producer) => producer.queue
989
- );
990
- const consumers = (config.queues.consumers || []).map(
991
- (consumer) => consumer.queue
992
- );
993
-
994
- const queueNames = producers.concat(consumers);
995
- for (const queue of queueNames) {
996
- try {
997
- await getQueue(config, queue);
998
- } catch (err) {
999
- const queueErr = err as FetchError;
1000
- if (queueErr.code === 100123) {
1001
- // queue_not_found
1002
- throw new Error(
1003
- `Queue "${queue}" does not exist. To create it, run: wrangler queues create ${queue}`
1004
- );
1005
- }
1006
- throw err;
1007
- }
1008
- }
1009
- }
1010
-
1011
- function updateQueueConsumers(config: Config): Promise<string[]>[] {
1012
- const consumers = config.queues.consumers || [];
1013
- return consumers.map((consumer) => {
1014
- const body: PutConsumerBody = {
1015
- dead_letter_queue: consumer.dead_letter_queue,
1016
- settings: {
1017
- batch_size: consumer.max_batch_size,
1018
- max_retries: consumer.max_retries,
1019
- max_wait_time_ms: consumer.max_batch_timeout
1020
- ? 1000 * consumer.max_batch_timeout
1021
- : undefined,
1022
- },
1023
- };
1024
-
1025
- if (config.name === undefined) {
1026
- // TODO: how can we reliably get the current script name?
1027
- throw new Error("Script name is required to update queue consumers");
1028
- }
1029
- const scriptName = config.name;
1030
- const envName = undefined; // TODO: script environment for wrangler publish?
1031
- return putConsumer(config, consumer.queue, scriptName, envName, body).then(
1032
- () => [`Consumer for ${consumer.queue}`]
1033
- );
1034
- });
1035
- }