wrangler 0.0.0-ece06ea → 0.0.0-ef13735

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 (63) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +35 -21
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +66 -0
  5. package/pages/functions/filepath-routing.ts +219 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/dev.test.tsx +73 -0
  10. package/src/__tests__/guess-worker-format.test.ts +51 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +715 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1381 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +93 -100
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +55 -47
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +641 -112
  37. package/src/dev.tsx +476 -355
  38. package/src/dialogs.tsx +6 -14
  39. package/src/guess-worker-format.ts +66 -0
  40. package/src/index.tsx +828 -496
  41. package/src/inspect.ts +596 -0
  42. package/src/kv.tsx +118 -45
  43. package/src/module-collection.ts +63 -0
  44. package/src/open-in-browser.ts +13 -0
  45. package/src/package-manager.ts +120 -0
  46. package/src/pages.tsx +915 -215
  47. package/src/paths.ts +26 -0
  48. package/src/proxy.ts +370 -0
  49. package/src/publish.ts +349 -290
  50. package/src/sites.tsx +184 -55
  51. package/src/tail.tsx +5 -3
  52. package/src/user.tsx +81 -91
  53. package/src/whoami.tsx +69 -0
  54. package/templates/new-worker.js +15 -0
  55. package/templates/new-worker.ts +15 -0
  56. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  57. package/wrangler-dist/cli.js +119231 -130682
  58. package/wrangler-dist/cli.js.map +3 -3
  59. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  60. package/src/__tests__/mock-cfetch.js +0 -46
  61. package/src/api/inspect.ts +0 -441
  62. package/src/cfetch.ts +0 -72
  63. package/src/util/fetch.ts +0 -74
package/src/publish.ts CHANGED
@@ -1,32 +1,35 @@
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 * as esbuild from "esbuild";
6
+ import { execaCommand } from "execa";
7
+ import tmp from "tmp-promise";
8
+ import { toFormData } from "./api/form_data";
9
+ import { fetchResult } from "./cfetch";
10
+ import guessWorkerFormat from "./guess-worker-format";
11
+ import makeModuleCollector from "./module-collection";
10
12
  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";
13
+ import type { CfScriptFormat, CfWorkerInit } from "./api/worker";
14
+ import type { Config } from "./config";
15
+ import type { AssetPaths } from "./sites";
16
+ import type { Metafile } from "esbuild";
15
17
 
16
18
  type Props = {
17
19
  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;
20
+ format: CfScriptFormat | undefined;
21
+ script: string | undefined;
22
+ name: string | undefined;
23
+ env: string | undefined;
24
+ compatibilityDate: string | undefined;
25
+ compatibilityFlags: string[] | undefined;
26
+ assetPaths: AssetPaths | undefined;
27
+ triggers: (string | number)[] | undefined;
28
+ routes: (string | number)[] | undefined;
29
+ legacyEnv: boolean | undefined;
30
+ jsxFactory: undefined | string;
31
+ jsxFragment: undefined | string;
32
+ experimentalPublic: boolean;
30
33
  };
31
34
 
32
35
  function sleep(ms: number) {
@@ -34,21 +37,27 @@ function sleep(ms: number) {
34
37
  }
35
38
 
36
39
  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
40
  // TODO: warn if git/hg has uncommitted changes
44
41
  const { config } = props;
45
42
  const {
46
43
  account_id: accountId,
47
44
  build,
48
45
  // @ts-expect-error hidden
49
- __path__,
46
+ __path__: wranglerTomlPath,
50
47
  } = config;
51
48
 
49
+ const envRootObj =
50
+ props.env && config.env ? config.env[props.env] || {} : config;
51
+
52
+ assert(
53
+ envRootObj.compatibility_date || props.compatibilityDate,
54
+ "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."
55
+ );
56
+
57
+ if (accountId === undefined) {
58
+ throw new Error("No account_id provided.");
59
+ }
60
+
52
61
  const triggers = props.triggers || config.triggers?.crons;
53
62
  const routes = props.routes || config.routes;
54
63
 
@@ -63,292 +72,342 @@ export default async function publish(props: Props): Promise<void> {
63
72
  '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
73
  );
65
74
 
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);
75
+ if (config.site?.["entry-point"]) {
76
+ console.warn(
77
+ "Deprecation notice: The `site.entry-point` config field is no longer used.\n" +
78
+ "The entry-point should be specified via the command line (e.g. `wrangler publish path/to/script`) or the `build.upload.main` config field.\n" +
79
+ "Please remove the `site.entry-point` field from the `wrangler.toml` file."
80
+ );
72
81
  }
