wrangler 0.0.0-ece06ea → 0.0.0-ed4f2ef

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