wrangler 0.0.0-e41c7e41 → 0.0.0-e44afaf79

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