wrangler 0.0.0-e22f9d7 → 0.0.0-e2b7352

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 (100) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +33 -16
  6. package/pages/functions/buildWorker.ts +1 -1
  7. package/pages/functions/filepath-routing.test.ts +212 -28
  8. package/pages/functions/filepath-routing.ts +91 -131
  9. package/pages/functions/routes.ts +11 -18
  10. package/pages/functions/template-worker.ts +19 -33
  11. package/src/__tests__/configuration.test.ts +2820 -0
  12. package/src/__tests__/dev.test.tsx +535 -61
  13. package/src/__tests__/guess-worker-format.test.ts +68 -0
  14. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  15. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  16. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  17. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  18. package/src/__tests__/helpers/mock-bin.ts +36 -0
  19. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +52 -16
  20. package/src/__tests__/helpers/mock-console.ts +70 -0
  21. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  26. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  27. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  28. package/src/__tests__/https-options.test.ts +127 -0
  29. package/src/__tests__/index.test.ts +773 -77
  30. package/src/__tests__/jest.setup.ts +53 -6
  31. package/src/__tests__/kv.test.ts +725 -456
  32. package/src/__tests__/logout.test.ts +52 -0
  33. package/src/__tests__/package-manager.test.ts +206 -0
  34. package/src/__tests__/pages.test.ts +82 -0
  35. package/src/__tests__/parse.test.ts +322 -0
  36. package/src/__tests__/publish.test.ts +3509 -0
  37. package/src/__tests__/r2.test.ts +198 -0
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +425 -0
  40. package/src/__tests__/sentry.test.ts +146 -0
  41. package/src/__tests__/tail.test.ts +638 -0
  42. package/src/__tests__/whoami.test.tsx +100 -0
  43. package/src/bundle.ts +155 -0
  44. package/src/cfetch/index.ts +21 -19
  45. package/src/cfetch/internal.ts +92 -22
  46. package/src/cli.ts +10 -0
  47. package/src/config/README.md +107 -0
  48. package/src/config/config.ts +218 -0
  49. package/src/config/diagnostics.ts +80 -0
  50. package/src/config/environment.ts +371 -0
  51. package/src/config/index.ts +62 -0
  52. package/src/config/validation-helpers.ts +554 -0
  53. package/src/config/validation.ts +1232 -0
  54. package/src/{api/preview.ts → create-worker-preview.ts} +61 -23
  55. package/src/create-worker-upload-form.ts +217 -0
  56. package/src/dev/dev.tsx +392 -0
  57. package/src/dev/local.tsx +232 -0
  58. package/src/dev/remote.tsx +203 -0
  59. package/src/dev/use-esbuild.ts +104 -0
  60. package/src/dialogs.tsx +2 -2
  61. package/src/entry.ts +240 -0
  62. package/src/environment-variables.ts +33 -0
  63. package/src/https-options.ts +122 -0
  64. package/src/index.tsx +1218 -803
  65. package/src/inspect.ts +103 -25
  66. package/src/intl-polyfill.d.ts +139 -0
  67. package/src/{kv.tsx → kv.ts} +104 -61
  68. package/src/miniflare-cli/README.md +30 -0
  69. package/src/miniflare-cli/enum-keys.ts +17 -0
  70. package/src/miniflare-cli/index.ts +37 -0
  71. package/src/module-collection.ts +229 -35
  72. package/src/open-in-browser.ts +25 -0
  73. package/src/package-manager.ts +126 -0
  74. package/src/pages.tsx +74 -44
  75. package/src/parse.ts +183 -0
  76. package/src/paths.ts +26 -0
  77. package/src/proxy.ts +177 -39
  78. package/src/publish.ts +286 -300
  79. package/src/r2.ts +50 -0
  80. package/src/reporting.ts +131 -0
  81. package/src/selfsigned.d.ts +29 -0
  82. package/src/sites.tsx +224 -62
  83. package/src/tail/filters.ts +279 -0
  84. package/src/tail/index.ts +299 -0
  85. package/src/tail/printing.ts +62 -0
  86. package/src/user.tsx +278 -178
  87. package/src/whoami.tsx +69 -0
  88. package/src/{api/worker.ts → worker.ts} +45 -37
  89. package/templates/new-worker.js +15 -0
  90. package/templates/new-worker.ts +15 -0
  91. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  92. package/templates/tsconfig.json +105 -0
  93. package/wrangler-dist/cli.js +130377 -112126
  94. package/wrangler-dist/cli.js.map +3 -3
  95. package/src/__tests__/run-in-tmp.ts +0 -19
  96. package/src/__tests__/run-wrangler.ts +0 -32
  97. package/src/api/form_data.ts +0 -131
  98. package/src/config.ts +0 -487
  99. package/src/dev.tsx +0 -784
  100. package/src/tail.tsx +0 -73
