@vite-hub/cli 0.5.1 → 0.6.0

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.
@@ -299,7 +299,7 @@ export declare function consoleOrigin(value: string): string;
299
299
  * `vitehub login` saved for the Console. Without `console`, the Console is `VITEHUB_CONSOLE_URL`, else the only saved
300
300
  * Console, else console.vitehub.dev. `undefined` when there is no key.
301
301
  */
302
- export declare function readConsoleCredential(env: NodeJS.ProcessEnv, console?: string): Promise<{
302
+ export declare function readConsoleCredential(env: NodeJS.ProcessEnv, console?: string, signal?: AbortSignal): Promise<{
303
303
  origin: string;
304
304
  token: string;
305
305
  source: "env" | "file";
@@ -543,6 +543,23 @@ type DeployCheckoutsOutput = {
543
543
  } | {
544
544
  error: CheckoutPushError;
545
545
  };
546
+ /** What `vitehub deploy --json` prints in `console` after it linked the app. */
547
+ interface DeployConsoleOutput {
548
+ /** The Console origin. */
549
+ console: string;
550
+ /** The id of the app in the Console. */
551
+ app: string;
552
+ /** The Console page of the app. */
553
+ url: string;
554
+ /** True when this deploy linked the app. False when the Console had it. */
555
+ created: boolean;
556
+ /** The key variable that this deploy set on the host. Missing when the host had it. */
557
+ keySet?: string;
558
+ /** True when the app answered a signed request of the Console. */
559
+ linked: boolean;
560
+ /** Why the app did not answer, such as `401 CONSOLE_KEY_UNKNOWN: ...`. Only when `linked` is false. */
561
+ problem?: string;
562
+ }
546
563
  /** One set of names that the app reads, without its values. */
547
564
  interface EnvDiffEntry {
548
565
  names: readonly string[];
@@ -592,6 +609,8 @@ interface SetupDeployArgs {
592
609
  check: boolean;
593
610
  /** False with --no-index-now: do not send the sitemap URLs to IndexNow. */
594
611
  indexNow: boolean;
612
+ /** False with --no-console: do not link the app in the Console of the saved login. */
613
+ console: boolean;
595
614
  temporary: boolean;
596
615
  yes: boolean;
597
616
  json: boolean;
@@ -600,7 +619,8 @@ interface SetupDeployArgs {
600
619
  /** What `vitehub deploy --json` prints, after `schemaVersion: 1`. */
601
620
  interface SetupDeployOutput {
602
621
  host: DeployHost;
603
- url: string;
622
+ /** The URL that serves the new version. Missing when the host reports none, such as a Worker with only `*.example.com/*` routes. */
623
+ url?: string;
604
624
  deploymentId?: string;
605
625
  version?: string;
606
626
  temporary?: {
@@ -614,12 +634,14 @@ interface SetupDeployOutput {
614
634
  checkouts?: DeployCheckoutsOutput;
615
635
  /** The env names that the deploy checked and set. Never a value. */
616
636
  env: DeployEnvOutput;
617
- /** The `deploy.check` paths and how the deployed app answered. Missing when the build has none, or with --no-check. */
637
+ /** The `deploy.check` paths and how the deployed app answered. Missing when the build has none, with --no-check, or without `url`. */
618
638
  checks?: DeployCheckResult[];
619
639
  /** How to roll production back. Only when a check failed. */
620
640
  rollback?: DeployRollback;
621
641
  /** The IndexNow submission. Missing when the build has no `deploy.indexNow`, for a preview, and with --no-index-now. */
622
642
  indexNow?: DeployIndexNowOutput;
643
+ /** The Console link. Missing without `console: true`, without a `vitehub login`, for a preview, and with --no-console. */
644
+ console?: DeployConsoleOutput;
623
645
  }
624
646
  export declare function readDeployArgs(args: readonly string[]): SetupDeployArgs;
625
647
  export declare const deployCommand: ViteHubCliCommand;
@@ -1,9 +1,7 @@
1
- import { _ as applySetupAdd, a as updateCommand, c as planSetupRemove, d as initCommandDefinition, f as initPackages, g as addCommand, h as setupCatalog, i as readUpdateArgs, l as readRemoveArgs, m as readInitArgs, n as setupCommands, o as updateInstallArgs, p as nuxiPackage, r as planSetupUpdate, s as applySetupRemove, u as removeCommand, v as planSetupAdd, y as readAddArgs } from "../commands-C003KqWY.js";
2
- import { a as defaultConsoleUrl, c as readConsoleCredential, i as consoleUrlVariable, l as whoamiCommand, n as consoleOrigin, o as loginCommand, r as consoleTokenVariable, s as logoutCommand, t as consoleCredentialsFile } from "../console-auth-CpOpbA7U.js";
3
- import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, r as readDeployArgs, s as readSetupLive, t as deployCommand } from "../deploy-BZ2iQjZL.js";
4
- import { i as setupFailure, o as writeSetupError, r as setupExitCodes } from "../envelope-DbplCDko.js";
5
- import { F as setupStatus, H as readSetupProject, I as shellQuote, c as linkSetupProject, d as readSetupLinkStatus, f as readSetupLinks, m as unlinkSetupProject, p as selectSetupLink, r as SETUP_LINK_FILE, u as readSetupLinkState } from "../env-DRI0QH4-.js";
6
- import { m as cliErrorDiagnostics } from "../provision-DlknnTAt.js";
1
+ import { _ as applySetupAdd, a as updateCommand, c as planSetupRemove, d as initCommandDefinition, f as initPackages, g as addCommand, h as setupCatalog, i as readUpdateArgs, l as readRemoveArgs, m as readInitArgs, n as setupCommands, o as updateInstallArgs, p as nuxiPackage, r as planSetupUpdate, s as applySetupRemove, u as removeCommand, v as planSetupAdd, y as readAddArgs } from "../commands-D0WSlS7h.js";
2
+ import { B as readConsoleCredential, D as shellQuote, E as setupStatus, F as consoleTokenVariable, G as setupFailure, I as consoleUrlVariable, L as defaultConsoleUrl, N as consoleCredentialsFile, P as consoleOrigin, R as loginCommand, V as whoamiCommand, W as setupExitCodes, Y as cliErrorDiagnostics, q as writeSetupError, z as logoutCommand } from "../provision-akHsvf-B.js";
3
+ import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, r as readDeployArgs, s as readSetupLive, t as deployCommand } from "../deploy-DwNjKrHq.js";
4
+ import { L as readSetupProject, d as readSetupLinkState, f as readSetupLinkStatus, h as unlinkSetupProject, i as SETUP_LINK_FILE, l as linkSetupProject, m as selectSetupLink, p as readSetupLinks } from "../env-BiVwma4a.js";
7
5
  import { join } from "pathe";
8
6
  import { readFile } from "node:fs/promises";
9
7
  import { createHash, randomUUID } from "node:crypto";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/cli",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Command-line workflows for ViteHub projects.",
5
5
  "keywords": [
6
6
  "agent",
@@ -46,7 +46,7 @@
46
46
  "@dotenvx/primitives": "^4.4.0",
47
47
  "@noble/ciphers": "^2.4.0",
48
48
  "@noble/hashes": "^2.4.0",
49
- "@vite-hub/runtime": "0.5.1",
49
+ "@vite-hub/runtime": "0.6.0",
50
50
  "birpc": "^4.2.0",
51
51
  "diff": "^9.0.0",
52
52
  "nostics": "1.4.0",
@@ -57,7 +57,7 @@
57
57
  "devDependencies": {
58
58
  "@types/node": "^24.19.2",
59
59
  "@types/semver": "^7.8.0",
60
- "@vite-hub/forge": "0.5.1",
60
+ "@vite-hub/forge": "0.6.0",
61
61
  "@vite-hub/internal": "0.0.1",
62
62
  "nuxt": "npm:nuxt-nightly@5.0.0-2611222336-0ed8910",
63
63
  "typescript": "^6.0.3",
@@ -67,7 +67,7 @@
67
67
  "vitest": "5.1.0"
68
68
  },
69
69
  "peerDependencies": {
70
- "@vite-hub/forge": "0.5.1",
70
+ "@vite-hub/forge": "0.6.0",
71
71
  "nuxt": "^4.7.0 || >=5.0.0-0",
72
72
  "vite": ">=8.0.0"
73
73
  },
@@ -1,311 +0,0 @@
1
- import { m as cliErrorDiagnostics } from "./provision-DlknnTAt.js";
2
- import { o as writeSetupError, r as setupExitCodes, s as writeSetupJson } from "./envelope-DbplCDko.js";
3
- import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
- import { dirname, join } from "node:path";
5
- import { homedir, hostname } from "node:os";
6
- import { parseArgs } from "node:util";
7
- // src/setup/console-auth.ts
8
- /** The hosted Console. `--console` and `VITEHUB_CONSOLE_URL` name a self-hosted one. */
9
- const defaultConsoleUrl = "https://console.vitehub.dev";
10
- /** An API key for CI. It wins over the saved key, and `vitehub logout` does not remove it. */
11
- const consoleTokenVariable = "VITEHUB_CONSOLE_TOKEN";
12
- const consoleUrlVariable = "VITEHUB_CONSOLE_URL";
13
- const clientId = "vitehub-cli";
14
- /** `$XDG_CONFIG_HOME/vitehub/credentials.json`, else `~/.config/vitehub/credentials.json`. */
15
- function consoleCredentialsFile(env) {
16
- const base = env.XDG_CONFIG_HOME || join(env.HOME || env.USERPROFILE || homedir(), ".config");
17
- return join(base, "vitehub", "credentials.json");
18
- }
19
- async function readCredentials(file) {
20
- const text = await readFile(file, "utf8").catch((error) => {
21
- if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return void 0;
22
- throw error;
23
- });
24
- if (text === void 0) return {
25
- version: 1,
26
- consoles: {}
27
- };
28
- const parsed = JSON.parse(text);
29
- const consoles = parsed instanceof Object ? Reflect.get(parsed, "consoles") : void 0;
30
- return {
31
- version: 1,
32
- consoles: consoles instanceof Object ? consoles : {}
33
- };
34
- }
35
- async function writeCredentials(file, value) {
36
- await mkdir(dirname(file), {
37
- mode: 448,
38
- recursive: true
39
- });
40
- const temporary = `${file}.${process.pid}.tmp`;
41
- await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
42
- await chmod(temporary, 384);
43
- await rename(temporary, file);
44
- }
45
- /** The origin of a Console URL. Plain `http` is accepted only for a Console on this machine. */
46
- function consoleOrigin(value) {
47
- let url;
48
- try {
49
- url = new URL(value);
50
- } catch {
51
- throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be a URL, such as ${defaultConsoleUrl}. Got ${JSON.stringify(value)}.` });
52
- }
53
- const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
54
- if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be an https:// URL. Plain http:// is only for a Console on localhost. Got ${url.origin}.` });
55
- return url.origin;
56
- }
57
- /**
58
- * The key that a command sends to a Console, and where it came from: `VITEHUB_CONSOLE_TOKEN`, else the key that
59
- * `vitehub login` saved for the Console. Without `console`, the Console is `VITEHUB_CONSOLE_URL`, else the only saved
60
- * Console, else console.vitehub.dev. `undefined` when there is no key.
61
- */
62
- async function readConsoleCredential(env, console) {
63
- const file = await readCredentials(consoleCredentialsFile(env));
64
- const named = console ?? env["VITEHUB_CONSOLE_URL"];
65
- const saved = Object.keys(file.consoles);
66
- const origin = consoleOrigin(named ?? (saved.length === 1 ? saved[0] : "https://console.vitehub.dev"));
67
- const token = env[consoleTokenVariable];
68
- if (token) return {
69
- origin,
70
- source: "env",
71
- token
72
- };
73
- const credential = file.consoles[origin];
74
- return credential ? {
75
- origin,
76
- saved: credential,
77
- source: "file",
78
- token: credential.token
79
- } : void 0;
80
- }
81
- function readArgs(args, usage, extra = {}) {
82
- try {
83
- return parseArgs({
84
- args,
85
- options: {
86
- ...extra.console ? { console: { type: "string" } } : {},
87
- help: {
88
- short: "h",
89
- type: "boolean",
90
- default: false
91
- },
92
- json: {
93
- type: "boolean",
94
- default: false
95
- }
96
- },
97
- strict: true
98
- }).values;
99
- } catch (error) {
100
- throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
101
- }
102
- }
103
- async function postJson(context, url, body) {
104
- const response = await (context.fetch ?? fetch)(url, {
105
- body: JSON.stringify(body),
106
- headers: {
107
- accept: "application/json",
108
- "content-type": "application/json"
109
- },
110
- method: "POST"
111
- });
112
- const data = await response.json().catch(() => ({}));
113
- return {
114
- data: data instanceof Object ? data : {},
115
- headers: response.headers,
116
- status: response.status
117
- };
118
- }
119
- function loginFailed(origin, message) {
120
- return cliErrorDiagnostics.CLI_CONSOLE_LOGIN_FAILED({
121
- console: origin,
122
- message
123
- });
124
- }
125
- const wait = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
126
- const dateFormat = new Intl.DateTimeFormat("en-GB", {
127
- day: "numeric",
128
- month: "short",
129
- year: "numeric",
130
- timeZone: "UTC"
131
- });
132
- function groupCode(code) {
133
- return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
134
- }
135
- async function deviceLogin(origin, context, prompt) {
136
- const started = await postJson(context, `${origin}/api/auth/device/code`, {
137
- client_id: clientId,
138
- client_name: `vitehub CLI on ${hostname()}`
139
- }).catch((error) => {
140
- throw loginFailed(origin, `The Console did not answer: ${error instanceof Error ? error.message : String(error)}`);
141
- });
142
- if (started.status !== 200 || typeof started.data.device_code !== "string") throw loginFailed(origin, `The Console answered ${started.status} to the device code request${typeof started.data.error === "string" ? ` (${started.data.error})` : ""}. Is ${origin} a ViteHub Console?`);
143
- const code = started.data;
144
- prompt.write(`Open ${code.verification_uri} and enter the code ${groupCode(code.user_code)}\n`);
145
- if (code.verification_uri_complete) prompt.write(`Or open ${code.verification_uri_complete}\n`);
146
- prompt.write("Waiting for approval...\n");
147
- let interval = Number.isFinite(code.interval) ? code.interval : 5;
148
- const deadline = Date.now() + code.expires_in * 1e3;
149
- while (Date.now() < deadline) {
150
- await wait(interval);
151
- const answer = await postJson(context, `${origin}/api/auth/cli/token`, {
152
- client_id: clientId,
153
- device_code: code.device_code
154
- });
155
- if (answer.status === 200 && typeof answer.data.access_token === "string") return answer.data;
156
- if (answer.status === 429) {
157
- interval = Math.max(interval, Number(answer.headers.get("retry-after")) || 60);
158
- continue;
159
- }
160
- const error = answer.data.error;
161
- if (error === "authorization_pending") continue;
162
- if (error === "slow_down") {
163
- interval += 5;
164
- continue;
165
- }
166
- if (error === "access_denied") throw loginFailed(origin, "The sign-in was denied in the browser.");
167
- if (error === "expired_token") break;
168
- throw loginFailed(origin, `The Console answered ${answer.status}${typeof error === "string" ? ` (${error})` : ""}.`);
169
- }
170
- throw loginFailed(origin, "The code expired before anyone approved it.");
171
- }
172
- const loginUsage = "vitehub login [--console <url>] [--json]";
173
- const loginCommand = {
174
- description: `Sign in to a ViteHub Console with the device flow, and save an API key for this machine. The default Console is ${defaultConsoleUrl}; --console or ${consoleUrlVariable} names another.`,
175
- name: "login",
176
- usage: loginUsage,
177
- run: async (args, context) => {
178
- const json = args.includes("--json");
179
- try {
180
- const values = readArgs(args, loginUsage, { console: true });
181
- if (values.help) {
182
- context.stdout.write(`Usage: ${loginUsage}\n\n${loginCommand.description}\n`);
183
- return setupExitCodes.done;
184
- }
185
- const origin = consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev");
186
- const answer = await deviceLogin(origin, context, json ? context.stderr : context.stdout);
187
- const file = consoleCredentialsFile(context.env);
188
- const saved = await readCredentials(file);
189
- const credential = {
190
- expiresAt: Date.now() + answer.expires_in * 1e3,
191
- keyId: answer.key_id,
192
- team: answer.team,
193
- token: answer.access_token,
194
- user: answer.user
195
- };
196
- await writeCredentials(file, {
197
- version: 1,
198
- consoles: {
199
- ...saved.consoles,
200
- [origin]: credential
201
- }
202
- });
203
- const result = {
204
- console: origin,
205
- expiresAt: new Date(credential.expiresAt).toISOString(),
206
- file,
207
- team: credential.team,
208
- user: credential.user
209
- };
210
- if (json) writeSetupJson(context, result);
211
- else context.stdout.write(`Signed in to ${origin} as ${credential.user.name}${credential.user.email ? ` (${credential.user.email})` : ""} in team ${credential.team.name}.\nThe API key expires on ${dateFormat.format(new Date(credential.expiresAt))}. Saved in ${file}.\n`);
212
- if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is set, so commands use it instead of this key.\n`);
213
- return setupExitCodes.done;
214
- } catch (error) {
215
- return writeSetupError(context, json, error);
216
- }
217
- }
218
- };
219
- const whoamiUsage = "vitehub whoami [--console <url>] [--json]";
220
- const whoamiCommand = {
221
- description: `Show the person and the team of the Console API key: ${consoleTokenVariable}, else the key of \`vitehub login\`.`,
222
- name: "whoami",
223
- usage: whoamiUsage,
224
- run: async (args, context) => {
225
- const json = args.includes("--json");
226
- try {
227
- const values = readArgs(args, whoamiUsage, { console: true });
228
- if (values.help) {
229
- context.stdout.write(`Usage: ${whoamiUsage}\n\n${whoamiCommand.description}\n`);
230
- return setupExitCodes.done;
231
- }
232
- const credential = await readConsoleCredential(context.env, values.console);
233
- if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
234
- const response = await (context.fetch ?? fetch)(`${credential.origin}/api/whoami`, { headers: {
235
- accept: "application/json",
236
- authorization: `Bearer ${credential.token}`
237
- } });
238
- if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
239
- if (!response.ok) throw cliErrorDiagnostics.CLI_R0001({ message: `[vitehub] ${credential.origin} answered ${response.status} to /api/whoami.` });
240
- const me = await response.json();
241
- const source = credential.source === "env" ? consoleTokenVariable : consoleCredentialsFile(context.env);
242
- if (json) writeSetupJson(context, {
243
- console: credential.origin,
244
- expiresAt: new Date(me.key.expiresAt).toISOString(),
245
- projectIds: me.projectIds,
246
- roles: me.roles,
247
- source,
248
- team: me.team,
249
- user: me.user
250
- });
251
- else {
252
- context.stdout.write(`${me.user.name}${me.user.email ? ` (${me.user.email})` : ""} in team ${me.team.name} (${me.roles.join(", ")}) on ${credential.origin}\n`);
253
- context.stdout.write(`Key from ${source}, for ${me.projectIds ? `${me.projectIds.length} project${me.projectIds.length === 1 ? "" : "s"}` : "every project of the team"}, expires on ${dateFormat.format(new Date(me.key.expiresAt))}.\n`);
254
- }
255
- return setupExitCodes.done;
256
- } catch (error) {
257
- return writeSetupError(context, json, error);
258
- }
259
- }
260
- };
261
- const logoutUsage = "vitehub logout [--console <url>] [--json]";
262
- const logoutCommand = {
263
- description: "Revoke the API key of `vitehub login` on the Console and remove it from this machine.",
264
- name: "logout",
265
- usage: logoutUsage,
266
- run: async (args, context) => {
267
- const json = args.includes("--json");
268
- try {
269
- const values = readArgs(args, logoutUsage, { console: true });
270
- if (values.help) {
271
- context.stdout.write(`Usage: ${logoutUsage}\n\n${logoutCommand.description}\n`);
272
- return setupExitCodes.done;
273
- }
274
- const file = consoleCredentialsFile(context.env);
275
- const saved = await readCredentials(file);
276
- const credential = await readConsoleCredential({
277
- ...context.env,
278
- [consoleTokenVariable]: void 0
279
- }, values.console);
280
- if (!credential) {
281
- if (json) writeSetupJson(context, { removed: false });
282
- else context.stdout.write("Not signed in.\n");
283
- return setupExitCodes.done;
284
- }
285
- const response = await (context.fetch ?? fetch)(`${credential.origin}/api/api-keys/current`, {
286
- headers: { authorization: `Bearer ${credential.token}` },
287
- method: "DELETE"
288
- }).catch(() => void 0);
289
- const revoked = response !== void 0 && (response.status === 204 || response.status === 401 || response.status === 404);
290
- const { [credential.origin]: _removed, ...consoles } = saved.consoles;
291
- await writeCredentials(file, {
292
- version: 1,
293
- consoles
294
- });
295
- if (json) writeSetupJson(context, {
296
- console: credential.origin,
297
- removed: true,
298
- revoked
299
- });
300
- else {
301
- context.stdout.write(`Signed out of ${credential.origin}.\n`);
302
- if (!revoked) context.stderr.write("[vitehub] The Console did not revoke the key. Revoke it in Account settings, under API keys.\n");
303
- }
304
- if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is still set. Unset it to sign out completely.\n`);
305
- return setupExitCodes.done;
306
- } catch (error) {
307
- return writeSetupError(context, json, error);
308
- }
309
- }
310
- };
311
- export { defaultConsoleUrl as a, readConsoleCredential as c, consoleUrlVariable as i, whoamiCommand as l, consoleOrigin as n, loginCommand as o, consoleTokenVariable as r, logoutCommand as s, consoleCredentialsFile as t };
@@ -1,87 +0,0 @@
1
- import { m as cliErrorDiagnostics } from "./provision-DlknnTAt.js";
2
- import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
3
- // src/setup/envelope.ts
4
- /** Exit codes of the setup commands. */
5
- const setupExitCodes = {
6
- done: 0,
7
- error: 1,
8
- inputNeeded: 2,
9
- conflict: 3,
10
- stalePlan: 4
11
- };
12
- function isDiagnostic(error) {
13
- return error instanceof Error && typeof Reflect.get(error, "code") === "string" && typeof Reflect.get(error, "why") === "string";
14
- }
15
- function toSetupError(error) {
16
- const diagnostic = isDiagnostic(error) ? error : cliErrorDiagnostics.CLI_SETUP_FAILED({ message: error instanceof Error ? error.message : String(error) });
17
- const why = diagnostic.why.replace(/^\[vitehub\] /u, "");
18
- return {
19
- code: diagnostic.code,
20
- message: /^.*?[.!?](?=\s|$)/u.exec(why)?.[0] ?? why,
21
- why,
22
- ...diagnostic.fix ? { fix: diagnostic.fix } : {},
23
- ...diagnostic.docs ? { docs: diagnostic.docs } : {}
24
- };
25
- }
26
- /** Prints one JSON document with `schemaVersion: 1` on stdout. */
27
- function writeSetupJson(context, data) {
28
- context.stdout.write(`${JSON.stringify({
29
- schemaVersion: 1,
30
- ...data
31
- })}\n`);
32
- }
33
- /** Adds the exit code and the missing input of a setup command to its diagnostic. */
34
- function setupFailure(diagnostic, exitCode, details = {}) {
35
- return Object.assign(diagnostic, {
36
- details,
37
- exitCode
38
- });
39
- }
40
- /** Whether `error` is a diagnostic that `setupFailure()` gave an exit code. */
41
- function isSetupFailure(error) {
42
- if (!(error instanceof Error)) return false;
43
- const details = Reflect.get(error, "details");
44
- return typeof Reflect.get(error, "exitCode") === "number" && typeof details === "object" && details !== null;
45
- }
46
- function formatMissing(missing) {
47
- return missing.map((item) => {
48
- const choices = item.choices ?? [];
49
- if (choices.every((choice) => typeof choice === "string")) return `Missing: ${item.field}${choices.length ? ` (${choices.join(", ")})` : ""}\n`;
50
- return `Missing: ${item.field}\n${choices.map((choice) => typeof choice === "string" ? ` ${choice}\n` : ` ${choice.id}${choice.name ? ` ${choice.name}` : ""}\n`).join("")}`;
51
- }).join("");
52
- }
53
- /**
54
- * Reports `error` as one JSON document on stdout with `--json`, else on stderr, and returns its exit code.
55
- * A `SetupFailure` adds `missing`, `rerun`, and its `data` to the document. Any other error exits with 1.
56
- */
57
- function writeSetupError(context, json, error) {
58
- if (isSetupFailure(error)) {
59
- const { data, missing, rerun } = error.details;
60
- if (json) writeSetupJson(context, {
61
- ...data,
62
- error: toSetupError(error),
63
- ...missing ? { missing } : {},
64
- ...rerun ? { rerun } : {}
65
- });
66
- else context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n${formatMissing(missing ?? [])}${rerun ? `Run: ${rerun}\n` : ""}`);
67
- return error.exitCode;
68
- }
69
- if (json) writeSetupJson(context, { error: toSetupError(error) });
70
- else context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
71
- return setupExitCodes.error;
72
- }
73
- /** Reads `--json` and `--help`. Throws `CLI_R0003` for any other argument. */
74
- function readSetupArgs(args, usage) {
75
- const unknown = args.find((arg) => arg !== "--json" && arg !== "-h" && arg !== "--help");
76
- if (unknown !== void 0) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown argument ${JSON.stringify(unknown)}. Usage: ${usage}` });
77
- return {
78
- help: args.includes("-h") || args.includes("--help"),
79
- json: args.includes("--json")
80
- };
81
- }
82
- /** Rows as plain text columns, two spaces apart. */
83
- function table(rows) {
84
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
85
- return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()).join("\n");
86
- }
87
- export { table as a, setupFailure as i, readSetupArgs as n, writeSetupError as o, setupExitCodes as r, writeSetupJson as s, isSetupFailure as t };