73
82
 
74
- if (props.legacyEnv) {
75
- scriptName += props.env ? `-${props.env}` : "";
76
- }
77
- const envName = props.env ?? "production";
83
+ assert(
84
+ !config.site || config.site.bucket,
85
+ "A [site] definition requires a `bucket` field with a path to the site's public directory."
86
+ );
78
87
 
79
88
  const destination = await tmp.dir({ unsafeCleanup: true });
89
+ try {
90
+ let file: string;
91
+ let dir = process.cwd();
92
+ if (props.script) {
93
+ // If the script name comes from the command line it is relative to the current working directory.
94
+ file = path.resolve(props.script);
95
+ } else {
96
+ // If the script name comes from the config, then it is relative to the wrangler.toml file.
97
+ if (build?.upload?.main === undefined) {
98
+ throw new Error(
99
+ "Missing entry-point: The entry-point should be specified via the command line (e.g. `wrangler publish path/to/script`) or the `build.upload.main` config field."
100
+ );
101
+ }
102
+ dir = path.resolve(
103
+ path.dirname(wranglerTomlPath),
104
+ (build.upload.format === "modules" && build.upload.dir) || ""
105
+ );
106
+ file = path.resolve(dir, build.upload.main);
107
+ }
80
108
 
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
- );
126
-
127
- const { format } = props;
128
- const bundle = {
129
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
130
- exports: chunks[1].exports,
131
- };
109
+ if (props.legacyEnv) {
110
+ scriptName += props.env ? `-${props.env}` : "";
111
+ }
112
+ const envName = props.env ?? "production";
113
+
114
+ if (props.config.build?.command) {
115
+ // TODO: add a deprecation message here?
116
+ console.log("running:", props.config.build.command);
117
+ await execaCommand(props.config.build.command, {
118
+ shell: true,
119
+ stdout: "inherit",
120
+ stderr: "inherit",
121
+ ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
122
+ });
123
+ }
132
124
 
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.
125
+ const format = await guessWorkerFormat(file, props.format);
135
126
 
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
- }
127
+ if (props.experimentalPublic && format === "service-worker") {
128
+ // TODO: check config too
129
+ throw new Error(
130
+ "You cannot publish in the service worker format with a public directory."
131
+ );
132
+ }
146
133
 
