@vite-hub/cli 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -1,15 +1,10 @@
1
- #!/usr/bin/env node
1
+ import { A as operationInputJsonSchema, B as isRecord, D as operationCliPath, E as operationCall, F as collectViteHubCliContribution, I as createCliDiscoveryNitroCloser, L as findViteHubDevServerUrl, M as setupCommandNames, N as resolveViteHubProjectRoot, O as operationsOf, R as getStableStdoutWrite, S as callOperation, T as createOperationRegistry, b as loadAllEnv, h as PROVISION_STATE_FILE, j as reservedOperationNamespaces, k as parseOperationInput, m as cliErrorDiagnostics, t as createProvisionNamespace, v as readProvisionStateSync, w as collectOperationContributions, x as withViteStageEnvironment, z as withStdoutOnStderr } from "./provision-D8OvBBzi.js";
2
2
  import { spawn } from "node:child_process";
3
- import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
4
  import process$1 from "node:process";
5
- import { fileURLToPath } from "node:url";
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";
11
- import { mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, relative, resolve } from "pathe";
12
6
  import { createInterface } from "node:readline/promises";
7
+ import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
13
8
  //#region ../internal/dist/inspect.js
14
9
  async function collectContributors(plugins) {
15
10
  const contributors = [];
@@ -35,6 +30,12 @@ async function collectViteHubProviderOutputEntries(plugins) {
35
30
  for (const contributor of await collectContributors(plugins)) for (const entry of contributor.providerOutput ?? []) entries.set(entry.path, entry);
36
31
  return [...entries.values()];
37
32
  }
33
+ /** Collects host resources from active plugins in plugin order. */
34
+ async function collectViteHubResourceSummaries(plugins) {
35
+ const resources = [];
36
+ for (const contributor of await collectContributors(plugins)) resources.push(...await contributor.resources?.() ?? []);
37
+ return resources;
38
+ }
38
39
  const redactedInspectionValue = "[redacted]";
39
40
  const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
40
41
  const secretValuePattern = /^(?:[a-z][a-z0-9+.-]*:\/\/[^/\s?#]*@|bearer\s)/i;
@@ -99,702 +100,23 @@ function redactInspectionValue(value, key) {
99
100
  return visit(value, key);
100
101
  }
101
102
  //#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
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
- }
164
- async function resolveContributor(value) {
165
- return typeof value === "function" ? await value() : value;
166
- }
167
- /** Resolves command namespaces and Provision Steps from one contribution per plugin. */
168
- async function collectViteHubCliContribution(plugins) {
169
- const namespaces = /* @__PURE__ */ new Map();
170
- const steps = /* @__PURE__ */ new Map();
171
- for (const plugin of plugins) {
172
- if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
173
- const metadata = plugin.vitehub;
174
- const contributor = await resolveContributor(metadata?.cli);
175
- if (!contributor) continue;
176
- for (const namespace of contributor.namespaces) {
177
- const existing = namespaces.get(namespace.name);
178
- if (!existing) {
179
- namespaces.set(namespace.name, {
180
- ...namespace,
181
- features: [...namespace.features]
182
- });
183
- continue;
184
- }
185
- const features = new Map(existing.features.map((feature) => [feature.name, feature]));
186
- for (const feature of namespace.features) features.set(feature.name, feature);
187
- existing.features = [...features.values()];
188
- }
189
- for (const step of contributor.provision ?? []) steps.set(step.id, step);
190
- }
191
- return {
192
- namespaces: [...namespaces.values()],
193
- provision: [...steps.values()]
194
- };
195
- }
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();
507
- for (const plugin of plugins) {
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)}`);
710
- }
711
- }
712
- //#endregion
713
- //#region ../internal/dist/provision-state.js
714
- const PROVISION_STATE_FILE = ".vitehub/provision.json";
715
- function getProvisionStatePath(rootDir) {
716
- return resolve(rootDir, PROVISION_STATE_FILE);
717
- }
718
- async function readProvisionState(rootDir) {
719
- const path = getProvisionStatePath(rootDir);
720
- try {
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
- });
740
- }
741
- }
742
- async function writeProvisionState(rootDir, next) {
743
- const path = getProvisionStatePath(rootDir);
744
- const merged = mergeProvisionState(await readProvisionState(rootDir), next);
745
- await mkdir(dirname(path), { recursive: true });
746
- await writeFile(path, `${JSON.stringify(sortState(merged), null, 2)}\n`, "utf8");
747
- }
748
- function mergeProvisionState(base, next) {
749
- const merged = structuredClone(base);
750
- for (const provider of Object.keys(next)) {
751
- const categories = next[provider];
752
- if (!categories) continue;
753
- const target = merged[provider] ??= {};
754
- for (const [category, ids] of Object.entries(categories)) setOwn(target, category, {
755
- ...(Object.hasOwn(target, category) ? target[category] : void 0) ?? {},
756
- ...ids
757
- });
758
- }
759
- return merged;
760
- }
761
- function parseProvisionState(raw) {
762
- const parsed = JSON.parse(raw);
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
- });
786
- }
787
- function sortState(state) {
788
- return sortKeys(state);
789
- }
790
- function sortKeys(value) {
791
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
792
- return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]));
793
- }
103
+ //#region src/drain.ts
104
+ /** `vitehub drain MAINPID [STATUS_URL]`, for a service manager that stops a Node server. It needs no project. */
105
+ const drainCommand = {
106
+ description: "Drain a running Node server before it stops, for systemd ExecStop. Needs no project.",
107
+ name: "drain",
108
+ run: async (args, context) => {
109
+ const { runDrain } = await import("@vite-hub/runtime/internal/drain");
110
+ return await runDrain(args, context);
111
+ },
112
+ usage: "vitehub drain MAINPID [STATUS_URL]"
113
+ };
794
114
  //#endregion
795
115
  //#region src/inspect.ts
796
116
  const definitionsUsage = "vitehub inspect definitions [--kind <kind>] [--json]";
797
- const providerOutputUsage = "vitehub inspect provider-output [--json]";
117
+ const providerOutputUsage = "vitehub inspect output [--json]";
118
+ const resourcesUsage = "vitehub inspect resources [--json]";
119
+ const routesUsage = "vitehub inspect routes [--json]";
798
120
  function parseArgs$1(args, options) {
799
121
  const parsed = {
800
122
  help: false,
@@ -991,21 +313,218 @@ async function runProviderOutput(args, context, plugins) {
991
313
  context.stdout.write(lines.join("\n"));
992
314
  return 0;
993
315
  }
316
+ const wranglerIdFields = {
317
+ "cloudflare-d1": ["d1_databases", "database_id"],
318
+ "cloudflare-kv-namespace": ["kv_namespaces", "id"]
319
+ };
320
+ function readGeneratedWranglerIds(entries) {
321
+ const ids = /* @__PURE__ */ new Map();
322
+ for (const entry of entries) {
323
+ if (basename(entry.path) !== "wrangler.json" || !existsSync(entry.path) || !statSync(entry.path).isFile()) continue;
324
+ let config;
325
+ try {
326
+ config = JSON.parse(readFileSync(entry.path, "utf8"));
327
+ } catch {
328
+ continue;
329
+ }
330
+ if (!config || typeof config !== "object") continue;
331
+ for (const [kind, [field, idField]] of Object.entries(wranglerIdFields)) {
332
+ const bindings = Reflect.get(config, field);
333
+ if (!Array.isArray(bindings)) continue;
334
+ for (const binding of bindings) {
335
+ const name = binding && typeof binding === "object" ? Reflect.get(binding, "binding") : void 0;
336
+ const id = binding && typeof binding === "object" ? Reflect.get(binding, idField) : void 0;
337
+ if (typeof name === "string" && typeof id === "string" && id && !ids.has(`${kind}:${name}`)) ids.set(`${kind}:${name}`, id);
338
+ }
339
+ }
340
+ }
341
+ return ids;
342
+ }
343
+ function describeSource(resource) {
344
+ switch (resource.source) {
345
+ case "config": return "config";
346
+ case "env": return `env ${resource.env ?? ""}`.trim();
347
+ case "name": return "bound by name";
348
+ case "provider-output": return "generated provider output";
349
+ case "provision-state": return PROVISION_STATE_FILE;
350
+ default: return "none";
351
+ }
352
+ }
353
+ async function runResources(args, context, plugins) {
354
+ const parsed = parseArgs$1(args, { kind: false });
355
+ if (parsed.help) {
356
+ context.stdout.write([
357
+ `Usage: ${resourcesUsage}`,
358
+ "",
359
+ "Lists the host resources that Definitions and stores map to: D1, KV, R2, Queues, Vercel Blob, and the Sandbox Durable Object and Container.",
360
+ "Shows each resource name, its id, and where the id came from: config, env, Provision State, generated provider output, or the host binds it by name.",
361
+ "Reads local config and files only. It never calls a provider API.",
362
+ "",
363
+ "Options:",
364
+ " --json Print machine-readable JSON.",
365
+ " -h, --help Show this help.",
366
+ ""
367
+ ].join("\n"));
368
+ return 0;
369
+ }
370
+ if (parsed.error) {
371
+ context.stderr.write(`${parsed.error}\nUsage: ${resourcesUsage}\n`);
372
+ return 1;
373
+ }
374
+ const generatedIds = readGeneratedWranglerIds(await collectViteHubProviderOutputEntries(plugins));
375
+ const resources = (await collectViteHubResourceSummaries(plugins)).map((resource) => {
376
+ const generatedId = resource.id || !resource.binding ? void 0 : generatedIds.get(`${resource.kind}:${resource.binding}`);
377
+ return generatedId ? {
378
+ ...resource,
379
+ id: generatedId,
380
+ source: "provider-output"
381
+ } : resource;
382
+ });
383
+ if (parsed.json) {
384
+ writeJson(context, { resources });
385
+ return 0;
386
+ }
387
+ if (!resources.length) {
388
+ context.stdout.write("No Definition maps to a host resource.\n");
389
+ return 0;
390
+ }
391
+ const lines = [];
392
+ for (const resource of resources) {
393
+ lines.push(`${resource.host}\t${resource.kind}\t${resource.definition}`);
394
+ if (resource.name) lines.push(` Name: ${resource.name}`);
395
+ if (resource.binding) lines.push(` Binding: ${resource.binding}`);
396
+ if (resource.id) lines.push(` Id: ${String(redactInspectionValue(resource.id, "id"))}`);
397
+ lines.push(` Source: ${describeSource(resource)}`);
398
+ if (resource.note) lines.push(` Note: ${resource.note}`);
399
+ }
400
+ lines.push("");
401
+ context.stdout.write(lines.join("\n"));
402
+ return 0;
403
+ }
404
+ function findPackage(file) {
405
+ for (let dir = dirname(file); dir !== dirname(dir); dir = dirname(dir)) {
406
+ const manifest = resolve(dir, "package.json");
407
+ if (!existsSync(manifest)) continue;
408
+ const name = Reflect.get(Object(JSON.parse(readFileSync(manifest, "utf8"))), "name");
409
+ if (typeof name === "string") return {
410
+ dir,
411
+ name
412
+ };
413
+ }
414
+ }
415
+ function routeHandler(rootDir, file) {
416
+ const path = relative(rootDir, file);
417
+ const generated = file.lastIndexOf("/.vitehub/");
418
+ if (generated !== -1) {
419
+ const [first, second] = file.slice(generated + 10).split("/");
420
+ return {
421
+ handler: path,
422
+ owner: (first === "nitro" ? second : first) || "vite-hub"
423
+ };
424
+ }
425
+ const owned = path.startsWith("..") || path.split("/").includes("node_modules") ? findPackage(file) : void 0;
426
+ return owned ? {
427
+ handler: `${owned.name}/${relative(owned.dir, file)}`,
428
+ owner: owned.name
429
+ } : {
430
+ handler: path,
431
+ owner: "app"
432
+ };
433
+ }
434
+ function readRoutes(rootDir, handlers) {
435
+ const routes = [];
436
+ const seen = /* @__PURE__ */ new Set();
437
+ for (const entry of handlers) {
438
+ const handler = Reflect.get(Object(entry), "handler");
439
+ if (typeof handler !== "string") continue;
440
+ const middleware = Reflect.get(Object(entry), "middleware") === true;
441
+ const route = Reflect.get(Object(entry), "route");
442
+ const methods = Reflect.get(Object(entry), "method");
443
+ const method = typeof methods === "string" ? methods.toUpperCase() : Array.isArray(methods) && methods.length ? methods.map(String).join(",").toUpperCase() : "*";
444
+ const report = {
445
+ .../^[#\u0000]/.test(handler) ? {
446
+ handler,
447
+ owner: "app"
448
+ } : routeHandler(rootDir, resolve(rootDir, handler)),
449
+ method,
450
+ ...middleware ? { middleware: true } : {},
451
+ route: typeof route === "string" && route ? route : "/**"
452
+ };
453
+ const key = `${report.method} ${report.route} ${report.handler} ${middleware}`;
454
+ if (seen.has(key)) continue;
455
+ seen.add(key);
456
+ routes.push(report);
457
+ }
458
+ return [...routes.filter((route) => route.middleware), ...routes.filter((route) => !route.middleware)];
459
+ }
460
+ async function runRoutes(args, context, handlers) {
461
+ const parsed = parseArgs$1(args, { kind: false });
462
+ if (parsed.help) {
463
+ context.stdout.write([
464
+ `Usage: ${routesUsage}`,
465
+ "",
466
+ "Lists the server routes and middleware that ViteHub and other Vite plugins add to the production build.",
467
+ "Shows each method, path, owner, and handler file. Routes in server/routes and server/api are not listed.",
468
+ "",
469
+ "Options:",
470
+ " --json Print machine-readable JSON.",
471
+ " -h, --help Show this help.",
472
+ ""
473
+ ].join("\n"));
474
+ return 0;
475
+ }
476
+ if (parsed.error) {
477
+ context.stderr.write(`${parsed.error}\nUsage: ${routesUsage}\n`);
478
+ return 1;
479
+ }
480
+ const routes = readRoutes(context.rootDir, handlers);
481
+ if (parsed.json) {
482
+ writeJson(context, { routes });
483
+ return 0;
484
+ }
485
+ if (!routes.length) {
486
+ context.stdout.write("No plugin adds a server route.\n");
487
+ return 0;
488
+ }
489
+ const methodWidth = Math.max(6, ...routes.map((route) => route.method.length));
490
+ const routeWidth = Math.max(4, ...routes.map((route) => route.route.length));
491
+ const ownerWidth = Math.max(5, ...routes.map((route) => route.owner.length));
492
+ const lines = [`${"METHOD".padEnd(methodWidth)} ${"PATH".padEnd(routeWidth)} ${"OWNER".padEnd(ownerWidth)} HANDLER`];
493
+ for (const route of routes) lines.push(`${route.method.padEnd(methodWidth)} ${route.route.padEnd(routeWidth)} ${route.owner.padEnd(ownerWidth)} ${route.handler}${route.middleware ? " (middleware)" : ""}`);
494
+ lines.push("");
495
+ context.stdout.write(lines.join("\n"));
496
+ return 0;
497
+ }
994
498
  /** Built-in namespace that renders package-owned inspection data. */
995
- function createInspectNamespace(plugins, operations = []) {
499
+ function createInspectNamespace(plugins, operations = [], handlers = []) {
996
500
  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
- }],
501
+ description: "Inspect discovered Definitions, host resources, server routes, and generated Provider Output.",
502
+ features: [
503
+ {
504
+ description: "List Definitions discovered by each active package.",
505
+ name: "definitions",
506
+ run: (args, context) => runDefinitions(args, context, plugins, operations),
507
+ usage: definitionsUsage
508
+ },
509
+ {
510
+ description: "List generated Provider Output files with secrets redacted.",
511
+ name: "output",
512
+ run: (args, context) => runProviderOutput(args, context, plugins),
513
+ usage: providerOutputUsage
514
+ },
515
+ {
516
+ description: "List the host resources that Definitions map to and where their ids come from.",
517
+ name: "resources",
518
+ run: (args, context) => runResources(args, context, plugins),
519
+ usage: resourcesUsage
520
+ },
521
+ {
522
+ description: "List the server routes that plugins add to the build, with method, path, and owner.",
523
+ name: "routes",
524
+ run: (args, context) => runRoutes(args, context, handlers),
525
+ usage: routesUsage
526
+ }
527
+ ],
1009
528
  name: "inspect"
1010
529
  };
1011
530
  }
@@ -1019,7 +538,7 @@ async function flattenPlugins(value, plugins, seen) {
1019
538
  for (const item of value) await flattenPlugins(item, plugins, seen);
1020
539
  return;
1021
540
  }
1022
- if (!isPlainObject(value) || seen.has(value)) return;
541
+ if (!isRecord(value) || seen.has(value)) return;
1023
542
  seen.add(value);
1024
543
  if (isThenable(value)) {
1025
544
  await flattenPlugins(await value, plugins, seen);
@@ -1038,138 +557,6 @@ async function flattenPluginOptions(plugins) {
1038
557
  return flattened;
1039
558
  }
1040
559
  //#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
560
  //#region src/operations.ts
1174
561
  /** Reads every contributed operation of the resolved plugins. A module that fails to load is reported on stderr. */
1175
562
  async function loadCliOperations(plugins, stderr) {
@@ -1331,7 +718,7 @@ function helpOf(operation, flags) {
1331
718
  ];
1332
719
  const described = flags.map((flag) => ` ${positional.includes(flag.key) ? `<${kebab(flag.key)}>` : `--${kebab(flag.key)}`} ${describeFlag(flag)}${flag.description ? `. ${flag.description}` : ""}`);
1333
720
  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.", "");
721
+ 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> The app URL, such as https://app.example.com. 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
722
  return lines.join("\n");
1336
723
  }
1337
724
  function usageError(message) {
@@ -1525,78 +912,17 @@ function resolveTarget(parsed, context) {
1525
912
  const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
1526
913
  if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: "--url must use HTTPS, except for localhost." })) };
1527
914
  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." })) };
915
+ const consolePath = /(?:^|\/)_vitehub(?:\/|$)/.exec(base.pathname);
916
+ if (consolePath) {
917
+ const app = `${base.origin}${base.pathname.slice(0, consolePath.index).replace(/\/$/, "")}`;
918
+ return { failure: failureOf(cliErrorDiagnostics.CLI_R0003({ message: `--url is the app URL, not the Console URL. Pass --url ${app}.` })) };
919
+ }
1528
920
  return { target: parsed.url };
1529
921
  }
1530
- const found = findViteHubDevServerUrl(acceptedRoots(context.rootDir), context.env);
922
+ const roots = acceptedRoots(context.rootDir);
923
+ const found = findViteHubDevServerUrl(roots, context.env);
1531
924
  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
- };
925
+ return { failure: failureOf(cliErrorDiagnostics.CLI_R0005({ message: `No dev server is running for ${roots.at(-1)}.` }), 503) };
1600
926
  }
1601
927
  function featureOf(operation) {
1602
928
  const flags = flagsOf(operation);
@@ -1632,7 +958,7 @@ function featureOf(operation) {
1632
958
  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
959
  confirmed = true;
1634
960
  }
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({
961
+ const result = await callOperation({
1636
962
  confirmed,
1637
963
  env: context.env,
1638
964
  ...context.fetch ? { fetch: context.fetch } : {},
@@ -1649,20 +975,77 @@ function featureOf(operation) {
1649
975
  usage: usageOf(operation, flags)
1650
976
  };
1651
977
  }
1652
- /** One namespace per operation namespace, with a command for each operation. */
978
+ /** `vitehub <namespace> <group> <command>`: one feature that runs the commands whose name starts with `<group> `. */
979
+ function groupOf(namespace, name, commands) {
980
+ const usage = `vitehub ${namespace} ${name} <${commands.map((command) => command.name).join("|")}> [args...]`;
981
+ const help = () => {
982
+ const width = Math.max(...commands.map((command) => command.name.length));
983
+ return [
984
+ `Usage: ${usage}`,
985
+ "",
986
+ "Commands:",
987
+ ...commands.map((command) => ` ${command.name.padEnd(width)} ${command.description ?? ""}`.trimEnd()),
988
+ "",
989
+ `Run \`vitehub ${namespace} ${name} <command> --help\` for the options of one command.`,
990
+ ""
991
+ ].join("\n");
992
+ };
993
+ return {
994
+ description: `${commands.map((command) => command.name).join(", ")}.`,
995
+ name,
996
+ async run(args, context) {
997
+ const [commandName, ...rest] = args;
998
+ if (commandName === "-h" || commandName === "--help") {
999
+ context.stdout.write(help());
1000
+ return 0;
1001
+ }
1002
+ const command = commands.find((candidate) => candidate.name === commandName);
1003
+ if (!command) {
1004
+ context.stderr.write(`${commandName ? `Unknown ViteHub CLI command: ${namespace} ${name} ${commandName}\n` : ""}${help()}`);
1005
+ return 1;
1006
+ }
1007
+ return await command.run(rest, context) ?? 0;
1008
+ },
1009
+ usage
1010
+ };
1011
+ }
1012
+ /**
1013
+ * One namespace per operation namespace, with a command for each operation. A command name with a space, such as
1014
+ * `jobs list`, becomes `list` in the `jobs` group: `vitehub queue jobs list`.
1015
+ */
1653
1016
  function createOperationNamespaces(operations) {
1654
1017
  const namespaces = /* @__PURE__ */ new Map();
1018
+ const groups = /* @__PURE__ */ new Map();
1655
1019
  for (const operation of operations) {
1656
- const { namespace: name } = operationCliPath(operation);
1020
+ const { command, namespace: name } = operationCliPath(operation);
1657
1021
  const namespace = namespaces.get(name) ?? {
1658
1022
  description: `Run the ${name} operations of the app.`,
1659
1023
  features: [],
1660
1024
  name
1661
1025
  };
1662
- namespace.features.push(featureOf(operation));
1663
- if (operation.cli?.default) namespace.defaultFeature = operationCliPath(operation).command;
1026
+ const space = command.indexOf(" ");
1027
+ if (space < 0) namespace.features.push(featureOf(operation));
1028
+ else {
1029
+ const groupName = command.slice(0, space);
1030
+ const key = `${name} ${groupName}`;
1031
+ const group = groups.get(key) ?? {
1032
+ commands: [],
1033
+ name: groupName,
1034
+ namespace: name
1035
+ };
1036
+ group.commands.push({
1037
+ ...featureOf(operation),
1038
+ name: command.slice(space + 1)
1039
+ });
1040
+ groups.set(key, group);
1041
+ }
1042
+ if (operation.cli?.default) namespace.defaultFeature = command;
1664
1043
  namespaces.set(name, namespace);
1665
1044
  }
1045
+ for (const group of groups.values()) {
1046
+ const namespace = namespaces.get(group.namespace);
1047
+ if (!namespace.features.some((feature) => feature.name === group.name)) namespace.features.push(groupOf(group.namespace, group.name, group.commands));
1048
+ }
1666
1049
  return [...namespaces.values()];
1667
1050
  }
