wrangler 0.0.0-e6733a3 → 0.0.0-e9307365

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 (220) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +159 -27
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5416 -0
  6. package/package.json +171 -124
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4022 -0
  10. package/src/__tests__/dev.test.tsx +1290 -62
  11. package/src/__tests__/generate.test.ts +93 -0
  12. package/src/__tests__/guess-worker-format.test.ts +85 -0
  13. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  14. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +263 -0
  18. package/src/__tests__/helpers/mock-console.ts +97 -0
  19. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  31. package/src/__tests__/https-options.test.ts +163 -0
  32. package/src/__tests__/index.test.ts +242 -284
  33. package/src/__tests__/init.test.ts +1992 -0
  34. package/src/__tests__/jest.setup.ts +138 -10
  35. package/src/__tests__/kv.test.ts +1459 -886
  36. package/src/__tests__/logger.test.ts +141 -0
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +353 -0
  39. package/src/__tests__/pages.test.ts +1261 -0
  40. package/src/__tests__/parse.test.ts +330 -0
  41. package/src/__tests__/publish.test.ts +6914 -0
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +317 -0
  44. package/src/__tests__/route.test.ts +45 -0
  45. package/src/__tests__/secret.test.ts +492 -0
  46. package/src/__tests__/tail.test.ts +698 -0
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +144 -0
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +289 -0
  52. package/src/__tests__/worker-namespace.test.ts +327 -0
  53. package/src/abort.d.ts +3 -0
  54. package/src/api/dev.ts +86 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +472 -0
  58. package/src/cfetch/index.ts +88 -69
  59. package/src/cfetch/internal.ts +156 -44
  60. package/src/cli.ts +24 -6
  61. package/src/config/README.md +107 -0
  62. package/src/config/config.ts +263 -0
  63. package/src/config/diagnostics.ts +80 -0
  64. package/src/config/environment.ts +485 -0
  65. package/src/config/index.ts +251 -0
  66. package/src/config/validation-helpers.ts +584 -0
  67. package/src/config/validation.ts +1856 -0
  68. package/src/config-cache.ts +84 -0
  69. package/src/create-worker-preview.ts +257 -0
  70. package/src/create-worker-upload-form.ts +288 -0
  71. package/src/dev/dev-vars.ts +36 -0
  72. package/src/dev/dev.tsx +531 -0
  73. package/src/dev/local.tsx +385 -0
  74. package/src/dev/remote.tsx +413 -0
  75. package/src/dev/use-esbuild.ts +175 -0
  76. package/src/dev/validate-dev-props.ts +31 -0
  77. package/src/dev-registry.tsx +157 -0
  78. package/src/dev.tsx +603 -758
  79. package/src/dialogs.tsx +117 -59
  80. package/src/durable.ts +102 -0
  81. package/src/entry.ts +328 -0
  82. package/src/environment-variables.ts +35 -0
  83. package/src/errors.ts +11 -0
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +127 -0
  89. package/src/index.tsx +2166 -1956
  90. package/src/init.ts +549 -0
  91. package/src/inspect.ts +703 -477
  92. package/src/intl-polyfill.d.ts +139 -0
  93. package/src/is-interactive.ts +12 -0
  94. package/src/kv.ts +430 -0
  95. package/src/logger.ts +73 -0
  96. package/src/metrics/index.ts +5 -0
  97. package/src/metrics/is-ci.ts +14 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/README.md +30 -0
  103. package/src/miniflare-cli/assets.ts +543 -0
  104. package/src/miniflare-cli/enum-keys.ts +17 -0
  105. package/src/miniflare-cli/index.ts +85 -0
  106. package/src/miniflare-cli/request-context.ts +40 -0
  107. package/src/module-collection.ts +247 -53
  108. package/src/open-in-browser.ts +17 -0
  109. package/src/package-manager.ts +219 -0
  110. package/src/pages/build.tsx +204 -0
  111. package/src/pages/constants.ts +8 -0
  112. package/src/pages/deployments.tsx +106 -0
  113. package/src/pages/dev.tsx +414 -0
  114. package/src/pages/functions/buildPlugin.ts +105 -0
  115. package/src/pages/functions/buildWorker.ts +151 -0
  116. package/src/pages/functions/filepath-routing.test.ts +234 -0
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes.ts +151 -0
  120. package/src/pages/index.tsx +84 -0
  121. package/src/pages/projects.tsx +163 -0
  122. package/src/pages/publish.tsx +338 -0
  123. package/src/pages/types.ts +40 -0
  124. package/src/pages/upload.tsx +415 -0
  125. package/src/pages/utils.ts +12 -0
  126. package/src/parse.ts +286 -0
  127. package/src/paths.ts +26 -0
  128. package/src/preview.ts +31 -0
  129. package/src/proxy.ts +434 -252
  130. package/src/publish.ts +794 -345
  131. package/src/pubsub/index.ts +286 -0
  132. package/src/pubsub/pubsub-commands.tsx +623 -0
  133. package/src/r2.ts +118 -0
  134. package/src/selfsigned.d.ts +29 -0
  135. package/src/sites.tsx +357 -99
  136. package/src/tail/filters.ts +279 -0
  137. package/src/tail/index.ts +299 -0
  138. package/src/tail/printing.ts +67 -0
  139. package/src/update-check.ts +19 -0
  140. package/src/user/choose-account.tsx +69 -0
  141. package/src/user/env-vars.ts +46 -0
  142. package/src/user/generate-auth-url.ts +33 -0
  143. package/src/user/generate-random-state.ts +16 -0
  144. package/src/user/index.ts +3 -0
  145. package/src/user/user.tsx +1189 -0
  146. package/src/whoami.tsx +169 -0
  147. package/src/worker-namespace.ts +206 -0
  148. package/src/worker.ts +203 -0
  149. package/src/zones.ts +76 -0
  150. package/templates/checked-fetch.js +17 -0
  151. package/templates/first-party-worker-module-facade.ts +18 -0
  152. package/templates/format-dev-errors.ts +32 -0
  153. package/templates/gitignore +171 -0
  154. package/templates/new-worker-scheduled.js +17 -0
  155. package/templates/new-worker-scheduled.ts +32 -0
  156. package/templates/new-worker.js +15 -0
  157. package/templates/new-worker.ts +30 -0
  158. package/templates/no-op-worker.js +10 -0
  159. package/templates/pages-shim.ts +9 -0
  160. package/templates/pages-template-plugin.ts +155 -0
  161. package/templates/pages-template-worker.ts +161 -0
  162. package/templates/serve-static-assets.ts +63 -0
  163. package/templates/service-bindings-module-facade.js +51 -0
  164. package/templates/service-bindings-sw-facade.js +39 -0
  165. package/templates/tsconfig.json +105 -0
  166. package/wrangler-dist/cli.d.ts +327 -0
  167. package/wrangler-dist/cli.js +134880 -109997
  168. package/pages/functions/buildWorker.ts +0 -62
  169. package/pages/functions/filepath-routing.test.ts +0 -39
  170. package/pages/functions/filepath-routing.ts +0 -221
  171. package/pages/functions/identifiers.ts +0 -78
  172. package/pages/functions/routes.ts +0 -158
  173. package/pages/functions/template-worker.ts +0 -144
  174. package/src/__tests__/mock-cfetch.ts +0 -171
  175. package/src/__tests__/mock-dialogs.ts +0 -65
  176. package/src/__tests__/run-in-tmp.ts +0 -19
  177. package/src/__tests__/run-wrangler.ts +0 -32
  178. package/src/api/form_data.ts +0 -131
  179. package/src/api/preview.ts +0 -128
  180. package/src/api/worker.ts +0 -155
  181. package/src/config.ts +0 -487
  182. package/src/kv.tsx +0 -267
  183. package/src/pages.tsx +0 -1031
  184. package/src/tail.tsx +0 -73
  185. package/src/user.tsx +0 -1025
  186. package/static-asset-facade.js +0 -47
  187. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  188. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  189. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  190. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  191. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  192. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  193. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  194. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  195. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  196. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  201. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  202. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  203. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  204. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  205. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  206. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  207. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  209. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  210. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  211. package/vendor/wrangler-mime/LICENSE +0 -21
  212. package/vendor/wrangler-mime/Mime.js +0 -97
  213. package/vendor/wrangler-mime/README.md +0 -187
  214. package/vendor/wrangler-mime/cli.js +0 -46
  215. package/vendor/wrangler-mime/index.js +0 -4
  216. package/vendor/wrangler-mime/lite.js +0 -4
  217. package/vendor/wrangler-mime/package.json +0 -52
  218. package/vendor/wrangler-mime/types/other.js +0 -1
  219. package/vendor/wrangler-mime/types/standard.js +0 -1
  220. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts CHANGED