147
- const content = await readFile(chunks[0], { encoding: "utf-8" });
148
- destination.cleanup();
134
+ if ("wasm_modules" in config && format === "modules") {
135
+ throw new Error(
136
+ "You cannot configure [wasm_modules] with an ES Module worker. Instead, import the .wasm module directly in your code"
137
+ );
138
+ }
149
139
 
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`
140
+ const moduleCollector = makeModuleCollector();
141
+ const result = await esbuild.build({
142
+ ...(props.experimentalPublic
143
+ ? {
144
+ stdin: {
145
+ contents: readFileSync(
146
+ path.join(__dirname, "../templates/static-asset-facade.js"),
147
+ "utf8"
148
+ ).replace("__ENTRY_POINT__", file),
149
+ sourcefile: "static-asset-facade.js",
150
+ resolveDir: path.dirname(file),
151
+ },
152
+ nodePaths: [path.join(__dirname, "../vendor")],
153
+ }
154
+ : { entryPoints: [file] }),
155
+ bundle: true,
156
+ absWorkingDir: dir,
157
+ outdir: destination.path,
158
+ external: ["__STATIC_CONTENT_MANIFEST"],
159
+ format: "esm",
160
+ sourcemap: true,
161
+ metafile: true,
162
+ conditions: ["worker", "browser"],
163
+ loader: {
164
+ ".js": "jsx",
165
+ ".html": "text",
166
+ ".pem": "text",
167
+ ".txt": "text",
168
+ },
169
+ plugins: [moduleCollector.plugin],
170
+ ...(jsxFactory && { jsxFactory }),
171
+ ...(jsxFragment && { jsxFragment }),
172
+ });
173
+
174
+ // result.metafile is defined because of the `metafile: true` option above.
175
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
176
+ const metafile = result.metafile!;
177
+ const entryPoints = Object.entries(metafile.outputs).filter(
178
+ ([_path, output]) => output.entryPoint !== undefined
156
179
  );
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
162
- );
163
- if (foundIndex === -1) {
164
- 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...`
180
+ assert(
181
+ entryPoints.length > 0,
182
+ `Cannot find entry-point "${file}" in generated bundle.` +
183
+ listEntryPoints(entryPoints)
184
+ );
185
+ assert(
186
+ entryPoints.length < 2,
187
+ "More than one entry-point found for generated bundle." +
188
+ listEntryPoints(entryPoints)
189
+ );
190
+ const entryPointExports = entryPoints[0][1].exports;
191
+ const resolvedEntryPointPath = path.resolve(dir, entryPoints[0][0]);
192
+ const bundle = {
193
+ type: entryPointExports.length > 0 ? "esm" : "commonjs",
194
+ exports: entryPointExports,
195
+ };
196
+
197
+ let content = readFileSync(resolvedEntryPointPath, {
198
+ encoding: "utf-8",
199
+ });
200
+
201
+ // if config.migrations
202
+ // get current migration tag
203
+ let migrations;
204
+ if (config.migrations !== undefined) {
205
+ const scripts = await fetchResult<
206
+ { id: string; migration_tag: string }[]
207
+ >(`/accounts/${accountId}/workers/scripts`);
208
+ const script = scripts.find(({ id }) => id === scriptName);
209
+ if (script?.migration_tag) {
210
+ // was already published once
211
+ const foundIndex = config.migrations.findIndex(
212
+ (migration) => migration.tag === script.migration_tag
166
213
  );
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
- };
214
+ if (foundIndex === -1) {
215
+ console.warn(
216
+ `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...`
217
+ );
218
+ migrations = {
219
+ old_tag: script.migration_tag,
220
+ new_tag: config.migrations[config.migrations.length - 1].tag,
221
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
222
+ };
223
+ } else {
224
+ migrations = {
225
+ old_tag: script.migration_tag,
226
+ new_tag: config.migrations[config.migrations.length - 1].tag,
227
+ steps: config.migrations
228
+ .slice(foundIndex + 1)
229
+ .map(({ tag: _tag, ...rest }) => rest),
230
+ };
231
+ }
172
232
  } else {
173
233
  migrations = {
174
- old_tag: script.migration_tag,
175
234
  new_tag: config.migrations[config.migrations.length - 1].tag,
176
- steps: config.migrations
177
- .slice(foundIndex + 1)
178
- .map(({ tag: _tag, ...rest }) => rest),
235
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
179
236
  };
180
237
  }
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
238
  }
187
- }
188
239
 
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
- {}
240
+ const assets = await syncAssets(
241
+ accountId,
242
+ scriptName,
243
+ props.assetPaths,
244
+ false,
245
+ props.env
246
+ );
247
+
248
+ const bindings: CfWorkerInit["bindings"] = {
249
+ kv_namespaces: (envRootObj.kv_namespaces || []).concat(
250
+ assets.namespace
251
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
252
+ : []
215
253
  ),
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
- {}
254
+ vars: envRootObj.vars,
255
+ wasm_modules: config.wasm_modules,
256
+ durable_objects: envRootObj.durable_objects,
257
+ services: envRootObj.experimental_services,
258
+ };
259
+
260
+ const workerType = bundle.type === "esm" ? "esm" : "commonjs";
261
+ if (workerType !== "esm" && assets.manifest) {
262
+ content = `const __STATIC_CONTENT_MANIFEST = ${JSON.stringify(
263
+ assets.manifest
264
+ )};\n${content}`;
265
+ }
266
+
267
+ const worker: CfWorkerInit = {
268
+ name: scriptName,
269
+ main: {
270
+ name: path.basename(resolvedEntryPointPath),
271
+ content: content,
272
+ type: workerType,
273
+ },
274
+ bindings,
275
+ ...(migrations && { migrations }),
276
+ modules: moduleCollector.modules.concat(
277
+ assets.manifest && workerType === "esm"
278
+ ? {
279
+ name: "__STATIC_CONTENT_MANIFEST",
280
+ content: JSON.stringify(assets.manifest),
281
+ type: "text",
282
+ }
283
+ : []
224
284
  ),
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
- }
285
+ compatibility_date: config.compatibility_date,
286
+ compatibility_flags: config.compatibility_flags,
287
+ usage_model: config.usage_model,
288
+ };
289
+
290
+ const start = Date.now();
291
+ const notProd = !props.legacyEnv && props.env;
292
+ const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
293
+ const workerUrl = notProd
294
+ ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
295
+ : `/accounts/${accountId}/workers/scripts/${scriptName}`;
296
+
297
+ // Upload the script so it has time to propagate.
298
+ const { available_on_subdomain } = await fetchResult(
299
+ workerUrl,
300
+ {
301
+ method: "PUT",
302
+ body: toFormData(worker),
303
+ },
304
+ new URLSearchParams({ available_on_subdomains: "true" })
305
+ );
246
306
 
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),
307
+ const uploadMs = Date.now() - start;
308
+ console.log("Uploaded", workerName, formatTime(uploadMs));
309
+ const deployments: Promise<string[]>[] = [];
310
+
311
+ const userSubdomain = (
312
+ await fetchResult<{ subdomain: string }>(
313
+ `/accounts/${accountId}/workers/subdomain`
314
+ )
315
+ ).subdomain;
316
+
317
+ const scriptURL =
318
+ props.legacyEnv || !props.env
319
+ ? `${scriptName}.${userSubdomain}.workers.dev`
320
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
321
+
322
+ // Enable the `workers.dev` subdomain.
323
+ // TODO: Make this configurable.
324
+ if (!available_on_subdomain) {
325
+ deployments.push(
326
+ fetchResult(`${workerUrl}/subdomain`, {
327
+ method: "POST",
328
+ body: JSON.stringify({ enabled: true }),
329
+ headers: {
330
+ "Content-Type": "application/json",
331
+ },
332
+ })
333
+ .then(() => [scriptURL])
334
+ // Add a delay when the subdomain is first created.
335
+ // This is to prevent an issue where a negative cache-hit
336
+ // causes the subdomain to be unavailable for 30 seconds.
337
+ // This is a temporary measure until we fix this on the edge.
338
+ .then(async (url) => {
339
+ await sleep(3000);
340
+ return url;
341
+ })
342
+ );
343
+ } else {
344
+ deployments.push(Promise.resolve([scriptURL]));
260
345
  }