1668
1051
  /**
@@ -1686,273 +1069,184 @@ function mergeOperationNamespaces(written, generated) {
1686
1069
  return merged;
1687
1070
  }
1688
1071
  //#endregion
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
- }
1721
- function resolveCloudflareProvisionConfig(env) {
1722
- const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
1723
- const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
1724
- if (!accountId || !token) return;
1725
- return {
1726
- accountId,
1727
- token
1728
- };
1729
- }
1730
- function resolveVercelProvisionConfig(env) {
1731
- const token = trimmedEnv(env.VERCEL_TOKEN);
1732
- if (!token) return;
1733
- return {
1734
- token,
1735
- teamId: trimmedEnv(env.VERCEL_TEAM_ID) ?? trimmedEnv(env.VERCEL_ORG_ID)
1736
- };
1737
- }
1738
- function trimmedEnv(value) {
1739
- const trimmed = value?.trim();
1740
- return trimmed ? trimmed : void 0;
1741
- }
1742
- //#endregion
1743
- //#region src/provision.ts
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);
1072
+ //#region src/seed.ts
1073
+ const usage = "vitehub seed [<primitive>...] [--remote [--url <url>]] [--stage <name>] [--database <name>] [--timeout <ms>]";
1074
+ function writeUsage(seeds, stream) {
1075
+ stream.write([
1076
+ `Usage: ${usage}`,
1077
+ "",
1078
+ "Writes the seed files of the app: the Database seed files, and the files in server/seed/kv/ and server/seed/blob/.",
1079
+ "Without --remote, it writes only local data: the local database, and the KV and Blob stores of the dev server.",
1080
+ "Name primitives to seed only them, such as `vitehub seed kv blob`.",
1081
+ "",
1082
+ "Seed files:",
1083
+ ...seeds.length ? seeds.map((seed) => ` ${seed.name.padEnd(9)} ${seed.files}`) : [" None. Turn on Database, KV, or Blob in the ViteHub config."],
1084
+ "",
1085
+ "Options:",
1086
+ " --remote Write the deployed data. KV and Blob seeds call the deployed app, with",
1087
+ " VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to sign the calls.",
1088
+ " --url <url> Deployed app URL for --remote. Defaults to `vitehub({ publicUrl })`.",
1089
+ " --stage <name> Load Vite env files for this mode. Variables from the current process take precedence.",
1090
+ " --database <name> Seed only this database.",
1091
+ " --timeout <ms> Request timeout of each call to the app.",
1092
+ " -h, --help Show this help.",
1093
+ ""
1094
+ ].join("\n"));
1755
1095
  }
1756
- function parseArgs(command, args) {
1096
+ function parseArgs(args, seeds) {
1757
1097
  const parsed = {
1758
- dryRun: false,
1759
1098
  help: false,
1760
- json: false
1099
+ names: [],
1100
+ remote: false
1761
1101
  };
1762
1102
  for (let index = 0; index < args.length; index++) {
1763
1103
  const arg = args[index];
1764
- if (arg === "-h" || arg === "--help") parsed.help = true;
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}`;
1779
- }
1780
- return parsed;
1781
- }
1782
- function writeUsage(command, stream) {
1783
- const lines = command === "run" ? [
1784
- `Usage: ${USAGE.run}`,
1785
- "",
1786
- "Idempotently creates missing provider resources for the app's Definitions.",
1787
- "Never deletes or mutates existing resources.",
1788
- "",
1789
- "Options:",
1790
- " --provider <name> Target provider: cloudflare or vercel (required).",
1791
- " --dry-run Print the plan without applying it.",
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`);
1806
- }
1807
- function resolveProvider(command, parsed, context) {
1808
- if (parsed.help) {
1809
- writeUsage(command, context.stdout);
1810
- return { exitCode: 0 };
1811
- }
1812
- if (parsed.error) {
1813
- context.stderr.write(`${parsed.error}\n`);
1814
- writeUsage(command, context.stderr);
1815
- return { exitCode: 1 };
1816
- }
1817
- if (!isProvisionProvider(parsed.provider)) {
1818
- context.stderr.write("Provision requires --provider cloudflare|vercel.\n");
1819
- writeUsage(command, context.stderr);
1820
- return { exitCode: 1 };
1821
- }
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(), {
1829
- env: context.env,
1830
- fetch: globalThis.fetch,
1831
- logger: {
1832
- log: (message) => (json ? context.stderr : context.stdout).write(`${message}\n`),
1833
- warn: (message) => {
1834
- if (!json) context.stderr.write(`${message}\n`);
1835
- }
1104
+ if (arg === "-h" || arg === "--help") {
1105
+ parsed.help = true;
1106
+ continue;
1836
1107
  }
1837
- });
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`);
1108
+ if (arg === "--remote") {
1109
+ parsed.remote = true;
1110
+ continue;
1111
+ }
1112
+ const option = [
1113
+ "--database",
1114
+ "--stage",
1115
+ "--timeout",
1116
+ "--url"
1117
+ ].find((name) => arg === name || arg.startsWith(`${name}=`));
1118
+ if (option) {
1119
+ const value = arg === option ? args[++index] : arg.slice(option.length + 1);
1120
+ if (!value || value.startsWith("-")) return `${option} requires a value.`;
1121
+ if (option === "--timeout") {
1122
+ const timeout = Number(value);
1123
+ if (!Number.isSafeInteger(timeout) || timeout <= 0) return "--timeout must be a positive integer of milliseconds.";
1124
+ parsed.timeout = timeout;
1125
+ } else parsed[option.slice(2)] = value;
1126
+ continue;
1127
+ }
1128
+ if (arg.startsWith("-")) return `Unknown option: ${arg}`;
1129
+ if (!seeds.some((seed) => seed.name === arg)) return `Unknown seed: ${arg}. Seeds of this app: ${seeds.map((seed) => seed.name).join(", ") || "none"}.`;
1130
+ if (!parsed.names.includes(arg)) parsed.names.push(arg);
1852
1131
  }
1132
+ if (parsed.url && !parsed.remote) return "--url names a deployed app. Add --remote to write its data.";
1133
+ if (parsed.database && parsed.names.some((name) => name !== "database")) return "--database seeds only the Database. Remove the other primitive names.";
1134
+ return parsed;
1853
1135
  }
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`);
1136
+ /** Runs the selected seeds in order and stops at the first failure. */
1137
+ async function runSeeds(seeds, parsed, context) {
1138
+ const selected = parsed.names.length || parsed.database ? seeds.filter((seed) => parsed.names.includes(seed.name) || parsed.database && seed.name === "database") : seeds;
1139
+ if (parsed.database && !selected.length) {
1140
+ context.stderr.write("[vitehub] --database needs the Database. Turn on Database in the ViteHub config.\n");
1861
1141
  return 1;
1862
1142
  }
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;
1143
+ let env = { ...context.env };
1144
+ return await withViteStageEnvironment(env, async () => {
1145
+ if (parsed.stage) {
1146
+ const { loadEnv } = await import("vite");
1147
+ env = {
1148
+ ...loadAllEnv(loadEnv, parsed.stage, context.rootDir),
1149
+ ...env
1150
+ };
1151
+ Object.assign(process.env, env);
1869
1152
  }
1870
- writeActions(actions, context.stdout);
1871
- }
1872
- let state = {};
1873
- if (!parsed.dryRun) for (const { action } of actions) {
1874
- const result = await action.apply();
1875
- if (result.ids) state = mergeProvisionState(state, result.ids);
1876
- }
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;
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");
1931
- return 0;
1153
+ const options = {
1154
+ env,
1155
+ remote: parsed.remote,
1156
+ ...parsed.database ? { database: parsed.database } : {},
1157
+ ...parsed.timeout ? { timeout: parsed.timeout } : {},
1158
+ ...parsed.remote && (parsed.url ?? context.publicUrl) ? { url: parsed.url ?? context.publicUrl } : {}
1159
+ };
1160
+ const empty = [];
1161
+ for (const seed of selected) {
1162
+ const code = await seed.run(options, {
1163
+ ...context,
1164
+ env
1165
+ });
1166
+ if (code === void 0) empty.push(seed);
1167
+ else if (code !== 0) return code;
1168
+ }
1169
+ const missing = parsed.names.length ? empty : empty.length === selected.length ? empty : [];
1170
+ if (!missing.length) return 0;
1171
+ context.stderr.write([
1172
+ "[vitehub] Nothing to seed. Add seed files:",
1173
+ ...missing.map((seed) => ` ${seed.name.padEnd(9)} ${seed.files}`),
1174
+ ""
1175
+ ].join("\n"));
1176
+ return 1;
1177
+ });
1932
1178
  }