@@ -1,358 +1,807 @@
1
1
  import assert from "node:assert";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
3
  import path from "node:path";
3
- import { readFile } from "node:fs/promises";
4
- import esbuild from "esbuild";
5
- import { execa } from "execa";
4
+ import { URLSearchParams } from "node:url";
6
5
  import tmp from "tmp-promise";
7
- import type { CfWorkerInit } from "./api/worker";
8
- import { toFormData } from "./api/form_data";
9
- import { fetchResult } from "./cfetch";
10
- import type { Config } from "./config";
11
- import makeModuleCollector from "./module-collection";
6
+ import { bundleWorker } from "./bundle";
7
+ import { printBundleSize } from "./bundle-reporter";
8
+ import { fetchListResult, fetchResult } from "./cfetch";
9
+ import { printBindings } from "./config";
10
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
11
+ import { confirm } from "./dialogs";
12
+ import { getMigrationsToUpload } from "./durable";
13
+ import { logger } from "./logger";
14
+ import { getMetricsUsageHeaders } from "./metrics";
15
+ import { ParseError } from "./parse";
12
16
  import { syncAssets } from "./sites";
13
-
14
- type CfScriptFormat = undefined | "modules" | "service-worker";
17
+ import { getZoneForRoute } from "./zones";
18
+ import type { Config } from "./config";
19
+ import type {
20
+ Route,
21
+ ZoneIdRoute,
22
+ ZoneNameRoute,
23
+ CustomDomainRoute,
24
+ } from "./config/environment";
25
+ import type { Entry } from "./entry";
26
+ import type { AssetPaths } from "./sites";
27
+ import type { CfWorkerInit } from "./worker";
15
28
 
16
29
  type Props = {
17
- config: Config;
18
- format?: CfScriptFormat;
19
- script?: string;
20
- name?: string;
21
- env?: string;
22
- compatibilityDate?: string;
23
- compatibilityFlags?: string[];
24
- public?: string;
25
- site?: string;
26
- triggers?: (string | number)[];
27
- routes?: (string | number)[];
28
- legacyEnv?: boolean;
29
- jsxFactory: undefined | string;
30
- jsxFragment: undefined | string;
30
+ config: Config;
31
+ accountId: string | undefined;
32
+ entry: Entry;
33
+ rules: Config["rules"];
34
+ name: string | undefined;
35
+ env: string | undefined;
36
+ compatibilityDate: string | undefined;
37
+ compatibilityFlags: string[] | undefined;
38
+ assetPaths: AssetPaths | undefined;
39
+ triggers: string[] | undefined;
40
+ routes: string[] | undefined;
41
+ legacyEnv: boolean | undefined;
42
+ jsxFactory: string | undefined;
43
+ jsxFragment: string | undefined;
44
+ tsconfig: string | undefined;
45
+ isWorkersSite: boolean;
46
+ minify: boolean | undefined;
47
+ nodeCompat: boolean | undefined;
48
+ outDir: string | undefined;
49
+ dryRun: boolean | undefined;
50
+ noBundle: boolean | undefined;
51
+ };
52
+
53
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
54
+
55
+ export type CustomDomain = {
56
+ id: string;
57
+ zone_id: string;
58
+ zone_name: string;
59
+ hostname: string;
60
+ service: string;
61
+ environment: string;
62
+ };
63
+ type UpdatedCustomDomain = CustomDomain & { modified: boolean };
64
+ type ConflictingCustomDomain = CustomDomain & {
65
+ external_dns_record_id?: string;
66
+ external_cert_id?: string;
67
+ };
68
+
69
+ export type CustomDomainChangeset = {
70
+ added: CustomDomain[];
71
+ removed: CustomDomain[];
72
+ updated: UpdatedCustomDomain[];
73
+ conflicting: ConflictingCustomDomain[];
31
74
  };
