wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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