@vite-hub/cli 0.7.0 → 0.9.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.
@@ -0,0 +1,271 @@
1
+ import { d as cliErrorDiagnostics } from "./provision-D0ct9RDq.js";
2
+ import { u as selectConsole } from "./console-auth-BunROd7u.js";
3
+ import { a as table, c as __exportAll, o as writeSetupError, r as setupExitCodes, s as writeSetupJson } from "./envelope-DXB-0EcA.js";
4
+ import { c as shellQuote } from "./status-HXNfm9mB.js";
5
+ import { parseArgs } from "node:util";
6
+ // src/setup/console-apps.ts
7
+ var console_apps_exports = /* @__PURE__ */ __exportAll({
8
+ appsCommand: () => appsCommand,
9
+ checkConsoleApp: () => checkConsoleApp,
10
+ checkProblem: () => checkProblem,
11
+ consoleAppUrl: () => consoleAppUrl,
12
+ consoleClient: () => consoleClient,
13
+ linkConsoleApp: () => linkConsoleApp,
14
+ listConsoleApps: () => listConsoleApps,
15
+ openConsole: () => openConsole
16
+ });
17
+ /**
18
+ * The Console of `--console`, else `VITEHUB_CONSOLE_URL`, else `console.url` in the app config, else the only saved
19
+ * Console, else console.vitehub.dev.
20
+ */
21
+ async function openConsole(context, console) {
22
+ const { origin, credential } = await selectConsole(context, console);
23
+ if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: origin });
24
+ return consoleClient(context, credential);
25
+ }
26
+ function consoleClient(context, credential, signal) {
27
+ return {
28
+ origin: credential.origin,
29
+ async request(path, init = {}) {
30
+ const response = await (context.fetch ?? fetch)(`${credential.origin}${path}`, {
31
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
32
+ headers: {
33
+ accept: "application/json",
34
+ authorization: `Bearer ${credential.token}`,
35
+ ...init.body === void 0 ? {} : { "content-type": "application/json" }
36
+ },
37
+ method: init.method ?? "GET",
38
+ ...signal ? {
39
+ redirect: "error",
40
+ signal
41
+ } : {}
42
+ }).catch((error) => {
43
+ throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
44
+ code: "FETCH_FAILED",
45
+ console: credential.origin,
46
+ message: `The Console did not answer ${path}: ${error instanceof Error ? error.message : String(error)}`
47
+ });
48
+ });
49
+ if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
50
+ const body = response.status === 204 ? {} : await response.json().catch(() => ({}));
51
+ const record = body instanceof Object ? body : {};
52
+ if (!response.ok) throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
53
+ code: typeof record.code === "string" ? record.code : String(response.status),
54
+ console: credential.origin,
55
+ ...typeof record.fix === "string" ? { fix: record.fix } : {},
56
+ message: typeof record.message === "string" ? record.message : `${credential.origin} answered ${response.status} to ${path}.`
57
+ });
58
+ return {
59
+ body: record,
60
+ status: response.status
61
+ };
62
+ }
63
+ };
64
+ }
65
+ /** The apps of the team of the key. */
66
+ async function listConsoleApps(client) {
67
+ const { body } = await client.request("/api/projects");
68
+ return Array.isArray(body.projects) ? body.projects : [];
69
+ }
70
+ /** Link an app, or register a site with `kind: "site"`. Linking a URL again returns the same link with `created: false`. */
71
+ async function linkConsoleApp(client, input) {
72
+ const { body, status } = await client.request("/api/projects", {
73
+ body: input,
74
+ method: "POST"
75
+ });
76
+ return {
77
+ app: body.project,
78
+ created: status === 201
79
+ };
80
+ }
81
+ async function checkConsoleApp(client, id) {
82
+ const { body } = await client.request(`/api/projects/${encodeURIComponent(id)}/check`, {
83
+ body: {},
84
+ method: "POST"
85
+ });
86
+ return {
87
+ answer: body.answer,
88
+ linked: body.linked === true,
89
+ status: typeof body.status === "number" ? body.status : 0
90
+ };
91
+ }
92
+ /** The Console page of an app. */
93
+ function consoleAppUrl(origin, app) {
94
+ return `${origin}/open?project=${encodeURIComponent(app.url)}`;
95
+ }
96
+ /** The text of a check that did not link, such as `401 CONSOLE_KEY_UNKNOWN: ...`. */
97
+ function checkProblem(check) {
98
+ const answer = Object(check.answer);
99
+ const code = Reflect.get(answer, "code");
100
+ const message = Reflect.get(answer, "message");
101
+ return [check.status ? String(check.status) : "", typeof code === "string" ? code : ""].filter(Boolean).join(" ") + (typeof message === "string" ? `: ${message}` : "");
102
+ }
103
+ const usage = {
104
+ check: "vitehub apps check <id> [--console <url>] [--json]",
105
+ link: "vitehub apps link <url> [--label <name>] [--kind site] [--console <url>] [--json]",
106
+ list: "vitehub apps list [--console <url>] [--json]",
107
+ unlink: "vitehub apps unlink <id> --delete-hosted-comments [--console <url>] [--json]"
108
+ };
109
+ function readAppsArgs(command, args) {
110
+ let parsed;
111
+ try {
112
+ parsed = parseArgs({
113
+ allowPositionals: true,
114
+ args,
115
+ options: {
116
+ "console": { type: "string" },
117
+ "help": {
118
+ default: false,
119
+ short: "h",
120
+ type: "boolean"
121
+ },
122
+ "json": {
123
+ default: false,
124
+ type: "boolean"
125
+ },
126
+ ...command === "link" ? {
127
+ kind: { type: "string" },
128
+ label: { type: "string" }
129
+ } : {},
130
+ ...command === "unlink" ? { "delete-hosted-comments": {
131
+ default: false,
132
+ type: "boolean"
133
+ } } : {}
134
+ },
135
+ strict: true
136
+ });
137
+ } catch (error) {
138
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage[command]}` });
139
+ }
140
+ const { positionals, values } = parsed;
141
+ const expected = command === "list" ? 0 : 1;
142
+ if (!values.help && positionals.length !== expected) {
143
+ const message = expected ? `Pass one ${command === "link" ? "URL" : "app id"}.` : `Got ${JSON.stringify(positionals[0])}.`;
144
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage[command]}` });
145
+ }
146
+ return {
147
+ positionals,
148
+ values: {
149
+ "delete-hosted-comments": false,
150
+ ...values
151
+ }
152
+ };
153
+ }
154
+ function appName(app) {
155
+ return app.label ? `${app.label} (${app.url})` : app.url;
156
+ }
157
+ async function runApps(command, args, context) {
158
+ const { positionals, values } = readAppsArgs(command, args);
159
+ if (values.help) {
160
+ context.stdout.write(`Usage: ${usage[command]}\n\n${appsHelp[command]}\n`);
161
+ return setupExitCodes.done;
162
+ }
163
+ const client = await openConsole(context, values.console);
164
+ const write = (result, text) => {
165
+ if (values.json) writeSetupJson(context, {
166
+ console: client.origin,
167
+ ...result
168
+ });
169
+ else context.stdout.write(text);
170
+ };
171
+ if (command === "list") {
172
+ const [apps, me] = await Promise.all([listConsoleApps(client), client.request("/api/whoami")]);
173
+ const team = {
174
+ ...me.body.team,
175
+ role: me.body.roles.join(",")
176
+ };
177
+ const rows = apps.map((app) => [
178
+ app.id,
179
+ app.label ?? "",
180
+ app.url,
181
+ app.keyVariable ? "app" : "site"
182
+ ]);
183
+ write({
184
+ apps,
185
+ team
186
+ }, apps.length ? `${table([[
187
+ "id",
188
+ "label",
189
+ "url",
190
+ "kind"
191
+ ], ...rows])}\n` : `Team ${team.name} has no apps. Run \`vitehub apps link <url>\`, or \`vitehub deploy\` in the app folder.\n`);
192
+ return setupExitCodes.done;
193
+ }
194
+ if (command === "link") {
195
+ if (values.kind !== void 0 && values.kind !== "site") throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --kind takes only "site". Usage: ${usage.link}` });
196
+ const { app, created } = await linkConsoleApp(client, {
197
+ url: positionals[0],
198
+ ...values.label ? { label: values.label } : {},
199
+ ...values.kind === "site" ? { kind: "site" } : {}
200
+ });
201
+ const verb = created ? "Linked" : "Already linked";
202
+ if (app.keyVariable === null) {
203
+ const script = `<script type="module" src="${client.origin}/hosted-comments.js" data-vitehub-comments="${app.id}"><\/script>`;
204
+ const next = `Add the script to the HTML of ${app.url} and of the pages to review, then open ${app.url}?vitehub and choose Comments.`;
205
+ write({
206
+ app,
207
+ script,
208
+ next
209
+ }, `${verb} the site ${appName(app)} as ${app.id}.\n${script}\n${next}\n`);
210
+ return setupExitCodes.done;
211
+ }
212
+ const variable = `${app.keyVariable}=${app.publicKey}`;
213
+ const check = `vitehub apps check ${shellQuote(app.id)} --console ${shellQuote(client.origin)}`;
214
+ const next = `Set ${app.keyVariable} in the environment of ${app.url} and enable console: true in its vitehub config. On Node, also set publicUrl: ${JSON.stringify(new URL(app.url).origin)} in that config. Deploy it, then run \`${check}\`.`;
215
+ write({
216
+ app,
217
+ variable,
218
+ next
219
+ }, `${verb} ${appName(app)} as ${app.id}.\n${variable}\n${next}\n`);
220
+ return setupExitCodes.done;
221
+ }
222
+ const id = positionals[0];
223
+ if (command === "check") {
224
+ const check = await checkConsoleApp(client, id);
225
+ write(check, check.linked ? `The app answers signed requests of ${client.origin}.\n` : `The app does not accept the Console yet: ${checkProblem(check)}\n`);
226
+ return check.linked ? setupExitCodes.done : setupExitCodes.error;
227
+ }
228
+ if (!values["delete-hosted-comments"]) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unlinking permanently deletes the hosted comment threads and replies of the app. Pass --delete-hosted-comments to confirm. Usage: ${usage.unlink}` });
229
+ const app = (await listConsoleApps(client)).find((item) => item.id === id);
230
+ const { status } = await client.request(`/api/projects/${encodeURIComponent(id)}?deleteHostedComments=true`, { method: "DELETE" });
231
+ if (status !== 204) throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
232
+ code: String(status),
233
+ console: client.origin,
234
+ fix: "Check that the Console and its proxy return the project API response, not a sign-in page. Run `vitehub apps list` to see if the app is still linked.",
235
+ message: "The Console did not confirm the unlink (expected status 204)."
236
+ });
237
+ const next = app?.keyVariable ? `Remove ${app.keyVariable} from the environment of ${app.url}.` : "";
238
+ write({
239
+ unlinked: id,
240
+ next
241
+ }, `Unlinked ${app ? appName(app) : id}.${next ? ` ${next}` : ""}\n`);
242
+ return setupExitCodes.done;
243
+ }
244
+ const appsHelp = {
245
+ check: "Call project.get on a linked app with a signed request from the Console. Exits with 1 if the request fails.",
246
+ link: "Link a deployed ViteHub app to your team, or register a site for Hosted Comments with --kind site. Linking a URL again returns the same link and key. Only owners and admins may link.",
247
+ list: "List the apps of the team of your Console key, with the id that the other commands take.",
248
+ unlink: "Unlink an app. This deletes the private key of the link and the hosted comment threads of the app. Only owners and admins may unlink."
249
+ };
250
+ const appsUsage = "vitehub apps <list|link|check|unlink> [args...]";
251
+ /** `vitehub apps`: the CLI side of the `list_apps`, `link_app`, `check_app`, and `unlink_app` tools of the Console MCP. */
252
+ const appsCommand = {
253
+ description: "List, link, check, and unlink the apps of your team in the ViteHub Console. Each command matches a tool of the Console MCP. Needs `vitehub login`.",
254
+ name: "apps",
255
+ usage: appsUsage,
256
+ run: async (args, context) => {
257
+ const json = args.includes("--json");
258
+ try {
259
+ const [command, ...rest] = args;
260
+ if (command === void 0 || command === "-h" || command === "--help") {
261
+ context.stdout.write(`Usage: ${appsUsage}\n\n${appsCommand.description}\n\n${Object.keys(usage).map((name) => ` ${usage[name]}\n ${appsHelp[name]}`).join("\n")}\n`);
262
+ return setupExitCodes.done;
263
+ }
264
+ if (!Object.hasOwn(usage, command)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown command \`vitehub apps ${command}\`. Usage: ${appsUsage}` });
265
+ return await runApps(command, rest, context);
266
+ } catch (error) {
267
+ return writeSetupError(context, json, error);
268
+ }
269
+ }
270
+ };
271
+ export { consoleClient as a, listConsoleApps as c, consoleAppUrl as i, checkConsoleApp as n, console_apps_exports as o, checkProblem as r, linkConsoleApp as s, appsCommand as t };