32
75
 
33
76
  function sleep(ms: number) {
34
- return new Promise((resolve) => setTimeout(resolve, ms));
77
+ return new Promise((resolve) => setTimeout(resolve, ms));
78
+ }
79
+
80
+ function renderRoute(route: Route): string {
81
+ let result = "";
82
+ if (typeof route === "string") {
83
+ result = route;
84
+ } else {
85
+ result = route.pattern;
86
+ const isCustomDomain = Boolean(
87
+ "custom_domain" in route && route.custom_domain
88
+ );
89
+ if (isCustomDomain && "zone_id" in route) {
90
+ result += ` (custom domain - zone id: ${route.zone_id})`;
91
+ } else if (isCustomDomain && "zone_name" in route) {
92
+ result += ` (custom domain - zone name: ${route.zone_name})`;
93
+ } else if (isCustomDomain) {
94
+ result += ` (custom domain)`;
95
+ } else if ("zone_id" in route) {
96
+ result += ` (zone id: ${route.zone_id})`;
97
+ } else if ("zone_name" in route) {
98
+ result += ` (zone name: ${route.zone_name})`;
99
+ }
100
+ }
101
+ return result;
102
+ }
103
+
104
+ // publishing to custom domains involves a few more steps than just updating
105
+ // the routing table, and thus the api implementing it is fairly defensive -
106
+ // it will error eagerly on conflicts against existing domains or existing
107
+ // managed DNS records
108
+
109
+ // however, you can pass params to override the errors. to know if we should
110
+ // override the current state, we generate a "changeset" of required actions
111
+ // to get to the state we want (specified by the list of custom domains). the
112
+ // changeset returns an "updated" collection (existing custom domains
113
+ // connected to other scripts) and a "conflicting" collection (the requested
114
+ // custom domains that have a managed, conflicting DNS record preventing the
115
+ // host's use as a custom domain). with this information, we can prompt to
116
+ // the user what will occur if we create the custom domains requested, and
117
+ // add the override param if they confirm the action
118
+ //
119
+ // if a user does not confirm that they want to override, we skip publishing
120
+ // to these custom domains, but continue on through the rest of the
121
+ // publish stage
122
+ async function publishCustomDomains(
123
+ workerUrl: string,
124
+ accountId: string,
125
+ domains: Array<RouteObject>
126
+ ): Promise<string[]> {
127
+ const config = {
128
+ override_scope: true,
129
+ override_existing_origin: false,
130
+ override_existing_dns_record: false,
131
+ };
132
+ const origins = domains.map((domainRoute) => {
133
+ return {
134
+ hostname: domainRoute.pattern,
135
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
136
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
137
+ };
138
+ });
139
+
140
+ const fail = () => {
141
+ return [
142
+ domains.length > 1
143
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
144
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
145
+ ];
146
+ };
147
+
148
+ if (!process.stdout.isTTY) {
149
+ // running in non-interactive mode.
150
+ // existing origins / dns records are not indicative of errors,
151
+ // so we aggressively update rather than aggressively fail
152
+ config.override_existing_origin = true;
153
+ config.override_existing_dns_record = true;
154
+ } else {
155
+ // get a changeset for operations required to achieve a state with the requested domains
156
+ const changeset = await fetchResult<CustomDomainChangeset>(
157
+ `${workerUrl}/domains/changeset?replace_state=true`,
158
+ {
159
+ method: "POST",
160
+ body: JSON.stringify(origins),
161
+ headers: {
162
+ "Content-Type": "application/json",
163
+ },
164
+ }
165
+ );
166
+
167
+ const updatesRequired = changeset.updated.filter(
168
+ (domain) => domain.modified
169
+ );
170
+ if (updatesRequired.length > 0) {
171
+ // find out which scripts the conflict domains are already attached to
172
+ // so we can provide that in the confirmation prompt
173
+ const existing = await Promise.all(
174
+ updatesRequired.map((domain) =>
175
+ fetchResult<CustomDomain>(
176
+ `/accounts/${accountId}/workers/domains/records/${domain.id}`
177
+ )
178
+ )
179
+ );
180
+ const existingRendered = existing
181
+ .map(
182
+ (domain) =>
183
+ `\t• ${domain.hostname} (used as a domain for "${domain.service}")`
184
+ )
185
+ .join("\n");
186
+ const message = `Custom Domains already exist for these domains:
187
+ ${existingRendered}
188
+ Update them to point to this script instead?`;
189
+ if (!(await confirm(message))) return fail();
190
+ config.override_existing_origin = true;
191
+ }
192
+
193
+ if (changeset.conflicting.length > 0) {
194
+ const conflicitingRendered = changeset.conflicting
195
+ .map((domain) => `\t• ${domain.hostname}`)
196
+ .join("\n");
197
+ const message = `You already have DNS records that conflict for these Custom Domains:
198
+ ${conflicitingRendered}
199
+ Update them to point to this script instead?`;
200
+ if (!(await confirm(message))) return fail();
201
+ config.override_existing_dns_record = true;
202
+ }
203
+ }
204
+
205
+ // publish to domains
206
+ await fetchResult(`${workerUrl}/domains/records`, {
207
+ method: "PUT",
208
+ body: JSON.stringify({ ...config, origins }),
209
+ headers: {
210
+ "Content-Type": "application/json",
211
+ },
212
+ });
213
+
214
+ return domains.map((domain) => renderRoute(domain));
35
215
  }