261
- );
262
346
 
263
- const uploadMs = Date.now() - start;
264
- console.log("Uploaded", workerName, formatTime(uploadMs));
265
- const deployments: Promise<string[]>[] = [];
266
-
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`, {
283
- method: "POST",
284
- body: JSON.stringify({ enabled: true }),
285
- headers: {
286
- "Content-Type": "application/json",
287
- },
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;
347
+ // Update routing table for the script.
348
+ if (routes && routes.length) {
349
+ deployments.push(
350
+ fetchResult(`${workerUrl}/routes`, {
351
+ // TODO: PATCH will not delete previous routes on this script,
352
+ // whereas PUT will. We need to decide on the default behaviour
353
+ // and how to configure it.
354
+ method: "PUT",
355
+ body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
356
+ headers: {
357
+ "Content-Type": "application/json",
358
+ },
359
+ }).then(() => {
360
+ if (routes.length > 10) {
361
+ return routes
362
+ .slice(0, 9)
363
+ .map(String)
364
+ .concat([`...and ${routes.length - 10} more routes`]);
365
+ }
366
+ return routes.map(String);
297
367
  })
298
- );
299
- } else {
300
- deployments.push(Promise.resolve([scriptURL]));
301
- }
368
+ );
369
+ }
302
370
 
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
- }
371
+ // Configure any schedules for the script.
372
+ // TODO: rename this to `schedules`?
373
+ if (triggers && triggers.length) {
374
+ deployments.push(
375
+ fetchResult(`${workerUrl}/schedules`, {
376
+ // TODO: Unlike routes, this endpoint does not support PATCH.
377
+ // So technically, this will override any previous schedules.
378
+ // We should change the endpoint to support PATCH.
379
+ method: "PUT",
380
+ body: JSON.stringify(triggers.map((cron) => ({ cron }))),
381
+ headers: {
382
+ "Content-Type": "application/json",
383
+ },
384
+ }).then(() => triggers.map(String))
385
+ );
386
+ }
326
387
 
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
- }
388
+ if (!deployments.length) {
389
+ return;
390
+ }
343
391
 
344
- if (!deployments.length) {
345
- return;
392
+ const targets = await Promise.all(deployments);
393
+ const deployMs = Date.now() - start - uploadMs;
394
+ console.log("Deployed", workerName, formatTime(deployMs));
395
+ for (const target of targets.flat()) {
396
+ console.log(" ", target);
397
+ }
398
+ } finally {
399
+ await destination.cleanup();
346
400
  }
401
+ }
347
402
 
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);
353
- }
403
+ function listEntryPoints(
404
+ outputs: [string, ValueOf<Metafile["outputs"]>][]
405
+ ): string {
406
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
407
+ }
408
+
409
+ type ValueOf<T> = T[keyof T];
410
+
411
+ function formatTime(duration: number) {
412
+ return `(${(duration / 1000).toFixed(2)} sec)`;
354
413
  }