wrangler 0.0.0-e2f9bb2 → 0.0.0-e3278fa

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 (90) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +3 -1
  3. package/bin/wrangler.js +36 -4
  4. package/package.json +12 -7
  5. package/pages/functions/buildPlugin.ts +13 -0
  6. package/pages/functions/buildWorker.ts +14 -1
  7. package/pages/functions/template-plugin.ts +3 -2
  8. package/src/__tests__/configuration.test.ts +370 -87
  9. package/src/__tests__/dev.test.tsx +298 -77
  10. package/src/__tests__/helpers/mock-dialogs.ts +43 -2
  11. package/src/__tests__/index.test.ts +79 -72
  12. package/src/__tests__/init.test.ts +718 -123
  13. package/src/__tests__/jest.setup.ts +8 -0
  14. package/src/__tests__/kv.test.ts +173 -146
  15. package/src/__tests__/package-manager.test.ts +154 -7
  16. package/src/__tests__/pages.test.ts +478 -53
  17. package/src/__tests__/parse.test.ts +8 -0
  18. package/src/__tests__/publish.test.ts +1094 -215
  19. package/src/__tests__/r2.test.ts +55 -36
  20. package/src/__tests__/secret.test.ts +39 -4
  21. package/src/__tests__/whoami.test.tsx +34 -0
  22. package/src/abort.d.ts +3 -0
  23. package/src/bundle.ts +34 -6
  24. package/src/cfetch/index.ts +21 -4
  25. package/src/cfetch/internal.ts +23 -18
  26. package/src/config/config.ts +2 -2
  27. package/src/config/environment.ts +40 -14
  28. package/src/config/index.ts +162 -0
  29. package/src/config/validation-helpers.ts +10 -1
  30. package/src/config/validation.ts +180 -65
  31. package/src/create-worker-preview.ts +32 -22
  32. package/src/create-worker-upload-form.ts +22 -8
  33. package/src/dev/dev.tsx +12 -18
  34. package/src/dev/local.tsx +10 -0
  35. package/src/dev/remote.tsx +40 -16
  36. package/src/dialogs.tsx +48 -0
  37. package/src/durable.ts +102 -0
  38. package/src/entry.ts +64 -9
  39. package/src/index.tsx +548 -317
  40. package/src/inspect.ts +39 -0
  41. package/src/kv.ts +114 -25
  42. package/src/open-in-browser.ts +5 -12
  43. package/src/package-manager.ts +50 -3
  44. package/src/pages.tsx +434 -207
  45. package/src/parse.ts +23 -4
  46. package/src/proxy.ts +59 -35
  47. package/src/publish.ts +374 -127
  48. package/src/sites.tsx +61 -28
  49. package/src/user.tsx +23 -2
  50. package/src/whoami.tsx +3 -2
  51. package/src/worker.ts +10 -1
  52. package/src/zones.ts +73 -0
  53. package/templates/new-worker-scheduled.js +17 -0
  54. package/templates/new-worker-scheduled.ts +32 -0
  55. package/templates/new-worker.ts +16 -1
  56. package/templates/static-asset-facade.js +0 -4
  57. package/wrangler-dist/cli.js +96965 -83414
  58. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  59. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  60. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  61. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  62. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  63. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  64. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  65. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  66. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  67. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  68. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  69. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  70. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  71. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  72. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  73. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  74. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  75. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  76. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  77. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  78. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  79. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  80. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  81. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  82. package/vendor/wrangler-mime/LICENSE +0 -21
  83. package/vendor/wrangler-mime/Mime.js +0 -97
  84. package/vendor/wrangler-mime/README.md +0 -187
  85. package/vendor/wrangler-mime/cli.js +0 -46
  86. package/vendor/wrangler-mime/index.js +0 -4
  87. package/vendor/wrangler-mime/lite.js +0 -4
  88. package/vendor/wrangler-mime/package.json +0 -52
  89. package/vendor/wrangler-mime/types/other.js +0 -1
  90. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/publish.ts CHANGED
@@ -4,18 +4,29 @@ import path from "node:path";
4
4
  import { URLSearchParams } from "node:url";
