wrangler 0.0.0-e9307365 → 0.0.0-e94b46ff7

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