package/src/publish.ts CHANGED
@@ -1,33 +1,34 @@
1
1
  import assert from "node:assert";
2
+ import { readFileSync } from "node:fs";
2
3
  import path from "node:path";
3
- import { readFile } from "node:fs/promises";
4
- import esbuild from "esbuild";
5
- import { execa } from "execa";
4
+ import { URLSearchParams } from "node:url";
6
5
  import tmp from "tmp-promise";
7
- import type { CfWorkerInit } from "./api/worker";
8
- import { toFormData } from "./api/form_data";
6
+ import { bundleWorker } from "./bundle";
9
7
  import { fetchResult } from "./cfetch";
10
- import type { Config } from "./config";
11
- import makeModuleCollector from "./module-collection";
8
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
12
9
  import { syncAssets } from "./sites";
13
-
14
- type CfScriptFormat = undefined | "modules" | "service-worker";
10
+ import type { Config } from "./config";
11
+ import type { Entry } from "./entry";
12
+ import type { AssetPaths } from "./sites";
13
+ import type { CfWorkerInit } from "./worker";
15
14
 
16
15
  type Props = {
17
16
  config: Config;
18
- format?: CfScriptFormat;
19
- script?: string;
20
- name?: string;
21
- env?: string;
22
- compatibilityDate?: string;
23
- compatibilityFlags?: string[];
24
- public?: string;
25
- site?: string;
26
- triggers?: (string | number)[];
27
- routes?: (string | number)[];
28
- legacyEnv?: boolean;
17
+ accountId: string;
18
+ entry: Entry;
19
+ rules: Config["rules"];
20
+ name: string | undefined;
21
+ env: string | undefined;
22
+ compatibilityDate: string | undefined;
23
+ compatibilityFlags: string[] | undefined;
24
+ assetPaths: AssetPaths | undefined;
25
+ triggers: (string | number)[] | undefined;
26
+ routes: (string | number)[] | undefined;
27
+ legacyEnv: boolean | undefined;
29
28
  jsxFactory: undefined | string;
30
29
  jsxFragment: undefined | string;
30
+ tsconfig: undefined | string;
31
+ experimentalPublic: boolean;
31
32
  };
32
33
 