5
5
  import tmp from "tmp-promise";
6
6
  import { bundleWorker } from "./bundle";
7
- import { fetchResult } from "./cfetch";
7
+ import { fetchListResult, fetchResult } from "./cfetch";
8
+ import { printBindings } from "./config";
8
9
  import { createWorkerUploadForm } from "./create-worker-upload-form";
10
+ import { confirm } from "./dialogs";
11
+ import { getMigrationsToUpload } from "./durable";
9
12
  import { logger } from "./logger";
13
+ import { ParseError } from "./parse";
10
14
  import { syncAssets } from "./sites";
15
+ import { getZoneForRoute } from "./zones";
11
16
  import type { Config } from "./config";
17
+ import type {
18
+ Route,
19
+ ZoneIdRoute,
20
+ ZoneNameRoute,
21
+ CustomDomainRoute,
22
+ } from "./config/environment";
12
23
  import type { Entry } from "./entry";
13
24
  import type { AssetPaths } from "./sites";
14
25
  import type { CfWorkerInit } from "./worker";
15
26
 
16
27
  type Props = {
17
28
  config: Config;
18
- accountId: string;
29
+ accountId: string | undefined;
19
30
  entry: Entry;
20
31
  rules: Config["rules"];
21
32
  name: string | undefined;
@@ -36,10 +47,178 @@ type Props = {
36
47
  dryRun: boolean | undefined;
37
48
  };
38
49
 
50
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
51
+
39
52
  function sleep(ms: number) {
40
53
  return new Promise((resolve) => setTimeout(resolve, ms));
41
54
  }
42
55
 
56
+ function renderRoute(route: Route): string {
57
+ let result = "";
58
+ if (typeof route === "string") {
59
+ result = route;
60
+ } else {
61
+ result = route.pattern;
62
+ const isCustomDomain = Boolean(
63
+ "custom_domain" in route && route.custom_domain
64
+ );
65
+ if (isCustomDomain && "zone_id" in route) {
66
+ result += ` (custom domain - zone id: ${route.zone_id})`;
67
+ } else if (isCustomDomain && "zone_name" in route) {
68
+ result += ` (custom domain - zone name: ${route.zone_name})`;
69
+ } else if (isCustomDomain) {
70
+ result += ` (custom domain)`;
71
+ } else if ("zone_id" in route) {
72
+ result += ` (zone id: ${route.zone_id})`;
73
+ } else if ("zone_name" in route) {
74
+ result += ` (zone name: ${route.zone_name})`;
75
+ }
76
+ }
77
+ return result;
78
+ }
79
+
80
+ // this function takes a string with quotes in it
81
+ // (i.e. `hello "world", if that really is your name`)
82
+ // and peels out the first instance of a substring
83
+ // bounded by quotes (so, in the example above, `world`)
84
+ //
85
+ // this is useful because the /domains api will return
86
+ // which domains conflicted in an error message, bounded
87
+ // by a string, which we can use to provide helpful
88
+ // messages to a user
89
+ function getQuoteBoundedSubstring(content: string) {
90
+ const matches = content.split('"');
91
+ return matches[1] ?? "";
92
+ }
93
+
94
+ function isOriginConflictError(
95
+ e: unknown
96
+ ): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
97
+ return (
98
+ typeof e === "object" &&
99
+ e !== null &&
100
+ (e as { code: number }).code === 100116
101
+ );
102
+ }
103
+
104
+ function isDNSConflictError(
105
+ e: unknown
106
+ ): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
107
+ return (
108
+ typeof e === "object" &&
109
+ e !== null &&
110
+ (e as { code: number }).code === 100117
111
+ );
112
+ }
113
+
114
+ // empty error class to throw and then explicitly catch via `instanceof`
115
+ class CustomDomainOverrideRejected extends Error {}
116
+
117
+ // publishing to custom domains involves a few more steps than just updating
118
+ // the routing table, and thus the api implementing it is fairly defensive -
119
+ // it will error eagerly on conflicts against existing domains or existing
120
+ // managed DNS records
121
+ //
122
+ // however, you can pass params to override the errors. we start on the
123
+ // defensive path, and if one of these errors occur, we prompt the user
124
+ // for confirmation that they do indeed want to override the conflicts, and
125
+ // then retry the request with the right override added
126
+ //
127
+ // if a user does not confirm that they want to override, we skip publishing
128
+ // to these custom domains, but continue on through the rest of the
129
+ // publish stage
130
+ function publishCustomDomains(
131
+ workerUrl: string,
132
+ domains: Array<RouteObject>
133
+ ): Promise<string[]> {
134
+ const config = {
135
+ override_scope: true,
136
+ override_existing_origin: false,
137
+ override_existing_dns_record: false,
138
+ };
139
+ const origins = domains.map((domainRoute) => {
140
+ return {
141
+ hostname: domainRoute.pattern,
142
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
143
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
144
+ };
145
+ });
146
+
147
+ if (!process.stdout.isTTY) {
148
+ // running in non-interactive mode.
149
+ // existing origins / dns records are not indicative of errors,
150
+ // so we aggressively update rather than aggressively fail
151
+ config.override_existing_origin = true;
152
+ config.override_existing_dns_record = true;
153
+ }
154
+
155
+ // Mixing promise chains with async/await is funky, but it allows us to keep related
156
+ // logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
157
+ // while retaining the flexibility of promise chain fall-throughs. We can group error
158
+ // handling logic in dedicated catch calls, and all we have to do is re-throw an
159
+ // error and it will pass down to the next catch call
160
+ return fetchResult(`${workerUrl}/domains`, {
161
+ method: "PUT",
162
+ body: JSON.stringify({ ...config, origins }),
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ },
166
+ })
167
+ .catch(async (err) => {
168
+ if (isOriginConflictError(err)) {
169
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
170
+ const shouldContinue = await confirm(
171
+ `Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
172
+ );
173
+ if (!shouldContinue) {
174
+ throw new CustomDomainOverrideRejected();
175
+ }
176
+ config.override_existing_origin = true;
177
+ await fetchResult(`${workerUrl}/domains`, {
178
+ method: "PUT",
179
+ body: JSON.stringify({ ...config, origins }),
180
+ headers: {
181
+ "Content-Type": "application/json",
182
+ },
183
+ });
184
+ } else {
185
+ throw err;
186
+ }
187
+ })
188
+ .catch(async (err) => {
189
+ if (isDNSConflictError(err)) {
190
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
191
+ const shouldContinue = await confirm(
192
+ `You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
193
+ );
194
+ if (!shouldContinue) {
195
+ throw new CustomDomainOverrideRejected();
196
+ }
197
+ config.override_existing_dns_record = true;
198
+ await fetchResult(`${workerUrl}/domains`, {
199
+ method: "PUT",
200
+ body: JSON.stringify({ ...config, origins }),
201
+ headers: {
202
+ "Content-Type": "application/json",
203
+ },
204
+ });
205
+ } else {
206
+ throw err;
207
+ }
208
+ })
209
+ .then(() => domains.map((domain) => renderRoute(domain)))
210
+ .catch((err) => {
211
+ if (err instanceof CustomDomainOverrideRejected) {
212
+ return [
213
+ domains.length > 1
214
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
215
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
216
+ ];
217
+ }
218
+ throw err;
219
+ });
220
+ }
221
+
43
222
  export default async function publish(props: Props): Promise<void> {
44
223
  // TODO: warn if git/hg has uncommitted changes
45
224
  const { config, accountId } = props;
@@ -52,6 +231,25 @@ export default async function publish(props: Props): Promise<void> {
52
231
  const triggers = props.triggers || config.triggers?.crons;
53
232
  const routes =
54
233
  props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
234
+ const routesOnly: Array<Route> = [];
235
+ const customDomainsOnly: Array<RouteObject> = [];
236
+ for (const route of routes) {
237
+ if (typeof route !== "string" && route.custom_domain) {
238
+ if (route.pattern.includes("*")) {
239
+ throw new Error(
240
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
241
+ );
242
+ }
243
+ if (route.pattern.includes("/")) {
244
+ throw new Error(
245
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
246
+ );
247
+ }
248
+ customDomainsOnly.push(route);
249
+ } else {
250
+ routesOnly.push(route);
251
+ }
252
+ }
55
253
 
56
254
  // deployToWorkersDev defaults to true only if there aren't any routes defined
57
255
  const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
@@ -64,7 +262,7 @@ export default async function publish(props: Props): Promise<void> {
64
262
  const nodeCompat = props.nodeCompat ?? config.node_compat;
65
263
  if (nodeCompat) {
66
264
  logger.warn(
67
- "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
265
+ "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."
68
266
  );
69
267
  }
70
268
 
@@ -95,7 +293,7 @@ export default async function publish(props: Props): Promise<void> {
95
293
  const envName = props.env ?? "production";
96
294
 
97
295
  const start = Date.now();
98
- const notProd = !props.legacyEnv && props.env;
296
+ const notProd = Boolean(!props.legacyEnv && props.env);
99
297
  const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
100
298
  const workerUrl = notProd
101
299
  ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
@@ -143,103 +341,19 @@ export default async function publish(props: Props): Promise<void> {
143
341
  }
144
342
  );
145
343
 
146
- // Some validation of durable objects + migrations
147
- if (config.durable_objects.bindings.length > 0) {
148
- // intrinsic [durable_objects] implies [migrations]
149
- const exportedDurableObjects = config.durable_objects.bindings.filter(
150
- (binding) => !binding.script_name
151
- );
152
- if (exportedDurableObjects.length > 0 && config.migrations.length === 0) {
153
- logger.warn(
154
- `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${exportedDurableObjects.map(
155
- (durable) => durable.class_name
156
- )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
157
- );
158
- }
159
- }
160
-
161
344
  const content = readFileSync(resolvedEntryPointPath, {
162
345
  encoding: "utf-8",
163
346
  });
164
347
 
165
- // if config.migrations
166
- let migrations;
167
- if (config.migrations.length > 0) {
168
- // get current migration tag
169
- type ScriptData = { id: string; migration_tag?: string };
170
- let script: ScriptData | undefined;
171
- if (!props.legacyEnv) {
172
- try {
173
- if (props.env) {
174
- const scriptData = await fetchResult<{
175
- script: ScriptData;
176
- }>(
177
- `/accounts/${accountId}/workers/services/${scriptName}/environments/${props.env}`
178
- );
179
- script = scriptData.script;
180
- } else {
181
- const scriptData = await fetchResult<{
182
- default_environment: {
183
- script: ScriptData;
184
- };
185
- }>(`/accounts/${accountId}/workers/services/${scriptName}`);
186
- script = scriptData.default_environment.script;
187
- }
188
- } catch (err) {
189
- if (
190
- ![
191
- 10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
192
- 10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
193
- ].includes((err as { code: number }).code)
194
- ) {
195
- throw err;
196
- }
197
- // else it's a 404, no script found, and we can proceed
198
- }
199
- } else {
200
- const scripts = await fetchResult<ScriptData[]>(
201
- `/accounts/${accountId}/workers/scripts`
202
- );
203
- script = scripts.find(({ id }) => id === scriptName);
204
- }
205
-
206
- if (script?.migration_tag) {
207
- // was already published once
208
- const scriptMigrationTag = script.migration_tag;
209
- const foundIndex = config.migrations.findIndex(
210
- (migration) => migration.tag === scriptMigrationTag
211
- );
212
- if (foundIndex === -1) {
213
- logger.warn(
214
- `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...`
215
- );
216
- migrations = {
217
- old_tag: script.migration_tag,
218
- new_tag: config.migrations[config.migrations.length - 1].tag,
219
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
220
- };
221
- } else {
222
- if (foundIndex !== config.migrations.length - 1) {
223
- // there are new migrations to send up
224
- migrations = {
225
- old_tag: script.migration_tag,
226
- new_tag: config.migrations[config.migrations.length - 1].tag,
227
- steps: config.migrations
228
- .slice(foundIndex + 1)
229
- .map(({ tag: _tag, ...rest }) => rest),
230
- };
231
- }
232
- // else, we're up to date, no migrations to send
233
- }
234
- } else {
235
- // first time publishing durable objects to this script,
236
- // so we send all the migrations
237
- migrations = {
238
- new_tag: config.migrations[config.migrations.length - 1].tag,
239
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
240
- };
241
- }
242
- }
348
+ // durable object migrations
349
+ const migrations = !props.dryRun
350
+ ? await getMigrationsToUpload(scriptName, {
351
+ accountId,
352
+ config,
353
+ legacyEnv: props.legacyEnv,
354
+ env: props.env,
355
+ })
356
+ : undefined;
243
357
 
244
358
  const assets = await syncAssets(
245
359
  accountId,
@@ -271,6 +385,7 @@ export default async function publish(props: Props): Promise<void> {
271
385
  data_blobs: config.data_blobs,
272
386
  durable_objects: config.durable_objects,
273
387
  r2_buckets: config.r2_buckets,
388
+ services: config.services,
274
389
  unsafe: config.unsafe?.bindings,
275
390
  };
276
391
 
@@ -298,6 +413,13 @@ export default async function publish(props: Props): Promise<void> {
298
413
  usage_model: config.usage_model,
299
414
  };
300
415
 
416
+ const withoutStaticAssets = {
417
+ ...bindings,
418
+ kv_namespaces: config.kv_namespaces,
419
+ text_blobs: config.text_blobs,
420
+ };
421
+ printBindings(withoutStaticAssets);
422
+
301
423
  if (!props.dryRun) {
302
424
  // Upload the script so it has time to propagate.
303
425
  // We can also now tell whether available_on_subdomain is set
@@ -324,6 +446,7 @@ export default async function publish(props: Props): Promise<void> {
324
446
  logger.log(`--dry-run: exiting now.`);
325
447
  return;
326
448
  }
449
+ assert(accountId, "Missing accountId");
327
450
 
328
451
  const uploadMs = Date.now() - start;
329
452
  const deployments: Promise<string[]>[] = [];
@@ -374,43 +497,25 @@ export default async function publish(props: Props): Promise<void> {
374
497
  logger.log("Uploaded", workerName, formatTime(uploadMs));
375
498
 
376
499
  // Update routing table for the script.
377
- if (routes.length > 0) {
500
+ if (routesOnly.length > 0) {
378
501
  deployments.push(
379
- fetchResult(`${workerUrl}/routes`, {
380
- // Note: PUT will delete previous routes on this script.
381
- method: "PUT",
382
- body: JSON.stringify(
383
- routes.map((route) =>
384
- typeof route !== "object" ? { pattern: route } : route
385
- )
386
- ),
387
- headers: {
388
- "Content-Type": "application/json",
389
- },
390
- }).then(() => {
391
- if (routes.length > 10) {
392
- return routes
502
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
503
+ if (routesOnly.length > 10) {
504
+ return routesOnly
393
505
  .slice(0, 9)
394
- .map((route) =>
395
- typeof route === "string"
396
- ? route
397
- : "zone_id" in route
398
- ? `${route.pattern} (zone id: ${route.zone_id})`
399
- : `${route.pattern} (zone name: ${route.zone_name})`
400
- )
401
- .concat([`...and ${routes.length - 10} more routes`]);
506
+ .map((route) => renderRoute(route))
507
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
402
508
  }
403
- return routes.map((route) =>
404
- typeof route === "string"
405
- ? route
406
- : "zone_id" in route
407
- ? `${route.pattern} (zone id: ${route.zone_id})`
408
- : `${route.pattern} (zone name: ${route.zone_name})`
409
- );
509
+ return routesOnly.map((route) => renderRoute(route));
410
510
  })
411
511
  );
412
512
  }
413
513
 
514
+ // Update custom domains for the script
515
+ if (customDomainsOnly.length > 0) {
516
+ deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
517
+ }
518
+
414
519
  // Configure any schedules for the script.
415
520
  // TODO: rename this to `schedules`?
416
521
  if (triggers && triggers.length) {
@@ -467,3 +572,145 @@ async function getSubdomain(accountId: string): Promise<string> {
467
572
  }
468
573
  }
469
574
  }
575
+
576
+ /**
577
+ * Associate the newly deployed Worker with the given routes.
578
+ */
579
+ async function publishRoutes(
580
+ routes: Route[],
581
+ {
582
+ workerUrl,
583
+ scriptName,
584
+ notProd,
585
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
586
+ ): Promise<string[]> {
587
+ try {
588
+ return await fetchResult(`${workerUrl}/routes`, {
589
+ // Note: PUT will delete previous routes on this script.
590
+ method: "PUT",
591
+ body: JSON.stringify(
592
+ routes.map((route) =>
593
+ typeof route !== "object" ? { pattern: route } : route
594
+ )
595
+ ),
596
+ headers: {
597
+ "Content-Type": "application/json",
598
+ },
599
+ });
600
+ } catch (e) {
601
+ if (isAuthenticationError(e)) {
602
+ // An authentication error is probably due to a known issue,
603
+ // where the user is logged in via an API token that does not have "All Zones".
604
+ return await publishRoutesFallback(routes, { scriptName, notProd });
605
+ } else {
606
+ throw e;
607
+ }
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Try updating routes for the Worker using a less optimal zone-based API.
613
+ *
614
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
615
+ */
616
+ async function publishRoutesFallback(
617
+ routes: Route[],
618
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
619
+ ) {
620
+ if (notProd) {
621
+ throw new Error(
622
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
623
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
624
+ );
625
+ }
626
+ logger.warn(
627
+ "The current authentication token does not have 'All Zones' permissions.\n" +
628
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
629
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
630
+ "Existing routes for this Worker in such zones will not be deleted."
631
+ );
632
+
633
+ const deployedRoutes: string[] = [];
634
+
635
+ // Collect the routes (and their zones) that will be deployed.
636
+ const activeZones = new Map<string, string>();
637
+ const routesToDeploy = new Map<string, string>();
638
+ for (const route of routes) {
639
+ const zone = await getZoneForRoute(route);
640
+ if (zone) {
641
+ activeZones.set(zone.id, zone.host);
642
+ routesToDeploy.set(
643
+ typeof route === "string" ? route : route.pattern,
644
+ zone.id
645
+ );
646
+ }
647
+ }
648
+
649
+ // Collect the routes that are already deployed.
650
+ const allRoutes = new Map<string, string>();
651
+ const alreadyDeployedRoutes = new Set<string>();
652
+ for (const [zone, host] of activeZones) {
653
+ try {
654
+ for (const { pattern, script } of await fetchListResult<{
655
+ pattern: string;
656
+ script: string;
657
+ }>(`/zones/${zone}/workers/routes`)) {
658
+ allRoutes.set(pattern, script);
659
+ if (script === scriptName) {
660
+ alreadyDeployedRoutes.add(pattern);
661
+ }
662
+ }
663
+ } catch (e) {
664
+ if (isAuthenticationError(e)) {
665
+ e.notes.push({
666
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
667
+ });
668
+ }
669
+ throw e;
670
+ }
671
+ }
672
+
673
+ // Deploy each route that is not already deployed.
674
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
675
+ if (allRoutes.has(routePattern)) {
676
+ const knownScript = allRoutes.get(routePattern);
677
+ if (knownScript === scriptName) {
678
+ // This route is already associated with this worker, so no need to hit the API.
679
+ alreadyDeployedRoutes.delete(routePattern);
680
+ continue;
681
+ } else {
682
+ throw new Error(
683
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
684
+ );
685
+ }
686
+ }
687
+
688
+ const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
689
+ method: "POST",
690
+ body: JSON.stringify({
691
+ pattern: routePattern,
692
+ script: scriptName,
693
+ }),
694
+ headers: {
695
+ "Content-Type": "application/json",
696
+ },
697
+ });
698
+
699
+ deployedRoutes.push(pattern);
700
+ }
701
+
702
+ if (alreadyDeployedRoutes.size) {
703
+ logger.warn(
704
+ "Previously deployed routes:\n" +
705
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
706
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
707
+ "If these routes are not wanted then you can remove them in the dashboard."
708
+ );
709
+ }
710
+
711
+ return deployedRoutes;
712
+ }
713
+
714
+ function isAuthenticationError(e: unknown): e is ParseError {
715
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
716
+ }