@vite-hub/cli 0.3.0 → 0.4.1

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.
@@ -0,0 +1,1153 @@
1
+ import { A as readDeployCommit, B as readSetupProject, C as denoOrganization, D as build, E as listCloudflareDeployments, I as hostFromNitroPreset, O as readBuildOutput, P as setupStatus, S as denoAdapter, T as cloudflareAdapter, Z as __exportAll, _ as listVercelDeployments, a as ensureViteHubGitignore, b as netlifyAdapter, f as readSetupLinks, g as hasVercelLogin, h as writeSeparateResourcesNote, i as addSetupLink, k as createDeployRun, l as readLinkHostOption, p as selectSetupLink, s as hostRequired, t as checkDeployEnv, v as vercelAdapter, w as listDenoDeployments, x as abortable, y as listNetlifyDeployments } from "./env-B1Gg-WnA.js";
2
+ import { C as callOperationFromCli, _ as readProvisionState, a as writeProvisionActions, d as planProvisionSteps, f as resolveHostCredentials, g as mergeProvisionState, h as PROVISION_STATE_FILE, i as provisionEnv, m as cliErrorDiagnostics, n as isProvisionHost, r as provisionActionStatus, y as writeProvisionState } from "./provision-DXl97xG0.js";
3
+ import { a as table, i as setupFailure, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-B4mPbSbj.js";
4
+ import { createRequire } from "node:module";
5
+ import { existsSync } from "node:fs";
6
+ import process from "node:process";
7
+ import { basename, join } from "pathe";
8
+ import { readFile } from "node:fs/promises";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { pathToFileURL } from "node:url";
11
+ import { parseArgs } from "node:util";
12
+ //#region src/setup/deploy/after.ts
13
+ /** Waits between the attempts of one path: a new version can take a few seconds to reach every edge location. */
14
+ const checkRetryDelaysMs = [
15
+ 1e3,
16
+ 2e3,
17
+ 4e3
18
+ ];
19
+ const checkTimeoutMs = 1e4;
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
+ function reason(error) {
22
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `no answer within ${checkTimeoutMs / 1e3} seconds`;
23
+ return error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
24
+ }
25
+ /**
26
+ * Requests each path on the deployed URL until it answers with a 2xx status, with a few retries. Redirects are
27
+ * followed, so the final answer counts. The request asks the cache to skip, so a cached answer of the previous version
28
+ * does not pass the check.
29
+ */
30
+ async function runDeployChecks(baseUrl, paths, fetchImpl, delays = checkRetryDelaysMs) {
31
+ const origin = new URL(baseUrl);
32
+ return await Promise.all(paths.map(async (path) => {
33
+ const url = new URL(path, origin).href;
34
+ let last = {
35
+ ok: false,
36
+ path,
37
+ url
38
+ };
39
+ for (let attempt = 0; attempt <= delays.length; attempt++) {
40
+ if (attempt) await sleep(delays[attempt - 1]);
41
+ try {
42
+ const response = await fetchImpl(url, {
43
+ cache: "no-store",
44
+ headers: {
45
+ "cache-control": "no-cache",
46
+ "user-agent": "vitehub-deploy-check"
47
+ },
48
+ redirect: "follow",
49
+ signal: AbortSignal.timeout(checkTimeoutMs)
50
+ });
51
+ await response.body?.cancel();
52
+ last = {
53
+ ok: response.ok,
54
+ path,
55
+ status: response.status,
56
+ url
57
+ };
58
+ } catch (error) {
59
+ last = {
60
+ error: reason(error),
61
+ ok: false,
62
+ path,
63
+ url
64
+ };
65
+ }
66
+ if (last.ok) break;
67
+ }
68
+ return last;
69
+ }));
70
+ }
71
+ /** One line per failed check, such as `/api/health: 503` or `/: fetch failed`. */
72
+ function formatFailedChecks(checks) {
73
+ return checks.filter((check) => !check.ok).map((check) => `${check.path}: ${check.status ?? check.error ?? "no answer"}`).join(", ");
74
+ }
75
+ function quote(value) {
76
+ return /^[\w./:@=-]+$/u.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
77
+ }
78
+ /**
79
+ * The rollback of each host, from its CLI help in test/fixtures/host-cli-help/:
80
+ * - Wrangler 4.158 `wrangler rollback <version-id> --name <worker> --yes`.
81
+ * - Vercel CLI 65.16 `vercel rollback <deployment> --yes`.
82
+ * - Netlify CLI 27.11 `netlify api restoreSiteDeploy`, the `POST /sites/{site_id}/deploys/{deploy_id}/restore` API.
83
+ * - Deno Deploy CLI 0.0.9909 has no rollback command.
84
+ */
85
+ function rollbackFor(host, input) {
86
+ const { previous } = input;
87
+ if (!previous) return { note: input.lookupFailed ? `The previous production deployment is not known: ${input.lookupFailed} Run \`vitehub deployments\` to find it.` : "This was the first production deploy, so there is no earlier deployment to roll back to." };
88
+ const described = {
89
+ deploymentId: previous.id,
90
+ ...previous.version ? { version: previous.version } : {}
91
+ };
92
+ switch (host) {
93
+ case "cloudflare": return {
94
+ command: `npx wrangler rollback ${quote(previous.version ?? previous.id)} --name ${quote(input.projectName)} --yes`,
95
+ previous: described
96
+ };
97
+ case "vercel": return {
98
+ command: `npx vercel rollback ${quote(previous.id)} --yes`,
99
+ previous: described
100
+ };
101
+ case "netlify": return input.siteId ? {
102
+ command: `npx netlify api restoreSiteDeploy --data ${quote(JSON.stringify({
103
+ deploy_id: previous.id,
104
+ site_id: input.siteId
105
+ }))}`,
106
+ previous: described
107
+ } : {
108
+ note: `Publish deploy ${previous.id} again in the Netlify dashboard, under Deploys.`,
109
+ previous: described
110
+ };
111
+ case "deno": return {
112
+ note: `The Deno Deploy CLI has no rollback command. Promote revision ${previous.id} to production in the Deno Deploy dashboard.`,
113
+ previous: described
114
+ };
115
+ }
116
+ }
117
+ const xmlEntities = {
118
+ amp: "&",
119
+ apos: "'",
120
+ gt: ">",
121
+ lt: "<",
122
+ quot: "\""
123
+ };
124
+ /** Text of an XML element: CDATA kept as it is, named and numeric character references decoded. */
125
+ function decodeXml(text) {
126
+ return text.split(/(<!\[CDATA\[[\s\S]*?\]\]>)/u).map((part) => part.startsWith("<![CDATA[") ? part.slice(9, -3) : part.replace(/&(?:#x([\da-f]+)|#(\d+)|(amp|lt|gt|quot|apos));/giu, (match, hex, decimal, name) => {
127
+ if (name) return xmlEntities[name];
128
+ const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
129
+ return code <= 1114111 ? String.fromCodePoint(code) : match;
130
+ })).join("").trim();
131
+ }
132
+ function locations(xml) {
133
+ return [...xml.matchAll(/<loc>([\s\S]*?)<\/loc>/gu)].map((match) => decodeXml(match[1])).filter(Boolean);
134
+ }
135
+ /** IndexNow takes at most 10,000 URLs in one request. */
136
+ const indexNowBatch = 1e4;
137
+ /** A sitemap index may list sitemaps on other paths. Read at most this many. */
138
+ const nestedSitemapLimit = 50;
139
+ /**
140
+ * Reads `<url>/sitemap.xml`, one level of a sitemap index included, and sends every URL of the site to IndexNow.
141
+ * https://www.indexnow.org/documentation: 200 and 202 accept the URLs, 403 means the key file was not found.
142
+ */
143
+ async function submitIndexNow(indexNow, fetchImpl) {
144
+ const origin = new URL(indexNow.url);
145
+ const read = async (url) => {
146
+ const response = await fetchImpl(url, {
147
+ headers: { "user-agent": "vitehub-deploy" },
148
+ signal: AbortSignal.timeout(checkTimeoutMs)
149
+ });
150
+ if (!response.ok) throw Object.assign(/* @__PURE__ */ new Error(`${url} answered ${response.status}.`), { status: response.status });
151
+ return await response.text();
152
+ };
153
+ const sameSite = (url) => URL.canParse(url) && new URL(url).origin === origin.origin;
154
+ let urls;
155
+ try {
156
+ const sitemap = await read(new URL("/sitemap.xml", origin).href);
157
+ urls = /<sitemapindex[\s>]/u.test(sitemap) ? (await Promise.all(locations(sitemap).filter(sameSite).slice(0, nestedSitemapLimit).map(read))).flatMap(locations) : locations(sitemap);
158
+ } catch (error) {
159
+ const status = error instanceof Error ? Reflect.get(error, "status") : void 0;
160
+ return {
161
+ error: `The sitemap could not be read: ${reason(error)}`,
162
+ ...typeof status === "number" ? { status } : {}
163
+ };
164
+ }
165
+ const urlList = [...new Set(urls.filter(sameSite))];
166
+ if (!urlList.length) return { error: `${origin.origin}/sitemap.xml lists no URL of ${origin.host}.` };
167
+ let status = 0;
168
+ for (let start = 0; start < urlList.length; start += indexNowBatch) {
169
+ const response = await fetchImpl("https://api.indexnow.org/indexnow", {
170
+ body: JSON.stringify({
171
+ host: origin.host,
172
+ key: indexNow.key,
173
+ keyLocation: `${origin.origin}/${indexNow.key}.txt`,
174
+ urlList: urlList.slice(start, start + indexNowBatch)
175
+ }),
176
+ headers: { "content-type": "application/json; charset=utf-8" },
177
+ method: "POST",
178
+ signal: AbortSignal.timeout(checkTimeoutMs)
179
+ }).catch((error) => error instanceof Error ? error : new Error(String(error)));
180
+ if (response instanceof Error) return { error: `IndexNow did not answer: ${reason(response)}` };
181
+ await response.body?.cancel();
182
+ status = response.status;
183
+ if (status === 403) return {
184
+ error: `IndexNow did not find the key file at ${origin.origin}/${indexNow.key}.txt.`,
185
+ status
186
+ };
187
+ if (!response.ok) return {
188
+ error: `IndexNow answered ${status}.`,
189
+ status
190
+ };
191
+ }
192
+ return {
193
+ status,
194
+ submitted: urlList.length
195
+ };
196
+ }
197
+ //#endregion
198
+ //#region src/setup/deploy/checkouts.ts
199
+ /** The lock file of `vitehub pull` and `vitehub push`, at the project root. */
200
+ const lockFile = "vitehub.lock";
201
+ function isCheckoutModule(value) {
202
+ return Object(value) === value && typeof Reflect.get(Object(value), "localCheckoutStatus") === "function" && typeof Reflect.get(Object(value), "pullWorkspaces") === "function" && typeof Reflect.get(Object(value), "pushWorkspaces") === "function";
203
+ }
204
+ /** The checkout module of the Workspace package. */
205
+ const checkoutSpecifiers = ["@vite-hub/workspace/checkout", "vite-hub/workspace/checkout"];
206
+ /** True when `specifier` itself does not resolve: the package is not installed, or it has no `./checkout` export. */
207
+ function isNotInstalled(error, specifier) {
208
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
209
+ if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED") return true;
210
+ return code === "MODULE_NOT_FOUND" && error instanceof Error && error.message.includes(`'${specifier}'`);
211
+ }
212
+ /**
213
+ * The checkout module of the Workspace package that the project installs. Undefined only when no specifier resolves.
214
+ * A module that resolves but does not load stops the deploy, because a silent skip would deploy without the push.
215
+ */
216
+ async function importCheckoutModule(root) {
217
+ const require = createRequire(join(root, "package.json"));
218
+ for (const specifier of checkoutSpecifiers) {
219
+ let file;
220
+ try {
221
+ file = require.resolve(specifier);
222
+ } catch (error) {
223
+ if (isNotInstalled(error, specifier)) continue;
224
+ throw moduleFailure(specifier, specifier, error);
225
+ }
226
+ let module;
227
+ try {
228
+ module = await import(pathToFileURL(file).href);
229
+ } catch (error) {
230
+ throw moduleFailure(specifier, file, error);
231
+ }
232
+ if (!isCheckoutModule(module)) throw moduleFailure(specifier, file, /* @__PURE__ */ new TypeError("It does not export localCheckoutStatus, pullWorkspaces and pushWorkspaces."));
233
+ return module;
234
+ }
235
+ }
236
+ function moduleFailure(specifier, file, error) {
237
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
238
+ return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CHECKOUT_MODULE_FAILED({
239
+ file,
240
+ message,
241
+ specifier
242
+ }), setupExitCodes.error);
243
+ }
244
+ /**
245
+ * True when `vitehub.lock` lists at least one checkout folder. False without a lock. A lock that is not JSON, such as
246
+ * one with a Git conflict, counts, so the checkout module reports it.
247
+ */
248
+ async function lockHasCheckouts(root) {
249
+ let source;
250
+ try {
251
+ source = await readFile(join(root, lockFile), "utf8");
252
+ } catch (error) {
253
+ if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return false;
254
+ throw error;
255
+ }
256
+ let lock;
257
+ try {
258
+ lock = JSON.parse(source);
259
+ } catch {
260
+ return true;
261
+ }
262
+ const workspaces = Object(lock) === lock ? Reflect.get(Object(lock), "workspaces") : void 0;
263
+ return Object(workspaces) === workspaces && Object.keys(Object(workspaces)).length > 0;
264
+ }
265
+ /**
266
+ * Pulls the checkout folders of `vitehub.lock` before the build. Undefined when the project has no lock file,
267
+ * no checkout, or no Workspace package to read them: then deploy does not push. Without a checkout, deploy does not
268
+ * load the Workspace package. Without the package, a lock with checkouts gets one warning on `stderr`. Throws when the
269
+ * package does not load, the pull fails, or a checkout has an open conflict before or after the pull.
270
+ */
271
+ async function prepareDeployCheckouts(root, context) {
272
+ if (!await lockHasCheckouts(root)) return void 0;
273
+ const module = await importCheckoutModule(root);
274
+ if (!module) {
275
+ context.stderr.write("[vitehub] vitehub.lock has checkout folders, but the deploy does not push them because the Workspace package is not installed. Install @vite-hub/workspace or vite-hub.\n");
276
+ return;
277
+ }
278
+ const statuses = await module.localCheckoutStatus(root);
279
+ if (!statuses?.length) return void 0;
280
+ assertNoConflicts(statuses);
281
+ const before = await readLock(root);
282
+ const pulled = await module.pullWorkspaces(checkoutContext(root, context));
283
+ assertNoConflicts(await module.localCheckoutStatus(root) ?? []);
284
+ return {
285
+ before,
286
+ module,
287
+ pulls: new Map(pulled.map((result) => [result.workspace, result])),
288
+ root,
289
+ statuses
290
+ };
291
+ }
292
+ function assertNoConflicts(statuses) {
293
+ const conflicts = statuses.flatMap((status) => status.local.conflicted.map((path) => `${status.dir}/${path}`));
294
+ if (conflicts.length) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CHECKOUT_CONFLICT({ files: conflicts.join(", ") }), setupExitCodes.error);
295
+ }
296
+ async function readLock(root) {
297
+ return await readFile(join(root, lockFile), "utf8").catch(() => void 0);
298
+ }
299
+ function checkoutContext(root, context) {
300
+ const call = async (operation, input, remote) => await callOperationFromCli({
301
+ env: context.env,
302
+ ...context.fetch ? { fetch: context.fetch } : {},
303
+ rootDir: root,
304
+ timeout: 12e4,
305
+ ...remote ? { url: remote } : {}
306
+ }, operation, input);
307
+ return {
308
+ call,
309
+ rootDir: root
310
+ };
311
+ }
312
+ /**
313
+ * Pushes every checkout folder, as `vitehub push` does. The `remote` of each lock entry decides where it goes. Returns
314
+ * the results and the files changed since the pre-build pull: `vitehub.lock`, and the files that either pull wrote.
315
+ */
316
+ async function pushDeployCheckouts(checkouts, context) {
317
+ const results = (await checkouts.module.pushWorkspaces(checkoutContext(checkouts.root, context))).map((result) => {
318
+ const before = checkouts.pulls.get(result.workspace);
319
+ return before ? {
320
+ ...result,
321
+ pull: {
322
+ ...result.pull,
323
+ files: [...before.files, ...result.pull.files],
324
+ from: before.from
325
+ }
326
+ } : result;
327
+ });
328
+ const dirs = new Map(checkouts.statuses.map((status) => [status.workspace, status.dir]));
329
+ const pulled = results.flatMap((result) => [...result.pull.files, ...result.after?.files ?? []].filter((file) => file.action !== "kept").map((file) => `${dirs.get(result.workspace) ?? result.workspace}/${file.path}`));
330
+ return {
331
+ changed: [.../* @__PURE__ */ new Set([...checkouts.before === await readLock(checkouts.root) ? [] : [lockFile], ...pulled])],
332
+ results
333
+ };
334
+ }
335
+ /** The code, message, and fix of a failed push, as `vitehub push --json` prints them. */
336
+ function checkoutPushError(error) {
337
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
338
+ const fix = error instanceof Error ? Reflect.get(error, "fix") : void 0;
339
+ return {
340
+ code: typeof code === "string" ? code : "WORKSPACE_CHECKOUT_FAILED",
341
+ message: error instanceof Error ? error.message : String(error),
342
+ ...typeof fix === "string" ? { fix } : {}
343
+ };
344
+ }
345
+ function formatPull(result, workspace) {
346
+ if (result.from === result.head && !result.files.length) return "";
347
+ const lines = [`${workspace}: pulled ${result.ref} ${result.from ?? "(empty)"} -> ${result.head ?? "(empty)"}`];
348
+ for (const file of result.files) lines.push(` ${file.action.padEnd(8)} ${file.path}${file.note ? `\n ${file.note}` : ""}`);
349
+ return `${lines.join("\n")}\n`;
350
+ }
351
+ /** The text of `vitehub push`, then the files to commit. */
352
+ function formatDeployCheckouts(pushed) {
353
+ const text = pushed.results.map((result) => {
354
+ const pulled = formatPull(result.pull, result.workspace);
355
+ if (!result.revision) return `${pulled}${result.workspace}: nothing to push.\n`;
356
+ return `${pulled}${result.workspace}: pushed ${result.pushed.length} ${result.pushed.length === 1 ? "file" : "files"} to ${result.ref} (${result.revision})\n${result.pushed.map((path) => ` ${path}`).join("\n")}\n${result.after ? formatPull(result.after, result.workspace) : ""}`;
357
+ }).join("");
358
+ if (!pushed.changed.length) return text;
359
+ return `${text}The push changed these files. Commit them:\n${pushed.changed.map((path) => ` ${path}`).join("\n")}\n`;
360
+ }
361
+ //#endregion
362
+ //#region src/setup/deployments.ts
363
+ const usage$1 = "vitehub deployments [--host <host>] [--limit <n>] [--json]";
364
+ const listers = {
365
+ cloudflare: listCloudflareDeployments,
366
+ deno: listDenoDeployments,
367
+ netlify: listNetlifyDeployments,
368
+ vercel: listVercelDeployments
369
+ };
370
+ /** How long `vitehub deployments` waits for the host. */
371
+ const DEPLOYMENTS_TIMEOUT_MS = 3e4;
372
+ /** How long `vitehub status` waits for the host before it reports `liveReason: "timeout"`. */
373
+ const STATUS_HOST_TIMEOUT_MS = 5e3;
374
+ /** A fetch that gives up after `ms`, so a slow host cannot hold the command. */
375
+ function fetchWithTimeout(fetchImpl, ms, signal) {
376
+ return async (input, init) => {
377
+ signal?.throwIfAborted();
378
+ return await fetchImpl(input, {
379
+ ...init,
380
+ signal: signal ?? AbortSignal.timeout(ms)
381
+ });
382
+ };
383
+ }
384
+ function deploymentsContext(root, link, credentials, context, run, timeoutMs, signal) {
385
+ return {
386
+ credentials,
387
+ env: context.env,
388
+ fetch: fetchWithTimeout(context.fetch ?? globalThis.fetch, timeoutMs, signal),
389
+ link,
390
+ root,
391
+ run: signal ? (command, args, options) => run(command, args, {
392
+ ...options,
393
+ signal
394
+ }) : run,
395
+ timeoutMs
396
+ };
397
+ }
398
+ function readLimit(value) {
399
+ if (value === void 0) return 10;
400
+ const limit = Number(value);
401
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --limit must be a whole number from 1 to 100, not ${JSON.stringify(value)}. Usage: ${usage$1}` });
402
+ return limit;
403
+ }
404
+ function readDeploymentsArgs(args) {
405
+ try {
406
+ const { values } = parseArgs({
407
+ args: [...args],
408
+ options: {
409
+ help: {
410
+ short: "h",
411
+ type: "boolean",
412
+ default: false
413
+ },
414
+ host: { type: "string" },
415
+ json: {
416
+ type: "boolean",
417
+ default: false
418
+ },
419
+ limit: { type: "string" }
420
+ },
421
+ strict: true
422
+ });
423
+ return {
424
+ help: values.help,
425
+ host: readLinkHostOption(values.host),
426
+ json: values.json,
427
+ limit: readLimit(values.limit)
428
+ };
429
+ } catch (error) {
430
+ if (isSetupFailure(error) || error instanceof Error && "why" in error) throw error;
431
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage$1}` });
432
+ }
433
+ }
434
+ function shortCommit(commit) {
435
+ return commit ? `${commit.sha.slice(0, 7)}${commit.dirty ? " (dirty)" : ""}` : "-";
436
+ }
437
+ function writeDeployments(output, context) {
438
+ if (!output.deployments.length) {
439
+ context.stdout.write(`${output.project.name} on ${output.host} has no deployments.\n`);
440
+ return;
441
+ }
442
+ context.stdout.write(`${table([[
443
+ "",
444
+ "id",
445
+ "target",
446
+ "state",
447
+ "commit",
448
+ "created",
449
+ "url"
450
+ ], ...output.deployments.map((item) => [
451
+ item.live ? "live" : "",
452
+ item.id,
453
+ item.target,
454
+ item.state,
455
+ shortCommit(item.commit),
456
+ item.createdAt,
457
+ item.url ?? "-"
458
+ ])])}\n`);
459
+ }
460
+ async function runDeployments(host, limit, json, context) {
461
+ const project = await readSetupProject(context.rootDir, context.env);
462
+ const selected = selectSetupLink(await readSetupLinks(project.root), host);
463
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, "vitehub deployments");
464
+ const link = selected.link;
465
+ if (!link) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_NOT_LINKED({ host }), setupExitCodes.inputNeeded, {
466
+ missing: [{ field: "link" }],
467
+ rerun: host ? `vitehub link --host ${host}` : "vitehub link"
468
+ });
469
+ const credentials = await resolveHostCredentials(link.host, {
470
+ cwd: project.root,
471
+ env: context.env,
472
+ ...context.runHostCli ? { run: context.runHostCli } : {}
473
+ });
474
+ if (!credentials.ok) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_CREDENTIALS_MISSING({
475
+ fix: credentials.fix,
476
+ host: link.host
477
+ }), setupExitCodes.inputNeeded, { missing: credentials.missing.map((field) => ({ field })) });
478
+ const run = createDeployRun(context.stderr, []);
479
+ const output = {
480
+ deployments: await listers[link.host](deploymentsContext(project.root, link, credentials, context, run, DEPLOYMENTS_TIMEOUT_MS), { limit }),
481
+ host: link.host,
482
+ project: link.project
483
+ };
484
+ if (json) writeSetupJson(context, output);
485
+ else writeDeployments(output, context);
486
+ return setupExitCodes.done;
487
+ }
488
+ const deploymentsCommand = {
489
+ description: "List the deployments of the linked project, read from the host each time. Marks the one that receives production traffic. --host picks a linked host other than the default.",
490
+ name: "deployments",
491
+ run: async (args, context) => {
492
+ const json = args.includes("--json");
493
+ try {
494
+ const parsed = readDeploymentsArgs(args);
495
+ if (parsed.help) {
496
+ context.stdout.write(`Usage: ${usage$1}\n\n${deploymentsCommand.description}\n`);
497
+ return setupExitCodes.done;
498
+ }
499
+ return await runDeployments(parsed.host, parsed.limit, parsed.json, context);
500
+ } catch (error) {
501
+ return writeSetupError(context, json, error);
502
+ }
503
+ },
504
+ usage: usage$1
505
+ };
506
+ /**
507
+ * Compares the live commit with HEAD: `git rev-list --left-right --count <sha>...HEAD` prints the commits that only
508
+ * the deployment has, then the commits that only HEAD has.
509
+ */
510
+ async function compareWithHead(run, root, env, sha) {
511
+ const git = async (args) => {
512
+ try {
513
+ return await run("git", args, {
514
+ cwd: root,
515
+ env,
516
+ timeoutMs: STATUS_HOST_TIMEOUT_MS
517
+ });
518
+ } catch {
519
+ return;
520
+ }
521
+ };
522
+ const inside = await git(["rev-parse", "--is-inside-work-tree"]);
523
+ if (inside?.exitCode !== 0 || inside.stdout.trim() !== "true") return { unknownReason: "no-git" };
524
+ if ((await git([
525
+ "cat-file",
526
+ "-e",
527
+ `${sha}^{commit}`
528
+ ]))?.exitCode !== 0) return { unknownReason: "commit-not-local" };
529
+ const counts = await git([
530
+ "rev-list",
531
+ "--left-right",
532
+ "--count",
533
+ `${sha}...HEAD`
534
+ ]);
535
+ const match = counts?.exitCode === 0 ? /^(\d+)\s+(\d+)/u.exec(counts.stdout.trim()) : void 0;
536
+ if (!match) return { unknownReason: "no-git" };
537
+ return {
538
+ ahead: Number(match[1]),
539
+ behind: Number(match[2])
540
+ };
541
+ }
542
+ function isTimeout(error) {
543
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return true;
544
+ return error instanceof Error && error.cause instanceof Error && isTimeout(error.cause);
545
+ }
546
+ /**
547
+ * The deployment that receives production traffic, for `vitehub status`. It asks the host only when the project is
548
+ * linked and the credentials resolved. The signal shares status's deadline with credential discovery; standalone
549
+ * callers get `STATUS_HOST_TIMEOUT_MS`. It never throws: a failure is a `liveReason`.
550
+ */
551
+ async function readSetupLive(root, link, credentials, context, options) {
552
+ if (options.offline) return {
553
+ live: null,
554
+ liveReason: "offline"
555
+ };
556
+ if (!link) return {
557
+ live: null,
558
+ liveReason: "not-linked"
559
+ };
560
+ const signal = options.signal ?? AbortSignal.timeout(5e3);
561
+ if (signal.aborted) return {
562
+ live: null,
563
+ liveReason: "timeout"
564
+ };
565
+ if (!credentials?.ok || credentials.host !== link.host) return {
566
+ live: null,
567
+ liveReason: "no-credentials"
568
+ };
569
+ const run = createDeployRun(context.stderr, []);
570
+ try {
571
+ const deployment = (await abortable(signal, "Host deployment lookup timed out", () => listers[link.host](deploymentsContext(root, link, credentials, context, run, STATUS_HOST_TIMEOUT_MS, signal), {
572
+ includeLive: true,
573
+ limit: 10
574
+ }))).find((item) => item.live);
575
+ if (!deployment) return {
576
+ live: null,
577
+ liveReason: "no-live-deployment"
578
+ };
579
+ const base = {
580
+ deploymentId: deployment.id,
581
+ ...deployment.url ? { url: deployment.url } : {}
582
+ };
583
+ if (!deployment.commit) return {
584
+ live: {
585
+ ...base,
586
+ unknownReason: "no-marker"
587
+ },
588
+ liveReason: null
589
+ };
590
+ const commit = {
591
+ dirty: deployment.commit.dirty,
592
+ sha: deployment.commit.sha
593
+ };
594
+ return {
595
+ live: {
596
+ ...base,
597
+ commit,
598
+ ...await compareWithHead(run, root, context.env, commit.sha)
599
+ },
600
+ liveReason: null
601
+ };
602
+ } catch (error) {
603
+ return {
604
+ live: null,
605
+ liveReason: isTimeout(error) ? "timeout" : "host-error"
606
+ };
607
+ }
608
+ }
609
+ /** How long `vitehub deploy` waits for the host when it reads the deployment that a failed check rolls back to. */
610
+ const DEPLOY_PREVIOUS_TIMEOUT_MS = 1e4;
611
+ /**
612
+ * The deployment that receives production traffic now, read before `vitehub deploy` replaces it. It throws when the
613
+ * host request fails, so the caller can say why the rollback target is not known.
614
+ */
615
+ async function readLiveDeployment(root, link, credentials, context, run) {
616
+ const signal = AbortSignal.timeout(DEPLOY_PREVIOUS_TIMEOUT_MS);
617
+ return (await abortable(signal, "Host deployment lookup timed out", () => listers[link.host](deploymentsContext(root, link, credentials, context, run, DEPLOY_PREVIOUS_TIMEOUT_MS, signal), {
618
+ includeLive: true,
619
+ limit: 1
620
+ }))).find((item) => item.live);
621
+ }
622
+ const reasonLabels = {
623
+ "host-error": "unknown (the host request failed; run `vitehub deployments` for the error)",
624
+ "no-credentials": "unknown (no host credentials)",
625
+ "no-live-deployment": "none (nothing receives production traffic)",
626
+ "not-linked": "unknown (not linked)",
627
+ "offline": "not checked (--offline)",
628
+ "timeout": "unknown (the host did not answer in time)"
629
+ };
630
+ const unknownLabels = {
631
+ "commit-not-local": "commit not in this repository",
632
+ "no-git": "no git repository",
633
+ "no-marker": "no commit marker"
634
+ };
635
+ function plural(count, word) {
636
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
637
+ }
638
+ /** The `live` line of `vitehub status`, such as `abc1234 (3 commits behind)`. */
639
+ function liveLabel(status) {
640
+ const { live } = status;
641
+ if (!live) return reasonLabels[status.liveReason ?? "no-live-deployment"];
642
+ const name = live.commit ? live.commit.sha.slice(0, 7) : live.deploymentId;
643
+ const notes = [];
644
+ if (live.unknownReason) notes.push(unknownLabels[live.unknownReason]);
645
+ else if (live.ahead || live.behind) notes.push([live.behind ? `${plural(live.behind, "commit")} behind` : "", live.ahead ? `${plural(live.ahead, "commit")} ahead` : ""].filter(Boolean).join(", "));
646
+ else notes.push("up to date");
647
+ if (live.commit?.dirty) notes.push("with uncommitted changes");
648
+ return `${name} (${notes.join(", ")})${live.url ? ` ${live.url}` : ""}`;
649
+ }
650
+ //#endregion
651
+ //#region src/setup/deploy/provision.ts
652
+ /** A step whose recorded state declares nothing has no resource to create, so deploy does not ask the host. */
653
+ function declaresResources(step, env) {
654
+ const described = step.recordedState?.({ env });
655
+ return described === void 0 || described.some((category) => category.declared.length > 0);
656
+ }
657
+ /** Says which credential the steps miss, for the reason of SETUP_DEPLOY_PROVISION_UNCHECKED. */
658
+ function missingCredential(host, env) {
659
+ if (host === "cloudflare" && !env.CLOUDFLARE_ACCOUNT_ID?.trim()) return "Set CLOUDFLARE_ACCOUNT_ID, or run `vitehub link --host cloudflare --account <id>`. A `wrangler login` with several accounts does not say which one to use.";
660
+ if (host === "vercel" && !env.VERCEL_TOKEN?.trim()) return "A saved `vercel login` cannot create Vercel resources. Set VERCEL_TOKEN to a token from https://vercel.com/account/tokens.";
661
+ if (host === "vercel" && !env.VERCEL_PROJECT_ID?.trim()) return "Run `vitehub link --host vercel` to store the project id, or set VERCEL_PROJECT_ID.";
662
+ return "Fix the cause of the warnings.";
663
+ }
664
+ async function confirmProvision(count, host) {
665
+ const terminal = createInterface({
666
+ input: process.stdin,
667
+ output: process.stderr
668
+ });
669
+ try {
670
+ return /^y(?:es)?$/iu.test((await terminal.question(`Create or change ${count} ${count === 1 ? "resource" : "resources"} on ${host}? [y/N] `)).trim());
671
+ } finally {
672
+ terminal.close();
673
+ }
674
+ }
675
+ /**
676
+ * Runs the Provision Steps of `host` before the build, with the credentials that deploy resolved, such as a
677
+ * `wrangler login`. It creates missing resources and records their ids in `.vitehub/provision.json`, so the build
678
+ * binds them and a second deploy creates nothing. Returns undefined when the host has no step with a resource.
679
+ */
680
+ async function provisionForDeploy(input, context) {
681
+ const { host } = input;
682
+ if (!isProvisionHost(host) || !context.loadProvision) return;
683
+ const env = provisionEnv(context.env, input.credentials, {
684
+ ...input.link?.account?.id ? { accountId: input.link.account.id } : {},
685
+ ...input.link?.project.id ? { projectId: input.link.project.id } : {}
686
+ });
687
+ const loaded = await context.loadProvision(host);
688
+ const steps = loaded.steps.filter((step) => step.provider === host && declaresResources(step, env));
689
+ if (!steps.length) return;
690
+ const root = loaded.rootDir;
691
+ await readProvisionState(root);
692
+ const plan = await planProvisionSteps(host, steps, {
693
+ env,
694
+ fetch: context.fetch ?? globalThis.fetch,
695
+ logger: {
696
+ log: (message) => context.stderr.write(`${message}\n`),
697
+ warn: (message) => context.stderr.write(`${message}\n`)
698
+ }
699
+ });
700
+ if (!plan.checked) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PROVISION_UNCHECKED({
701
+ host,
702
+ missing: missingCredential(host, env),
703
+ warnings: plan.warnings.join(" ")
704
+ }), setupExitCodes.inputNeeded, { rerun: input.rerun });
705
+ const changes = plan.actions.flatMap((planned) => {
706
+ const status = provisionActionStatus(planned);
707
+ return status === "exists" ? [] : [{
708
+ planned,
709
+ status
710
+ }];
711
+ });
712
+ if (changes.length && !input.build) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PROVISION_NEEDS_BUILD({
713
+ count: changes.length,
714
+ host
715
+ }), setupExitCodes.conflict);
716
+ if (changes.length) {
717
+ if (!input.json) {
718
+ context.stdout.write(`Provision on ${host}:\n`);
719
+ writeProvisionActions(changes.map((change) => change.planned), context.stdout);
720
+ }
721
+ if (!input.yes && !await confirmProvision(changes.length, host)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The resources were not confirmed. Nothing was created or deployed." }), setupExitCodes.error);
722
+ }
723
+ let state = {};
724
+ try {
725
+ for (const { action } of plan.actions) {
726
+ const result = await action.apply();
727
+ if (result.ids) state = mergeProvisionState(state, result.ids);
728
+ }
729
+ } finally {
730
+ if (Object.keys(state).length) await writeProvisionState(root, state);
731
+ }
732
+ if (changes.length && !input.json) context.stdout.write(`Provisioned ${changes.length} ${changes.length === 1 ? "resource" : "resources"} on ${host}. Ids are in ${PROVISION_STATE_FILE}.\n`);
733
+ return {
734
+ changed: changes.map(({ planned, status }) => ({
735
+ kind: planned.action.kind,
736
+ name: planned.action.name,
737
+ status,
738
+ step: planned.step
739
+ })),
740
+ ids: state[host] ?? {}
741
+ };
742
+ }
743
+ //#endregion
744
+ //#region src/setup/deploy.ts
745
+ var deploy_exports = /* @__PURE__ */ __exportAll({
746
+ deployCommand: () => deployCommand,
747
+ readDeployArgs: () => readDeployArgs,
748
+ resolveDefaultDeployTarget: () => resolveDefaultDeployTarget
749
+ });
750
+ const deployHosts = [
751
+ "cloudflare",
752
+ "vercel",
753
+ "netlify",
754
+ "deno"
755
+ ];
756
+ const temporaryHosts = ["cloudflare", "vercel"];
757
+ const usage = "vitehub deploy [--host <host>] [--preview] [--push-env] [--no-build] [--no-provision] [--no-push] [--no-check] [--no-index-now] [--temporary] [--yes] [--json]";
758
+ const help = `--host picks a host target of .vitehub/link.json. Without it, deploy uses the default target. The build runs
759
+ with VITEHUB_HOST set to that host, which wins over \`host\` in vitehub(). Each host has its own resources, such as D1,
760
+ KV, R2, and libSQL.
761
+
762
+ On Cloudflare and Vercel, deploy first creates the missing resources of the app, such as D1, KV, R2, Queues, and Vercel
763
+ Blob, with the same login, and records their ids in .vitehub/provision.json. The build binds those ids, and a second
764
+ deploy creates nothing. It lists what it creates and asks first, unless you pass --yes. --no-provision skips it.
765
+
766
+ With checkout folders in vitehub.lock, a production deploy pulls them and checks for conflicts before the build, and
767
+ pushes them after the deploy, as \`vitehub push\` does. A --preview deploy does not push, so a preview never writes
768
+ the shared Workspace ref. --no-push skips the pull, the check and the push.
769
+
770
+ After the build, deploy checks the env names that the build lists. A production deploy reads stage production, a
771
+ --preview deploy stage preview: the shell, then .env.<stage> files. Each required name must be on the host or have a
772
+ local value, or nothing is deployed. Deploy sets the names that the host lacks from their local values; --push-env
773
+ also replaces the names that the host has. Cloudflare gets the values with the new version through --secrets-file.
774
+ Cloudflare always re-supplies local stage values and needs a local value for every existing Worker secret, so an
775
+ omitted secret cannot inherit from another stage. With --yes, a missing VITEHUB_SECRET is generated and set.
776
+
777
+ After the upload, deploy requests the paths of \`deploy.check\` in vitehub(), and the health route with \`health\`, on
778
+ the deployed URL. When one does not answer with a 2xx status, deploy exits with 1 and prints the command that rolls
779
+ production back to the deployment it replaced. --no-check skips the checks. With \`deploy.indexNow\`, a production
780
+ deploy that passed its checks then sends the URLs of /sitemap.xml to IndexNow. --no-index-now skips it.
781
+ `;
782
+ function readDeployArgs(args) {
783
+ try {
784
+ const { values } = parseArgs({
785
+ args: [...args],
786
+ options: {
787
+ "help": {
788
+ short: "h",
789
+ type: "boolean",
790
+ default: false
791
+ },
792
+ "host": { type: "string" },
793
+ "json": {
794
+ type: "boolean",
795
+ default: false
796
+ },
797
+ "no-build": {
798
+ type: "boolean",
799
+ default: false
800
+ },
801
+ "no-check": {
802
+ type: "boolean",
803
+ default: false
804
+ },
805
+ "no-index-now": {
806
+ type: "boolean",
807
+ default: false
808
+ },
809
+ "no-provision": {
810
+ type: "boolean",
811
+ default: false
812
+ },
813
+ "no-push": {
814
+ type: "boolean",
815
+ default: false
816
+ },
817
+ "preview": {
818
+ type: "boolean",
819
+ default: false
820
+ },
821
+ "push-env": {
822
+ type: "boolean",
823
+ default: false
824
+ },
825
+ "temporary": {
826
+ type: "boolean",
827
+ default: false
828
+ },
829
+ "yes": {
830
+ short: "y",
831
+ type: "boolean",
832
+ default: false
833
+ }
834
+ },
835
+ strict: true
836
+ });
837
+ return {
838
+ build: !values["no-build"],
839
+ check: !values["no-check"],
840
+ help: values.help,
841
+ indexNow: !values["no-index-now"],
842
+ ...values.host === void 0 ? {} : { host: values.host },
843
+ json: values.json,
844
+ preview: values.preview,
845
+ pushEnv: values["push-env"],
846
+ provision: !values["no-provision"],
847
+ push: !values["no-push"],
848
+ temporary: values.temporary,
849
+ yes: values.yes
850
+ };
851
+ } catch (error) {
852
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
853
+ }
854
+ }
855
+ function rerunCommand(args, extra = {}) {
856
+ return [
857
+ "vitehub deploy",
858
+ ...args.host ? [`--host ${args.host}`] : [],
859
+ ...args.preview ? ["--preview"] : [],
860
+ ...args.pushEnv ? ["--push-env"] : [],
861
+ ...args.build ? [] : ["--no-build"],
862
+ ...args.provision && extra.provision !== false ? [] : ["--no-provision"],
863
+ ...args.push ? [] : ["--no-push"],
864
+ ...args.check ? [] : ["--no-check"],
865
+ ...args.indexNow ? [] : ["--no-index-now"],
866
+ ...args.temporary || extra.temporary ? ["--temporary"] : [],
867
+ "--yes",
868
+ ...args.json ? ["--json"] : []
869
+ ].join(" ");
870
+ }
871
+ function supportedHost(host) {
872
+ const found = deployHosts.find((item) => item === host);
873
+ if (!found) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_HOST_UNSUPPORTED({ host }), setupExitCodes.conflict);
874
+ return found;
875
+ }
876
+ /**
877
+ * The host that `vitehub deploy` picks without `--host`: the default target, else the only target, else the config host.
878
+ * `vitehub provision` resolves its host the same way.
879
+ */
880
+ async function resolveDefaultDeployTarget(root, env, command) {
881
+ const project = await readSetupProject(root, env);
882
+ const selected = selectSetupLink(await readSetupLinks(project.root));
883
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, command);
884
+ return {
885
+ host: selected.link?.host ?? setupStatus(project, env).host.name,
886
+ link: selected.link
887
+ };
888
+ }
889
+ /** `--host`, else the default target, else the only target, else the config host. The CLI host wins over the config. */
890
+ function deployTarget(project, links, option, env) {
891
+ if (option !== void 0) {
892
+ const named = hostFromNitroPreset(option);
893
+ if (!named) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown host ${JSON.stringify(option)}. Use cloudflare, vercel, netlify, or deno. Usage: ${usage}` });
894
+ const host = supportedHost(named);
895
+ return {
896
+ host,
897
+ link: links.targets.find((target) => target.host === host)
898
+ };
899
+ }
900
+ const selected = selectSetupLink(links);
901
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, "vitehub deploy");
902
+ if (selected.link) return {
903
+ host: selected.link.host,
904
+ link: selected.link
905
+ };
906
+ return {
907
+ host: supportedHost(setupStatus(project, env).host.name),
908
+ link: void 0
909
+ };
910
+ }
911
+ function temporaryUnsupported(reason) {
912
+ return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_TEMPORARY_UNSUPPORTED({ reason }), setupExitCodes.conflict);
913
+ }
914
+ /** Cloudflare: Wrangler refuses `--temporary` with a login. Vercel: the CLI refuses it in CI and in a linked folder. */
915
+ function assertTemporary(host, args, credentials, project, env) {
916
+ if (!temporaryHosts.includes(host)) throw temporaryUnsupported(`${host} has no temporary deploy. Only cloudflare and vercel have one.`);
917
+ if (args.preview) throw temporaryUnsupported("A temporary deploy always goes to production, so --preview does not apply.");
918
+ if (credentials.ok) throw temporaryUnsupported(`It is for a machine without a ${host} login, and credentials were found (${credentials.source}).`);
919
+ if (host === "vercel") {
920
+ if (env.CI && env.CI !== "0" && env.CI !== "false") throw temporaryUnsupported("The Vercel CLI refuses temporary deploys in CI.");
921
+ if (existsSync(join(project.root, ".vercel", "project.json"))) throw temporaryUnsupported("The folder is linked to a Vercel project in .vercel/project.json.");
922
+ }
923
+ }
924
+ function credentialsMissing(host, credentials, args) {
925
+ const temporary = temporaryHosts.includes(host);
926
+ const offer = temporary ? ` Or deploy without an account: run \`${rerunCommand(args, { temporary: true })}\`${host === "cloudflare" ? " and claim the Worker within 60 minutes" : " and claim the deployment with the link that it prints"}.` : "";
927
+ return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CREDENTIALS_MISSING({
928
+ fix: `${credentials.fix}${offer}`,
929
+ host
930
+ }), setupExitCodes.inputNeeded, {
931
+ missing: credentials.missing.map((field) => ({ field })),
932
+ ...temporary ? { rerun: rerunCommand(args, { temporary: true }) } : {}
933
+ });
934
+ }
935
+ async function confirmDeploy(name, host, preview) {
936
+ const terminal = createInterface({
937
+ input: process.stdin,
938
+ output: process.stderr
939
+ });
940
+ try {
941
+ return /^y(?:es)?$/iu.test((await terminal.question(`Deploy ${name} to ${host}${preview ? " as a preview" : " production"}? [y/N] `)).trim());
942
+ } finally {
943
+ terminal.close();
944
+ }
945
+ }
946
+ async function hostAdapter(host, context) {
947
+ switch (host) {
948
+ case "cloudflare": return await cloudflareAdapter(context);
949
+ case "vercel": return vercelAdapter(context);
950
+ case "netlify": return netlifyAdapter(context);
951
+ case "deno": return await denoAdapter(context, denoOrganization(context.link, context.env));
952
+ }
953
+ }
954
+ /** Records the host project after a first deploy, so `status` finds it. It stays unverified until `vitehub link`. */
955
+ async function recordLink(root, host, result, fallbackName) {
956
+ const project = result.project ?? { name: fallbackName };
957
+ await addSetupLink(root, {
958
+ host,
959
+ ...project.accountId ? { account: { id: project.accountId } } : {},
960
+ project: {
961
+ ...project.id ? { id: project.id } : {},
962
+ name: project.name
963
+ },
964
+ verified: false,
965
+ linkedAt: (/* @__PURE__ */ new Date()).toISOString()
966
+ });
967
+ await ensureViteHubGitignore(root);
968
+ }
969
+ function writeDeployed(output, name, context) {
970
+ context.stdout.write(`Deployed ${name} to ${output.host}: ${output.url}\n`);
971
+ if (output.deploymentId) context.stdout.write(`Deployment: ${output.deploymentId}\n`);
972
+ if (output.version) context.stdout.write(`Version: ${output.version}\n`);
973
+ if (output.commit) context.stdout.write(`Commit: ${output.commit.sha}${output.commit.dirty ? " (with uncommitted changes)" : ""}\n`);
974
+ for (const check of output.checks ?? []) context.stdout.write(`Checked ${check.path}: ${check.status ?? check.error}\n`);
975
+ if (output.temporary) {
976
+ const window = output.host === "cloudflare" ? "within 60 minutes" : output.temporary.expiresAt ? `before ${output.temporary.expiresAt}` : "soon";
977
+ context.stdout.write(`This is a temporary deploy. Claim it ${window}, or the host deletes it. Do not share the claim link:\n${output.temporary.claimUrl}\n`);
978
+ }
979
+ }
980
+ /** Pushes the checkout folders after the deploy. A failed push does not undo the deploy, so it exits with 1 and says so. */
981
+ async function pushCheckouts(checkouts, deployed, args, context) {
982
+ try {
983
+ const pushed = await pushDeployCheckouts(checkouts, context);
984
+ if (!args.json) context.stdout.write(formatDeployCheckouts(pushed));
985
+ return {
986
+ ...deployed,
987
+ checkouts: pushed
988
+ };
989
+ } catch (error) {
990
+ const failure = checkoutPushError(error);
991
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PUSH_FAILED({
992
+ fix: failure.fix,
993
+ message: `${failure.code}: ${failure.message}`,
994
+ url: deployed.url
995
+ }), setupExitCodes.error, {
996
+ data: {
997
+ ...deployed,
998
+ checkouts: { error: failure }
999
+ },
1000
+ rerun: "vitehub push"
1001
+ });
1002
+ }
1003
+ }
1004
+ async function runDeploy(args, context) {
1005
+ const project = await readSetupProject(context.rootDir, context.env);
1006
+ const links = await readSetupLinks(project.root);
1007
+ const { host, link } = deployTarget(project, links, args.host, context.env);
1008
+ if (args.preview && host === "deno") throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PREVIEW_UNSUPPORTED({ host }), setupExitCodes.conflict);
1009
+ const credentials = await resolveHostCredentials(host, {
1010
+ cwd: project.root,
1011
+ env: context.env,
1012
+ ...context.runHostCli ? { run: context.runHostCli } : {}
1013
+ });
1014
+ const vercelLogin = host === "vercel" && !credentials.ok && await hasVercelLogin(project.root, context);
1015
+ if (args.temporary && vercelLogin) throw temporaryUnsupported("It is for a machine without a vercel login, and a saved CLI login was found.");
1016
+ if (args.temporary) assertTemporary(host, args, credentials, project, context.env);
1017
+ else if (!credentials.ok && !vercelLogin) throw credentialsMissing(host, credentials, args);
1018
+ const interactive = !args.json && !!process.stdin.isTTY && !!process.stderr.isTTY;
1019
+ if (!args.yes) {
1020
+ if (!interactive) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub deploy` publishes the app and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, { rerun: rerunCommand(args) });
1021
+ if (!await confirmDeploy(link?.project.name ?? basename(project.root), host, args.preview)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The deploy was not confirmed. Nothing was deployed." }), setupExitCodes.error);
1022
+ }
1023
+ const provisioned = args.provision && !args.temporary ? await provisionForDeploy({
1024
+ build: args.build,
1025
+ credentials,
1026
+ host,
1027
+ json: args.json,
1028
+ link,
1029
+ rerun: rerunCommand(args, { provision: false }),
1030
+ yes: args.yes
1031
+ }, context) : void 0;
1032
+ const checkouts = args.push && !args.preview ? await prepareDeployCheckouts(project.root, context) : void 0;
1033
+ if (!link && !args.temporary) writeSeparateResourcesNote(context, host, links);
1034
+ if (args.build) await build(project, host, context);
1035
+ const output = await readBuildOutput(project.root, host);
1036
+ const projectName = link?.project.name ?? output.identityName;
1037
+ if (!projectName) throw setupFailure(cliErrorDiagnostics.SETUP_LINK_NAME_REQUIRED(), setupExitCodes.inputNeeded, {
1038
+ missing: [{ field: "project" }],
1039
+ rerun: "vitehub link --project <name>"
1040
+ });
1041
+ const secrets = credentials.ok ? [credentials.token] : [];
1042
+ const run = createDeployRun(context.stderr, secrets);
1043
+ const env = await checkDeployEnv({
1044
+ context,
1045
+ entries: output.env,
1046
+ envDir: output.envDir,
1047
+ host,
1048
+ interactive,
1049
+ link: args.temporary ? void 0 : link,
1050
+ outputDir: output.outputDir,
1051
+ preview: args.preview,
1052
+ pushEnv: args.pushEnv,
1053
+ root: project.root,
1054
+ run,
1055
+ secrets,
1056
+ yes: args.yes
1057
+ });
1058
+ const deployContext = {
1059
+ commit: await readDeployCommit(run, project.root, context.env),
1060
+ credentials,
1061
+ env: context.env,
1062
+ fetch: context.fetch ?? globalThis.fetch,
1063
+ link,
1064
+ outputDir: output.outputDir,
1065
+ preview: args.preview,
1066
+ projectName,
1067
+ root: project.root,
1068
+ run,
1069
+ secrets,
1070
+ temporary: args.temporary,
1071
+ upload: env.upload
1072
+ };
1073
+ const adapter = await hostAdapter(host, deployContext);
1074
+ await env.apply();
1075
+ const checkPaths = args.check ? output.deploy.check : [];
1076
+ const previous = checkPaths.length && !args.preview && !args.temporary ? await previousDeployment(project.root, link, credentials, context, run) : void 0;
1077
+ const result = await adapter.deploy();
1078
+ if (!link && !args.temporary) await recordLink(project.root, host, result, projectName);
1079
+ const checks = checkPaths.length ? await runDeployChecks(result.url, checkPaths, deployContext.fetch) : void 0;
1080
+ const deployed = {
1081
+ host,
1082
+ url: result.url,
1083
+ ...result.deploymentId ? { deploymentId: result.deploymentId } : {},
1084
+ ...result.version ? { version: result.version } : {},
1085
+ ...result.claim ? { temporary: {
1086
+ claimUrl: result.claim.url,
1087
+ ...result.claim.expiresAt ? { expiresAt: result.claim.expiresAt } : {}
1088
+ } } : {},
1089
+ ...deployContext.commit ? { commit: deployContext.commit } : {},
1090
+ env: env.output,
1091
+ ...provisioned ? { provision: provisioned } : {},
1092
+ ...checks ? { checks } : {}
1093
+ };
1094
+ if (checks?.some((check) => !check.ok)) throw checkFailed(deployed, host, previous, projectName, link, result, args.preview);
1095
+ if (!args.json) writeDeployed(deployed, projectName, context);
1096
+ const pushed = checkouts ? await pushCheckouts(checkouts, deployed, args, context) : deployed;
1097
+ const indexNow = output.deploy.indexNow && args.indexNow && !args.preview && !args.temporary ? await submitIndexNow(output.deploy.indexNow, deployContext.fetch) : void 0;
1098
+ if (indexNow && !args.json) context.stderr.write("submitted" in indexNow ? `IndexNow: sent ${indexNow.submitted} URLs (${indexNow.status}).\n` : `IndexNow: nothing was sent. ${indexNow.error} The deploy is done.\n`);
1099
+ const final = indexNow ? {
1100
+ ...pushed,
1101
+ indexNow
1102
+ } : pushed;
1103
+ if (args.json) writeSetupJson(context, final);
1104
+ return setupExitCodes.done;
1105
+ }
1106
+ /** The deployment that serves production before this deploy. Without a link or a token there is nothing to read. */
1107
+ async function previousDeployment(root, link, credentials, context, run) {
1108
+ if (!link) return { failed: "the project was not linked before this deploy." };
1109
+ if (!credentials.ok) return { failed: `deploy used the saved ${link.host} CLI login, which gives no API token.` };
1110
+ try {
1111
+ return { deployment: await readLiveDeployment(root, link, credentials, context, run) };
1112
+ } catch (error) {
1113
+ return { failed: error instanceof Error ? error.message : String(error) };
1114
+ }
1115
+ }
1116
+ /** A deployed app that failed a check. Production now serves it, so the error says how to roll back. */
1117
+ function checkFailed(deployed, host, previous, projectName, link, result, preview) {
1118
+ const rollback = preview ? { note: "This was a preview deploy, so production did not change." } : rollbackFor(host, {
1119
+ previous: previous && "deployment" in previous ? previous.deployment : void 0,
1120
+ projectName: link?.project.name ?? result.project?.name ?? projectName,
1121
+ ...previous && "failed" in previous ? { lookupFailed: previous.failed } : {},
1122
+ ...host === "netlify" && (link?.project.id ?? result.project?.id) ? { siteId: link?.project.id ?? result.project?.id } : {}
1123
+ });
1124
+ const failure = cliErrorDiagnostics.SETUP_DEPLOY_CHECK_FAILED({
1125
+ failed: formatFailedChecks(deployed.checks ?? []),
1126
+ rollback: rollback.command ? `Run \`${rollback.command}\` to put the previous deployment back on production.` : rollback.note,
1127
+ url: deployed.url
1128
+ });
1129
+ return setupFailure(failure, setupExitCodes.error, { data: {
1130
+ ...deployed,
1131
+ rollback
1132
+ } });
1133
+ }
1134
+ const deployCommand = {
1135
+ description: "Create the missing host resources, build the app for a linked host, check its env, and deploy it with your local login. --host picks the host. Pushes the checkout folders of vitehub.lock.",
1136
+ name: "deploy",
1137
+ run: async (args, context) => {
1138
+ const json = args.includes("--json");
1139
+ try {
1140
+ const parsed = readDeployArgs(args);
1141
+ if (parsed.help) {
1142
+ context.stdout.write(`Usage: ${usage}\n\n${deployCommand.description}\n\n${help}`);
1143
+ return setupExitCodes.done;
1144
+ }
1145
+ return await runDeploy(parsed, context);
1146
+ } catch (error) {
1147
+ return writeSetupError(context, json, error);
1148
+ }
1149
+ },
1150
+ usage
1151
+ };
1152
+ //#endregion
1153
+ export { deploymentsCommand as a, STATUS_HOST_TIMEOUT_MS as i, deploy_exports as n, liveLabel as o, readDeployArgs as r, readSetupLive as s, deployCommand as t };