@vite-hub/cli 0.0.3 → 0.1.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.
- package/LICENSE +201 -0
- package/README.md +93 -22
- package/dist/index.d.ts +88 -13
- package/dist/index.js +2013 -102
- package/package.json +25 -8
package/dist/index.js
CHANGED
|
@@ -1,18 +1,175 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { realpathSync } from "node:fs";
|
|
4
|
-
import process from "node:process";
|
|
3
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import process$1 from "node:process";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { dirname, resolve } from "pathe";
|
|
6
|
+
import { dirname, relative, resolve } from "pathe";
|
|
7
|
+
import { basename, dirname as dirname$1, join, parse, resolve as resolve$1 } from "node:path";
|
|
8
|
+
import { defineDiagnostics } from "nostics";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
|
|
7
11
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
12
|
+
import { createInterface } from "node:readline/promises";
|
|
13
|
+
//#region ../internal/dist/inspect.js
|
|
14
|
+
async function collectContributors(plugins) {
|
|
15
|
+
const contributors = [];
|
|
16
|
+
for (const plugin of plugins) {
|
|
17
|
+
if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
18
|
+
const metadata = plugin.vitehub;
|
|
19
|
+
if (!metadata || typeof metadata !== "object" || !Object.hasOwn(metadata, "inspect")) continue;
|
|
20
|
+
const value = metadata.inspect;
|
|
21
|
+
const contributor = typeof value === "function" ? await value() : value;
|
|
22
|
+
if (contributor) contributors.push(contributor);
|
|
23
|
+
}
|
|
24
|
+
return contributors;
|
|
25
|
+
}
|
|
26
|
+
/** Collects Definition inspectors from active plugins. A later plugin replaces an earlier inspector of the same kind. */
|
|
27
|
+
async function collectViteHubDefinitionInspectors(plugins) {
|
|
28
|
+
const inspectors = /* @__PURE__ */ new Map();
|
|
29
|
+
for (const contributor of await collectContributors(plugins)) for (const inspector of contributor.definitions ?? []) inspectors.set(inspector.kind, inspector);
|
|
30
|
+
return [...inspectors.values()];
|
|
31
|
+
}
|
|
32
|
+
/** Collects Provider Output entries from active plugins, keyed by path. */
|
|
33
|
+
async function collectViteHubProviderOutputEntries(plugins) {
|
|
34
|
+
const entries = /* @__PURE__ */ new Map();
|
|
35
|
+
for (const contributor of await collectContributors(plugins)) for (const entry of contributor.providerOutput ?? []) entries.set(entry.path, entry);
|
|
36
|
+
return [...entries.values()];
|
|
37
|
+
}
|
|
38
|
+
const redactedInspectionValue = "[redacted]";
|
|
39
|
+
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
40
|
+
const secretValuePattern = /^(?:[a-z][a-z0-9+.-]*:\/\/[^/\s?#]*@|bearer\s)/i;
|
|
41
|
+
/** Whether an inspection field names a credential, regardless of its value. */
|
|
42
|
+
function isSecretInspectionKey(key) {
|
|
43
|
+
return secretKeyPattern.test(key);
|
|
44
|
+
}
|
|
45
|
+
const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
|
|
46
|
+
const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
|
|
47
|
+
const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
|
|
48
|
+
const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
|
|
49
|
+
const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
|
|
50
|
+
/**
|
|
51
|
+
* Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
|
|
52
|
+
* `name=value` pairs with a secret name are replaced with `[redacted]`.
|
|
53
|
+
*/
|
|
54
|
+
function redactInspectionText(value) {
|
|
55
|
+
return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Removes values that can carry credentials before inspection output leaves the process.
|
|
59
|
+
* Keys that name secrets, plaintext Worker `vars`, and URLs with embedded credentials are redacted.
|
|
60
|
+
*/
|
|
61
|
+
function redactInspectionValue(value, key) {
|
|
62
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
63
|
+
let remaining = 1e3;
|
|
64
|
+
function visit(entry, entryKey, depth = 0) {
|
|
65
|
+
if (entryKey && isSecretInspectionKey(entryKey)) return redactedInspectionValue;
|
|
66
|
+
if (--remaining < 0 || depth > 10) return "[truncated]";
|
|
67
|
+
if (typeof entry === "string") {
|
|
68
|
+
const text = entry.slice(0, 1e4);
|
|
69
|
+
return secretValuePattern.test(text) ? redactedInspectionValue : redactInspectionText(text);
|
|
70
|
+
}
|
|
71
|
+
if (typeof entry === "bigint") return entry.toString();
|
|
72
|
+
if (typeof entry === "number") return Number.isFinite(entry) ? entry : String(entry);
|
|
73
|
+
if (entry === null || typeof entry === "boolean") return entry;
|
|
74
|
+
if (typeof entry !== "object") return entry === void 0 ? null : "[unsupported]";
|
|
75
|
+
if (seen.has(entry)) return "[circular]";
|
|
76
|
+
seen.add(entry);
|
|
77
|
+
try {
|
|
78
|
+
let dateTime;
|
|
79
|
+
try {
|
|
80
|
+
dateTime = Date.prototype.getTime.call(entry);
|
|
81
|
+
} catch {}
|
|
82
|
+
if (dateTime !== void 0) return Number.isNaN(dateTime) ? "Invalid Date" : Date.prototype.toISOString.call(entry);
|
|
83
|
+
if (Array.isArray(entry)) return entry.slice(0, 100).map((item) => visit(item, void 0, depth + 1));
|
|
84
|
+
let setValues;
|
|
85
|
+
try {
|
|
86
|
+
setValues = [...Set.prototype.values.call(entry)];
|
|
87
|
+
} catch {}
|
|
88
|
+
if (setValues) return setValues.slice(0, 100).map((item) => visit(item, void 0, depth + 1));
|
|
89
|
+
let mapEntries;
|
|
90
|
+
try {
|
|
91
|
+
mapEntries = [...Map.prototype.entries.call(entry)];
|
|
92
|
+
} catch {}
|
|
93
|
+
const entries = mapEntries ? mapEntries.map(([name, item]) => [String(name), item]) : Object.entries(entry);
|
|
94
|
+
return Object.fromEntries(entries.slice(0, 100).map(([name, item]) => [name, name === "vars" && item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).slice(0, 100).map((variable) => [variable, redactedInspectionValue])) : visit(item, name, depth + 1)]));
|
|
95
|
+
} finally {
|
|
96
|
+
seen.delete(entry);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return visit(value, key);
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region ../internal/dist/object.js
|
|
103
|
+
function isPlainObject(value) {
|
|
104
|
+
if (value === null || Object(value) !== value || Array.isArray(value)) return false;
|
|
105
|
+
return typeof value === "object";
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
8
108
|
//#region ../internal/dist/cli.js
|
|
109
|
+
const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
|
|
110
|
+
const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
|
|
111
|
+
const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
|
|
112
|
+
const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
|
|
113
|
+
const stdoutRedirectGlobal = globalThis;
|
|
114
|
+
/**
|
|
115
|
+
* Sends `process.stdout` writes to stderr while `run` loads project config.
|
|
116
|
+
* Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
|
|
117
|
+
*/
|
|
118
|
+
async function withStdoutOnStderr(run, stderr = process.stderr) {
|
|
119
|
+
getStableStdoutWrite();
|
|
120
|
+
const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
|
|
121
|
+
let release;
|
|
122
|
+
stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
|
|
123
|
+
release = resolve;
|
|
124
|
+
});
|
|
125
|
+
await previous;
|
|
126
|
+
const write = process.stdout.write;
|
|
127
|
+
if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
|
|
128
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
|
|
129
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
|
|
130
|
+
}
|
|
131
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
|
|
132
|
+
process.stdout.write = ((chunk, encoding, callback) => {
|
|
133
|
+
const done = typeof encoding === "function" ? encoding : callback;
|
|
134
|
+
let called = false;
|
|
135
|
+
const onComplete = (error) => {
|
|
136
|
+
if (called) return;
|
|
137
|
+
called = true;
|
|
138
|
+
done?.(error);
|
|
139
|
+
};
|
|
140
|
+
const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
|
|
141
|
+
if (done && !called) {
|
|
142
|
+
if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
|
|
143
|
+
else if (stderr.write.length < 2) onComplete();
|
|
144
|
+
}
|
|
145
|
+
return result;
|
|
146
|
+
});
|
|
147
|
+
try {
|
|
148
|
+
return await run();
|
|
149
|
+
} finally {
|
|
150
|
+
process.stdout.write = write;
|
|
151
|
+
stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
|
|
152
|
+
release();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Returns the unredirected process stdout writer for payload output. */
|
|
156
|
+
function getStableStdoutWrite() {
|
|
157
|
+
const current = process.stdout.write;
|
|
158
|
+
if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
|
|
159
|
+
stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
|
|
160
|
+
stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
|
|
161
|
+
}
|
|
162
|
+
return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
|
|
163
|
+
}
|
|
9
164
|
async function resolveContributor(value) {
|
|
10
165
|
return typeof value === "function" ? await value() : value;
|
|
11
166
|
}
|
|
12
|
-
|
|
167
|
+
/** Resolves command namespaces and Provision Steps from one contribution per plugin. */
|
|
168
|
+
async function collectViteHubCliContribution(plugins) {
|
|
13
169
|
const namespaces = /* @__PURE__ */ new Map();
|
|
170
|
+
const steps = /* @__PURE__ */ new Map();
|
|
14
171
|
for (const plugin of plugins) {
|
|
15
|
-
if (!plugin || typeof plugin !== "object") continue;
|
|
172
|
+
if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
16
173
|
const metadata = plugin.vitehub;
|
|
17
174
|
const contributor = await resolveContributor(metadata?.cli);
|
|
18
175
|
if (!contributor) continue;
|
|
@@ -29,17 +186,528 @@ async function collectViteHubCliNamespaces(plugins) {
|
|
|
29
186
|
for (const feature of namespace.features) features.set(feature.name, feature);
|
|
30
187
|
existing.features = [...features.values()];
|
|
31
188
|
}
|
|
189
|
+
for (const step of contributor.provision ?? []) steps.set(step.id, step);
|
|
32
190
|
}
|
|
33
|
-
return
|
|
191
|
+
return {
|
|
192
|
+
namespaces: [...namespaces.values()],
|
|
193
|
+
provision: [...steps.values()]
|
|
194
|
+
};
|
|
34
195
|
}
|
|
35
|
-
|
|
36
|
-
|
|
196
|
+
/** File in the project root where the running dev server tells commands where it listens. */
|
|
197
|
+
const viteHubDevServerFile = ".vitehub/dev-server.json";
|
|
198
|
+
/** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
|
|
199
|
+
function readViteHubDevServerFile(root) {
|
|
200
|
+
try {
|
|
201
|
+
const value = JSON.parse(readFileSync(join(root, viteHubDevServerFile), "utf8"));
|
|
202
|
+
const url = isPlainObject(value) ? value.url : void 0;
|
|
203
|
+
const served = isPlainObject(value) ? value.root : void 0;
|
|
204
|
+
return typeof url === "string" && url && typeof served === "string" && served ? {
|
|
205
|
+
root: served,
|
|
206
|
+
url
|
|
207
|
+
} : void 0;
|
|
208
|
+
} catch {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Where a command finds the dev server of its project: the file that the server wrote in a project root, else
|
|
214
|
+
* `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
|
|
215
|
+
*/
|
|
216
|
+
function findViteHubDevServerUrl(roots, env) {
|
|
217
|
+
for (const root of roots) {
|
|
218
|
+
const file = readViteHubDevServerFile(root);
|
|
219
|
+
if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
|
|
220
|
+
}
|
|
221
|
+
return env["VITEHUB_DEV_SERVER_URL"] || void 0;
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region ../internal/dist/error-diagnostics-fYDviUE4.js
|
|
225
|
+
const dynamicError$1 = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
226
|
+
const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
227
|
+
docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
|
|
228
|
+
codes: {
|
|
229
|
+
INTERNAL_R0012: dynamicError$1,
|
|
230
|
+
INTERNAL_R0013: dynamicError$1,
|
|
231
|
+
INTERNAL_R0014: {
|
|
232
|
+
why: ({ path }) => `Cannot read Provision State from "${path}".`,
|
|
233
|
+
fix: "Check file access and restore valid JSON while preserving existing resource IDs."
|
|
234
|
+
},
|
|
235
|
+
INTERNAL_R0020: {
|
|
236
|
+
fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
|
|
237
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
238
|
+
},
|
|
239
|
+
INTERNAL_R0021: {
|
|
240
|
+
fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
|
|
241
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
242
|
+
},
|
|
243
|
+
INTERNAL_R0022: {
|
|
244
|
+
fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
|
|
245
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
246
|
+
},
|
|
247
|
+
INTERNAL_R0024: {
|
|
248
|
+
fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
|
|
249
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
250
|
+
},
|
|
251
|
+
INTERNAL_R0023: {
|
|
252
|
+
fix: "Ask for access to the section of this operation.",
|
|
253
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
254
|
+
},
|
|
255
|
+
INTERNAL_B0001: dynamicError$1,
|
|
256
|
+
INTERNAL_B0002: dynamicError$1,
|
|
257
|
+
INTERNAL_B0003: dynamicError$1,
|
|
258
|
+
INTERNAL_B0004: dynamicError$1,
|
|
259
|
+
INTERNAL_B0005: dynamicError$1,
|
|
260
|
+
INTERNAL_B0006: dynamicError$1,
|
|
261
|
+
INTERNAL_B0007: dynamicError$1,
|
|
262
|
+
INTERNAL_B0008: dynamicError$1,
|
|
263
|
+
INTERNAL_B0009: dynamicError$1,
|
|
264
|
+
INTERNAL_B0010: dynamicError$1,
|
|
265
|
+
INTERNAL_B0011: dynamicError$1,
|
|
266
|
+
INTERNAL_B0012: dynamicError$1,
|
|
267
|
+
INTERNAL_B0013: dynamicError$1,
|
|
268
|
+
INTERNAL_B0014: dynamicError$1,
|
|
269
|
+
INTERNAL_B0015: dynamicError$1,
|
|
270
|
+
INTERNAL_B0016: dynamicError$1,
|
|
271
|
+
INTERNAL_B0017: dynamicError$1,
|
|
272
|
+
INTERNAL_B0018: dynamicError$1,
|
|
273
|
+
INTERNAL_B0019: dynamicError$1,
|
|
274
|
+
INTERNAL_B0020: dynamicError$1,
|
|
275
|
+
INTERNAL_B0021: dynamicError$1,
|
|
276
|
+
INTERNAL_B0022: dynamicError$1,
|
|
277
|
+
INTERNAL_B0023: dynamicError$1,
|
|
278
|
+
INTERNAL_B0024: dynamicError$1,
|
|
279
|
+
INTERNAL_B0025: dynamicError$1,
|
|
280
|
+
INTERNAL_B0026: dynamicError$1,
|
|
281
|
+
INTERNAL_B0027: dynamicError$1,
|
|
282
|
+
INTERNAL_B0028: dynamicError$1,
|
|
283
|
+
INTERNAL_B0029: dynamicError$1,
|
|
284
|
+
INTERNAL_B0030: dynamicError$1,
|
|
285
|
+
INTERNAL_B0031: dynamicError$1,
|
|
286
|
+
INTERNAL_B0032: dynamicError$1,
|
|
287
|
+
INTERNAL_B0033: dynamicError$1,
|
|
288
|
+
INTERNAL_B0034: dynamicError$1,
|
|
289
|
+
INTERNAL_B0035: dynamicError$1,
|
|
290
|
+
INTERNAL_B0036: dynamicError$1,
|
|
291
|
+
INTERNAL_B0037: dynamicError$1,
|
|
292
|
+
INTERNAL_B0038: dynamicError$1,
|
|
293
|
+
INTERNAL_B0039: dynamicError$1,
|
|
294
|
+
INTERNAL_B0040: dynamicError$1,
|
|
295
|
+
INTERNAL_B0041: dynamicError$1,
|
|
296
|
+
INTERNAL_B0042: dynamicError$1,
|
|
297
|
+
INTERNAL_B0043: dynamicError$1,
|
|
298
|
+
INTERNAL_B0044: dynamicError$1,
|
|
299
|
+
INTERNAL_B0045: dynamicError$1,
|
|
300
|
+
INTERNAL_B0046: dynamicError$1,
|
|
301
|
+
INTERNAL_B0047: dynamicError$1,
|
|
302
|
+
INTERNAL_B0048: {
|
|
303
|
+
fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
|
|
304
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
305
|
+
},
|
|
306
|
+
INTERNAL_B0049: {
|
|
307
|
+
fix: "Set `cli: { namespace, command }` on one of the two operations.",
|
|
308
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
309
|
+
},
|
|
310
|
+
INTERNAL_B0050: {
|
|
311
|
+
fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
|
|
312
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
313
|
+
},
|
|
314
|
+
INTERNAL_R0025: {
|
|
315
|
+
fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
|
|
316
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
317
|
+
},
|
|
318
|
+
INTERNAL_R0026: {
|
|
319
|
+
why: "The server parsed a destructive operation that the CLI did not confirm.",
|
|
320
|
+
fix: "Review the operation, then run it again with --yes to confirm the change."
|
|
321
|
+
},
|
|
322
|
+
INTERNAL_C0001: dynamicError$1,
|
|
323
|
+
INTERNAL_C0002: dynamicError$1,
|
|
324
|
+
INTERNAL_R0001: dynamicError$1,
|
|
325
|
+
INTERNAL_R0002: dynamicError$1,
|
|
326
|
+
INTERNAL_R0003: dynamicError$1,
|
|
327
|
+
INTERNAL_R0004: dynamicError$1,
|
|
328
|
+
INTERNAL_R0005: dynamicError$1,
|
|
329
|
+
INTERNAL_R0006: dynamicError$1,
|
|
330
|
+
INTERNAL_R0007: dynamicError$1,
|
|
331
|
+
INTERNAL_R0008: dynamicError$1,
|
|
332
|
+
INTERNAL_R0009: dynamicError$1,
|
|
333
|
+
INTERNAL_R0010: dynamicError$1,
|
|
334
|
+
INTERNAL_R0011: dynamicError$1
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
//#endregion
|
|
338
|
+
//#region ../internal/dist/build/vite.js
|
|
339
|
+
const projectRootDirectoryMarkers = [
|
|
340
|
+
["server", "agents"],
|
|
341
|
+
["server", "channels"],
|
|
342
|
+
["server", "connections"],
|
|
343
|
+
["server", "browsers"],
|
|
344
|
+
["server", "emails"],
|
|
345
|
+
["server", "schedules"],
|
|
346
|
+
["server", "workspaces"]
|
|
347
|
+
];
|
|
348
|
+
const projectRootFileMarkers = [
|
|
349
|
+
["package.json"],
|
|
350
|
+
["nuxt.config.ts"],
|
|
351
|
+
["nuxt.config.mts"],
|
|
352
|
+
["nuxt.config.js"],
|
|
353
|
+
["nuxt.config.mjs"]
|
|
354
|
+
];
|
|
355
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
356
|
+
const resolvedRoot = resolve$1(root);
|
|
357
|
+
const temporaryRoot = resolve$1(tmpdir());
|
|
358
|
+
const sharedTemporaryRoot = dirname$1(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
359
|
+
if (options.projectRoot) return resolve$1(resolvedRoot, options.projectRoot);
|
|
360
|
+
if (basename(resolvedRoot) === "app") {
|
|
361
|
+
const parent = dirname$1(resolvedRoot);
|
|
362
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
363
|
+
"nuxt.config.ts",
|
|
364
|
+
"nuxt.config.mts",
|
|
365
|
+
"nuxt.config.js",
|
|
366
|
+
"nuxt.config.mjs"
|
|
367
|
+
]))) return parent;
|
|
368
|
+
}
|
|
369
|
+
let current = resolvedRoot;
|
|
370
|
+
while (true) {
|
|
371
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
372
|
+
if (hasProjectRootMarker(current)) return current;
|
|
373
|
+
const parent = dirname$1(current);
|
|
374
|
+
if (parent === current) return resolvedRoot;
|
|
375
|
+
current = parent;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
379
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
380
|
+
if (statSync(resolve$1(root, ...marker)).isDirectory()) return true;
|
|
381
|
+
} catch (error) {
|
|
382
|
+
if (error.code !== "ENOENT") throw error;
|
|
383
|
+
}
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
function hasProjectRootMarker(root) {
|
|
387
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
388
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
389
|
+
}
|
|
390
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
391
|
+
for (const marker of markers) {
|
|
392
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
393
|
+
try {
|
|
394
|
+
if (statSync(resolve$1(root, ...path)).isFile()) return true;
|
|
395
|
+
} catch (error) {
|
|
396
|
+
if (error.code !== "ENOENT") throw error;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
//#endregion
|
|
402
|
+
//#region ../internal/dist/standard-schema.js
|
|
403
|
+
function readOwn(value, key) {
|
|
404
|
+
if (value === null || Object(value) !== value) return;
|
|
405
|
+
try {
|
|
406
|
+
return Reflect.get(Object(value), key);
|
|
407
|
+
} catch {
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function isRecord(value) {
|
|
412
|
+
return value !== null && Object(value) === value && !Array.isArray(value);
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Read a Standard JSON Schema projection without throwing.
|
|
416
|
+
*
|
|
417
|
+
* Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
|
|
418
|
+
* (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
|
|
419
|
+
*/
|
|
420
|
+
function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
|
|
421
|
+
const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
|
|
422
|
+
const project = readOwn(jsonSchema, direction);
|
|
423
|
+
if (typeof project !== "function") return;
|
|
424
|
+
try {
|
|
425
|
+
const result = project.call(jsonSchema, libraryOptions ? {
|
|
426
|
+
target,
|
|
427
|
+
libraryOptions
|
|
428
|
+
} : { target });
|
|
429
|
+
return isRecord(result) ? result : void 0;
|
|
430
|
+
} catch {
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
//#region ../internal/dist/operations.js
|
|
436
|
+
/** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way. */
|
|
437
|
+
const operationRpcPath = "/_vitehub/rpc/__call";
|
|
438
|
+
/** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
|
|
439
|
+
const operationRpcHeader = "x-vitehub-console";
|
|
440
|
+
/** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
|
|
441
|
+
const operationRootHeader = "x-vitehub-root";
|
|
442
|
+
const operationExpectedRootsHeader = "x-vitehub-expected-roots";
|
|
443
|
+
/** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
|
|
444
|
+
function projectRootHash(root) {
|
|
445
|
+
const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
446
|
+
let first = 3735928559;
|
|
447
|
+
let second = 1103547991;
|
|
448
|
+
for (let index = 0; index < normalized.length; index++) {
|
|
449
|
+
const code = normalized.charCodeAt(index);
|
|
450
|
+
first = Math.imul(first ^ code, 2654435761);
|
|
451
|
+
second = Math.imul(second ^ code, 1597334677);
|
|
452
|
+
}
|
|
453
|
+
first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
|
|
454
|
+
second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
|
|
455
|
+
return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
|
|
456
|
+
}
|
|
457
|
+
/** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
|
|
458
|
+
const operationSurfaceHeader = "x-vitehub-surface";
|
|
459
|
+
/** Generated CLI commands ask the server to check confirmation after it parses the input. */
|
|
460
|
+
const operationConfirmationHeader = "x-vitehub-confirmation";
|
|
461
|
+
const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
|
|
462
|
+
const kinds = /* @__PURE__ */ new Set([
|
|
463
|
+
"read",
|
|
464
|
+
"write",
|
|
465
|
+
"destructive"
|
|
466
|
+
]);
|
|
467
|
+
function isObject$1(value) {
|
|
468
|
+
return value !== null && Object(value) === value && !Array.isArray(value);
|
|
469
|
+
}
|
|
470
|
+
function invalidDefinition(name, reason) {
|
|
471
|
+
return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
|
|
472
|
+
}
|
|
473
|
+
function checkDefinition(definition) {
|
|
474
|
+
if (!isObject$1(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
|
|
475
|
+
const { name } = definition;
|
|
476
|
+
if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
|
|
477
|
+
if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
|
|
478
|
+
const { section } = definition;
|
|
479
|
+
if (section !== false && !(section instanceof Function) && (String(section) !== section || !section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false.");
|
|
480
|
+
if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
|
|
481
|
+
const input = definition.input;
|
|
482
|
+
if (!isObject$1(input) || !isObject$1(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
|
|
483
|
+
if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
|
|
484
|
+
const { maxRequestBytes } = definition;
|
|
485
|
+
if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
|
|
486
|
+
if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
|
|
487
|
+
}
|
|
488
|
+
/** The default limit of a call, in bytes. */
|
|
489
|
+
const defaultRequestBytes = 65536;
|
|
490
|
+
/** CLI namespaces owned by built-in commands. */
|
|
491
|
+
const reservedOperationNamespaces = ["inspect", "provision"];
|
|
492
|
+
function isOperation(value) {
|
|
493
|
+
try {
|
|
494
|
+
checkDefinition(value);
|
|
495
|
+
return true;
|
|
496
|
+
} catch {
|
|
497
|
+
return false;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
function pluginName(plugin) {
|
|
501
|
+
const name = Reflect.get(plugin, "name");
|
|
502
|
+
return String(name) === name && name ? name : "unnamed plugin";
|
|
503
|
+
}
|
|
504
|
+
/** Reads `plugin.vitehub.operations` from resolved Vite plugins. The same module and export from two plugins counts once. */
|
|
505
|
+
async function collectOperationContributions(plugins) {
|
|
506
|
+
const collected = /* @__PURE__ */ new Map();
|
|
37
507
|
for (const plugin of plugins) {
|
|
38
|
-
if (!plugin ||
|
|
39
|
-
const
|
|
40
|
-
|
|
508
|
+
if (!isObject$1(plugin) || !Object.hasOwn(plugin, "vitehub")) continue;
|
|
509
|
+
const declared = Reflect.get(Object(Reflect.get(plugin, "vitehub")), "operations");
|
|
510
|
+
if (declared === void 0) continue;
|
|
511
|
+
const entries = declared instanceof Function ? await declared() : declared;
|
|
512
|
+
const owner = pluginName(plugin);
|
|
513
|
+
if (!Array.isArray(entries)) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} sets vitehub.operations, which must be a list of { module, export }.` });
|
|
514
|
+
for (const entry of entries) {
|
|
515
|
+
if (!isObject$1(entry) || String(entry.module) !== entry.module || !entry.module) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} contributes an operation entry without a module.` });
|
|
516
|
+
const exportName = String(entry.export) === entry.export && entry.export ? entry.export : "default";
|
|
517
|
+
const key = `${entry.module}#${exportName}`;
|
|
518
|
+
if (collected.has(key)) continue;
|
|
519
|
+
collected.set(key, {
|
|
520
|
+
module: entry.module,
|
|
521
|
+
export: exportName,
|
|
522
|
+
plugin: owner,
|
|
523
|
+
...entry.load instanceof Function ? { load: entry.load } : {},
|
|
524
|
+
...entry.runtime === false ? { runtime: false } : {}
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return [...collected.values()];
|
|
529
|
+
}
|
|
530
|
+
/** Operations of one module export, flat. A single operation or an array both work. */
|
|
531
|
+
function operationsOf(value) {
|
|
532
|
+
const list = Array.isArray(value) ? value : [value];
|
|
533
|
+
const operations = [];
|
|
534
|
+
for (const item of list) {
|
|
535
|
+
if (!isOperation(item)) throw invalidDefinition(isObject$1(item) ? item.name : void 0, "a contributed export must hold defineOperation() results.");
|
|
536
|
+
operations.push(item);
|
|
537
|
+
}
|
|
538
|
+
return operations;
|
|
539
|
+
}
|
|
540
|
+
/** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
|
|
541
|
+
function operationCliPath(operation) {
|
|
542
|
+
const dot = operation.name.indexOf(".");
|
|
543
|
+
return {
|
|
544
|
+
command: operation.cli?.command ?? operation.name.slice(dot + 1),
|
|
545
|
+
namespace: operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
|
|
550
|
+
* Claude reject a dot in a tool name. `content.publish` is `content_publish`.
|
|
551
|
+
*/
|
|
552
|
+
function operationToolName(name) {
|
|
553
|
+
return name.replace(/[^\w-]/g, "_");
|
|
554
|
+
}
|
|
555
|
+
/** Build the registry by name. A duplicate name or CLI command fails with `INTERNAL_B0048` or `INTERNAL_B0049`, two MCP tool names that match with `INTERNAL_B0050`. */
|
|
556
|
+
function createOperationRegistry(sources) {
|
|
557
|
+
const byName = /* @__PURE__ */ new Map();
|
|
558
|
+
for (const source of sources) for (const operation of source.operations) {
|
|
559
|
+
const existing = byName.get(operation.name);
|
|
560
|
+
if (existing && existing.operation !== operation) {
|
|
561
|
+
const owners = [existing.plugin, source.plugin].filter(Boolean).join(" and ");
|
|
562
|
+
throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] Two operations are named ${JSON.stringify(operation.name)}${owners ? ` (${owners})` : ""}.` });
|
|
563
|
+
}
|
|
564
|
+
byName.set(operation.name, {
|
|
565
|
+
operation,
|
|
566
|
+
...source.plugin ? { plugin: source.plugin } : {}
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
|
|
570
|
+
const commands = /* @__PURE__ */ new Map();
|
|
571
|
+
for (const operation of operations) {
|
|
572
|
+
const { command, namespace } = operationCliPath(operation);
|
|
573
|
+
if (reservedOperationNamespaces.includes(namespace)) throw invalidDefinition(operation.name, `the CLI namespace ${JSON.stringify(namespace)} is reserved for built-in commands. Set cli.namespace to another name.`);
|
|
574
|
+
const key = `${namespace} ${command}`;
|
|
575
|
+
const other = commands.get(key);
|
|
576
|
+
if (other) throw internalErrorDiagnostics.INTERNAL_B0049({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the CLI command \`vitehub ${key}\`.` });
|
|
577
|
+
commands.set(key, operation);
|
|
578
|
+
}
|
|
579
|
+
const tools = /* @__PURE__ */ new Map();
|
|
580
|
+
for (const operation of operations) {
|
|
581
|
+
if (operation.mcp === false) continue;
|
|
582
|
+
const tool = operationToolName(operation.name);
|
|
583
|
+
const other = tools.get(tool);
|
|
584
|
+
if (other) throw internalErrorDiagnostics.INTERNAL_B0050({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the MCP tool ${JSON.stringify(tool)}.` });
|
|
585
|
+
tools.set(tool, operation);
|
|
586
|
+
}
|
|
587
|
+
return {
|
|
588
|
+
get: (name) => byName.get(name)?.operation,
|
|
589
|
+
list: () => [...operations]
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
/** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
|
|
593
|
+
function operationInputJsonSchema(operation) {
|
|
594
|
+
return standardJsonSchema(operation.input, "input") ?? { type: "object" };
|
|
595
|
+
}
|
|
596
|
+
/** Issues of a failed Standard Schema check as one short line per issue. */
|
|
597
|
+
function describeInputIssues(issues) {
|
|
598
|
+
return issues.slice(0, 5).map((issue) => {
|
|
599
|
+
const path = (issue.path ?? []).map((segment) => String(isObject$1(segment) && "key" in segment ? segment.key : segment)).join(".");
|
|
600
|
+
return path ? `${path}: ${issue.message}` : issue.message;
|
|
601
|
+
}).join(" ");
|
|
602
|
+
}
|
|
603
|
+
/** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
|
|
604
|
+
async function parseOperationInput(operation, input) {
|
|
605
|
+
const result = await operation.input["~standard"].validate(input ?? {});
|
|
606
|
+
if (!result.issues) return result.value;
|
|
607
|
+
const error = internalErrorDiagnostics.INTERNAL_R0022({ message: `Invalid input for ${operation.name}. ${describeInputIssues(result.issues)}` });
|
|
608
|
+
throw Object.assign(error, { status: 400 });
|
|
609
|
+
}
|
|
610
|
+
/** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
|
|
611
|
+
function operationCall(operation, input) {
|
|
612
|
+
return {
|
|
613
|
+
kind: operation.kind,
|
|
614
|
+
readOnly: operation.readOnlyWhen?.(input) === true
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
function text(value) {
|
|
618
|
+
return String(value) === value && value ? value : void 0;
|
|
619
|
+
}
|
|
620
|
+
const operationCredentialHint = "Set VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.";
|
|
621
|
+
/** Headers of an operation call. The credentials are the ones the Agent Invocations CLI reads. */
|
|
622
|
+
function operationHeaders(env) {
|
|
623
|
+
const headers = new Headers({
|
|
624
|
+
"accept": "application/json",
|
|
625
|
+
"content-type": "application/json",
|
|
626
|
+
[operationRpcHeader]: "1",
|
|
627
|
+
[operationSurfaceHeader]: "cli"
|
|
628
|
+
});
|
|
629
|
+
if (env.VITEHUB_CONSOLE_AUTHORIZATION) headers.set("authorization", env.VITEHUB_CONSOLE_AUTHORIZATION);
|
|
630
|
+
if (env.VITEHUB_CONSOLE_COOKIE) headers.set("cookie", env.VITEHUB_CONSOLE_COOKIE);
|
|
631
|
+
if (env.CF_ACCESS_CLIENT_ID) headers.set("cf-access-client-id", env.CF_ACCESS_CLIENT_ID);
|
|
632
|
+
if (env.CF_ACCESS_CLIENT_SECRET) headers.set("cf-access-client-secret", env.CF_ACCESS_CLIENT_SECRET);
|
|
633
|
+
return headers;
|
|
634
|
+
}
|
|
635
|
+
function unreachable(message, status = 503) {
|
|
636
|
+
const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
|
|
637
|
+
return {
|
|
638
|
+
ok: false,
|
|
639
|
+
code: "INTERNAL_R0024",
|
|
640
|
+
fix: Reflect.get(error, "fix"),
|
|
641
|
+
message,
|
|
642
|
+
status
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
function hasCredentials(env) {
|
|
646
|
+
return Boolean(env.VITEHUB_CONSOLE_AUTHORIZATION || env.VITEHUB_CONSOLE_COOKIE || env.CF_ACCESS_CLIENT_ID || env.CF_ACCESS_CLIENT_SECRET);
|
|
647
|
+
}
|
|
648
|
+
/** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
|
|
649
|
+
async function callOperation(target, name, input) {
|
|
650
|
+
let origin = "the ViteHub app";
|
|
651
|
+
try {
|
|
652
|
+
const base = new URL(target.url);
|
|
653
|
+
if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
|
|
654
|
+
const url = new URL(operationRpcPath.slice(1), base);
|
|
655
|
+
origin = url.origin;
|
|
656
|
+
const env = target.roots?.length ? {} : target.env;
|
|
657
|
+
const headers = operationHeaders(env);
|
|
658
|
+
if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
|
|
659
|
+
if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
|
|
660
|
+
const response = await (target.fetch ?? fetch)(url.href, {
|
|
661
|
+
body: JSON.stringify({
|
|
662
|
+
operation: name,
|
|
663
|
+
input: input ?? {}
|
|
664
|
+
}),
|
|
665
|
+
headers,
|
|
666
|
+
method: "POST",
|
|
667
|
+
redirect: "manual",
|
|
668
|
+
signal: AbortSignal.timeout(target.timeout ?? 3e4)
|
|
669
|
+
});
|
|
670
|
+
const served = response.headers.get(operationRootHeader);
|
|
671
|
+
if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
|
|
672
|
+
const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
|
|
673
|
+
const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
|
|
674
|
+
return {
|
|
675
|
+
ok: false,
|
|
676
|
+
code: "INTERNAL_R0025",
|
|
677
|
+
fix: Reflect.get(error, "fix"),
|
|
678
|
+
message,
|
|
679
|
+
status: 409
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
const body = await response.text();
|
|
683
|
+
let json;
|
|
684
|
+
try {
|
|
685
|
+
json = body ? JSON.parse(body) : void 0;
|
|
686
|
+
} catch {
|
|
687
|
+
json = void 0;
|
|
688
|
+
}
|
|
689
|
+
if (isObject$1(json) && json.ok === true) return {
|
|
690
|
+
ok: true,
|
|
691
|
+
value: json.value
|
|
692
|
+
};
|
|
693
|
+
if (isObject$1(json) && String(json.code) === json.code && String(json.message) === json.message) {
|
|
694
|
+
const failure = {
|
|
695
|
+
ok: false,
|
|
696
|
+
code: json.code,
|
|
697
|
+
message: json.message,
|
|
698
|
+
status: Number.isInteger(json.status) ? Number(json.status) : response.status
|
|
699
|
+
};
|
|
700
|
+
if (text(json.fix)) failure.fix = text(json.fix);
|
|
701
|
+
if (text(json.docs)) failure.docs = text(json.docs);
|
|
702
|
+
if (isObject$1(json.details)) failure.details = json.details;
|
|
703
|
+
if ((failure.status === 401 || failure.status === 403) && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
|
|
704
|
+
return failure;
|
|
705
|
+
}
|
|
706
|
+
if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
|
|
707
|
+
return unreachable(`${url.origin} did not answer as a ViteHub app (HTTP ${response.status}). Pass the origin of an app that runs ViteHub.`, response.status);
|
|
708
|
+
} catch (error) {
|
|
709
|
+
return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
710
|
}
|
|
42
|
-
return [...steps.values()];
|
|
43
711
|
}
|
|
44
712
|
//#endregion
|
|
45
713
|
//#region ../internal/dist/provision-state.js
|
|
@@ -48,10 +716,27 @@ function getProvisionStatePath(rootDir) {
|
|
|
48
716
|
return resolve(rootDir, PROVISION_STATE_FILE);
|
|
49
717
|
}
|
|
50
718
|
async function readProvisionState(rootDir) {
|
|
719
|
+
const path = getProvisionStatePath(rootDir);
|
|
51
720
|
try {
|
|
52
|
-
return parseProvisionState(await readFile(
|
|
53
|
-
} catch {
|
|
54
|
-
return {};
|
|
721
|
+
return parseProvisionState(await readFile(path, "utf8"));
|
|
722
|
+
} catch (cause) {
|
|
723
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
|
|
724
|
+
throw internalErrorDiagnostics.INTERNAL_R0014({
|
|
725
|
+
path,
|
|
726
|
+
cause
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function readProvisionStateSync(rootDir) {
|
|
731
|
+
const path = getProvisionStatePath(rootDir);
|
|
732
|
+
try {
|
|
733
|
+
return parseProvisionState(readFileSync(path, "utf8"));
|
|
734
|
+
} catch (cause) {
|
|
735
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
|
|
736
|
+
throw internalErrorDiagnostics.INTERNAL_R0014({
|
|
737
|
+
path,
|
|
738
|
+
cause
|
|
739
|
+
});
|
|
55
740
|
}
|
|
56
741
|
}
|
|
57
742
|
async function writeProvisionState(rootDir, next) {
|
|
@@ -66,16 +751,38 @@ function mergeProvisionState(base, next) {
|
|
|
66
751
|
const categories = next[provider];
|
|
67
752
|
if (!categories) continue;
|
|
68
753
|
const target = merged[provider] ??= {};
|
|
69
|
-
for (const [category, ids] of Object.entries(categories)) target
|
|
70
|
-
...target[category],
|
|
754
|
+
for (const [category, ids] of Object.entries(categories)) setOwn(target, category, {
|
|
755
|
+
...(Object.hasOwn(target, category) ? target[category] : void 0) ?? {},
|
|
71
756
|
...ids
|
|
72
|
-
};
|
|
757
|
+
});
|
|
73
758
|
}
|
|
74
759
|
return merged;
|
|
75
760
|
}
|
|
76
761
|
function parseProvisionState(raw) {
|
|
77
762
|
const parsed = JSON.parse(raw);
|
|
78
|
-
|
|
763
|
+
if (!isPlainObject(parsed)) return {};
|
|
764
|
+
const state = {};
|
|
765
|
+
for (const provider of ["cloudflare", "vercel"]) {
|
|
766
|
+
const categories = parsed[provider];
|
|
767
|
+
if (!isPlainObject(categories)) continue;
|
|
768
|
+
const validCategories = {};
|
|
769
|
+
for (const [category, ids] of Object.entries(categories)) {
|
|
770
|
+
if (!isPlainObject(ids)) continue;
|
|
771
|
+
const validIds = {};
|
|
772
|
+
for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
|
|
773
|
+
if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
|
|
774
|
+
}
|
|
775
|
+
if (Object.keys(validCategories).length) state[provider] = validCategories;
|
|
776
|
+
}
|
|
777
|
+
return state;
|
|
778
|
+
}
|
|
779
|
+
function setOwn(target, key, value) {
|
|
780
|
+
Object.defineProperty(target, key, {
|
|
781
|
+
configurable: true,
|
|
782
|
+
enumerable: true,
|
|
783
|
+
value,
|
|
784
|
+
writable: true
|
|
785
|
+
});
|
|
79
786
|
}
|
|
80
787
|
function sortState(state) {
|
|
81
788
|
return sortKeys(state);
|
|
@@ -85,7 +792,932 @@ function sortKeys(value) {
|
|
|
85
792
|
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]));
|
|
86
793
|
}
|
|
87
794
|
//#endregion
|
|
795
|
+
//#region src/inspect.ts
|
|
796
|
+
const definitionsUsage = "vitehub inspect definitions [--kind <kind>] [--json]";
|
|
797
|
+
const providerOutputUsage = "vitehub inspect provider-output [--json]";
|
|
798
|
+
function parseArgs$1(args, options) {
|
|
799
|
+
const parsed = {
|
|
800
|
+
help: false,
|
|
801
|
+
json: false
|
|
802
|
+
};
|
|
803
|
+
for (let index = 0; index < args.length; index++) {
|
|
804
|
+
const arg = args[index];
|
|
805
|
+
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
806
|
+
else if (arg === "--json") parsed.json = true;
|
|
807
|
+
else if (options.kind && arg === "--kind") {
|
|
808
|
+
const kind = args[index + 1];
|
|
809
|
+
if (!kind || kind.startsWith("-")) parsed.error ??= "Option --kind requires a value.";
|
|
810
|
+
else {
|
|
811
|
+
parsed.kind = kind;
|
|
812
|
+
index++;
|
|
813
|
+
}
|
|
814
|
+
} else if (options.kind && arg?.startsWith("--kind=")) {
|
|
815
|
+
const kind = arg.slice(7);
|
|
816
|
+
if (!kind) parsed.error ??= "Option --kind requires a value.";
|
|
817
|
+
else parsed.kind = kind;
|
|
818
|
+
} else if (arg) parsed.error ??= `Unknown inspect argument: ${arg}`;
|
|
819
|
+
}
|
|
820
|
+
return parsed;
|
|
821
|
+
}
|
|
822
|
+
function writeJson(context, value) {
|
|
823
|
+
context.stdout.write(`${JSON.stringify(redactInspectionValue(value), null, 2)}\n`);
|
|
824
|
+
}
|
|
825
|
+
function redactSummary(summary) {
|
|
826
|
+
return {
|
|
827
|
+
...summary,
|
|
828
|
+
fields: summary.fields.map((field) => ({
|
|
829
|
+
label: field.label,
|
|
830
|
+
value: String(redactInspectionValue(field.value, field.label))
|
|
831
|
+
}))
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
/** The operations of the app as one Definition kind. */
|
|
835
|
+
function operationInspector(operations) {
|
|
836
|
+
return {
|
|
837
|
+
kind: "operation",
|
|
838
|
+
label: "Operations",
|
|
839
|
+
list: () => operations.map((operation) => ({
|
|
840
|
+
fields: [
|
|
841
|
+
{
|
|
842
|
+
label: "Kind",
|
|
843
|
+
value: operation.kind
|
|
844
|
+
},
|
|
845
|
+
{
|
|
846
|
+
label: "Section",
|
|
847
|
+
value: typeof operation.section === "string" ? operation.section : operation.section === false ? "any" : "from input"
|
|
848
|
+
},
|
|
849
|
+
{
|
|
850
|
+
label: "Description",
|
|
851
|
+
value: operation.description
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
label: "Command",
|
|
855
|
+
value: `vitehub ${operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, operation.name.indexOf(".")))} ${operation.cli?.command ?? operation.name.slice(operation.name.indexOf(".") + 1)}`
|
|
856
|
+
}
|
|
857
|
+
],
|
|
858
|
+
file: "operations",
|
|
859
|
+
name: operation.name,
|
|
860
|
+
source: "operations"
|
|
861
|
+
}))
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
async function runDefinitions(args, context, plugins, operations) {
|
|
865
|
+
const parsed = parseArgs$1(args, { kind: true });
|
|
866
|
+
if (parsed.help) {
|
|
867
|
+
context.stdout.write([
|
|
868
|
+
`Usage: ${definitionsUsage}`,
|
|
869
|
+
"",
|
|
870
|
+
"Lists the Definitions that each active package discovered.",
|
|
871
|
+
"",
|
|
872
|
+
"Options:",
|
|
873
|
+
" --kind <kind> Show one kind only, for example queue or rate-limit.",
|
|
874
|
+
" --json Print machine-readable JSON.",
|
|
875
|
+
" -h, --help Show this help.",
|
|
876
|
+
""
|
|
877
|
+
].join("\n"));
|
|
878
|
+
return 0;
|
|
879
|
+
}
|
|
880
|
+
if (parsed.error) {
|
|
881
|
+
context.stderr.write(`${parsed.error}\nUsage: ${definitionsUsage}\n`);
|
|
882
|
+
return 1;
|
|
883
|
+
}
|
|
884
|
+
const inspectors = [...await collectViteHubDefinitionInspectors(plugins), ...operations.length ? [operationInspector(operations)] : []];
|
|
885
|
+
const selected = parsed.kind ? inspectors.filter((inspector) => inspector.kind === parsed.kind) : inspectors;
|
|
886
|
+
if (parsed.kind && !selected.length) {
|
|
887
|
+
const kinds = inspectors.map((inspector) => inspector.kind).sort();
|
|
888
|
+
context.stderr.write(`Unknown Definition kind: ${parsed.kind}\nAvailable kinds: ${kinds.length ? kinds.join(", ") : "none"}\n`);
|
|
889
|
+
return 1;
|
|
890
|
+
}
|
|
891
|
+
const groups = await Promise.all(selected.map(async (inspector) => ({
|
|
892
|
+
definitions: (await inspector.list()).map(redactSummary),
|
|
893
|
+
kind: inspector.kind,
|
|
894
|
+
label: inspector.label
|
|
895
|
+
})));
|
|
896
|
+
if (parsed.json) {
|
|
897
|
+
writeJson(context, { definitions: groups });
|
|
898
|
+
return 0;
|
|
899
|
+
}
|
|
900
|
+
if (!groups.length) {
|
|
901
|
+
context.stdout.write("No package contributes Definition inspection.\n");
|
|
902
|
+
return 0;
|
|
903
|
+
}
|
|
904
|
+
const lines = [];
|
|
905
|
+
for (const group of groups) {
|
|
906
|
+
lines.push(`${group.label} (${group.kind}): ${group.definitions.length}`);
|
|
907
|
+
if (!group.definitions.length) lines.push(" No Definitions discovered.");
|
|
908
|
+
for (const definition of group.definitions) {
|
|
909
|
+
lines.push(` ${definition.name} ${definition.file} [${definition.source}]`);
|
|
910
|
+
for (const field of definition.fields) lines.push(` ${field.label}: ${field.value}`);
|
|
911
|
+
}
|
|
912
|
+
lines.push("");
|
|
913
|
+
}
|
|
914
|
+
context.stdout.write(lines.join("\n"));
|
|
915
|
+
return 0;
|
|
916
|
+
}
|
|
917
|
+
function readProviderOutputEntry(rootDir, entry) {
|
|
918
|
+
const path = relative(rootDir, entry.path) || ".";
|
|
919
|
+
if (!existsSync(entry.path)) return {
|
|
920
|
+
description: entry.description,
|
|
921
|
+
exists: false,
|
|
922
|
+
owner: entry.owner,
|
|
923
|
+
path
|
|
924
|
+
};
|
|
925
|
+
const directory = statSync(entry.path).isDirectory();
|
|
926
|
+
const report = {
|
|
927
|
+
description: entry.description,
|
|
928
|
+
exists: true,
|
|
929
|
+
owner: entry.owner,
|
|
930
|
+
path,
|
|
931
|
+
type: directory ? "directory" : "file"
|
|
932
|
+
};
|
|
933
|
+
if (!directory && entry.path.endsWith(".json")) try {
|
|
934
|
+
report.content = JSON.parse(readFileSync(entry.path, "utf8"));
|
|
935
|
+
} catch {
|
|
936
|
+
report.content = "[unreadable JSON]";
|
|
937
|
+
}
|
|
938
|
+
return report;
|
|
939
|
+
}
|
|
940
|
+
async function runProviderOutput(args, context, plugins) {
|
|
941
|
+
const parsed = parseArgs$1(args, { kind: false });
|
|
942
|
+
if (parsed.help) {
|
|
943
|
+
context.stdout.write([
|
|
944
|
+
`Usage: ${providerOutputUsage}`,
|
|
945
|
+
"",
|
|
946
|
+
"Lists generated Provider Output files and shows which exist.",
|
|
947
|
+
"Run a production build first to generate deployment output.",
|
|
948
|
+
"JSON output includes file contents with credentials and Worker vars redacted.",
|
|
949
|
+
"",
|
|
950
|
+
"Options:",
|
|
951
|
+
" --json Print machine-readable JSON.",
|
|
952
|
+
" -h, --help Show this help.",
|
|
953
|
+
""
|
|
954
|
+
].join("\n"));
|
|
955
|
+
return 0;
|
|
956
|
+
}
|
|
957
|
+
if (parsed.error) {
|
|
958
|
+
context.stderr.write(`${parsed.error}\nUsage: ${providerOutputUsage}\n`);
|
|
959
|
+
return 1;
|
|
960
|
+
}
|
|
961
|
+
const reports = [...await collectViteHubProviderOutputEntries(plugins), {
|
|
962
|
+
description: "Provision State with non-secret provider resource ids",
|
|
963
|
+
owner: "cli",
|
|
964
|
+
path: resolve(context.rootDir, PROVISION_STATE_FILE)
|
|
965
|
+
}].map((entry) => readProviderOutputEntry(context.rootDir, entry)).sort((left, right) => left.path.localeCompare(right.path));
|
|
966
|
+
if (parsed.json) {
|
|
967
|
+
const provisionPath = relative(context.rootDir, resolve(context.rootDir, ".vitehub/provision.json")) || ".";
|
|
968
|
+
const providerOutput = reports.map((report) => {
|
|
969
|
+
if (report.path === provisionPath && report.exists && report.owner === "cli" && report.type === "file" && report.content !== "[unreadable JSON]") {
|
|
970
|
+
const provisionState = readProvisionStateSync(context.rootDir);
|
|
971
|
+
const provisionStateOutput = Object.fromEntries(Object.entries(provisionState).map(([provider, categories]) => [provider, Object.fromEntries(Object.entries(categories ?? {}).map(([category, ids]) => [category, Object.fromEntries(Object.entries(ids ?? {}).map(([key, id]) => [key, redactInspectionValue(id)]))]))]));
|
|
972
|
+
return {
|
|
973
|
+
...report,
|
|
974
|
+
content: provisionStateOutput
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
return redactInspectionValue(report);
|
|
978
|
+
});
|
|
979
|
+
context.stdout.write(`${JSON.stringify({ providerOutput }, null, 2)}\n`);
|
|
980
|
+
return 0;
|
|
981
|
+
}
|
|
982
|
+
const present = reports.filter((report) => report.exists);
|
|
983
|
+
const missing = reports.filter((report) => !report.exists);
|
|
984
|
+
const lines = [`Provider Output: ${present.length} of ${reports.length} present`];
|
|
985
|
+
for (const report of present) lines.push(` ${report.path} (${report.owner}) ${report.description}`);
|
|
986
|
+
if (missing.length) {
|
|
987
|
+
lines.push("", "Not generated:");
|
|
988
|
+
for (const report of missing) lines.push(` ${report.path} (${report.owner}) ${report.description}`);
|
|
989
|
+
}
|
|
990
|
+
lines.push("");
|
|
991
|
+
context.stdout.write(lines.join("\n"));
|
|
992
|
+
return 0;
|
|
993
|
+
}
|
|
994
|
+
/** Built-in namespace that renders package-owned inspection data. */
|
|
995
|
+
function createInspectNamespace(plugins, operations = []) {
|
|
996
|
+
return {
|
|
997
|
+
description: "Inspect discovered Definitions and generated Provider Output.",
|
|
998
|
+
features: [{
|
|
999
|
+
description: "List Definitions discovered by each active package.",
|
|
1000
|
+
name: "definitions",
|
|
1001
|
+
run: (args, context) => runDefinitions(args, context, plugins, operations),
|
|
1002
|
+
usage: definitionsUsage
|
|
1003
|
+
}, {
|
|
1004
|
+
description: "List generated Provider Output files with secrets redacted.",
|
|
1005
|
+
name: "provider-output",
|
|
1006
|
+
run: (args, context) => runProviderOutput(args, context, plugins),
|
|
1007
|
+
usage: providerOutputUsage
|
|
1008
|
+
}],
|
|
1009
|
+
name: "inspect"
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
//#endregion
|
|
1013
|
+
//#region ../internal/dist/contributions.js
|
|
1014
|
+
function isThenable(value) {
|
|
1015
|
+
return typeof value.then === "function";
|
|
1016
|
+
}
|
|
1017
|
+
async function flattenPlugins(value, plugins, seen) {
|
|
1018
|
+
if (Array.isArray(value)) {
|
|
1019
|
+
for (const item of value) await flattenPlugins(item, plugins, seen);
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
if (!isPlainObject(value) || seen.has(value)) return;
|
|
1023
|
+
seen.add(value);
|
|
1024
|
+
if (isThenable(value)) {
|
|
1025
|
+
await flattenPlugins(await value, plugins, seen);
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
plugins.push(value);
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
|
|
1032
|
+
* list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
|
|
1033
|
+
* filter this list, because `vitehub()` nests its plugins in an array.
|
|
1034
|
+
*/
|
|
1035
|
+
async function flattenPluginOptions(plugins) {
|
|
1036
|
+
const flattened = [];
|
|
1037
|
+
await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
|
|
1038
|
+
return flattened;
|
|
1039
|
+
}
|
|
1040
|
+
//#endregion
|
|
1041
|
+
//#region ../internal/dist/secret.js
|
|
1042
|
+
const secretEncoder = new TextEncoder();
|
|
1043
|
+
/** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
|
|
1044
|
+
const viteHubSecretSalt = "vitehub";
|
|
1045
|
+
function hex$1(buffer) {
|
|
1046
|
+
return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Reads the root app secret from an env record: `VITEHUB_SECRET`, then `NUXT_APP_SECRET`, so a Nuxt app needs only one
|
|
1050
|
+
* secret. Returns `undefined` when neither is a non-empty string.
|
|
1051
|
+
*/
|
|
1052
|
+
function readViteHubSecret(env) {
|
|
1053
|
+
for (const name of ["VITEHUB_SECRET", "NUXT_APP_SECRET"]) {
|
|
1054
|
+
const value = env[name];
|
|
1055
|
+
if (typeof value === "string" && value) return value;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Derives a 32-byte secret for one purpose from the root secret, hex-encoded. It uses HKDF-SHA256 with the salt
|
|
1060
|
+
* `vitehub` and the purpose as `info`. The result is stable while the root is unchanged and distinct for every purpose.
|
|
1061
|
+
* Throws a `TypeError` when the root is shorter than 32 characters or the purpose is empty. It uses no Node API.
|
|
1062
|
+
*/
|
|
1063
|
+
async function deriveViteHubSecret(root, purpose) {
|
|
1064
|
+
if (root.length < 32) throw new TypeError(`[vitehub] VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.`);
|
|
1065
|
+
if (!purpose) throw new TypeError("[vitehub] A derived secret requires a purpose.");
|
|
1066
|
+
const key = await globalThis.crypto.subtle.importKey("raw", secretEncoder.encode(root), "HKDF", false, ["deriveBits"]);
|
|
1067
|
+
return hex$1(await globalThis.crypto.subtle.deriveBits({
|
|
1068
|
+
hash: "SHA-256",
|
|
1069
|
+
info: secretEncoder.encode(purpose),
|
|
1070
|
+
name: "HKDF",
|
|
1071
|
+
salt: secretEncoder.encode(viteHubSecretSalt)
|
|
1072
|
+
}, key, 256));
|
|
1073
|
+
}
|
|
1074
|
+
//#endregion
|
|
1075
|
+
//#region ../internal/dist/dispatch.js
|
|
1076
|
+
/**
|
|
1077
|
+
* Dispatch lets a CLI run one server operation, such as a manual Schedule run, without a browser session.
|
|
1078
|
+
* The client signs the request with the dispatch key. The server derives the same key from its root secret.
|
|
1079
|
+
* It uses no Node API, so it also runs in Worker runtimes.
|
|
1080
|
+
*/
|
|
1081
|
+
/** The `deriveSecret()` purpose of the dispatch key. `vitehub secret derive vitehub:dispatch` prints the key. */
|
|
1082
|
+
const viteHubDispatchKeyPurpose = "vitehub:dispatch";
|
|
1083
|
+
const viteHubDispatchHeaders = {
|
|
1084
|
+
actor: "x-vitehub-dispatch-actor",
|
|
1085
|
+
nonce: "x-vitehub-dispatch-nonce",
|
|
1086
|
+
signature: "x-vitehub-dispatch-signature",
|
|
1087
|
+
timestamp: "x-vitehub-dispatch-timestamp"
|
|
1088
|
+
};
|
|
1089
|
+
const encoder = new TextEncoder();
|
|
1090
|
+
const keyPattern = /^[0-9a-f]{64}$/;
|
|
1091
|
+
function hex(buffer) {
|
|
1092
|
+
return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1093
|
+
}
|
|
1094
|
+
async function sha256(text) {
|
|
1095
|
+
return hex(await globalThis.crypto.subtle.digest("SHA-256", encoder.encode(text)));
|
|
1096
|
+
}
|
|
1097
|
+
async function hmac(key, message) {
|
|
1098
|
+
const cryptoKey = await globalThis.crypto.subtle.importKey("raw", encoder.encode(key), {
|
|
1099
|
+
hash: "SHA-256",
|
|
1100
|
+
name: "HMAC"
|
|
1101
|
+
}, false, ["sign"]);
|
|
1102
|
+
return hex(await globalThis.crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(message)));
|
|
1103
|
+
}
|
|
1104
|
+
function canonical(fields) {
|
|
1105
|
+
return [
|
|
1106
|
+
"vitehub-dispatch-v1",
|
|
1107
|
+
fields.operation,
|
|
1108
|
+
fields.timestamp,
|
|
1109
|
+
fields.nonce,
|
|
1110
|
+
fields.actor,
|
|
1111
|
+
fields.bodyHash
|
|
1112
|
+
].join("\n");
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Resolves the dispatch key of a client: `VITEHUB_DISPATCH_KEY`, or the key derived from `VITEHUB_SECRET` or
|
|
1116
|
+
* `NUXT_APP_SECRET`. Returns `undefined` when none is set. Throws a `TypeError` for a malformed `VITEHUB_DISPATCH_KEY`.
|
|
1117
|
+
*/
|
|
1118
|
+
async function resolveViteHubDispatchKey(env) {
|
|
1119
|
+
const key = env.VITEHUB_DISPATCH_KEY;
|
|
1120
|
+
if (typeof key === "string" && key) {
|
|
1121
|
+
if (!keyPattern.test(key)) throw new TypeError("[vitehub] VITEHUB_DISPATCH_KEY must be the 64-character hex key that `vitehub secret derive vitehub:dispatch` prints.");
|
|
1122
|
+
return key;
|
|
1123
|
+
}
|
|
1124
|
+
const root = readViteHubSecret(env);
|
|
1125
|
+
return root ? await deriveViteHubSecret(root, viteHubDispatchKeyPurpose) : void 0;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Signs one dispatch request and returns its headers. The signature covers the operation, the time, a one-time nonce,
|
|
1129
|
+
* the actor claim, and the exact body. The actor claim is self-asserted: anyone with the key can choose it.
|
|
1130
|
+
*/
|
|
1131
|
+
async function signViteHubDispatch(options) {
|
|
1132
|
+
const actor = options.actor ?? "";
|
|
1133
|
+
const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
|
|
1134
|
+
const nonce = hex(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)));
|
|
1135
|
+
const signature = await hmac(options.key, canonical({
|
|
1136
|
+
actor,
|
|
1137
|
+
bodyHash: await sha256(options.body),
|
|
1138
|
+
nonce,
|
|
1139
|
+
operation: options.operation,
|
|
1140
|
+
timestamp
|
|
1141
|
+
}));
|
|
1142
|
+
return {
|
|
1143
|
+
...actor ? { [viteHubDispatchHeaders.actor]: actor } : {},
|
|
1144
|
+
[viteHubDispatchHeaders.nonce]: nonce,
|
|
1145
|
+
[viteHubDispatchHeaders.signature]: `v1=${signature}`,
|
|
1146
|
+
[viteHubDispatchHeaders.timestamp]: timestamp
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
//#endregion
|
|
1150
|
+
//#region src/error-diagnostics.ts
|
|
1151
|
+
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
1152
|
+
const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
1153
|
+
docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
|
|
1154
|
+
codes: {
|
|
1155
|
+
CLI_R0001: dynamicError,
|
|
1156
|
+
CLI_R0002: dynamicError,
|
|
1157
|
+
CLI_R0003: {
|
|
1158
|
+
fix: "Run the command with --help to see its input.",
|
|
1159
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
1160
|
+
},
|
|
1161
|
+
CLI_R0005: {
|
|
1162
|
+
fix: "Start `vite dev` in this project, or pass `--url <origin>` of a running or deployed app. `VITEHUB_DEV_SERVER_URL` also names a server.",
|
|
1163
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
1164
|
+
},
|
|
1165
|
+
CLI_R0006: dynamicError,
|
|
1166
|
+
CLI_R0004: {
|
|
1167
|
+
fix: "Run it again with --yes, or check the change first with a dry run when the command has one.",
|
|
1168
|
+
why: ({ message }) => message === void 0 ? "" : String(message)
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
});
|
|
1172
|
+
//#endregion
|
|
1173
|
+
//#region src/operations.ts
|
|
1174
|
+
/** Reads every contributed operation of the resolved plugins. A module that fails to load is reported on stderr. */
|
|
1175
|
+
async function loadCliOperations(plugins, stderr) {
|
|
1176
|
+
const sources = [];
|
|
1177
|
+
for (const contribution of await collectOperationContributions(await flattenPluginOptions(plugins))) try {
|
|
1178
|
+
const exported = contribution.load ? await contribution.load() : Reflect.get(Object(await import(
|
|
1179
|
+
/* @vite-ignore */
|
|
1180
|
+
contribution.module
|
|
1181
|
+
)), contribution.export);
|
|
1182
|
+
sources.push({
|
|
1183
|
+
operations: operationsOf(exported),
|
|
1184
|
+
plugin: contribution.plugin
|
|
1185
|
+
});
|
|
1186
|
+
} catch (error) {
|
|
1187
|
+
stderr.write(`Could not load the operations of ${contribution.plugin} from ${contribution.module}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1188
|
+
}
|
|
1189
|
+
return createOperationRegistry(sources).list();
|
|
1190
|
+
}
|
|
1191
|
+
function kebab(key) {
|
|
1192
|
+
return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
1193
|
+
}
|
|
1194
|
+
function camel(flag) {
|
|
1195
|
+
return flag.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
|
|
1196
|
+
}
|
|
1197
|
+
function isObject(value) {
|
|
1198
|
+
return value !== null && Object(value) === value && !Array.isArray(value);
|
|
1199
|
+
}
|
|
1200
|
+
const scalarTypes = /* @__PURE__ */ new Set([
|
|
1201
|
+
"boolean",
|
|
1202
|
+
"integer",
|
|
1203
|
+
"number",
|
|
1204
|
+
"string"
|
|
1205
|
+
]);
|
|
1206
|
+
/** Reads the type of a JSON Schema node. Objects, unknown values, and lists of objects are JSON. */
|
|
1207
|
+
function readType(schema) {
|
|
1208
|
+
if (!isObject(schema)) return {
|
|
1209
|
+
alternatives: [],
|
|
1210
|
+
nullable: false,
|
|
1211
|
+
type: "json"
|
|
1212
|
+
};
|
|
1213
|
+
const options = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : void 0;
|
|
1214
|
+
if (options) {
|
|
1215
|
+
const parts = options.map(readType);
|
|
1216
|
+
const nulls = options.filter((option) => isObject(option) && option.type === "null").length;
|
|
1217
|
+
const present = parts.filter((_part, index) => !(isObject(options[index]) && options[index].type === "null"));
|
|
1218
|
+
const nullable = nulls > 0 || parts.some((part) => part.nullable);
|
|
1219
|
+
if (present.length === 1) return {
|
|
1220
|
+
...present[0],
|
|
1221
|
+
nullable
|
|
1222
|
+
};
|
|
1223
|
+
const scalars = present.map((part) => part.type);
|
|
1224
|
+
if (scalars.every((type) => type !== "json" && type !== "list")) return {
|
|
1225
|
+
alternatives: scalars.includes("string") ? ["string"] : scalars,
|
|
1226
|
+
nullable,
|
|
1227
|
+
type: scalars.includes("string") ? "string" : scalars[0]
|
|
1228
|
+
};
|
|
1229
|
+
return {
|
|
1230
|
+
alternatives: [],
|
|
1231
|
+
nullable,
|
|
1232
|
+
type: "json"
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
const declared = schema.type;
|
|
1236
|
+
if (Array.isArray(declared)) {
|
|
1237
|
+
const kinds = declared.filter((kind) => kind !== "null");
|
|
1238
|
+
const nullable = declared.includes("null");
|
|
1239
|
+
return kinds.length === 1 ? {
|
|
1240
|
+
...readType({
|
|
1241
|
+
...schema,
|
|
1242
|
+
type: kinds[0]
|
|
1243
|
+
}),
|
|
1244
|
+
nullable
|
|
1245
|
+
} : {
|
|
1246
|
+
alternatives: [],
|
|
1247
|
+
nullable,
|
|
1248
|
+
type: "json"
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
if (typeof declared === "string" && scalarTypes.has(declared)) return {
|
|
1252
|
+
alternatives: [],
|
|
1253
|
+
nullable: false,
|
|
1254
|
+
type: declared
|
|
1255
|
+
};
|
|
1256
|
+
if (declared === "array") {
|
|
1257
|
+
const items = readType(schema.items);
|
|
1258
|
+
return items.type === "json" || items.type === "list" ? {
|
|
1259
|
+
alternatives: [],
|
|
1260
|
+
nullable: false,
|
|
1261
|
+
type: "json"
|
|
1262
|
+
} : {
|
|
1263
|
+
alternatives: [],
|
|
1264
|
+
item: items.type,
|
|
1265
|
+
nullable: false,
|
|
1266
|
+
type: "list"
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === "string")) return {
|
|
1270
|
+
alternatives: [],
|
|
1271
|
+
nullable: false,
|
|
1272
|
+
type: "string"
|
|
1273
|
+
};
|
|
1274
|
+
if (typeof schema.const === "string") return {
|
|
1275
|
+
alternatives: [],
|
|
1276
|
+
nullable: false,
|
|
1277
|
+
type: "string"
|
|
1278
|
+
};
|
|
1279
|
+
return {
|
|
1280
|
+
alternatives: [],
|
|
1281
|
+
nullable: false,
|
|
1282
|
+
type: "json"
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
function flagsOf(operation) {
|
|
1286
|
+
const schema = operationInputJsonSchema(operation);
|
|
1287
|
+
const properties = isObject(schema.properties) ? Object.entries(schema.properties) : [];
|
|
1288
|
+
const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
|
|
1289
|
+
return properties.map(([key, property]) => {
|
|
1290
|
+
const description = isObject(property) ? property.description : void 0;
|
|
1291
|
+
return {
|
|
1292
|
+
...readType(property),
|
|
1293
|
+
key,
|
|
1294
|
+
required: required.includes(key),
|
|
1295
|
+
...typeof description === "string" ? { description } : {}
|
|
1296
|
+
};
|
|
1297
|
+
});
|
|
1298
|
+
}
|
|
1299
|
+
function usageOf(operation, flags) {
|
|
1300
|
+
const { command, namespace } = operationCliPath(operation);
|
|
1301
|
+
const positional = operation.cli?.positional ?? [];
|
|
1302
|
+
const names = positional.map((key) => {
|
|
1303
|
+
return flags.find((entry) => entry.key === key)?.required === false ? `[${kebab(key)}]` : `<${kebab(key)}>`;
|
|
1304
|
+
});
|
|
1305
|
+
const options = flags.filter((flag) => !positional.includes(flag.key)).map((flag) => {
|
|
1306
|
+
const name = `--${kebab(flag.key)}${flag.type === "boolean" ? "" : " <value>"}`;
|
|
1307
|
+
return flag.required ? name : `[${name}]`;
|
|
1308
|
+
});
|
|
1309
|
+
return [
|
|
1310
|
+
"vitehub",
|
|
1311
|
+
namespace,
|
|
1312
|
+
command,
|
|
1313
|
+
...names,
|
|
1314
|
+
...options,
|
|
1315
|
+
"[--input <json|@file>]",
|
|
1316
|
+
"[--json]",
|
|
1317
|
+
...operation.kind === "destructive" ? ["[--yes]"] : [],
|
|
1318
|
+
"[--url <origin>]"
|
|
1319
|
+
].join(" ");
|
|
1320
|
+
}
|
|
1321
|
+
function describeFlag(flag) {
|
|
1322
|
+
return `${flag.type === "json" ? "JSON" : flag.type === "list" ? "list (repeat the flag or separate with commas)" : flag.type}${flag.nullable ? " or null" : ""}${flag.required ? ", required" : ""}`;
|
|
1323
|
+
}
|
|
1324
|
+
function helpOf(operation, flags) {
|
|
1325
|
+
const positional = operation.cli?.positional ?? [];
|
|
1326
|
+
const lines = [
|
|
1327
|
+
`Usage: ${usageOf(operation, flags)}`,
|
|
1328
|
+
"",
|
|
1329
|
+
operation.description,
|
|
1330
|
+
""
|
|
1331
|
+
];
|
|
1332
|
+
const described = flags.map((flag) => ` ${positional.includes(flag.key) ? `<${kebab(flag.key)}>` : `--${kebab(flag.key)}`} ${describeFlag(flag)}${flag.description ? `. ${flag.description}` : ""}`);
|
|
1333
|
+
if (described.length) lines.push("Input:", ...described, "");
|
|
1334
|
+
lines.push("Options:", " --input <json|@file> Pass the whole input as JSON or from a file. Flags override it.", " --json Print JSON.", ...operation.kind === "destructive" ? [" --yes Run without asking. This operation changes or removes data."] : [], " --url <origin> Call a deployed app. Without it the command calls the running dev server.", " --timeout <ms> Wait this long for the answer. Default 30000.", " -h, --help Show this help.", "");
|
|
1335
|
+
return lines.join("\n");
|
|
1336
|
+
}
|
|
1337
|
+
function usageError(message) {
|
|
1338
|
+
return cliErrorDiagnostics.CLI_R0003({ message });
|
|
1339
|
+
}
|
|
1340
|
+
function parseJson(raw, name) {
|
|
1341
|
+
try {
|
|
1342
|
+
return JSON.parse(raw);
|
|
1343
|
+
} catch (error) {
|
|
1344
|
+
throw usageError(`--${name} must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
function convertScalar(type, name, raw) {
|
|
1348
|
+
switch (type) {
|
|
1349
|
+
case "integer":
|
|
1350
|
+
case "number": {
|
|
1351
|
+
const value = Number(raw);
|
|
1352
|
+
if (raw.trim() === "" || !Number.isFinite(value) || type === "integer" && !Number.isInteger(value)) throw usageError(`--${name} must be ${type === "integer" ? "a whole number" : "a number"}.`);
|
|
1353
|
+
return value;
|
|
1354
|
+
}
|
|
1355
|
+
case "boolean":
|
|
1356
|
+
if (raw !== "true" && raw !== "false") throw usageError(`--${name} must be true or false.`);
|
|
1357
|
+
return raw === "true";
|
|
1358
|
+
case "json": return parseJson(raw, name);
|
|
1359
|
+
default: return raw;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
function convert(flag, name, raw) {
|
|
1363
|
+
if (!flag) return raw;
|
|
1364
|
+
if (flag.nullable && raw === "null") return null;
|
|
1365
|
+
if (flag.alternatives.length > 1) {
|
|
1366
|
+
for (const type of flag.alternatives) try {
|
|
1367
|
+
return convertScalar(type, name, raw);
|
|
1368
|
+
} catch {
|
|
1369
|
+
continue;
|
|
1370
|
+
}
|
|
1371
|
+
throw usageError(`--${name} must be one of: ${flag.alternatives.join(", ")}.`);
|
|
1372
|
+
}
|
|
1373
|
+
return convertScalar(flag.type, name, raw);
|
|
1374
|
+
}
|
|
1375
|
+
function assign(input, flag, key, name, raw) {
|
|
1376
|
+
if (flag?.type === "list") {
|
|
1377
|
+
if (flag.nullable && raw === "null") {
|
|
1378
|
+
input[key] = null;
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
const items = raw.trim().startsWith("[") ? parseJson(raw, name) : raw.split(",").map((item) => item.trim()).filter(Boolean).map((item) => convertScalar(flag.item ?? "string", name, item));
|
|
1382
|
+
if (!Array.isArray(items)) throw usageError(`--${name} must be a list.`);
|
|
1383
|
+
input[key] = [...Array.isArray(input[key]) ? input[key] : [], ...items];
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
input[key] = convert(flag, name, raw);
|
|
1387
|
+
}
|
|
1388
|
+
/** `--input '{"a":1}'` or `--input @file.json`. */
|
|
1389
|
+
function readWholeInput(raw, cwd) {
|
|
1390
|
+
let text = raw;
|
|
1391
|
+
if (raw.startsWith("@")) try {
|
|
1392
|
+
text = readFileSync(resolve(cwd, raw.slice(1)), "utf8");
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
throw usageError(`--input could not read ${raw.slice(1)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1395
|
+
}
|
|
1396
|
+
const value = parseJson(text, "input");
|
|
1397
|
+
if (!isObject(value)) throw usageError("--input must be a JSON object.");
|
|
1398
|
+
return value;
|
|
1399
|
+
}
|
|
1400
|
+
function parseCall(operation, flags, args, cwd) {
|
|
1401
|
+
const parsed = {
|
|
1402
|
+
help: false,
|
|
1403
|
+
input: {},
|
|
1404
|
+
json: false,
|
|
1405
|
+
yes: false
|
|
1406
|
+
};
|
|
1407
|
+
const positional = [...operation.cli?.positional ?? []];
|
|
1408
|
+
const { command, namespace } = operationCliPath(operation);
|
|
1409
|
+
let whole = {};
|
|
1410
|
+
for (let index = 0; index < args.length; index++) {
|
|
1411
|
+
const arg = args[index];
|
|
1412
|
+
if (arg === "--") {
|
|
1413
|
+
for (const rest of args.slice(index + 1)) {
|
|
1414
|
+
const key = positional.shift();
|
|
1415
|
+
if (!key) throw usageError(`Unexpected argument ${JSON.stringify(rest)}.`);
|
|
1416
|
+
assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), rest);
|
|
1417
|
+
}
|
|
1418
|
+
break;
|
|
1419
|
+
}
|
|
1420
|
+
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
1421
|
+
else if (arg === "--json") parsed.json = true;
|
|
1422
|
+
else if (arg === "--yes" || arg === "-y") parsed.yes = true;
|
|
1423
|
+
else if (arg.startsWith("--")) {
|
|
1424
|
+
const equals = arg.indexOf("=");
|
|
1425
|
+
const name = arg.slice(2, equals === -1 ? void 0 : equals);
|
|
1426
|
+
const inline = equals === -1 ? void 0 : arg.slice(equals + 1);
|
|
1427
|
+
const take = () => {
|
|
1428
|
+
if (inline !== void 0) return inline;
|
|
1429
|
+
const next = args[index + 1];
|
|
1430
|
+
if (next === void 0 || next.startsWith("--") && next !== "--") throw usageError(`Option --${name} needs a value.`);
|
|
1431
|
+
index++;
|
|
1432
|
+
return next;
|
|
1433
|
+
};
|
|
1434
|
+
if (name === "url") parsed.url = take();
|
|
1435
|
+
else if (name === "input") whole = readWholeInput(take(), cwd);
|
|
1436
|
+
else if (name === "timeout") {
|
|
1437
|
+
const timeout = Number(take());
|
|
1438
|
+
if (!Number.isInteger(timeout) || timeout < 1) throw usageError("--timeout must be a whole number of milliseconds.");
|
|
1439
|
+
parsed.timeout = timeout;
|
|
1440
|
+
} else {
|
|
1441
|
+
const negated = name.startsWith("no-") && flags.some((flag) => flag.key === camel(name.slice(3)) && flag.type === "boolean");
|
|
1442
|
+
const key = camel(negated ? name.slice(3) : name);
|
|
1443
|
+
const flag = flags.find((entry) => entry.key === key);
|
|
1444
|
+
if (!flag) throw usageError(`Unknown option --${name}. Run \`vitehub ${namespace} ${command} --help\` for the input.`);
|
|
1445
|
+
if (flag.type === "boolean") {
|
|
1446
|
+
const next = args[index + 1];
|
|
1447
|
+
const value = inline !== void 0 ? convertScalar("boolean", name, inline) : !negated && (next === "true" || next === "false") ? (index++, next === "true") : true;
|
|
1448
|
+
parsed.input[key] = negated ? false : value;
|
|
1449
|
+
} else assign(parsed.input, flag, key, name, take());
|
|
1450
|
+
}
|
|
1451
|
+
} else {
|
|
1452
|
+
const key = positional.shift();
|
|
1453
|
+
if (!key) throw usageError(`Unexpected argument ${JSON.stringify(arg)}.`);
|
|
1454
|
+
assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), arg);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
parsed.input = {
|
|
1458
|
+
...whole,
|
|
1459
|
+
...parsed.input
|
|
1460
|
+
};
|
|
1461
|
+
return parsed;
|
|
1462
|
+
}
|
|
1463
|
+
function writeFailure(failure, parsed, context) {
|
|
1464
|
+
if (parsed.json) {
|
|
1465
|
+
context.stdout.write(`${JSON.stringify({ error: {
|
|
1466
|
+
code: failure.code,
|
|
1467
|
+
...failure.details ? { details: failure.details } : {},
|
|
1468
|
+
...failure.docs ? { docs: failure.docs } : {},
|
|
1469
|
+
...failure.fix ? { fix: failure.fix } : {},
|
|
1470
|
+
message: failure.message
|
|
1471
|
+
} }, null, 2)}\n`);
|
|
1472
|
+
return 1;
|
|
1473
|
+
}
|
|
1474
|
+
context.stderr.write([
|
|
1475
|
+
`${failure.code}: ${failure.message}`,
|
|
1476
|
+
...failure.fix ? [`Fix: ${failure.fix}`] : [],
|
|
1477
|
+
...failure.docs ? [`Docs: ${failure.docs}`] : [],
|
|
1478
|
+
""
|
|
1479
|
+
].join("\n"));
|
|
1480
|
+
return 1;
|
|
1481
|
+
}
|
|
1482
|
+
/** A coded failure for a thrown diagnostic. */
|
|
1483
|
+
function failureOf(error, status = 400) {
|
|
1484
|
+
const code = Reflect.get(Object(error), "code");
|
|
1485
|
+
const fix = Reflect.get(Object(error), "fix");
|
|
1486
|
+
return {
|
|
1487
|
+
code: typeof code === "string" && code ? code : "CLI_R0003",
|
|
1488
|
+
...typeof fix === "string" && fix ? { fix } : {},
|
|
1489
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1490
|
+
status
|
|
1491
|
+
};
|
|
1492
|
+
}
|
|
1493
|
+
async function confirm(operation, target) {
|
|
1494
|
+
const terminal = createInterface({
|
|
1495
|
+
input: process.stdin,
|
|
1496
|
+
output: process.stderr
|
|
1497
|
+
});
|
|
1498
|
+
try {
|
|
1499
|
+
const answer = await terminal.question(`${operation.description} This changes data at ${target}. Continue? [y/N] `);
|
|
1500
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
1501
|
+
} finally {
|
|
1502
|
+
terminal.close();
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
/** The roots that the CLI accepts a dev server for: the Vite root and the ViteHub project root. */
|
|
1506
|
+
function acceptedRoots(rootDir) {
|
|
1507
|
+
const roots = /* @__PURE__ */ new Set([rootDir]);
|
|
1508
|
+
try {
|
|
1509
|
+
roots.add(resolveViteHubProjectRoot(rootDir));
|
|
1510
|
+
} catch {}
|
|
1511
|
+
return [...roots];
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* Where a command sends its call: `--url`, else the dev server that wrote `.vitehub/dev-server.json` in this project,
|
|
1515
|
+
* else `VITEHUB_DEV_SERVER_URL`. There is no guess: another project may use port 5173.
|
|
1516
|
+
*/
|
|
1517
|
+
function resolveTarget(parsed, context) {
|
|
1518
|
+
if (parsed.url) {
|
|
1519
|
+
let base;
|
|
1520
|
+
try {
|
|
1521
|
+
base = new URL(parsed.url);
|
|
1522
|
+
} catch {
|
|
1523
|
+
return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must be a URL." })) };
|
|
1524
|
+
}
|
|
1525
|
+
const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
|
|
1526
|
+
if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must use HTTPS, except for localhost." })) };
|
|
1527
|
+
if (base.username || base.password || base.search || base.hash) return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must not contain credentials, a query, or a fragment." })) };
|
|
1528
|
+
return { target: parsed.url };
|
|
1529
|
+
}
|
|
1530
|
+
const found = findViteHubDevServerUrl(acceptedRoots(context.rootDir), context.env);
|
|
1531
|
+
if (found) return { target: found };
|
|
1532
|
+
return { failure: failureOf(cliErrorDiagnostics.CLI_R0005({ message: `No dev server is running for ${context.rootDir}.` }), 503) };
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Posts a signed dispatch to the route of an operation on a deployed app. Returns undefined when no dispatch key is set,
|
|
1536
|
+
* so the command falls back to the RPC with Console credentials.
|
|
1537
|
+
*/
|
|
1538
|
+
async function callDispatch(operation, route, url, input, context, timeout) {
|
|
1539
|
+
const base = new URL(url);
|
|
1540
|
+
let key;
|
|
1541
|
+
try {
|
|
1542
|
+
key = await resolveViteHubDispatchKey(context.env);
|
|
1543
|
+
} catch (error) {
|
|
1544
|
+
return {
|
|
1545
|
+
...failureOf(cliErrorDiagnostics.CLI_R0003({ message: error instanceof Error ? error.message : String(error) })),
|
|
1546
|
+
ok: false
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
if (!key) return void 0;
|
|
1550
|
+
if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
|
|
1551
|
+
const target = new URL(route.slice(1), base);
|
|
1552
|
+
const body = JSON.stringify(input ?? {});
|
|
1553
|
+
const actor = context.env.VITEHUB_ACTOR || context.env.USER || context.env.USERNAME || void 0;
|
|
1554
|
+
const headers = new Headers({
|
|
1555
|
+
accept: "application/json",
|
|
1556
|
+
"content-type": "application/json",
|
|
1557
|
+
...await signViteHubDispatch({
|
|
1558
|
+
actor,
|
|
1559
|
+
body,
|
|
1560
|
+
key,
|
|
1561
|
+
operation
|
|
1562
|
+
})
|
|
1563
|
+
});
|
|
1564
|
+
if (context.env.CF_ACCESS_CLIENT_ID) headers.set("cf-access-client-id", context.env.CF_ACCESS_CLIENT_ID);
|
|
1565
|
+
if (context.env.CF_ACCESS_CLIENT_SECRET) headers.set("cf-access-client-secret", context.env.CF_ACCESS_CLIENT_SECRET);
|
|
1566
|
+
let response;
|
|
1567
|
+
let text;
|
|
1568
|
+
try {
|
|
1569
|
+
response = await (context.fetch ?? fetch)(target.href, {
|
|
1570
|
+
body,
|
|
1571
|
+
headers,
|
|
1572
|
+
method: "POST",
|
|
1573
|
+
redirect: "manual",
|
|
1574
|
+
signal: AbortSignal.timeout(timeout ?? 3e4)
|
|
1575
|
+
});
|
|
1576
|
+
text = await response.text();
|
|
1577
|
+
} catch (error) {
|
|
1578
|
+
return {
|
|
1579
|
+
...failureOf(cliErrorDiagnostics.CLI_R0006({ message: `The signed request to ${target.origin} failed: ${redactInspectionText(error instanceof Error ? error.message : String(error))}` }), 502),
|
|
1580
|
+
ok: false
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
let json;
|
|
1584
|
+
try {
|
|
1585
|
+
json = text ? JSON.parse(text, (key, value) => isSecretInspectionKey(key) ? redactedInspectionValue : typeof value === "string" ? redactInspectionText(value) : value) : void 0;
|
|
1586
|
+
} catch {
|
|
1587
|
+
json = void 0;
|
|
1588
|
+
}
|
|
1589
|
+
if (response.ok && json !== void 0) return {
|
|
1590
|
+
ok: true,
|
|
1591
|
+
value: json
|
|
1592
|
+
};
|
|
1593
|
+
const message = Reflect.get(Object(json), "message");
|
|
1594
|
+
const failure = failureOf(cliErrorDiagnostics.CLI_R0006({ message: `The signed request failed with HTTP ${response.status}${typeof message === "string" && message ? `: ${message}` : "."}` }), response.status);
|
|
1595
|
+
if (response.status === 401) failure.fix = "Set VITEHUB_DISPATCH_KEY to the key of the app (`vitehub secret derive vitehub:dispatch` prints it), and keep the clock of this machine correct.";
|
|
1596
|
+
return {
|
|
1597
|
+
...failure,
|
|
1598
|
+
ok: false
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
function featureOf(operation) {
|
|
1602
|
+
const flags = flagsOf(operation);
|
|
1603
|
+
const { command } = operationCliPath(operation);
|
|
1604
|
+
return {
|
|
1605
|
+
description: operation.description,
|
|
1606
|
+
name: command,
|
|
1607
|
+
async run(args, context) {
|
|
1608
|
+
let parsed;
|
|
1609
|
+
try {
|
|
1610
|
+
parsed = parseCall(operation, flags, args, context.cwd);
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
const failure = failureOf(error);
|
|
1613
|
+
if (args.includes("--json")) return writeFailure(failure, { json: true }, context);
|
|
1614
|
+
context.stderr.write(`${failure.message}\nUsage: ${usageOf(operation, flags)}\n`);
|
|
1615
|
+
return 1;
|
|
1616
|
+
}
|
|
1617
|
+
if (parsed.help) {
|
|
1618
|
+
context.stdout.write(helpOf(operation, flags));
|
|
1619
|
+
return 0;
|
|
1620
|
+
}
|
|
1621
|
+
let reads;
|
|
1622
|
+
try {
|
|
1623
|
+
reads = operationCall(operation, await parseOperationInput(operation, parsed.input)).readOnly === true;
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
return writeFailure(failureOf(error), parsed, context);
|
|
1626
|
+
}
|
|
1627
|
+
const resolved = resolveTarget(parsed, context);
|
|
1628
|
+
if ("failure" in resolved) return writeFailure(resolved.failure, parsed, context);
|
|
1629
|
+
const target = resolved.target;
|
|
1630
|
+
let confirmed = parsed.yes;
|
|
1631
|
+
if (operation.kind === "destructive" && !parsed.yes && !reads) {
|
|
1632
|
+
if (!(process.stdin.isTTY && process.stderr.isTTY) || !await confirm(operation, target)) return writeFailure(failureOf(cliErrorDiagnostics.CLI_R0004({ message: `${operation.name} changes or removes data and was not confirmed.` })), parsed, context);
|
|
1633
|
+
confirmed = true;
|
|
1634
|
+
}
|
|
1635
|
+
const result = (operation.cli?.dispatch && parsed.url ? await callDispatch(operation.name, operation.cli.dispatch, parsed.url, parsed.input, context, parsed.timeout) : void 0) ?? await callOperation({
|
|
1636
|
+
confirmed,
|
|
1637
|
+
env: context.env,
|
|
1638
|
+
...context.fetch ? { fetch: context.fetch } : {},
|
|
1639
|
+
...parsed.url ? {} : { roots: acceptedRoots(context.rootDir) },
|
|
1640
|
+
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
1641
|
+
url: target
|
|
1642
|
+
}, operation.name, parsed.input);
|
|
1643
|
+
if (!result.ok) return writeFailure(result, parsed, context);
|
|
1644
|
+
const format = operation.cli?.format;
|
|
1645
|
+
const output = !parsed.json && format ? format(result.value) : `${JSON.stringify(result.value ?? null, null, 2)}\n`;
|
|
1646
|
+
context.stdout.write(output);
|
|
1647
|
+
return 0;
|
|
1648
|
+
},
|
|
1649
|
+
usage: usageOf(operation, flags)
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
/** One namespace per operation namespace, with a command for each operation. */
|
|
1653
|
+
function createOperationNamespaces(operations) {
|
|
1654
|
+
const namespaces = /* @__PURE__ */ new Map();
|
|
1655
|
+
for (const operation of operations) {
|
|
1656
|
+
const { namespace: name } = operationCliPath(operation);
|
|
1657
|
+
const namespace = namespaces.get(name) ?? {
|
|
1658
|
+
description: `Run the ${name} operations of the app.`,
|
|
1659
|
+
features: [],
|
|
1660
|
+
name
|
|
1661
|
+
};
|
|
1662
|
+
namespace.features.push(featureOf(operation));
|
|
1663
|
+
if (operation.cli?.default) namespace.defaultFeature = operationCliPath(operation).command;
|
|
1664
|
+
namespaces.set(name, namespace);
|
|
1665
|
+
}
|
|
1666
|
+
return [...namespaces.values()];
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* Adds the generated namespaces to the ones that packages wrote by hand. A hand-written command with the same name wins,
|
|
1670
|
+
* since it can offer more than the generated one, such as an editor.
|
|
1671
|
+
*/
|
|
1672
|
+
function mergeOperationNamespaces(written, generated) {
|
|
1673
|
+
const merged = written.map((namespace) => ({
|
|
1674
|
+
...namespace,
|
|
1675
|
+
features: [...namespace.features]
|
|
1676
|
+
}));
|
|
1677
|
+
for (const namespace of generated) {
|
|
1678
|
+
const existing = merged.find((candidate) => candidate.name === namespace.name);
|
|
1679
|
+
if (!existing) {
|
|
1680
|
+
merged.push(namespace);
|
|
1681
|
+
continue;
|
|
1682
|
+
}
|
|
1683
|
+
for (const feature of namespace.features) if (!existing.features.some((candidate) => candidate.name === feature.name)) existing.features.push(feature);
|
|
1684
|
+
if (namespace.defaultFeature && !existing.defaultFeature) existing.defaultFeature = namespace.defaultFeature;
|
|
1685
|
+
}
|
|
1686
|
+
return merged;
|
|
1687
|
+
}
|
|
1688
|
+
//#endregion
|
|
88
1689
|
//#region ../internal/dist/provision.js
|
|
1690
|
+
/** Plans one provider in step order and collects warnings and explicit unchecked state. */
|
|
1691
|
+
async function planProvisionSteps(provider, steps, context) {
|
|
1692
|
+
const warnings = [];
|
|
1693
|
+
let checked = true;
|
|
1694
|
+
const planContext = {
|
|
1695
|
+
...context,
|
|
1696
|
+
logger: {
|
|
1697
|
+
log: (message) => context.logger.log(message),
|
|
1698
|
+
warn(message) {
|
|
1699
|
+
warnings.push(message);
|
|
1700
|
+
context.logger.warn(message);
|
|
1701
|
+
}
|
|
1702
|
+
},
|
|
1703
|
+
markPlanUnchecked: () => {
|
|
1704
|
+
checked = false;
|
|
1705
|
+
}
|
|
1706
|
+
};
|
|
1707
|
+
const actions = [];
|
|
1708
|
+
for (const step of steps) {
|
|
1709
|
+
if (step.provider !== provider) continue;
|
|
1710
|
+
for (const action of await step.plan(planContext)) actions.push({
|
|
1711
|
+
action,
|
|
1712
|
+
step: step.id
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
return {
|
|
1716
|
+
actions,
|
|
1717
|
+
checked,
|
|
1718
|
+
warnings
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
89
1721
|
function resolveCloudflareProvisionConfig(env) {
|
|
90
1722
|
const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
|
|
91
1723
|
const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
|
|
@@ -109,23 +1741,47 @@ function trimmedEnv(value) {
|
|
|
109
1741
|
}
|
|
110
1742
|
//#endregion
|
|
111
1743
|
//#region src/provision.ts
|
|
112
|
-
|
|
1744
|
+
const PROVISION_PROVIDERS = ["cloudflare", "vercel"];
|
|
1745
|
+
const PROVIDER_CREDENTIALS = {
|
|
1746
|
+
cloudflare: "CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN",
|
|
1747
|
+
vercel: "VERCEL_TOKEN"
|
|
1748
|
+
};
|
|
1749
|
+
const USAGE = {
|
|
1750
|
+
run: "vitehub provision run --provider <cloudflare|vercel> [--dry-run] [--json]",
|
|
1751
|
+
status: "vitehub provision status --provider <cloudflare|vercel> [--json]"
|
|
1752
|
+
};
|
|
1753
|
+
function isProvisionProvider(value) {
|
|
1754
|
+
return PROVISION_PROVIDERS.some((provider) => provider === value);
|
|
1755
|
+
}
|
|
1756
|
+
function parseArgs(command, args) {
|
|
113
1757
|
const parsed = {
|
|
114
1758
|
dryRun: false,
|
|
115
|
-
help: false
|
|
1759
|
+
help: false,
|
|
1760
|
+
json: false
|
|
116
1761
|
};
|
|
117
1762
|
for (let index = 0; index < args.length; index++) {
|
|
118
1763
|
const arg = args[index];
|
|
119
1764
|
if (arg === "-h" || arg === "--help") parsed.help = true;
|
|
120
|
-
else if (arg === "--
|
|
121
|
-
else if (arg === "--
|
|
122
|
-
else if (arg
|
|
1765
|
+
else if (arg === "--json") parsed.json = true;
|
|
1766
|
+
else if (arg === "--dry-run" && command === "run") parsed.dryRun = true;
|
|
1767
|
+
else if (arg === "--provider") {
|
|
1768
|
+
const provider = args[index + 1];
|
|
1769
|
+
if (!provider || provider.startsWith("-")) parsed.error = "Option --provider requires a value.";
|
|
1770
|
+
else {
|
|
1771
|
+
parsed.provider = provider;
|
|
1772
|
+
index++;
|
|
1773
|
+
}
|
|
1774
|
+
} else if (arg?.startsWith("--provider=")) {
|
|
1775
|
+
const provider = arg.slice(11);
|
|
1776
|
+
if (!provider) parsed.error = "Option --provider requires a value.";
|
|
1777
|
+
else parsed.provider = provider;
|
|
1778
|
+
} else if (arg) parsed.error = `Unknown provision argument: ${arg}`;
|
|
123
1779
|
}
|
|
124
1780
|
return parsed;
|
|
125
1781
|
}
|
|
126
|
-
function writeUsage(
|
|
127
|
-
|
|
128
|
-
|
|
1782
|
+
function writeUsage(command, stream) {
|
|
1783
|
+
const lines = command === "run" ? [
|
|
1784
|
+
`Usage: ${USAGE.run}`,
|
|
129
1785
|
"",
|
|
130
1786
|
"Idempotently creates missing provider resources for the app's Definitions.",
|
|
131
1787
|
"Never deletes or mutates existing resources.",
|
|
@@ -133,68 +1789,213 @@ function writeUsage(context) {
|
|
|
133
1789
|
"Options:",
|
|
134
1790
|
" --provider <name> Target provider: cloudflare or vercel (required).",
|
|
135
1791
|
" --dry-run Print the plan without applying it.",
|
|
136
|
-
"
|
|
137
|
-
""
|
|
138
|
-
]
|
|
1792
|
+
" --json Print one JSON result to stdout.",
|
|
1793
|
+
" -h, --help Show this help."
|
|
1794
|
+
] : [
|
|
1795
|
+
`Usage: ${USAGE.status}`,
|
|
1796
|
+
"",
|
|
1797
|
+
"Shows the ids recorded in .vitehub/provision.json and the actions the current plan would apply.",
|
|
1798
|
+
"Never creates provider resources or writes Provision State.",
|
|
1799
|
+
"",
|
|
1800
|
+
"Options:",
|
|
1801
|
+
" --provider <name> Target provider: cloudflare or vercel (required).",
|
|
1802
|
+
" --json Print one JSON result to stdout.",
|
|
1803
|
+
" -h, --help Show this help."
|
|
1804
|
+
];
|
|
1805
|
+
stream.write(`${lines.join("\n")}\n\n`);
|
|
139
1806
|
}
|
|
140
|
-
|
|
141
|
-
const parsed = parseArgs(args);
|
|
1807
|
+
function resolveProvider(command, parsed, context) {
|
|
142
1808
|
if (parsed.help) {
|
|
143
|
-
writeUsage(context);
|
|
144
|
-
return 0;
|
|
1809
|
+
writeUsage(command, context.stdout);
|
|
1810
|
+
return { exitCode: 0 };
|
|
145
1811
|
}
|
|
146
|
-
if (parsed.
|
|
147
|
-
context.stderr.write(
|
|
148
|
-
writeUsage(context);
|
|
149
|
-
return 1;
|
|
1812
|
+
if (parsed.error) {
|
|
1813
|
+
context.stderr.write(`${parsed.error}\n`);
|
|
1814
|
+
writeUsage(command, context.stderr);
|
|
1815
|
+
return { exitCode: 1 };
|
|
150
1816
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
context.stderr.write(`Provision requires ${required} to be set. Dry-run preview does not require credentials (--dry-run).\n`);
|
|
156
|
-
return 1;
|
|
157
|
-
}
|
|
1817
|
+
if (!isProvisionProvider(parsed.provider)) {
|
|
1818
|
+
context.stderr.write("Provision requires --provider cloudflare|vercel.\n");
|
|
1819
|
+
writeUsage(command, context.stderr);
|
|
1820
|
+
return { exitCode: 1 };
|
|
158
1821
|
}
|
|
159
|
-
|
|
160
|
-
|
|
1822
|
+
return { provider: parsed.provider };
|
|
1823
|
+
}
|
|
1824
|
+
function hasProviderCredentials(provider, env) {
|
|
1825
|
+
return Boolean(provider === "cloudflare" ? resolveCloudflareProvisionConfig(env) : resolveVercelProvisionConfig(env));
|
|
1826
|
+
}
|
|
1827
|
+
async function planProvision(provider, context, options, json) {
|
|
1828
|
+
return await planProvisionSteps(provider, await options.collectSteps(), {
|
|
161
1829
|
env: context.env,
|
|
162
1830
|
fetch: globalThis.fetch,
|
|
163
1831
|
logger: {
|
|
164
|
-
log: (message) => context.stdout.write(`${message}\n`),
|
|
165
|
-
warn: (message) =>
|
|
1832
|
+
log: (message) => (json ? context.stderr : context.stdout).write(`${message}\n`),
|
|
1833
|
+
warn: (message) => {
|
|
1834
|
+
if (!json) context.stderr.write(`${message}\n`);
|
|
1835
|
+
}
|
|
166
1836
|
}
|
|
167
|
-
};
|
|
168
|
-
const actions = [];
|
|
169
|
-
for (const step of steps) for (const action of await step.plan(provisionContext)) actions.push({
|
|
170
|
-
stepId: step.id,
|
|
171
|
-
action
|
|
172
1837
|
});
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
1838
|
+
}
|
|
1839
|
+
function serializeAction({ action, step }) {
|
|
1840
|
+
return {
|
|
1841
|
+
...action.pending === void 0 ? {} : { pending: action.pending },
|
|
1842
|
+
exists: action.exists,
|
|
1843
|
+
kind: action.kind,
|
|
1844
|
+
name: action.name,
|
|
1845
|
+
step
|
|
1846
|
+
};
|
|
1847
|
+
}
|
|
1848
|
+
function writeActions(actions, stdout) {
|
|
1849
|
+
for (const { action } of actions) {
|
|
1850
|
+
const status = !action.exists ? "create" : action.pending ? "pending" : "exists";
|
|
1851
|
+
stdout.write(`${status}\t${action.kind}\t${action.name}\n`);
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
async function runProvision(args, context, options) {
|
|
1855
|
+
const parsed = parseArgs("run", args);
|
|
1856
|
+
const resolved = resolveProvider("run", parsed, context);
|
|
1857
|
+
if ("exitCode" in resolved) return resolved.exitCode;
|
|
1858
|
+
const { provider } = resolved;
|
|
1859
|
+
if (!parsed.dryRun && !hasProviderCredentials(provider, context.env)) {
|
|
1860
|
+
context.stderr.write(`Provision requires ${PROVIDER_CREDENTIALS[provider]} to be set. Dry-run preview does not require credentials (--dry-run).\n`);
|
|
1861
|
+
return 1;
|
|
1862
|
+
}
|
|
1863
|
+
if (!parsed.dryRun) await readProvisionState(context.rootDir);
|
|
1864
|
+
const { actions, warnings } = await planProvision(provider, context, options, parsed.json);
|
|
1865
|
+
if (!parsed.json) {
|
|
1866
|
+
if (!actions.length) {
|
|
1867
|
+
context.stdout.write(`provision: no ${provider} resources to create.\n`);
|
|
1868
|
+
return 0;
|
|
1869
|
+
}
|
|
1870
|
+
writeActions(actions, context.stdout);
|
|
176
1871
|
}
|
|
177
|
-
for (const { action } of actions) context.stdout.write(`${action.exists ? "exists" : "create"}\t${action.kind}\t${action.name}\n`);
|
|
178
|
-
if (parsed.dryRun) return 0;
|
|
179
1872
|
let state = {};
|
|
180
|
-
for (const { action } of actions) {
|
|
1873
|
+
if (!parsed.dryRun) for (const { action } of actions) {
|
|
181
1874
|
const result = await action.apply();
|
|
182
1875
|
if (result.ids) state = mergeProvisionState(state, result.ids);
|
|
183
1876
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
1877
|
+
const wroteState = Object.keys(state).length > 0;
|
|
1878
|
+
if (wroteState) await writeProvisionState(context.rootDir, state);
|
|
1879
|
+
if (parsed.json) context.stdout.write(`${JSON.stringify({
|
|
1880
|
+
actions: actions.map(serializeAction),
|
|
1881
|
+
ids: state[provider] ?? {},
|
|
1882
|
+
mode: parsed.dryRun ? "dry-run" : "apply",
|
|
1883
|
+
provider,
|
|
1884
|
+
schemaVersion: 1,
|
|
1885
|
+
stateFile: wroteState ? PROVISION_STATE_FILE : null,
|
|
1886
|
+
warnings
|
|
1887
|
+
})}\n`);
|
|
1888
|
+
else if (wroteState) context.stdout.write(`provision: wrote ids to ${PROVISION_STATE_FILE}\n`);
|
|
1889
|
+
return 0;
|
|
1890
|
+
}
|
|
1891
|
+
async function runProvisionStatus(args, context, options) {
|
|
1892
|
+
const parsed = parseArgs("status", args);
|
|
1893
|
+
const resolved = resolveProvider("status", parsed, context);
|
|
1894
|
+
if ("exitCode" in resolved) return resolved.exitCode;
|
|
1895
|
+
const { provider } = resolved;
|
|
1896
|
+
const recorded = (await readProvisionState(context.rootDir))[provider] ?? {};
|
|
1897
|
+
const hasCredentials = hasProviderCredentials(provider, context.env);
|
|
1898
|
+
const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, options, parsed.json) : {
|
|
1899
|
+
actions: [],
|
|
1900
|
+
checked: false,
|
|
1901
|
+
warnings: [`provision: plan not checked, missing ${PROVIDER_CREDENTIALS[provider]}.`]
|
|
1902
|
+
};
|
|
1903
|
+
const pending = actions.filter(({ action }) => action.pending ?? !action.exists).length;
|
|
1904
|
+
if (parsed.json) {
|
|
1905
|
+
context.stdout.write(`${JSON.stringify({
|
|
1906
|
+
plan: {
|
|
1907
|
+
actions: actions.map(serializeAction),
|
|
1908
|
+
checked,
|
|
1909
|
+
pending
|
|
1910
|
+
},
|
|
1911
|
+
provider,
|
|
1912
|
+
recorded,
|
|
1913
|
+
schemaVersion: 1,
|
|
1914
|
+
stateFile: PROVISION_STATE_FILE,
|
|
1915
|
+
warnings
|
|
1916
|
+
})}\n`);
|
|
1917
|
+
return 0;
|
|
1918
|
+
}
|
|
1919
|
+
const recordedEntries = Object.entries(recorded).flatMap(([category, ids]) => Object.entries(ids).map(([key, id]) => `${category}\t${key}\t${id}\n`));
|
|
1920
|
+
if (recordedEntries.length) {
|
|
1921
|
+
context.stdout.write(`recorded ${provider} ids (${PROVISION_STATE_FILE}):\n`);
|
|
1922
|
+
for (const entry of recordedEntries) context.stdout.write(entry);
|
|
1923
|
+
} else context.stdout.write(`recorded ${provider} ids: none in ${PROVISION_STATE_FILE}\n`);
|
|
1924
|
+
if (!checked) {
|
|
1925
|
+
if (!hasCredentials) context.stderr.write(`${warnings[0]}\n`);
|
|
1926
|
+
context.stdout.write("plan: not checked\n");
|
|
1927
|
+
return 0;
|
|
187
1928
|
}
|
|
1929
|
+
writeActions(actions, context.stdout);
|
|
1930
|
+
context.stdout.write(pending ? `plan: ${pending} pending ${pending === 1 ? "action" : "actions"}. Run \`vitehub provision run --provider ${provider}\` to apply.\n` : "plan: no pending actions\n");
|
|
188
1931
|
return 0;
|
|
189
1932
|
}
|
|
1933
|
+
/** Built-in namespace that orchestrates package-contributed Provision Steps. */
|
|
1934
|
+
function createProvisionNamespace(steps) {
|
|
1935
|
+
const options = { collectSteps: async () => [...steps] };
|
|
1936
|
+
return {
|
|
1937
|
+
description: "Idempotently create missing provider resources.",
|
|
1938
|
+
features: [{
|
|
1939
|
+
description: "Create missing provider resources for the app's Definitions.",
|
|
1940
|
+
name: "run",
|
|
1941
|
+
run: (args, context) => runProvision(args, context, options),
|
|
1942
|
+
usage: USAGE.run
|
|
1943
|
+
}, {
|
|
1944
|
+
description: "Show recorded provider ids and pending plan actions.",
|
|
1945
|
+
name: "status",
|
|
1946
|
+
run: (args, context) => runProvisionStatus(args, context, options),
|
|
1947
|
+
usage: USAGE.status
|
|
1948
|
+
}],
|
|
1949
|
+
name: "provision"
|
|
1950
|
+
};
|
|
1951
|
+
}
|
|
190
1952
|
//#endregion
|
|
191
1953
|
//#region src/index.ts
|
|
1954
|
+
const BUILTIN_NAMESPACE_NAMES = new Set(reservedOperationNamespaces);
|
|
1955
|
+
async function loadNuxtViteConfig(rootDir, command) {
|
|
1956
|
+
if (![
|
|
1957
|
+
"nuxt.config.ts",
|
|
1958
|
+
"nuxt.config.mts",
|
|
1959
|
+
"nuxt.config.cts",
|
|
1960
|
+
"nuxt.config.js",
|
|
1961
|
+
"nuxt.config.mjs",
|
|
1962
|
+
"nuxt.config.cjs"
|
|
1963
|
+
].some((file) => existsSync(resolve(rootDir, file)))) return;
|
|
1964
|
+
let loadNuxt;
|
|
1965
|
+
try {
|
|
1966
|
+
({loadNuxt} = await import("nuxt/kit"));
|
|
1967
|
+
} catch {
|
|
1968
|
+
throw cliErrorDiagnostics.CLI_R0001({ message: "[vitehub] Nuxt config was found, but Nuxt could not be loaded for CLI discovery." });
|
|
1969
|
+
}
|
|
1970
|
+
const nuxt = await loadNuxt({
|
|
1971
|
+
cwd: rootDir,
|
|
1972
|
+
dev: command === "serve",
|
|
1973
|
+
overrides: { vitehubCliDiscovery: true },
|
|
1974
|
+
ready: true
|
|
1975
|
+
});
|
|
1976
|
+
try {
|
|
1977
|
+
const { resolveConfig } = await import("vite");
|
|
1978
|
+
const viteRoot = nuxt.options.vite.root;
|
|
1979
|
+
const config = await resolveConfig({
|
|
1980
|
+
...nuxt.options.vite,
|
|
1981
|
+
configFile: false,
|
|
1982
|
+
root: viteRoot ? resolve(nuxt.options.rootDir || rootDir, viteRoot) : nuxt.options.rootDir || rootDir,
|
|
1983
|
+
vitehubCliDiscovery: true
|
|
1984
|
+
}, command, command === "build" ? "production" : "development");
|
|
1985
|
+
return {
|
|
1986
|
+
plugins: config.plugins,
|
|
1987
|
+
root: config.root
|
|
1988
|
+
};
|
|
1989
|
+
} finally {
|
|
1990
|
+
await nuxt.close();
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
192
1993
|
function defaultSpawn(command, args, options = {}) {
|
|
193
1994
|
return new Promise((resolveResult, reject) => {
|
|
194
1995
|
const child = spawn(command, args, {
|
|
195
1996
|
cwd: options.cwd,
|
|
196
1997
|
env: options.env,
|
|
197
|
-
shell: process.platform === "win32",
|
|
1998
|
+
shell: process$1.platform === "win32" && command !== process$1.execPath,
|
|
198
1999
|
stdio: [
|
|
199
2000
|
"inherit",
|
|
200
2001
|
options.stdout || "inherit",
|
|
@@ -208,61 +2009,101 @@ function defaultSpawn(command, args, options = {}) {
|
|
|
208
2009
|
}));
|
|
209
2010
|
});
|
|
210
2011
|
}
|
|
211
|
-
async function loadViteConfig(rootDir) {
|
|
2012
|
+
async function loadViteConfig(rootDir, command) {
|
|
212
2013
|
const { resolveConfig } = await import("vite");
|
|
213
|
-
return await resolveConfig({
|
|
2014
|
+
return await resolveConfig({
|
|
2015
|
+
root: rootDir,
|
|
2016
|
+
vitehubCliDiscovery: true
|
|
2017
|
+
}, command, command === "build" ? "production" : "development");
|
|
214
2018
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
return {
|
|
219
|
-
description: "Idempotently create missing provider resources.",
|
|
220
|
-
features: [{
|
|
221
|
-
description: "Create missing provider resources for the app's Definitions.",
|
|
222
|
-
name: "run",
|
|
223
|
-
run,
|
|
224
|
-
usage: "vitehub provision run --provider <cloudflare|vercel> [--dry-run]"
|
|
225
|
-
}],
|
|
226
|
-
name: "provision"
|
|
227
|
-
};
|
|
2019
|
+
/** Keeps at least two spaces between a help name and its description. */
|
|
2020
|
+
function helpNameWidth(names) {
|
|
2021
|
+
return Math.max(12, ...names.map((name) => name.length + 1));
|
|
228
2022
|
}
|
|
229
2023
|
function writeRootHelp(namespaces, stdout) {
|
|
2024
|
+
const width = helpNameWidth(namespaces.map((namespace) => namespace.name));
|
|
230
2025
|
stdout.write([
|
|
231
2026
|
"Usage: vitehub <namespace> <feature> [args...]",
|
|
232
2027
|
"",
|
|
233
2028
|
"Available namespaces:",
|
|
234
|
-
...namespaces.map((namespace) => ` ${namespace.name.padEnd(
|
|
2029
|
+
...namespaces.map((namespace) => ` ${namespace.name.padEnd(width)} ${namespace.description || ""}`.trimEnd()),
|
|
235
2030
|
""
|
|
236
2031
|
].join("\n"));
|
|
237
2032
|
}
|
|
238
2033
|
function writeNamespaceHelp(namespace, stdout) {
|
|
2034
|
+
const width = helpNameWidth(namespace.features.map((feature) => feature.name));
|
|
239
2035
|
stdout.write([
|
|
240
2036
|
`Usage: vitehub ${namespace.name} <feature> [args...]`,
|
|
241
2037
|
"",
|
|
242
2038
|
namespace.description || "",
|
|
243
2039
|
"",
|
|
244
2040
|
"Available features:",
|
|
245
|
-
...namespace.features.
|
|
2041
|
+
...namespace.features.flatMap((feature) => [` ${feature.name.padEnd(width)} ${feature.description || ""}`.trimEnd(), ...feature.usage ? [` Usage: ${feature.usage}`] : []]),
|
|
246
2042
|
""
|
|
247
2043
|
].filter(Boolean).join("\n"));
|
|
248
2044
|
}
|
|
249
2045
|
function isRootHelp(args) {
|
|
250
2046
|
return args[0] === "-h" || args[0] === "--help";
|
|
251
2047
|
}
|
|
2048
|
+
function readPackageVersion() {
|
|
2049
|
+
const manifest = readFileSync(new URL("../package.json", import.meta.url), "utf8");
|
|
2050
|
+
const version = /"version"\s*:\s*"([^"\\]+)"/u.exec(manifest)?.[1];
|
|
2051
|
+
if (!version) throw cliErrorDiagnostics.CLI_R0002({ message: "[vitehub] The installed @vite-hub/cli package manifest has no valid version." });
|
|
2052
|
+
return version;
|
|
2053
|
+
}
|
|
252
2054
|
async function runViteHubCli(options = {}) {
|
|
253
|
-
const args = options.args || process.argv.slice(2);
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
const
|
|
260
|
-
const
|
|
2055
|
+
const args = options.args || process$1.argv.slice(2);
|
|
2056
|
+
const stdout = { write: options.stdout ? options.stdout.write.bind(options.stdout) : getStableStdoutWrite() };
|
|
2057
|
+
if (args[0] === "-v" || args[0] === "--version") {
|
|
2058
|
+
stdout.write(`${readPackageVersion()}\n`);
|
|
2059
|
+
return 0;
|
|
2060
|
+
}
|
|
2061
|
+
const cwd = options.cwd || process$1.cwd();
|
|
2062
|
+
const env = options.env || process$1.env;
|
|
2063
|
+
const stderr = options.stderr || { write: (chunk, encoding, callback) => typeof encoding === "function" ? process$1.stderr.write(chunk, encoding) : process$1.stderr.write(chunk, encoding, callback) };
|
|
2064
|
+
const spawn = options.spawn || defaultSpawn;
|
|
2065
|
+
const runtimeNamespace = options.runtimeNamespaces?.find((namespace) => namespace.name === args[0] && !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
|
|
2066
|
+
if (runtimeNamespace) return await runNamespace(runtimeNamespace, args, {
|
|
2067
|
+
cwd,
|
|
2068
|
+
env,
|
|
2069
|
+
rootDir: cwd,
|
|
2070
|
+
spawn,
|
|
2071
|
+
stderr,
|
|
2072
|
+
stdout
|
|
2073
|
+
});
|
|
2074
|
+
const runtimeFeatures = options.runtimeFeatures?.find((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && namespace.name === args[0] && namespace.features.some((feature) => feature.name === args[1]));
|
|
2075
|
+
if (runtimeFeatures && (await options.runtimeFeatureGuard?.(args[0], args[1], cwd) ?? true)) return await runNamespace(runtimeFeatures, args, {
|
|
2076
|
+
cwd,
|
|
2077
|
+
env,
|
|
2078
|
+
rootDir: cwd,
|
|
2079
|
+
spawn,
|
|
2080
|
+
stderr,
|
|
2081
|
+
stdout
|
|
2082
|
+
});
|
|
2083
|
+
const command = args[0] === "inspect" && args[1] === "provider-output" ? "build" : "serve";
|
|
2084
|
+
const { contribution, operations, plugins, rootDir } = await withStdoutOnStderr(async () => {
|
|
2085
|
+
const config = await (options.loadConfig || loadViteConfig)(cwd, command);
|
|
2086
|
+
const nuxtConfig = config.vitehubConfigResolved ? void 0 : await (options.loadNuxtViteConfig || loadNuxtViteConfig)(cwd, command);
|
|
2087
|
+
const plugins = nuxtConfig?.plugins ?? config.plugins;
|
|
2088
|
+
return {
|
|
2089
|
+
contribution: await collectViteHubCliContribution(plugins),
|
|
2090
|
+
operations: await loadCliOperations(plugins, stderr),
|
|
2091
|
+
plugins,
|
|
2092
|
+
rootDir: resolve(nuxtConfig?.root || config.root || cwd)
|
|
2093
|
+
};
|
|
2094
|
+
}, stderr);
|
|
2095
|
+
const namespaces = [
|
|
2096
|
+
...mergeOperationNamespaces(contribution.namespaces, createOperationNamespaces(operations)).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name)),
|
|
2097
|
+
createInspectNamespace(plugins, operations),
|
|
2098
|
+
createProvisionNamespace(contribution.provision),
|
|
2099
|
+
...(options.runtimeNamespaces ?? []).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name))
|
|
2100
|
+
];
|
|
261
2101
|
const context = {
|
|
262
2102
|
cwd,
|
|
263
2103
|
env,
|
|
2104
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
264
2105
|
rootDir,
|
|
265
|
-
spawn
|
|
2106
|
+
spawn,
|
|
266
2107
|
stderr,
|
|
267
2108
|
stdout
|
|
268
2109
|
};
|
|
@@ -274,11 +2115,22 @@ async function runViteHubCli(options = {}) {
|
|
|
274
2115
|
const namespace = namespaces.find((item) => item.name === namespaceName);
|
|
275
2116
|
if (!namespace) {
|
|
276
2117
|
stderr.write(`Unknown ViteHub CLI namespace: ${namespaceName}\n`);
|
|
2118
|
+
if (namespaces.length === 2 && namespaces.every((item) => BUILTIN_NAMESPACE_NAMES.has(item.name))) stderr.write(`No ViteHub integration contributed the "${namespaceName}" commands. Run this from a configured project and enable the matching integration in vite.config.ts or nuxt.config.ts.\n`);
|
|
277
2119
|
writeRootHelp(namespaces, stderr);
|
|
278
2120
|
return 1;
|
|
279
2121
|
}
|
|
2122
|
+
return await runNamespace(namespace, args, context);
|
|
2123
|
+
}
|
|
2124
|
+
async function runNamespace(namespace, args, context) {
|
|
2125
|
+
const { stderr, stdout } = context;
|
|
280
2126
|
const featureName = args[1];
|
|
281
|
-
if (
|
|
2127
|
+
if (featureName === "-h" || featureName === "--help") {
|
|
2128
|
+
writeNamespaceHelp(namespace, stdout);
|
|
2129
|
+
return 0;
|
|
2130
|
+
}
|
|
2131
|
+
const defaultFeature = namespace.defaultFeature ? namespace.features.find((item) => item.name === namespace.defaultFeature) : void 0;
|
|
2132
|
+
if (defaultFeature && (!featureName || featureName.startsWith("-"))) return await defaultFeature.run(args.slice(1), context) ?? 0;
|
|
2133
|
+
if (!featureName) {
|
|
282
2134
|
writeNamespaceHelp(namespace, stdout);
|
|
283
2135
|
return 0;
|
|
284
2136
|
}
|
|
@@ -288,22 +2140,81 @@ async function runViteHubCli(options = {}) {
|
|
|
288
2140
|
writeNamespaceHelp(namespace, stderr);
|
|
289
2141
|
return 1;
|
|
290
2142
|
}
|
|
291
|
-
|
|
292
|
-
|
|
2143
|
+
return await feature.run(args.slice(2), context) ?? 0;
|
|
2144
|
+
}
|
|
2145
|
+
function trackStream(stream) {
|
|
2146
|
+
const writes = [];
|
|
2147
|
+
return {
|
|
2148
|
+
stream: { write(chunk, encoding, callback) {
|
|
2149
|
+
const result = Reflect.apply(stream.write, stream, [
|
|
2150
|
+
chunk,
|
|
2151
|
+
encoding,
|
|
2152
|
+
callback
|
|
2153
|
+
]);
|
|
2154
|
+
writes.push(Promise.resolve(result).then((value) => ({
|
|
2155
|
+
status: "fulfilled",
|
|
2156
|
+
value
|
|
2157
|
+
}), (reason) => ({
|
|
2158
|
+
reason,
|
|
2159
|
+
status: "rejected"
|
|
2160
|
+
})));
|
|
2161
|
+
return result;
|
|
2162
|
+
} },
|
|
2163
|
+
async flush() {
|
|
2164
|
+
const results = await Promise.all(writes);
|
|
2165
|
+
let flushFailure;
|
|
2166
|
+
try {
|
|
2167
|
+
if (stream.flush) await stream.flush();
|
|
2168
|
+
} catch (error) {
|
|
2169
|
+
flushFailure = { reason: error };
|
|
2170
|
+
}
|
|
2171
|
+
const rejected = results.find((result) => result.status === "rejected");
|
|
2172
|
+
if (rejected) throw rejected.reason;
|
|
2173
|
+
if (flushFailure) throw flushFailure.reason;
|
|
2174
|
+
}
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
function processEntrypointStream(stream) {
|
|
2178
|
+
return {
|
|
2179
|
+
flush: () => new Promise((resolveFlush, rejectFlush) => stream.write("", (error) => {
|
|
2180
|
+
if (error) rejectFlush(error);
|
|
2181
|
+
else resolveFlush();
|
|
2182
|
+
})),
|
|
2183
|
+
write: ((chunk, encoding, callback) => {
|
|
2184
|
+
if (typeof encoding === "function") return stream.write(chunk, encoding);
|
|
2185
|
+
return stream.write(chunk, encoding, callback);
|
|
2186
|
+
})
|
|
2187
|
+
};
|
|
2188
|
+
}
|
|
2189
|
+
function runViteHubCliEntrypoint(options = {}) {
|
|
2190
|
+
const stderr = trackStream(options.stderr || processEntrypointStream(process$1.stderr));
|
|
2191
|
+
const stdout = trackStream(options.stdout || processEntrypointStream(process$1.stdout));
|
|
2192
|
+
(async () => {
|
|
2193
|
+
let exitCode;
|
|
2194
|
+
try {
|
|
2195
|
+
exitCode = await runViteHubCli({
|
|
2196
|
+
...options,
|
|
2197
|
+
stderr: stderr.stream,
|
|
2198
|
+
stdout: stdout.stream
|
|
2199
|
+
});
|
|
2200
|
+
} catch (error) {
|
|
2201
|
+
try {
|
|
2202
|
+
stderr.stream.write(`${formatRuntimeDiagnosticError(error)}\n`);
|
|
2203
|
+
} catch {}
|
|
2204
|
+
exitCode = 1;
|
|
2205
|
+
}
|
|
2206
|
+
if ((await Promise.allSettled([stdout.flush(), stderr.flush()])).some((result) => result.status === "rejected")) exitCode = 1;
|
|
2207
|
+
process$1.exit(exitCode);
|
|
2208
|
+
})();
|
|
293
2209
|
}
|
|
294
2210
|
function isCliEntrypoint() {
|
|
295
|
-
if (!process.argv[1]) return false;
|
|
2211
|
+
if (!process$1.argv[1]) return false;
|
|
296
2212
|
try {
|
|
297
|
-
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
2213
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process$1.argv[1]);
|
|
298
2214
|
} catch {
|
|
299
2215
|
return false;
|
|
300
2216
|
}
|
|
301
2217
|
}
|
|
302
|
-
if (isCliEntrypoint())
|
|
303
|
-
process.exit(exitCode);
|
|
304
|
-
}).catch((error) => {
|
|
305
|
-
console.error(error instanceof Error ? error.message : error);
|
|
306
|
-
process.exit(1);
|
|
307
|
-
});
|
|
2218
|
+
if (isCliEntrypoint()) runViteHubCliEntrypoint();
|
|
308
2219
|
//#endregion
|
|
309
|
-
export { runViteHubCli };
|
|
2220
|
+
export { runViteHubCli, runViteHubCliEntrypoint };
|