wrangler 0.0.0-e64812e → 0.0.0-e8e684c7

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