1933
- /** Built-in namespace that orchestrates package-contributed Provision Steps. */
1934
- function createProvisionNamespace(steps) {
1935
- const options = { collectSteps: async () => [...steps] };
1179
+ /** The `vitehub seed` command, which runs the seeds that the ViteHub plugins contribute. */
1180
+ function createSeedNamespace(seeds) {
1936
1181
  return {
1937
- description: "Idempotently create missing provider resources.",
1182
+ defaultFeature: "seed",
1183
+ description: "Write the seed files of Database, KV, and Blob.",
1938
1184
  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
1185
+ description: "Write the seed files of Database, KV, and Blob.",
1186
+ name: "seed",
1187
+ run: async (args, context) => {
1188
+ const parsed = parseArgs(args, seeds);
1189
+ if (typeof parsed === "string") {
1190
+ context.stderr.write(`[vitehub] ${parsed}\n`);
1191
+ writeUsage(seeds, context.stderr);
1192
+ return 1;
1193
+ }
1194
+ if (parsed.help) {
1195
+ writeUsage(seeds, context.stdout);
1196
+ return 0;
1197
+ }
1198
+ if (!seeds.length) {
1199
+ context.stderr.write("[vitehub] No ViteHub primitive of this app has seed files. Turn on Database, KV, or Blob in the ViteHub config.\n");
1200
+ return 1;
1201
+ }
1202
+ return await runSeeds(seeds, parsed, context);
1203
+ },
1204
+ usage
1948
1205
  }],
1949
- name: "provision"
1206
+ name: "seed"
1950
1207
  };