36
216
 
37
217
  export default async function publish(props: Props): Promise<void> {
38
- if (props.public && props.format === "service-worker") {
39
- // TODO: check config too
40
- throw new Error(
41
- "You cannot use the service worker format with a public directory."
42
- );
43
- }
44
- // TODO: warn if git/hg has uncommitted changes
45
- const { config } = props;
46
- const {
47
- account_id: accountId,
48
- build,
49
- // @ts-expect-error hidden
50
- __path__,
51
- } = config;
52
-
53
- const envRootObj = props.env ? config.env[props.env] || {} : config;
54
-
55
- assert(
56
- envRootObj.compatibility_date || props["compatibility-date"],
57
- "A compatibility_date is required when publishing. Add one to your wrangler.toml file, or pass it in your terminal as --compatibility_date. See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
58
- );
59
-
60
- const triggers = props.triggers || config.triggers?.crons;
61
- const routes = props.routes || config.routes;
62
-
63
- const jsxFactory = props.jsxFactory || config.jsx_factory;
64
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
65
-
66
- assert(config.account_id, "missing account id");
67
-
68
- let scriptName = props.name || config.name;
69
- assert(
70
- scriptName,
71
- '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>"`'
72
- );
73
-
74
- let file: string;
75
- if (props.script) {
76
- file = props.script;
77
- } else {
78
- assert(build?.upload?.main, "missing main file");
79
- file = path.join(path.dirname(__path__), build.upload.main);
80
- }
81
-
82
- if (props.legacyEnv) {
83
- scriptName += props.env ? `-${props.env}` : "";
84
- }
85
- const envName = props.env ?? "production";
86
-
87
- const destination = await tmp.dir({ unsafeCleanup: true });
88
-
89
- if (props.config.build?.command) {
90
- // TODO: add a deprecation message here?
91
- console.log("running:", props.config.build.command);
92
- const buildCommandPieces = props.config.build.command.split(" ");
93
- await execa(buildCommandPieces[0], buildCommandPieces.slice(1), {
94
- stdout: "inherit",
95
- stderr: "inherit",
96
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
97
- });
98
- }
99
-
100
- const moduleCollector = makeModuleCollector();
101
- const result = await esbuild.build({
102
- ...(props.public
103
- ? {
104
- stdin: {
105
- contents: (
106
- await readFile(
107
- path.join(__dirname, "../static-asset-facade.js"),
108
- "utf8"
109
- )
110
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
111
- sourcefile: "static-asset-facade.js",
112
- resolveDir: path.dirname(file),
113
- },
114
- }
115
- : { entryPoints: [file] }),
116
- bundle: true,
117
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
118
- outdir: destination.path,
119
- external: ["__STATIC_CONTENT_MANIFEST"],
120
- format: "esm",
121
- sourcemap: true,
122
- metafile: true,
123
- conditions: ["worker", "browser"],
124
- loader: {
125
- ".js": "jsx",
126
- },
127
- plugins: [moduleCollector.plugin],
128
- ...(jsxFactory && { jsxFactory }),
129
- ...(jsxFragment && { jsxFragment }),
130
- });
131
-
132
- const chunks = Object.entries(result.metafile.outputs).find(
133
- ([_path, { entryPoint }]) =>
134
- entryPoint ===
135
- (props.public
136
- ? path.join(path.dirname(file), "static-asset-facade.js")
137
- : Object.keys(result.metafile.inputs)[0])
138
- );
139
-
140
- const { format } = props;
141
- const bundle = {
142
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
143
- exports: chunks[1].exports,
144
- };
145
-
146
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
147
- // That way we'll be able to accurately tell if this is a service worker or not.
148
-
149
- if (format === "modules" && bundle.type === "commonjs") {
150
- console.error("⎔ Cannot use modules with a commonjs bundle.");
151
- // TODO: a much better error message here, with what to do next
152
- return;
153
- }
154
- if (format === "service-worker" && bundle.type !== "esm") {
155
- console.error("⎔ Cannot use service-worker with a esm bundle.");
156
- // TODO: a much better error message here, with what to do next
157
- return;
158
- }
159
-
160
- const content = await readFile(chunks[0], { encoding: "utf-8" });
161
- await destination.cleanup();
162
-
163
- // if config.migrations
164
- // get current migration tag
165
- let migrations;
166
- if ("migrations" in config) {
167
- const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
168
- `/accounts/${accountId}/workers/scripts`
169
- );
170
- const script = scripts.find(({ id }) => id === scriptName);
171
- if (script?.migration_tag) {
172
- // was already published once
173
- const foundIndex = config.migrations.findIndex(
174
- (migration) => migration.tag === script.migration_tag
175
- );
176
- if (foundIndex === -1) {
177
- console.warn(
178
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
179
- );
180
- migrations = {
181
- old_tag: script.migration_tag,
182
- new_tag: config.migrations[config.migrations.length - 1].tag,
183
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
184
- };
185
- } else {
186
- migrations = {
187
- old_tag: script.migration_tag,
188
- new_tag: config.migrations[config.migrations.length - 1].tag,
189
- steps: config.migrations
190
- .slice(foundIndex + 1)
191
- .map(({ tag: _tag, ...rest }) => rest),
192
- };
193
- }
194
- } else {
195
- migrations = {
196
- new_tag: config.migrations[config.migrations.length - 1].tag,
197
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
198
- };
199
- }
200
- }
201
-
202
- const assets =
203
- props.public || props.site || props.config.site?.bucket // TODO: allow both
204
- ? await syncAssets(
205
- accountId,
206
- scriptName,
207
- props.public || props.site || props.config.site?.bucket,
208
- false
209
- )
210
- : { manifest: undefined, namespace: undefined };
211
-
212
- const bindings: CfWorkerInit["bindings"] = {
213
- kv_namespaces: envRootObj.kv_namespaces?.concat(
214
- assets.namespace
215
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
216
- : []
217
- ),
218
- vars: envRootObj.vars,
219
- durable_objects: envRootObj.durable_objects,
220
- services: envRootObj.experimental_services,
221
- };
222
-
223
- const worker: CfWorkerInit = {
224
- name: scriptName,
225
- main: {
226
- name: path.basename(chunks[0]),
227
- content: content,
228
- type: bundle.type === "esm" ? "esm" : "commonjs",
229
- },
230
- bindings,
231
- ...(migrations && { migrations }),
232
- modules: moduleCollector.modules.concat(
233
- assets.manifest
234
- ? {
235
- name: "__STATIC_CONTENT_MANIFEST",
236
- content: JSON.stringify(assets.manifest),
237
- type: "text",
238
- }
239
- : []
240
- ),
241
- compatibility_date: config.compatibility_date,
242
- compatibility_flags: config.compatibility_flags,
243
- usage_model: config.usage_model,
244
- };
245
-
246
- const start = Date.now();
247
- function formatTime(duration: number) {
248
- return `(${(duration / 1000).toFixed(2)} sec)`;
249
- }
250
-
251
- const notProd = !props.legacyEnv && props.env;
252
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
253
- const workerUrl = notProd
254
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
255
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
256
-
257
- // Upload the script so it has time to propagate.
258
- const { available_on_subdomain } = await fetchResult(
259
- `${workerUrl}?available_on_subdomain=true`,
260
- {
261
- method: "PUT",
262
- // @ts-expect-error: TODO: fix this type error!
263
- body: toFormData(worker),
264
- }
265
- );
266
-
267
- const uploadMs = Date.now() - start;
268
- console.log("Uploaded", workerName, formatTime(uploadMs));
269
- const deployments: Promise<string[]>[] = [];
270
-
271
- const userSubdomain = (
272
- await fetchResult<{ subdomain: string }>(
273
- `/accounts/${accountId}/workers/subdomain`
274
- )
275
- ).subdomain;
276
-
277
- const scriptURL =
278
- props.legacyEnv || !props.env
279
- ? `${scriptName}.${userSubdomain}.workers.dev`
280
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
281
-
282
- // Enable the `workers.dev` subdomain.
283
- // TODO: Make this configurable.
284
- if (!available_on_subdomain) {
285
- deployments.push(
286
- fetchResult(`${workerUrl}/subdomain`, {
287
- method: "POST",
288
- body: JSON.stringify({ enabled: true }),
289
- headers: {
290
- "Content-Type": "application/json",
291
- },
292
- })
293
- .then(() => [scriptURL])
294
- // Add a delay when the subdomain is first created.
295
- // This is to prevent an issue where a negative cache-hit
296
- // causes the subdomain to be unavailable for 30 seconds.
297
- // This is a temporary measure until we fix this on the edge.
298
- .then(async (url) => {
299
- await sleep(3000);
300
- return url;
301
- })
302
- );
303
- } else {
304
- deployments.push(Promise.resolve([scriptURL]));
305
- }
306
-
307
- // Update routing table for the script.
308
- if (routes && routes.length) {
309
- deployments.push(
310
- fetchResult(`${workerUrl}/routes`, {
311
- // TODO: PATCH will not delete previous routes on this script,
312
- // whereas PUT will. We need to decide on the default behaviour
313
- // and how to configure it.
314
- method: "PUT",
315
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
316
- headers: {
317
- "Content-Type": "application/json",
318
- },
319
- }).then(() => {
320
- if (routes.length > 10) {
321
- return routes
322
- .slice(0, 9)
323
- .map(String)
324
- .concat([`...and ${routes.length - 10} more routes`]);
325
- }
326
- return routes.map(String);
327
- })
328
- );
329
- }
330
-
331
- // Configure any schedules for the script.
332
- // TODO: rename this to `schedules`?
333
- if (triggers && triggers.length) {
334
- deployments.push(
335
- fetchResult(`${workerUrl}/schedules`, {
336
- // TODO: Unlike routes, this endpoint does not support PATCH.
337
- // So technically, this will override any previous schedules.
338
- // We should change the endpoint to support PATCH.
339
- method: "PUT",
340
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
341
- headers: {
342
- "Content-Type": "application/json",
343
- },
344
- }).then(() => triggers.map(String))
345
- );
346
- }
347
-
348
- if (!deployments.length) {
349
- return;
350
- }
351
-
352
- const targets = await Promise.all(deployments);
353
- const deployMs = Date.now() - start - uploadMs;
354
- console.log("Deployed", workerName, formatTime(deployMs));
355
- for (const target of targets.flat()) {
356
- console.log(" ", target);
357
- }
218
+ // TODO: warn if git/hg has uncommitted changes
219
+ const { config, accountId } = props;
220
+
221
+ if (!(props.compatibilityDate || config.compatibility_date)) {
222
+ const compatibilityDateStr = `${new Date().getFullYear()}-${(
223
+ new Date().getMonth() + ""
224
+ ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
225
+
226
+ throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
227
+ \`\`\`
228
+ compatibility_date = "${compatibilityDateStr}"
229
+ \`\`\`
230
+ Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
231
+ See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
232
+ }
233
+
234
+ const triggers = props.triggers || config.triggers?.crons;
235
+ const routes =
236
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
237
+ const routesOnly: Array<Route> = [];
238
+ const customDomainsOnly: Array<RouteObject> = [];
239
+ for (const route of routes) {
240
+ if (typeof route !== "string" && route.custom_domain) {
241
+ if (route.pattern.includes("*")) {
242
+ throw new Error(
243
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
244
+ );
245
+ }
246
+ if (route.pattern.includes("/")) {
247
+ throw new Error(
248
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
249
+ );
250
+ }
251
+ customDomainsOnly.push(route);
252
+ } else {
253
+ routesOnly.push(route);
254
+ }
255
+ }
256
+
257
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
258
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
259
+
260
+ const jsxFactory = props.jsxFactory || config.jsx_factory;
261
+ const jsxFragment = props.jsxFragment || config.jsx_fragment;
262
+
263
+ const minify = props.minify ?? config.minify;
264
+
265
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
266
+ if (nodeCompat) {
267
+ logger.warn(
268
+ "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."
269
+ );
270
+ }
271
+
272
+ // Warn if user tries minify or node-compat with no-bundle
273
+ if (props.noBundle && minify) {
274
+ logger.warn(
275
+ "`--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."
276
+ );
277
+ }
278
+
279
+ if (props.noBundle && nodeCompat) {
280
+ logger.warn(
281
+ "`--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."
282
+ );
283
+ }
284
+
285
+ const scriptName = props.name;
286
+ assert(
287
+ scriptName,
288
+ '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>"`'
289
+ );
290
+
291
+ assert(
292
+ !config.site || config.site.bucket,
293
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
294
+ );
295
+
296
+ if (props.outDir) {
297
+ // we're using a custom output directory,
298
+ // so let's first ensure it exists
299
+ mkdirSync(props.outDir, { recursive: true });
300
+ // add a README
301
+ const readmePath = path.join(props.outDir, "README.md");
302
+ writeFileSync(
303
+ readmePath,
304
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
305
+ );
306
+ }
307
+
308
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
309
+ const envName = props.env ?? "production";
310
+
311
+ const start = Date.now();
312
+ const notProd = Boolean(!props.legacyEnv && props.env);
313
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
314
+ const workerUrl = notProd
315
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
316
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
317
+
318
+ let available_on_subdomain; // we'll set this later
319
+
320
+ const { format } = props.entry;
321
+
322
+ if (
323
+ !props.isWorkersSite &&
324
+ Boolean(props.assetPaths) &&
325
+ format === "service-worker"
326
+ ) {
327
+ throw new Error(
328
+ "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/"
329
+ );
330
+ }
331
+
332
+ if (config.wasm_modules && format === "modules") {
333
+ throw new Error(
334
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
335
+ );
336
+ }
337
+
338
+ if (config.text_blobs && format === "modules") {
339
+ throw new Error(
340
+ "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"
341
+ );
342
+ }
343
+
344
+ if (config.data_blobs && format === "modules") {
345
+ throw new Error(
346
+ "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"
347
+ );
348
+ }
349
+ try {
350
+ if (props.noBundle) {
351
+ // if we're not building, let's just copy the entry to the destination directory
352
+ const destinationDir =
353
+ typeof destination === "string" ? destination : destination.path;
354
+ mkdirSync(destinationDir, { recursive: true });
355
+ writeFileSync(
356
+ path.join(destinationDir, path.basename(props.entry.file)),
357
+ readFileSync(props.entry.file, "utf-8")
358
+ );
359
+ }
360
+
361
+ const {
362
+ modules,
363
+ resolvedEntryPointPath,
364
+ bundleType,
365
+ }: Awaited<ReturnType<typeof bundleWorker>> = props.noBundle
366
+ ? // we can skip the whole bundling step and mock a bundle here
367
+ {
368
+ modules: [],
369
+ resolvedEntryPointPath: props.entry.file,
370
+ bundleType: props.entry.format === "modules" ? "esm" : "commonjs",
371
+ stop: undefined,
372
+ }
373
+ : await bundleWorker(
374
+ props.entry,
375
+ typeof destination === "string" ? destination : destination.path,
376
+ {
377
+ serveAssetsFromWorker:
378
+ !props.isWorkersSite && Boolean(props.assetPaths),
379
+ jsxFactory,
380
+ jsxFragment,
381
+ rules: props.rules,
382
+ tsconfig: props.tsconfig ?? config.tsconfig,
383
+ minify,
384
+ nodeCompat,
385
+ define: config.define,
386
+ checkFetch: false,
387
+ assets: config.assets && {
388
+ ...config.assets,
389
+ // enable the cache when publishing
390
+ bypassCache: false,
391
+ },
392
+ services: config.services,
393
+ // We don't set workerDefinitions here,
394
+ // because we don't want to apply the dev-time
395
+ // facades on top of it
396
+ workerDefinitions: undefined,
397
+ firstPartyWorkerDevFacade: false,
398
+ }
399
+ );
400
+
401
+ const content = readFileSync(resolvedEntryPointPath, {
402
+ encoding: "utf-8",
403
+ });
404
+
405
+ // durable object migrations
406
+ const migrations = !props.dryRun
407
+ ? await getMigrationsToUpload(scriptName, {
408
+ accountId,
409
+ config,
410
+ legacyEnv: props.legacyEnv,
411
+ env: props.env,
412
+ })
413
+ : undefined;
414
+
415
+ const assets = await syncAssets(
416
+ accountId,
417
+ // When we're using the newer service environments, we wouldn't
418
+ // have added the env name on to the script name. However, we must
419
+ // include it in the kv namespace name regardless (since there's no
420
+ // concept of service environments for kv namespaces yet).
421
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
422
+ props.assetPaths,
423
+ false,
424
+ props.dryRun
425
+ );
426
+
427
+ const bindings: CfWorkerInit["bindings"] = {
428
+ kv_namespaces: (config.kv_namespaces || []).concat(
429
+ assets.namespace
430
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
431
+ : []
432
+ ),
433
+ vars: config.vars,
434
+ wasm_modules: config.wasm_modules,
435
+ text_blobs: {
436
+ ...config.text_blobs,
437
+ ...(assets.manifest &&
438
+ format === "service-worker" && {
439
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
440
+ }),
441
+ },
442
+ data_blobs: config.data_blobs,
443
+ durable_objects: config.durable_objects,
444
+ r2_buckets: config.r2_buckets,
445
+ services: config.services,
446
+ worker_namespaces: config.worker_namespaces,
447
+ logfwdr: config.logfwdr,
448
+ unsafe: config.unsafe?.bindings,
449
+ };
450
+
451
+ if (assets.manifest) {
452
+ modules.push({
453
+ name: "__STATIC_CONTENT_MANIFEST",
454
+ content: JSON.stringify(assets.manifest),
455
+ type: "text",
456
+ });
457
+ }
458
+
459
+ const worker: CfWorkerInit = {
460
+ name: scriptName,
461
+ main: {
462
+ name: path.basename(resolvedEntryPointPath),
463
+ content: content,
464
+ type: bundleType,
465
+ },
466
+ bindings,
467
+ migrations,
468
+ modules,
469
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
470
+ compatibility_flags:
471
+ props.compatibilityFlags ?? config.compatibility_flags,
472
+ usage_model: config.usage_model,
473
+ };
474
+
475
+ void printBundleSize(
476
+ { name: path.basename(resolvedEntryPointPath), content: content },
477
+ modules
478
+ );
479
+
480
+ const withoutStaticAssets = {
481
+ ...bindings,
482
+ kv_namespaces: config.kv_namespaces,
483
+ text_blobs: config.text_blobs,
484
+ };
485
+ printBindings(withoutStaticAssets);
486
+
487
+ if (!props.dryRun) {
488
+ // Upload the script so it has time to propagate.
489
+ // We can also now tell whether available_on_subdomain is set
490
+ const result = await fetchResult<{
491
+ available_on_subdomain: boolean;
492
+ id: string | null;
493
+ etag: string | null;
494
+ pipeline_hash: string | null;
495
+ }>(
496
+ workerUrl,
497
+ {
498
+ method: "PUT",
499
+ body: createWorkerUploadForm(worker),
500
+ headers: await getMetricsUsageHeaders(config.send_metrics),
501
+ },
502
+ new URLSearchParams({
503
+ include_subdomain_availability: "true",
504
+ // pass excludeScript so the whole body of the
505
+ // script doesn't get included in the response
506
+ excludeScript: "true",
507
+ })
508
+ );
509
+
510
+ available_on_subdomain = result.available_on_subdomain;
511
+
512
+ if (config.first_party_worker) {
513
+ // Print some useful information returned after publishing
514
+ // Not all fields will be populated for every worker
515
+ // These fields are likely to be scraped by tools, so do not rename
516
+ if (result.id) logger.log("Worker ID: ", result.id);
517
+ if (result.etag) logger.log("Worker ETag: ", result.etag);
518
+ if (result.pipeline_hash)
519
+ logger.log("Worker PipelineHash: ", result.pipeline_hash);
520
+ }
521
+ }
522
+ } finally {
523
+ if (typeof destination !== "string") {
524
+ // this means we're using a temp dir,
525
+ // so let's clean up before we proceed
526
+ await destination.cleanup();
527
+ }
528
+ }
529
+
530
+ if (props.dryRun) {
531
+ logger.log(`--dry-run: exiting now.`);
532
+ return;
533
+ }
534
+ assert(accountId, "Missing accountId");
535
+
536
+ const uploadMs = Date.now() - start;
537
+ const deployments: Promise<string[]>[] = [];
538
+
539
+ if (deployToWorkersDev) {
540
+ // Deploy to a subdomain of `workers.dev`
541
+ const userSubdomain = await getSubdomain(accountId);
542
+ const scriptURL =
543
+ props.legacyEnv || !props.env
544
+ ? `${scriptName}.${userSubdomain}.workers.dev`
545
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
546
+ if (!available_on_subdomain) {
547
+ // Enable the `workers.dev` subdomain.
548
+ deployments.push(
549
+ fetchResult(`${workerUrl}/subdomain`, {
550
+ method: "POST",
551
+ body: JSON.stringify({ enabled: true }),
552
+ headers: {
553
+ "Content-Type": "application/json",
554
+ },
555
+ })
556
+ .then(() => [scriptURL])
557
+ // Add a delay when the subdomain is first created.
558
+ // This is to prevent an issue where a negative cache-hit
559
+ // causes the subdomain to be unavailable for 30 seconds.
560
+ // This is a temporary measure until we fix this on the edge.
561
+ .then(async (url) => {
562
+ await sleep(3000);
563
+ return url;
564
+ })
565
+ );
566
+ } else {
567
+ deployments.push(Promise.resolve([scriptURL]));
568
+ }
569
+ } else {
570
+ if (available_on_subdomain) {
571
+ // Disable the workers.dev deployment
572
+ await fetchResult(`${workerUrl}/subdomain`, {
573
+ method: "POST",
574
+ body: JSON.stringify({ enabled: false }),
575
+ headers: {
576
+ "Content-Type": "application/json",
577
+ },
578
+ });
579
+ }
580
+ }
581
+
582
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
583
+
584
+ // Update routing table for the script.
585
+ if (routesOnly.length > 0) {
586
+ deployments.push(
587
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
588
+ if (routesOnly.length > 10) {
589
+ return routesOnly
590
+ .slice(0, 9)
591
+ .map((route) => renderRoute(route))
592
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
593
+ }
594
+ return routesOnly.map((route) => renderRoute(route));
595
+ })
596
+ );
597
+ }
598
+
599
+ // Update custom domains for the script
600
+ if (customDomainsOnly.length > 0) {
601
+ deployments.push(
602
+ publishCustomDomains(workerUrl, accountId, customDomainsOnly)
603
+ );
604
+ }
605
+
606
+ // Configure any schedules for the script.
607
+ // TODO: rename this to `schedules`?
608
+ if (triggers && triggers.length) {
609
+ deployments.push(
610
+ fetchResult(`${workerUrl}/schedules`, {
611
+ // Note: PUT will override previous schedules on this script.
612
+ method: "PUT",
613
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
614
+ headers: {
615
+ "Content-Type": "application/json",
616
+ },
617
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
618
+ );
619
+ }
620
+
621
+ const targets = await Promise.all(deployments);
622
+ const deployMs = Date.now() - start - uploadMs;
623
+
624
+ if (deployments.length > 0) {
625
+ logger.log("Published", workerName, formatTime(deployMs));
626
+ for (const target of targets.flat()) {
627
+ // Append protocol only on workers.dev domains
628
+ logger.log(
629
+ " ",
630
+ (target.endsWith("workers.dev") ? "https://" : "") + target
631
+ );
632
+ }
633
+ } else {
634
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
635
+ }
636
+ }
637
+
638
+ function formatTime(duration: number) {
639
+ return `(${(duration / 1000).toFixed(2)} sec)`;
640
+ }
641
+
642
+ async function getSubdomain(accountId: string): Promise<string> {
643
+ try {
644
+ const { subdomain } = await fetchResult(
645
+ `/accounts/${accountId}/workers/subdomain`
646
+ );
647
+ return subdomain;
648
+ } catch (e) {
649
+ const error = e as { code?: number };
650
+ if (typeof error === "object" && !!error && error.code === 10007) {
651
+ // 10007 error code: not found
652
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
653
+
654
+ const errorMessage =
655
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
656
+ const solutionMessage =
657
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
658
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
659
+
660
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
661
+ } else {
662
+ throw e;
663
+ }
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Associate the newly deployed Worker with the given routes.
669
+ */
670
+ async function publishRoutes(
671
+ routes: Route[],
672
+ {
673
+ workerUrl,
674
+ scriptName,
675
+ notProd,
676
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
677
+ ): Promise<string[]> {
678
+ try {
679
+ return await fetchResult(`${workerUrl}/routes`, {
680
+ // Note: PUT will delete previous routes on this script.
681
+ method: "PUT",
682
+ body: JSON.stringify(
683
+ routes.map((route) =>
684
+ typeof route !== "object" ? { pattern: route } : route
685
+ )
686
+ ),
687
+ headers: {
688
+ "Content-Type": "application/json",
689
+ },
690
+ });
691
+ } catch (e) {
692
+ if (isAuthenticationError(e)) {
693
+ // An authentication error is probably due to a known issue,
694
+ // where the user is logged in via an API token that does not have "All Zones".
695
+ return await publishRoutesFallback(routes, { scriptName, notProd });
696
+ } else {
697
+ throw e;
698
+ }
699
+ }
700
+ }
701
+
702
+ /**
703
+ * Try updating routes for the Worker using a less optimal zone-based API.
704
+ *
705
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
706
+ */
707
+ async function publishRoutesFallback(
708
+ routes: Route[],
709
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
710
+ ) {
711
+ if (notProd) {
712
+ throw new Error(
713
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
714
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
715
+ );
716
+ }
717
+ logger.warn(
718
+ "The current authentication token does not have 'All Zones' permissions.\n" +
719
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
720
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
721
+ "Existing routes for this Worker in such zones will not be deleted."
722
+ );
723
+
724
+ const deployedRoutes: string[] = [];
725
+
726
+ // Collect the routes (and their zones) that will be deployed.
727
+ const activeZones = new Map<string, string>();
728
+ const routesToDeploy = new Map<string, string>();
729
+ for (const route of routes) {
730
+ const zone = await getZoneForRoute(route);
731
+ if (zone) {
732
+ activeZones.set(zone.id, zone.host);
733
+ routesToDeploy.set(
734
+ typeof route === "string" ? route : route.pattern,
735
+ zone.id
736
+ );
737
+ }
738
+ }
739
+
740
+ // Collect the routes that are already deployed.
741
+ const allRoutes = new Map<string, string>();
742
+ const alreadyDeployedRoutes = new Set<string>();
743
+ for (const [zone, host] of activeZones) {
744
+ try {
745
+ for (const { pattern, script } of await fetchListResult<{
746
+ pattern: string;
747
+ script: string;
748
+ }>(`/zones/${zone}/workers/routes`)) {
749
+ allRoutes.set(pattern, script);
750
+ if (script === scriptName) {
751
+ alreadyDeployedRoutes.add(pattern);
752
+ }
753
+ }
754
+ } catch (e) {
755
+ if (isAuthenticationError(e)) {
756
+ e.notes.push({
757
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
758
+ });
759
+ }
760
+ throw e;
761
+ }
762
+ }
763
+
764
+ // Deploy each route that is not already deployed.
765
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
766
+ if (allRoutes.has(routePattern)) {
767
+ const knownScript = allRoutes.get(routePattern);
768
+ if (knownScript === scriptName) {
769
+ // This route is already associated with this worker, so no need to hit the API.
770
+ alreadyDeployedRoutes.delete(routePattern);
771
+ continue;
772
+ } else {
773
+ throw new Error(
774
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
775
+ );
776
+ }
777
+ }
778
+
779
+ const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
780
+ method: "POST",
781
+ body: JSON.stringify({
782
+ pattern: routePattern,
783
+ script: scriptName,
784
+ }),
785
+ headers: {
786
+ "Content-Type": "application/json",
787
+ },
788
+ });
789
+
790
+ deployedRoutes.push(pattern);
791
+ }
792
+
793
+ if (alreadyDeployedRoutes.size) {
794
+ logger.warn(
795
+ "Previously deployed routes:\n" +
796
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
797
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
798
+ "If these routes are not wanted then you can remove them in the dashboard."
799
+ );
800
+ }
801
+
802
+ return deployedRoutes;
803
+ }
804
+
805
+ function isAuthenticationError(e: unknown): e is ParseError {
806
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
358
807
  }