wrangler 0.0.0-e151223 → 0.0.0-e1e2ee5c

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