1951
1208
  }
1952
1209
  //#endregion
1953
1210
  //#region src/index.ts
1954
1211
  const BUILTIN_NAMESPACE_NAMES = new Set(reservedOperationNamespaces);
1955
- async function loadNuxtViteConfig(rootDir, command) {
1212
+ /**
1213
+ * `vitehub env diff` and `vitehub env push` read the names of the last build and the variables of the linked host, and
1214
+ * `vitehub env pull` reads a Console with the key of `vitehub login`, so they run before the project config loads. The
1215
+ * other `env` features come from `hubEnv()`.
1216
+ */
1217
+ const hostEnvFeatures = {
1218
+ features: [
1219
+ {
1220
+ description: "Compare the env names of the last build with the names on the linked host. Exits with 1 when a required name is missing. Never reads values.",
1221
+ name: "diff",
1222
+ run: async (args, context) => await (await import("./env-DzoVtVJO.js").then((n) => n.n)).runEnvCommand({
1223
+ ...hostEnvFeatures.features[0],
1224
+ name: "diff"
1225
+ }, args, context),
1226
+ usage: "vitehub env diff [--host <host>] [--to github [--repo <owner/name>] [--environment <name>]] [--stage <name>] [--json]"
1227
+ },
1228
+ {
1229
+ description: "Set the host variables of the build's env names from the shell and .env.<stage>, with the host CLI. Prints names, never values. Never deletes a host variable.",
1230
+ name: "push",
1231
+ run: async (args, context) => await (await import("./env-DzoVtVJO.js").then((n) => n.n)).runEnvCommand({
1232
+ ...hostEnvFeatures.features[1],
1233
+ name: "push"
1234
+ }, args, context),
1235
+ usage: "vitehub env push [--host <host>] [--to github [--repo <owner/name>] [--environment <name>]] [--stage <name>] [--only <NAME>]... [--yes] [--json]"
1236
+ },
1237
+ {
1238
+ description: "Write the env values of a stage from a self-hosted Console to .env.<stage>. Needs `vitehub login` and the owner or admin role.",
1239
+ name: "pull",
1240
+ run: async (args, context) => await (await import("./console-env-C5YeAm2-.js")).envPullFeature.run(args, context),
1241
+ usage: "vitehub env pull --from console [--stage <name>] [--project <id>] [--console <url>] [--yes] [--json]"
1242
+ }
1243
+ ],
1244
+ name: "env"
1245
+ };
1246
+ async function loadSetupCommands() {
1247
+ return (await import("./commands-DPg3kL8m.js").then((n) => n.t)).setupCommands;
1248
+ }
1249
+ async function loadNuxtViteConfig(rootDir, command, mode) {
1956
1250
  if (![
1957
1251
  "nuxt.config.ts",
1958
1252
  "nuxt.config.mts",
@@ -1962,17 +1256,40 @@ async function loadNuxtViteConfig(rootDir, command) {
1962
1256
  "nuxt.config.cjs"
1963
1257
  ].some((file) => existsSync(resolve(rootDir, file)))) return;
1964
1258
  let loadNuxt;
1259
+ let loadNuxtConfig;
1965
1260
  try {
1966
- ({loadNuxt} = await import("nuxt/kit"));
1261
+ ({loadNuxt, loadNuxtConfig} = await import("nuxt/kit"));
1967
1262
  } catch {
1968
1263
  throw cliErrorDiagnostics.CLI_R0001({ message: "[vitehub] Nuxt config was found, but Nuxt could not be loaded for CLI discovery." });
1969
1264
  }
1970
- const nuxt = await loadNuxt({
1265
+ const options = {
1971
1266
  cwd: rootDir,
1972
1267
  dev: command === "serve",
1973
- overrides: { vitehubCliDiscovery: true },
1268
+ envName: mode ?? (command === "build" ? "production" : "development"),
1269
+ overrides: {
1270
+ devtools: { enabled: false },
1271
+ ...mode ? { vite: { mode } } : {},
1272
+ vitehubCliDiscovery: true
1273
+ },
1974
1274
  ready: true
1975
- });
1275
+ };
1276
+ if (mode) {
1277
+ const config = await loadNuxtConfig({
1278
+ ...options,
1279
+ dotenv: false,
1280
+ overrides: {
1281
+ ...options.overrides,
1282
+ dev: options.dev
1283
+ }
1284
+ });
1285
+ const nuxtRoot = config.rootDir || rootDir;
1286
+ const viteRoot = resolve(nuxtRoot, config.vite.root || nuxtRoot);
1287
+ const envDir = config.vite.envDir === false ? false : resolve(viteRoot, config.vite.envDir || ".");
1288
+ const { loadEnv } = await import("vite");
1289
+ Object.assign(process$1.env, loadAllEnv(loadEnv, mode, envDir));
1290
+ options.dotenv = false;
1291
+ }
1292
+ const nuxt = await loadNuxt(options);
1976
1293
  try {
1977
1294
  const { resolveConfig } = await import("vite");
1978
1295
  const viteRoot = nuxt.options.vite.root;
@@ -1981,8 +1298,23 @@ async function loadNuxtViteConfig(rootDir, command) {
1981
1298
  configFile: false,
1982
1299
  root: viteRoot ? resolve(nuxt.options.rootDir || rootDir, viteRoot) : nuxt.options.rootDir || rootDir,
1983
1300
  vitehubCliDiscovery: true
1984
- }, command, command === "build" ? "production" : "development");
1301
+ }, command, mode ?? (command === "build" ? "production" : "development"));
1985
1302
  return {
1303
+ nitro: { handlers: [...resolveRouteHandlers({
1304
+ ...Object(Reflect.get(config, "nitro")),
1305
+ alias: {
1306
+ ...nuxt.options.alias,
1307
+ ...Reflect.get(nuxt.options.nitro, "alias"),
1308
+ ...Reflect.get(Object(Reflect.get(config, "nitro")), "alias")
1309
+ }
1310
+ }, config.root), ...resolveRouteHandlers({
1311
+ ...nuxt.options.nitro,
1312
+ alias: {
1313
+ ...nuxt.options.alias,
1314
+ ...Reflect.get(nuxt.options.nitro, "alias")
1315
+ },
1316
+ handlers: [...nitroHandlers(nuxt.options.nitro), ...nuxt.options.serverHandlers]
1317
+ }, nuxt.options.rootDir || rootDir)] },
1986
1318
  plugins: config.plugins,
1987
1319
  root: config.root
1988
1320
  };
@@ -1990,6 +1322,39 @@ async function loadNuxtViteConfig(rootDir, command) {
1990
1322
  await nuxt.close();
1991
1323
  }
1992
1324
  }