33
34
  function sleep(ms: number) {
@@ -35,330 +36,315 @@ function sleep(ms: number) {
35
36
  }
36
37
 
37
38
  export default async function publish(props: Props): Promise<void> {
38
- if (props.public && props.format === "service-worker") {
39
- // TODO: check config too
40
- throw new Error(
41
- "You cannot use the service worker format with a public directory."
42
- );
43
- }
44
39
  // TODO: warn if git/hg has uncommitted changes
45
- const { config } = props;
46
- const {
47
- account_id: accountId,
48
- build,
49
- // @ts-expect-error hidden
50
- __path__,
51
- } = config;
52
-
53
- const envRootObj =
54
- props.env && config.env ? config.env[props.env] || {} : config;
40
+ const { config, accountId } = props;
55
41
 
56
42
  assert(
57
- envRootObj.compatibility_date || props.compatibilityDate,
43
+ props.compatibilityDate || config.compatibility_date,
58
44
  "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."
59
45
  );
60
46
 
61
- if (accountId === undefined) {
62
- throw new Error("No account_id provided.");
63
- }
64
-
65
47
  const triggers = props.triggers || config.triggers?.crons;
66
- const routes = props.routes || config.routes;
48
+ const routes =
49
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
50
+
51
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
52
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
67
53
 
68
54
  const jsxFactory = props.jsxFactory || config.jsx_factory;
69
55
  const jsxFragment = props.jsxFragment || config.jsx_fragment;
70
56
 
71
- assert(config.account_id, "missing account id");
72
-
73
- let scriptName = props.name || config.name;
57
+ const scriptName = props.name;
74
58
  assert(
75
59
  scriptName,
76
60
  '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>"`'
77
61
  );
78
62
 
79
- let file: string;
80
- if (props.script) {
81
- file = props.script;
82
- } else {
83
- assert(build?.upload?.main, "missing main file");
84
- file = path.join(path.dirname(__path__), build.upload.main);
85
- }
86
-
87
- if (props.legacyEnv) {
88
- scriptName += props.env ? `-${props.env}` : "";
89
- }
90
- const envName = props.env ?? "production";
63
+ assert(
64
+ !config.site || config.site.bucket,
65
+ "A [site] definition requires a `bucket` field with a path to the site's public directory."
66
+ );
91
67
 
92
68
  const destination = await tmp.dir({ unsafeCleanup: true });
69
+ try {
70
+ const envName = props.env ?? "production";
93
71
 
94
- if (props.config.build?.command) {
95
- // TODO: add a deprecation message here?
96
- console.log("running:", props.config.build.command);
97
- const buildCommandPieces = props.config.build.command.split(" ");
98
- await execa(buildCommandPieces[0], buildCommandPieces.slice(1), {
99
- stdout: "inherit",
100
- stderr: "inherit",
101
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
102
- });
103
- }
72
+ const { format } = props.entry;
104
73
 
105
- const moduleCollector = makeModuleCollector();
106
- const result = await esbuild.build({
107
- ...(props.public
108
- ? {
109
- stdin: {
110
- contents: (
111
- await readFile(
112
- path.join(__dirname, "../static-asset-facade.js"),
113
- "utf8"
114
- )
115
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
116
- sourcefile: "static-asset-facade.js",
117
- resolveDir: path.dirname(file),
118
- },
119
- }
120
- : { entryPoints: [file] }),
121
- bundle: true,
122
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
123
- outdir: destination.path,
124
- external: ["__STATIC_CONTENT_MANIFEST"],
125
- format: "esm",
126
- sourcemap: true,
127
- metafile: true,
128
- conditions: ["worker", "browser"],
129
- loader: {
130
- ".js": "jsx",
131
- },
132
- plugins: [moduleCollector.plugin],
133
- ...(jsxFactory && { jsxFactory }),
134
- ...(jsxFragment && { jsxFragment }),
135
- });
136
-
137
- // result.metafile is defined because of the `metafile: true` option above.
138
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
139
- const metafile = result.metafile!;
140
- const expectedEntryPoint = props.public
141
- ? path.join(path.dirname(file), "static-asset-facade.js")
142
- : file;
143
- const outputEntry = Object.entries(metafile.outputs).find(
144
- ([, { entryPoint }]) => entryPoint === expectedEntryPoint
145
- );
146
- if (outputEntry === undefined) {
147
- throw new Error(
148
- `Cannot find entry-point "${expectedEntryPoint}" in generated bundle.`
149
- );
150
- }
151
- const { format } = props;
152
- const bundle = {
153
- type: outputEntry[1].exports.length > 0 ? "esm" : "commonjs",
154
- exports: outputEntry[1].exports,
155
- };
156
-
157
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
158
- // That way we'll be able to accurately tell if this is a service worker or not.
159
-
160
- if (format === "modules" && bundle.type === "commonjs") {
161
- console.error("⎔ Cannot use modules with a commonjs bundle.");
162
- // TODO: a much better error message here, with what to do next
163
- return;
164
- }
165
- if (format === "service-worker" && bundle.type !== "esm") {
166
- console.error("⎔ Cannot use service-worker with a esm bundle.");
167
- // TODO: a much better error message here, with what to do next
168
- return;
169
- }
74
+ if (props.experimentalPublic && format === "service-worker") {
75
+ // TODO: check config too
76
+ throw new Error(
77
+ "You cannot publish in the service worker format with a public directory."
78
+ );
79
+ }
170
80
 
171
- const content = await readFile(outputEntry[0], { encoding: "utf-8" });
172
- await destination.cleanup();
81
+ if (config.wasm_modules && format === "modules") {
82
+ throw new Error(
83
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
84
+ );
85
+ }
173
86
 
174
- // if config.migrations
175
- // get current migration tag
176
- let migrations;
177
- if (config.migrations !== undefined) {
178
- const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
179
- `/accounts/${accountId}/workers/scripts`
180
- );
181
- const script = scripts.find(({ id }) => id === scriptName);
182
- if (script?.migration_tag) {
183
- // was already published once
184
- const foundIndex = config.migrations.findIndex(
185
- (migration) => migration.tag === script.migration_tag
87
+ if (config.text_blobs && format === "modules") {
88
+ throw new Error(
89
+ "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
186
90
  );
187
- if (foundIndex === -1) {
188
- console.warn(
189
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
91
+ }
92
+
93
+ const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
94
+ props.entry,
95
+ destination.path,
96
+ {
97
+ serveAssetsFromWorker: props.experimentalPublic,
98
+ jsxFactory,
99
+ jsxFragment,
100
+ rules: props.rules,
101
+ tsconfig: props.tsconfig ?? config.tsconfig,
102
+ }
103
+ );
104
+
105
+ const content = readFileSync(resolvedEntryPointPath, {
106
+ encoding: "utf-8",
107
+ });
108
+
109
+ // if config.migrations
110
+ // get current migration tag
111
+ let migrations;
112
+ if (config.migrations.length > 0) {
113
+ const scripts = await fetchResult<
114
+ { id: string; migration_tag: string }[]
115
+ >(`/accounts/${accountId}/workers/scripts`);
116
+ const script = scripts.find(({ id }) => id === scriptName);
117
+ if (script?.migration_tag) {
118
+ // was already published once
119
+ const foundIndex = config.migrations.findIndex(
120
+ (migration) => migration.tag === script.migration_tag
190
121
  );
191
- migrations = {
192
- old_tag: script.migration_tag,
193
- new_tag: config.migrations[config.migrations.length - 1].tag,
194
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
195
- };
122
+ if (foundIndex === -1) {
123
+ console.warn(
124
+ `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
125
+ );
126
+ migrations = {
127
+ old_tag: script.migration_tag,
128
+ new_tag: config.migrations[config.migrations.length - 1].tag,
129
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
130
+ };
131
+ } else {
132
+ migrations = {
133
+ old_tag: script.migration_tag,
134
+ new_tag: config.migrations[config.migrations.length - 1].tag,
135
+ steps: config.migrations
136
+ .slice(foundIndex + 1)
137
+ .map(({ tag: _tag, ...rest }) => rest),
138
+ };
139
+ }
196
140
  } else {
197
141
  migrations = {
198
- old_tag: script.migration_tag,
199
142
  new_tag: config.migrations[config.migrations.length - 1].tag,
200
- steps: config.migrations
201
- .slice(foundIndex + 1)
202
- .map(({ tag: _tag, ...rest }) => rest),
143
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
203
144
  };
204
145
  }
205
- } else {
206
- migrations = {
207
- new_tag: config.migrations[config.migrations.length - 1].tag,
208
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
209
- };
210
146
  }
211
- }
212
147
 
213
- const assetPath = props.public || props.site || props.config.site?.bucket; // TODO: allow both
214
- const assets = assetPath
215
- ? await syncAssets(accountId, scriptName, assetPath, false)
216
- : { manifest: undefined, namespace: undefined };
217
-
218
- const bindings: CfWorkerInit["bindings"] = {
219
- kv_namespaces: envRootObj.kv_namespaces?.concat(
220
- assets.namespace
221
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
222
- : []
223
- ),
224
- vars: envRootObj.vars,
225
- durable_objects: envRootObj.durable_objects,
226
- services: envRootObj.experimental_services,
227
- };
228
-
229
- const worker: CfWorkerInit = {
230
- name: scriptName,
231
- main: {
232
- name: path.basename(outputEntry[0]),
233
- content: content,
234
- type: bundle.type === "esm" ? "esm" : "commonjs",
235
- },
236
- bindings,
237
- ...(migrations && { migrations }),
238
- modules: moduleCollector.modules.concat(
239
- assets.manifest
240
- ? {
241
- name: "__STATIC_CONTENT_MANIFEST",
242
- content: JSON.stringify(assets.manifest),
243
- type: "text",
244
- }
245
- : []
246
- ),
247
- compatibility_date: config.compatibility_date,
248
- compatibility_flags: config.compatibility_flags,
249
- usage_model: config.usage_model,
250
- };
251
-
252
- const start = Date.now();
253
- function formatTime(duration: number) {
254
- return `(${(duration / 1000).toFixed(2)} sec)`;
255
- }
148
+ const assets = await syncAssets(
149
+ accountId,
150
+ // When we're using the newer service environments, we wouldn't
151
+ // have added the env name on to the script name. However, we must
152
+ // include it in the kv namespace name regardless (since there's no
153
+ // concept of service environments for kv namespaces yet).
154
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
155
+ props.assetPaths,
156
+ false
157
+ );
256
158
 
257
- const notProd = !props.legacyEnv && props.env;
258
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
259
- const workerUrl = notProd
260
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
261
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
262
-
263
- // Upload the script so it has time to propagate.
264
- const { available_on_subdomain } = await fetchResult(
265
- `${workerUrl}?available_on_subdomain=true`,
266
- {
267
- method: "PUT",
268
- // @ts-expect-error: TODO: fix this type error!
269
- body: toFormData(worker),
159
+ const bindings: CfWorkerInit["bindings"] = {
160
+ kv_namespaces: (config.kv_namespaces || []).concat(
161
+ assets.namespace
162
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
163
+ : []
164
+ ),
165
+ vars: config.vars,
166
+ wasm_modules: config.wasm_modules,
167
+ text_blobs: {
168
+ ...config.text_blobs,
169
+ ...(assets.manifest &&
170
+ format === "service-worker" && {
171
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
172
+ }),
173
+ },
174
+ durable_objects: config.durable_objects,
175
+ r2_buckets: config.r2_buckets,
176
+ unsafe: config.unsafe?.bindings,
177
+ };
178
+
179
+ if (assets.manifest) {
180
+ modules.push({
181
+ name: "__STATIC_CONTENT_MANIFEST",
182
+ content: JSON.stringify(assets.manifest),
183
+ type: "text",
184
+ });
270
185
  }
271
- );
272
186
 
273
- const uploadMs = Date.now() - start;
274
- console.log("Uploaded", workerName, formatTime(uploadMs));
275
- const deployments: Promise<string[]>[] = [];
187
+ const worker: CfWorkerInit = {
188
+ name: scriptName,
189
+ main: {
190
+ name: path.basename(resolvedEntryPointPath),
191
+ content: content,
192
+ type: bundleType,
193
+ },
194
+ bindings,
195
+ migrations,
196
+ modules,
197
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
198
+ compatibility_flags:
199
+ props.compatibilityFlags ?? config.compatibility_flags,
200
+ usage_model: config.usage_model,
201
+ };
202
+
203
+ const start = Date.now();
204
+ const notProd = !props.legacyEnv && props.env;
205
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
206
+ const workerUrl = notProd
207
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
208
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
209
+
210
+ // Upload the script so it has time to propagate.
211
+ const { available_on_subdomain } = await fetchResult(
212
+ workerUrl,
213
+ {
214
+ method: "PUT",
215
+ body: createWorkerUploadForm(worker),
216
+ },
217
+ new URLSearchParams({ available_on_subdomain: "true" })
218
+ );
276
219
 
277
- const userSubdomain = (
278
- await fetchResult<{ subdomain: string }>(
279
- `/accounts/${accountId}/workers/subdomain`
280
- )
281
- ).subdomain;
282
-
283
- const scriptURL =
284
- props.legacyEnv || !props.env
285
- ? `${scriptName}.${userSubdomain}.workers.dev`
286
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
287
-
288
- // Enable the `workers.dev` subdomain.
289
- // TODO: Make this configurable.
290
- if (!available_on_subdomain) {
291
- deployments.push(
292
- fetchResult(`${workerUrl}/subdomain`, {
220
+ const uploadMs = Date.now() - start;
221
+ const deployments: Promise<string[]>[] = [];
222
+
223
+ if (deployToWorkersDev) {
224
+ // Deploy to a subdomain of `workers.dev`
225
+ const userSubdomain = await getSubdomain(accountId);
226
+ const scriptURL =
227
+ props.legacyEnv || !props.env
228
+ ? `${scriptName}.${userSubdomain}.workers.dev`
229
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
230
+ if (!available_on_subdomain) {
231
+ // Enable the `workers.dev` subdomain.
232
+ deployments.push(
233
+ fetchResult(`${workerUrl}/subdomain`, {
234
+ method: "POST",
235
+ body: JSON.stringify({ enabled: true }),
236
+ headers: {
237
+ "Content-Type": "application/json",
238
+ },
239
+ })
240
+ .then(() => [scriptURL])
241
+ // Add a delay when the subdomain is first created.
242
+ // This is to prevent an issue where a negative cache-hit
243
+ // causes the subdomain to be unavailable for 30 seconds.
244
+ // This is a temporary measure until we fix this on the edge.
245
+ .then(async (url) => {
246
+ await sleep(3000);
247
+ return url;
248
+ })
249
+ );
250
+ } else {
251
+ deployments.push(Promise.resolve([scriptURL]));
252
+ }
253
+ } else {
254
+ // Disable the workers.dev deployment
255
+ await fetchResult(`${workerUrl}/subdomain`, {
293
256
  method: "POST",
294
- body: JSON.stringify({ enabled: true }),
257
+ body: JSON.stringify({ enabled: false }),
295
258
  headers: {
296
259
  "Content-Type": "application/json",
297
260
  },
298
- })
299
- .then(() => [scriptURL])
300
- // Add a delay when the subdomain is first created.
301
- // This is to prevent an issue where a negative cache-hit
302
- // causes the subdomain to be unavailable for 30 seconds.
303
- // This is a temporary measure until we fix this on the edge.
304
- .then(async (url) => {
305
- await sleep(3000);
306
- return url;
261
+ });
262
+ }
263
+
264
+ console.log("Uploaded", workerName, formatTime(uploadMs));
265
+
266
+ // Update routing table for the script.
267
+ if (routes.length > 0) {
268
+ deployments.push(
269
+ fetchResult(`${workerUrl}/routes`, {
270
+ // TODO: PATCH will not delete previous routes on this script,
271
+ // whereas PUT will. We need to decide on the default behaviour
272
+ // and how to configure it.
273
+ method: "PUT",
274
+ body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
275
+ headers: {
276
+ "Content-Type": "application/json",
277
+ },
278
+ }).then(() => {
279
+ if (routes.length > 10) {
280
+ return routes
281
+ .slice(0, 9)
282
+ .map(String)
283
+ .concat([`...and ${routes.length - 10} more routes`]);
284
+ }
285
+ return routes.map(String);
307
286
  })
308
- );
309
- } else {
310
- deployments.push(Promise.resolve([scriptURL]));
311
- }
287
+ );
288
+ }
312
289
 
313
- // Update routing table for the script.
314
- if (routes && routes.length) {
315
- deployments.push(
316
- fetchResult(`${workerUrl}/routes`, {
317
- // TODO: PATCH will not delete previous routes on this script,
318
- // whereas PUT will. We need to decide on the default behaviour
319
- // and how to configure it.
320
- method: "PUT",
321
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
322
- headers: {
323
- "Content-Type": "application/json",
324
- },
325
- }).then(() => {
326
- if (routes.length > 10) {
327
- return routes
328
- .slice(0, 9)
329
- .map(String)
330
- .concat([`...and ${routes.length - 10} more routes`]);
331
- }
332
- return routes.map(String);
333
- })
334
- );
335
- }
290
+ // Configure any schedules for the script.
291
+ // TODO: rename this to `schedules`?
292
+ if (triggers && triggers.length) {
293
+ deployments.push(
294
+ fetchResult(`${workerUrl}/schedules`, {
295
+ // TODO: Unlike routes, this endpoint does not support PATCH.
296
+ // So technically, this will override any previous schedules.
297
+ // We should change the endpoint to support PATCH.
298
+ method: "PUT",
299
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
300
+ headers: {
301
+ "Content-Type": "application/json",
302
+ },
303
+ }).then(() => triggers.map(String))
304
+ );
305
+ }
336
306
 
337
- // Configure any schedules for the script.
338
- // TODO: rename this to `schedules`?
339
- if (triggers && triggers.length) {
340
- deployments.push(
341
- fetchResult(`${workerUrl}/schedules`, {
342
- // TODO: Unlike routes, this endpoint does not support PATCH.
343
- // So technically, this will override any previous schedules.
344
- // We should change the endpoint to support PATCH.
345
- method: "PUT",
346
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
347
- headers: {
348
- "Content-Type": "application/json",
349
- },
350
- }).then(() => triggers.map(String))
351
- );
352
- }
307
+ const targets = await Promise.all(deployments);
308
+ const deployMs = Date.now() - start - uploadMs;
353
309
 
354
- if (!deployments.length) {
355
- return;
310
+ if (deployments.length > 0) {
311
+ console.log("Published", workerName, formatTime(deployMs));
312
+ for (const target of targets.flat()) {
313
+ console.log(" ", target);
314
+ }
315
+ } else {
316
+ console.log("No publish targets for", workerName, formatTime(deployMs));
317
+ }
318
+ } finally {
319
+ await destination.cleanup();
356
320
  }
321
+ }
357
322
 
358
- const targets = await Promise.all(deployments);
359
- const deployMs = Date.now() - start - uploadMs;
360
- console.log("Deployed", workerName, formatTime(deployMs));
361
- for (const target of targets.flat()) {
362
- console.log(" ", target);
323
+ function formatTime(duration: number) {
324
+ return `(${(duration / 1000).toFixed(2)} sec)`;
325
+ }
326
+
327
+ async function getSubdomain(accountId: string): Promise<string> {
328
+ try {
329
+ const { subdomain } = await fetchResult(
330
+ `/accounts/${accountId}/workers/subdomain`
331
+ );
332
+ return subdomain;
333
+ } catch (e) {
334
+ const error = e as { code?: number };
335
+ if (typeof error === "object" && !!error && error.code === 10007) {
336
+ // 10007 error code: not found
337
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
338
+
339
+ const errorMessage =
340
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
341
+ const solutionMessage =
342
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
343
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
344
+
345
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
346
+ } else {
347
+ throw e;
348
+ }
363
349
  }
364
350
  }