1325
+ function nitroHandlers(nitro) {
1326
+ const handlers = Reflect.get(Object(nitro), "handlers");
1327
+ return Array.isArray(handlers) ? handlers : [];
1328
+ }
1329
+ function resolveRouteHandlers(nitro, projectRoot) {
1330
+ const options = Object(nitro);
1331
+ const rootDir = resolve(projectRoot, Reflect.get(options, "rootDir") || ".");
1332
+ const pathOptions = {
1333
+ ...options,
1334
+ rootDir,
1335
+ buildDir: resolve(rootDir, Reflect.get(options, "buildDir") || ".")
1336
+ };
1337
+ const aliases = Object.entries(Reflect.get(options, "alias") || {}).filter((entry) => typeof entry[1] === "string").sort(([a], [b]) => b.length - a.length);
1338
+ return nitroHandlers(nitro).map((entry) => {
1339
+ const handler = Reflect.get(Object(entry), "handler");
1340
+ if (typeof handler !== "string") return entry;
1341
+ let file = handler.replace(/{{ ?([\w.]+) ?}}/g, (_, key) => {
1342
+ const value = key.split(".").reduce((object, part) => Reflect.get(Object(object), part), pathOptions);
1343
+ return value ? String(value) : key;
1344
+ });
1345
+ const visited = /* @__PURE__ */ new Set();
1346
+ while (true) {
1347
+ const alias = aliases.find(([key]) => file === key || file.startsWith(`${key}/`));
1348
+ if (!alias || visited.has(alias[0])) break;
1349
+ visited.add(alias[0]);
1350
+ file = alias[1] + file.slice(alias[0].length);
1351
+ }
1352
+ return {
1353
+ ...Object(entry),
1354
+ handler: /^[#\u0000]/.test(file) ? file : resolve(rootDir, file)
1355
+ };
1356
+ });
1357
+ }
1993
1358
  function defaultSpawn(command, args, options = {}) {
1994
1359
  return new Promise((resolveResult, reject) => {
1995
1360
  const child = spawn(command, args, {
@@ -1997,34 +1362,54 @@ function defaultSpawn(command, args, options = {}) {
1997
1362
  env: options.env,
1998
1363
  shell: process$1.platform === "win32" && command !== process$1.execPath,
1999
1364
  stdio: [
2000
- "inherit",
2001
- options.stdout || "inherit",
1365
+ options.stdin || "inherit",
1366
+ options.stdout === "stderr" ? process$1.stderr : options.stdout || "inherit",
2002
1367
  options.stderr || "inherit"
2003
1368
  ]
2004
1369
  });
1370
+ const stdout = [];
1371
+ child.stdout?.on("data", (chunk) => stdout.push(chunk));
1372
+ child.stderr?.resume();
2005
1373
  child.on("error", reject);
2006
1374
  child.on("close", (exitCode, signal) => resolveResult({
2007
1375
  exitCode,
2008
- signal
1376
+ signal,
1377
+ ...child.stdout ? { stdout: Buffer.concat(stdout).toString("utf8") } : {}
2009
1378
  }));
2010
1379
  });
2011
1380
  }
2012
- async function loadViteConfig(rootDir, command) {
1381
+ async function loadViteConfig(rootDir, command, mode) {
2013
1382
  const { resolveConfig } = await import("vite");
2014
- return await resolveConfig({
1383
+ const inlineConfig = {
2015
1384
  root: rootDir,
1385
+ ...mode ? { mode } : {},
2016
1386
  vitehubCliDiscovery: true
2017
- }, command, command === "build" ? "production" : "development");
1387
+ };
1388
+ const nitro = createCliDiscoveryNitroCloser();
1389
+ try {
1390
+ return await resolveConfig({
1391
+ ...inlineConfig,
1392
+ plugins: [nitro.plugin]
1393
+ }, command, mode ?? (command === "build" ? "production" : "development"));
1394
+ } finally {
1395
+ await nitro.close();
1396
+ }
2018
1397
  }
2019
1398
  /** Keeps at least two spaces between a help name and its description. */
2020
1399
  function helpNameWidth(names) {
2021
1400
  return Math.max(12, ...names.map((name) => name.length + 1));
2022
1401
  }
2023
- function writeRootHelp(namespaces, stdout) {
2024
- const width = helpNameWidth(namespaces.map((namespace) => namespace.name));
1402
+ function writeRootHelp(namespaces, commands, stdout) {
1403
+ const width = helpNameWidth([...commands, ...namespaces].map((item) => item.name));
2025
1404
  stdout.write([
2026
1405
  "Usage: vitehub <namespace> <feature> [args...]",
1406
+ " vitehub <command> [args...]",
2027
1407
  "",
1408
+ ...commands.length ? [
1409
+ "Project:",
1410
+ ...commands.map((command) => ` ${command.name.padEnd(width)} ${command.description}`.trimEnd()),
1411
+ ""
1412
+ ] : [],
2028
1413
  "Available namespaces:",
2029
1414
  ...namespaces.map((namespace) => ` ${namespace.name.padEnd(width)} ${namespace.description || ""}`.trimEnd()),
2030
1415
  ""
@@ -2045,12 +1430,36 @@ function writeNamespaceHelp(namespace, stdout) {
2045
1430
  function isRootHelp(args) {
2046
1431
  return args[0] === "-h" || args[0] === "--help";
2047
1432
  }
1433
+ function isHelpFlag(arg) {
1434
+ return arg === "-h" || arg === "--help";
1435
+ }
1436
+ /** The namespace that answers `vitehub <namespace> [<feature>] --help` without the project, if one does. */
1437
+ async function loadHelpNamespace(args, helpNamespaces) {
1438
+ const [name, feature, ...rest] = args;
1439
+ if (!name || !helpNamespaces || !Object.hasOwn(helpNamespaces, name) || BUILTIN_NAMESPACE_NAMES.has(name)) return;
1440
+ if (!isHelpFlag(feature) && !rest.some(isHelpFlag)) return;
1441
+ const namespace = await helpNamespaces[name]();
1442
+ if (namespace && (isHelpFlag(feature) || namespace.features.some((item) => item.name === feature))) return namespace;
1443
+ }
2048
1444
  function readPackageVersion() {
2049
1445
  const manifest = readFileSync(new URL("../package.json", import.meta.url), "utf8");
2050
1446
  const version = /"version"\s*:\s*"([^"\\]+)"/u.exec(manifest)?.[1];
2051
1447
  if (!version) throw cliErrorDiagnostics.CLI_R0002({ message: "[vitehub] The installed @vite-hub/cli package manifest has no valid version." });
2052
1448
  return version;
2053
1449
  }
1450
+ /** The last `--stage <name>` or `--stage=<name>` of the command. */
1451
+ function readStageArg(args) {
1452
+ let stage;
1453
+ for (let index = 0; index < args.length; index++) {
1454
+ const arg = args[index];
1455
+ if (arg.startsWith("--stage=")) stage = arg.slice(8) || void 0;
1456
+ else if (arg === "--stage") {
1457
+ const value = args[++index];
1458
+ stage = value && !value.startsWith("-") ? value : void 0;
1459
+ }
1460
+ }
1461
+ return stage;
1462
+ }
2054
1463
  async function runViteHubCli(options = {}) {
2055
1464
  const args = options.args || process$1.argv.slice(2);
2056
1465
  const stdout = { write: options.stdout ? options.stdout.write.bind(options.stdout) : getStableStdoutWrite() };
@@ -2062,6 +1471,45 @@ async function runViteHubCli(options = {}) {
2062
1471
  const env = options.env || process$1.env;
2063
1472
  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
1473
  const spawn = options.spawn || defaultSpawn;
1474
+ const stage = args[0] === "channels" && (args[1] === "sync" || args[1] === "history") || args[0] === "seed" ? readStageArg(args) : void 0;
1475
+ const loadProject = (command) => withStdoutOnStderr(async () => {
1476
+ const loadConfig = options.loadConfig || loadViteConfig;
1477
+ const loadNuxtConfig = options.loadNuxtViteConfig || loadNuxtViteConfig;
1478
+ const config = await (stage ? loadConfig(cwd, command, stage) : loadConfig(cwd, command));
1479
+ const nuxtConfig = config.vitehubConfigResolved ? void 0 : await (stage ? loadNuxtConfig(cwd, command, stage) : loadNuxtConfig(cwd, command));
1480
+ const plugins = nuxtConfig?.plugins ?? config.plugins;
1481
+ return {
1482
+ contribution: await collectViteHubCliContribution(plugins),
1483
+ handlers: resolveRouteHandlers(nuxtConfig ? nuxtConfig.nitro : config.nitro, nuxtConfig?.root || config.root || cwd),
1484
+ operations: await loadCliOperations(plugins, stderr),
1485
+ plugins,
1486
+ rootDir: resolve(nuxtConfig?.root || config.root || cwd)
1487
+ };
1488
+ }, stderr);
1489
+ const loadProvision = options.loadProvision ?? (async (host) => {
1490
+ const loaded = await withViteStageEnvironment({
1491
+ ...env,
1492
+ VITEHUB_HOST: host,
1493
+ VITEHUB_HOST_SOURCE: "cli"
1494
+ }, () => loadProject("build"));
1495
+ return {
1496
+ rootDir: loaded.rootDir,
1497
+ steps: loaded.contribution.provision
1498
+ };
1499
+ });
1500
+ const loadCommands = async () => options.commands ?? [...await loadSetupCommands(), drainCommand];
1501
+ const setupCommand = options.commands || setupCommandNames.includes(args[0] ?? "") ? (await loadCommands()).find((item) => item.name === args[0]) : void 0;
1502
+ if (setupCommand) return await setupCommand.run(args.slice(1), {
1503
+ cwd,
1504
+ env,
1505
+ ...options.fetch ? { fetch: options.fetch } : {},
1506
+ loadProvision,
1507
+ rootDir: cwd,
1508
+ ...options.runHostCli ? { runHostCli: options.runHostCli } : {},
1509
+ spawn,
1510
+ stderr,
1511
+ stdout
1512
+ });
2065
1513
  const runtimeNamespace = options.runtimeNamespaces?.find((namespace) => namespace.name === args[0] && !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
2066
1514
  if (runtimeNamespace) return await runNamespace(runtimeNamespace, args, {
2067
1515
  cwd,
@@ -2071,52 +1519,65 @@ async function runViteHubCli(options = {}) {
2071
1519
  stderr,
2072
1520
  stdout
2073
1521
  });
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]));
1522
+ const runtimeFeatures = [...options.runtimeFeatures ?? [], hostEnvFeatures].find((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && namespace.name === args[0] && namespace.features.some((feature) => feature.name === args[1]));
2075
1523
  if (runtimeFeatures && (await options.runtimeFeatureGuard?.(args[0], args[1], cwd) ?? true)) return await runNamespace(runtimeFeatures, args, {
2076
1524
  cwd,
2077
1525
  env,
1526
+ ...options.fetch ? { fetch: options.fetch } : {},
2078
1527
  rootDir: cwd,
1528
+ ...options.runHostCli ? { runHostCli: options.runHostCli } : {},
2079
1529
  spawn,
2080
1530
  stderr,
2081
1531
  stdout
2082
1532
  });
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);
1533
+ const helpNamespace = await loadHelpNamespace(args, options.helpNamespaces);
1534
+ if (helpNamespace) return await runNamespace(helpNamespace, args, {
1535
+ cwd,
1536
+ env,
1537
+ rootDir: cwd,
1538
+ spawn,
1539
+ stderr,
1540
+ stdout
1541
+ });
1542
+ const command = args[0] === "inspect" && (args[1] === "output" || args[1] === "resources" || args[1] === "routes") ? "build" : "serve";
1543
+ const { contribution, handlers, operations, plugins, rootDir } = await (stage ? withViteStageEnvironment(env, () => loadProject(command)) : loadProject(command));
1544
+ const runtimeNamespaces = (options.runtimeNamespaces ?? []).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
1545
+ const runtimeNames = new Set(runtimeNamespaces.map((namespace) => namespace.name));
2095
1546
  const namespaces = [
2096
- ...mergeOperationNamespaces(contribution.namespaces, createOperationNamespaces(operations)).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name)),
2097
- createInspectNamespace(plugins, operations),
1547
+ ...mergeOperationNamespaces(contribution.namespaces, createOperationNamespaces(operations)).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && !runtimeNames.has(namespace.name)),
1548
+ createInspectNamespace(plugins, operations, handlers),
2098
1549
  createProvisionNamespace(contribution.provision),
2099
- ...(options.runtimeNamespaces ?? []).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name))
1550
+ createSeedNamespace(contribution.seeds),
1551
+ ...runtimeNamespaces
2100
1552
  ];
1553
+ const envIndex = namespaces.findIndex((namespace) => namespace.name === hostEnvFeatures.name);
1554
+ const envNamespace = namespaces[envIndex];
1555
+ if (envNamespace) namespaces[envIndex] = {
1556
+ ...envNamespace,
1557
+ features: [...envNamespace.features, ...hostEnvFeatures.features.filter((feature) => !envNamespace.features.some((item) => item.name === feature.name))]
1558
+ };
1559
+ else namespaces.push(hostEnvFeatures);
2101
1560
  const context = {
2102
1561
  cwd,
2103
1562
  env,
2104
1563
  ...options.fetch ? { fetch: options.fetch } : {},
1564
+ ...contribution.publicUrl ? { publicUrl: contribution.publicUrl } : {},
2105
1565
  rootDir,
1566
+ ...options.runHostCli ? { runHostCli: options.runHostCli } : {},
2106
1567
  spawn,
2107
1568
  stderr,
2108
1569
  stdout
2109
1570
  };
2110
1571
  if (!args.length || isRootHelp(args)) {
2111
- writeRootHelp(namespaces, stdout);
1572
+ writeRootHelp(namespaces, await loadCommands(), stdout);
2112
1573
  return 0;
2113
1574
  }
2114
1575
  const namespaceName = args[0];
2115
1576
  const namespace = namespaces.find((item) => item.name === namespaceName);
2116
1577
  if (!namespace) {
2117
1578
  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`);
2119
- writeRootHelp(namespaces, stderr);
1579
+ if (namespaces.every((item) => BUILTIN_NAMESPACE_NAMES.has(item.name) || item === hostEnvFeatures)) 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`);
1580
+ writeRootHelp(namespaces, await loadCommands(), stderr);
2120
1581
  return 1;
2121
1582
  }
2122
1583
  return await runNamespace(namespace, args, context);
@@ -2124,12 +1585,13 @@ async function runViteHubCli(options = {}) {
2124
1585
  async function runNamespace(namespace, args, context) {
2125
1586
  const { stderr, stdout } = context;
2126
1587
  const featureName = args[1];
1588
+ const defaultFeature = namespace.defaultFeature ? namespace.features.find((item) => item.name === namespace.defaultFeature) : void 0;
1589
+ if (defaultFeature?.name === namespace.name && namespace.features.length === 1) return await defaultFeature.run(args.slice(1), context) ?? 0;
2127
1590
  if (featureName === "-h" || featureName === "--help") {
2128
1591
  writeNamespaceHelp(namespace, stdout);
2129
1592
  return 0;
2130
1593
  }
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;
1594
+ if (defaultFeature && (!featureName || featureName.startsWith("-") || !namespace.features.some((item) => item.name === featureName))) return await defaultFeature.run(args.slice(1), context) ?? 0;
2133
1595
  if (!featureName) {
2134
1596
  writeNamespaceHelp(namespace, stdout);
2135
1597
  return 0;
@@ -2207,14 +1669,5 @@ function runViteHubCliEntrypoint(options = {}) {
2207
1669
  process$1.exit(exitCode);
2208
1670
  })();
2209
1671
  }
2210
- function isCliEntrypoint() {
2211
- if (!process$1.argv[1]) return false;
2212
- try {
2213
- return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process$1.argv[1]);
2214
- } catch {
2215
- return false;
2216
- }
2217
- }
2218
- if (isCliEntrypoint()) runViteHubCliEntrypoint();
2219
1672
  //#endregion
2220
1673
  export { runViteHubCli, runViteHubCliEntrypoint };