@vite-hub/cli 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,9 @@
1
- import { B as readSetupProject, F as uninstallArgs, G as featureSupport, H as featureHosts, J as editViteHubConfig, K as features, L as hasDefinitionFiles, M as installCommand, N as setsOption, P as setupStatus, R as listMatchingFiles, U as featureIds, V as setupLockfiles, W as featurePackages, X as locateViteHubConfig, Y as insertViteHubConfig, Z as __exportAll, c as linkSetupProject, j as installArgs, l as readLinkHostOption, m as unlinkSetupProject, o as gitignoreWithViteHub, q as impliedFeatures, r as SETUP_LINK_FILE, u as readSetupLinkState, z as detectPackageManager } from "./env-B1Gg-WnA.js";
2
- import { m as cliErrorDiagnostics } from "./provision-DXl97xG0.js";
3
- import { a as table, i as setupFailure, n as readSetupArgs, o as writeSetupError, r as setupExitCodes, s as writeSetupJson } from "./envelope-B4mPbSbj.js";
4
- import { l as whoamiCommand, o as loginCommand, s as logoutCommand } from "./console-auth-B0HxFFiX.js";
5
- import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-C0RdI5OK.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
+ import { F as featureHosts, H as installSpecifier, I as featureIds, L as featurePackages, R as featureSupport, V as impliedFeatures, m as cliErrorDiagnostics, z as features } from "./provision-DlknnTAt.js";
3
+ import { B as listMatchingFiles, F as setupStatus, G as insertViteHubConfig, H as readSetupProject, I as shellQuote, K as locateViteHubConfig, L as uninstallArgs, M as installArgs, N as installCommand, P as missingProviderOption, U as setupLockfiles, V as detectPackageManager, W as editViteHubConfig, c as linkSetupProject, j as formatInstallCommand, l as readLinkHostOption, m as unlinkSetupProject, o as gitignoreWithViteHub, r as SETUP_LINK_FILE, u as readSetupLinkState, z as hasDefinitionFiles } from "./env-DRI0QH4-.js";
4
+ import { a as table, i as setupFailure, n as readSetupArgs, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-DbplCDko.js";
5
+ import { l as whoamiCommand, o as loginCommand, s as logoutCommand } from "./console-auth-CpOpbA7U.js";
6
+ import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-BZ2iQjZL.js";
6
7
  import { createRequire } from "node:module";
7
8
  import { existsSync, readFileSync } from "node:fs";
8
9
  import process from "node:process";
@@ -12,14 +13,30 @@ import { join as join$1 } from "node:path";
12
13
  import { createInterface } from "node:readline/promises";
13
14
  import { pathToFileURL } from "node:url";
14
15
  import { createTwoFilesPatch } from "diff";
15
- import { parseArgs } from "node:util";
16
- import semver, { Range, minVersion, subset, validRange } from "semver";
17
- //#region src/setup/add.ts
16
+ import { isDeepStrictEqual, parseArgs } from "node:util";
17
+ import semver, { Range, minVersion, satisfies, subset, validRange } from "semver";
18
+ // ../internal/dist/feature-inputs.js
19
+ function isLocaleTag(value) {
20
+ try {
21
+ return Intl.getCanonicalLocales(value).length === 1;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ function i18nLocaleListProblem(locales) {
27
+ if (!Array.isArray(locales) || locales.length === 0) return "`i18n.locales` is empty.";
28
+ const seen = /* @__PURE__ */ new Set();
29
+ for (const locale of locales) {
30
+ if (typeof locale !== "string" || !isLocaleTag(locale)) return `\`${String(locale)}\` is not a BCP 47 language tag.`;
31
+ if (seen.has(locale.toLowerCase())) return `\`${locale}\` is listed twice.`;
32
+ seen.add(locale.toLowerCase());
33
+ }
34
+ }
35
+ function mcpPublicRouteNeedsSignedAuth(publicRoute, auth) {
36
+ return !!publicRoute && auth !== true;
37
+ }
38
+ // src/setup/add.ts
18
39
  const usage$3 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
19
- /**
20
- * Values that `--option` can choose for an `explicit` host, first the one that `rerun` uses, and the feature that the
21
- * value needs. Options without an entry, such as `database.connection`, need a value that only the developer knows.
22
- */
23
40
  const optionChoices = {
24
41
  "cache.driver": {
25
42
  requires: "kv",
@@ -31,7 +48,6 @@ const optionChoices = {
31
48
  "sandboxTask.driver": { values: ["vercel"] },
32
49
  "workflow.driver": { values: ["openworkflow"] }
33
50
  };
34
- /** Option keys that select a provider or a store. A feature that sets one does not use the host default. */
35
51
  const providerKeys = ["driver", "store"];
36
52
  function selectsProvider(id, value, host) {
37
53
  if (!isRecord$1(value)) return false;
@@ -41,15 +57,12 @@ function selectsProvider(id, value, host) {
41
57
  }
42
58
  return providerKeys.some((key) => value[key] !== void 0);
43
59
  }
44
- /** How `host` supports `id`, with the override that `env` selects, such as BLOB_READ_WRITE_TOKEN for the Vercel Workspace. */
45
60
  function hostSupport(id, host, env) {
46
61
  const support = featureSupport(id, host);
47
62
  if (support.level !== "native") return support;
48
63
  return support.envOverrides?.find((override) => env[override.env]?.trim())?.support ?? support;
49
64
  }
50
- /** The value that turns a feature on, when `true` is not valid for its key. */
51
65
  const enabledValues = { env: {} };
52
- /** Keep owner packages on the running CLI's pkg.pr.new preview. */
53
66
  function installSpecifiers(packages) {
54
67
  const manifest = JSON.parse(readFileSync(new URL(import.meta.resolve("@vite-hub/cli/package.json")), "utf8"));
55
68
  const dependencies = isRecord$1(manifest) && isRecord$1(manifest.dependencies) ? manifest.dependencies : {};
@@ -61,7 +74,7 @@ function installSpecifiers(packages) {
61
74
  ref
62
75
  }] : [];
63
76
  })[0];
64
- return packages.map((name) => preview && name.startsWith("@vite-hub/") ? `${preview.base}/${name}@${preview.ref}` : name);
77
+ return packages.map((name) => preview && name.startsWith("@vite-hub/") ? `${preview.base}/${name}@${preview.ref}` : installSpecifier(name));
65
78
  }
66
79
  function invalid$3(message, commandUsage = usage$3) {
67
80
  return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${commandUsage}` });
@@ -73,7 +86,12 @@ function readFeatureId(value, commandUsage = usage$3) {
73
86
  if (!id) throw invalid$3(`Unknown feature ${JSON.stringify(value)}. Run \`vitehub catalog\` to list the features.`, commandUsage);
74
87
  return id;
75
88
  }
76
- function optionValue(value) {
89
+ function optionValue(value, key) {
90
+ if (key === "i18n.locales" && value.trimStart().startsWith("[")) try {
91
+ return JSON.parse(value);
92
+ } catch {
93
+ throw invalid$3(`--option ${key} must contain a valid JSON array.`);
94
+ }
77
95
  if (value === "true" || value === "false" || value === "null" || /^-?\d+(?:\.\d+)?$/u.test(value)) return JSON.parse(value);
78
96
  return value;
79
97
  }
@@ -130,21 +148,16 @@ function readAddArgs(args) {
130
148
  const id = head ?? (parsed.features.length === 1 ? parsed.features[0] : void 0);
131
149
  const keys = head ? path.slice(1) : path;
132
150
  if (!id || !keys.length || keys.some((key) => !key)) throw invalid$3(`--option ${JSON.stringify(option)} must start with one of the features, such as \`${parsed.features[0] ?? "email"}.driver=resend\`.`);
133
- setPath(parsed.options[id] ??= {}, keys, optionValue(option.slice(separator + 1)));
151
+ setPath(parsed.options[id] ??= {}, keys, optionValue(option.slice(separator + 1), `${id}.${keys.join(".")}`));
134
152
  }
135
153
  return parsed;
136
154
  }
137
- /** Quotes `value` for a POSIX shell when it needs quotes. */
138
- function shellQuote(value) {
139
- return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
140
- }
141
155
  /** `value` as `--option` values under `prefix`, such as `["email.driver=resend"]`. */
142
156
  function flattenOptions(prefix, value, out = []) {
143
157
  if (isRecord$1(value)) for (const [key, child] of Object.entries(value)) flattenOptions(`${prefix}.${key}`, child, out);
144
158
  else out.push(`${prefix}=${value === null || typeof value !== "object" ? String(value) : JSON.stringify(value)}`);
145
159
  return out;
146
160
  }
147
- /** The `vitehub add` command for `args`, with `extra` options and `--yes` unless it is a dry run. */
148
161
  function rerunCommand$1(args, extra = {}, extraFeatures = []) {
149
162
  const ids = [...args.features, ...extraFeatures.filter((id) => !args.features.includes(id))];
150
163
  const options = [.../* @__PURE__ */ new Set([
@@ -189,10 +202,6 @@ function toSource(value) {
189
202
  function setupDiff(path, before, after) {
190
203
  return createTwoFilesPatch(before ? `a/${path}` : "/dev/null", after ? `b/${path}` : "/dev/null", before, after, void 0, void 0, { context: 3 }).replace(/^=+\n/u, "");
191
204
  }
192
- /**
193
- * The config value that `add` writes for `id`, `undefined` when the config already turns it on, or `expression` when
194
- * the key is an expression that only a person can edit.
195
- */
196
205
  function nextValue(id, status, project, options) {
197
206
  const current = project.config?.ok ? project.config.site.keys[id] : void 0;
198
207
  if (current?.kind === "expression") return "expression";
@@ -225,6 +234,11 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
225
234
  feature: id,
226
235
  host
227
236
  }), setupExitCodes.conflict);
237
+ if (id === "email" && driver === "smtp" && host === "cloudflare") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
238
+ detail: "The \"smtp\" driver opens TCP connections with nodemailer, and Cloudflare Workers cannot run it. On Cloudflare, use the \"cloudflare\" or \"resend\" driver, or a driver module that sends over HTTP.",
239
+ feature: id,
240
+ host
241
+ }), setupExitCodes.conflict);
228
242
  if (support.level === "unsupported") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
229
243
  detail: support.detail,
230
244
  feature: id,
@@ -232,6 +246,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
232
246
  }), setupExitCodes.conflict);
233
247
  }
234
248
  const missing = [];
249
+ const inputFixes = [];
235
250
  const defaults = {};
236
251
  const requires = [];
237
252
  let rerunnable = true;
@@ -250,7 +265,6 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
250
265
  };
251
266
  for (const id of inputFeatures) {
252
267
  const support = featureSupport(id, host);
253
- const options = args.options[id];
254
268
  const current = project.config?.ok ? project.config.site.keys[id] : void 0;
255
269
  const value = valueFor(id);
256
270
  if (id === "observability" && isRecord$1(value) && value.papercuts) {
@@ -306,14 +320,14 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
306
320
  if (invocations === "database" || isRecord$1(invocations) && invocations.store === "database") requireFeature("database");
307
321
  const storageSelected = id === "workflow" && host !== "netlify" && selectsProvider(id, value, host);
308
322
  if (support.level === "explicit" && !storageSelected) {
309
- const key = support.option.slice(id.length + 1);
310
- if (!(options && key in options) && !setsOption(project, support.option)) {
323
+ const field = missingProviderOption(project, support.option, value);
324
+ if (field) {
311
325
  const choices = optionChoices[support.option];
312
326
  missing.push({
313
- field: support.option,
327
+ field,
314
328
  ...choices ? { choices: choices.values } : {}
315
329
  });
316
- if (choices) setPath(defaults[id] ??= {}, [key], choices.values[0]);
330
+ if (choices) setPath(defaults[id] ??= {}, field.split(".").slice(1), choices.values[0]);
317
331
  else rerunnable = false;
318
332
  }
319
333
  }
@@ -351,16 +365,73 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
351
365
  host
352
366
  }), setupExitCodes.conflict);
353
367
  for (const id of Object.keys(args.options)) if (!inputFeatures.includes(id)) throw invalid$3(`${id} is not requested or required by ${args.features.join(", ")}.`);
368
+ const site = project.config?.ok ? project.config.site : void 0;
369
+ if (inputFeatures.includes("i18n") && site?.keys.i18n?.kind !== "expression") {
370
+ const i18n = valueFor("i18n");
371
+ const problem = i18nLocaleListProblem(isRecord$1(i18n) ? i18n.locales : void 0);
372
+ if (problem) {
373
+ missing.push({ field: "i18n.locales" });
374
+ inputFixes.push(`${problem} Pass a nonempty JSON array, such as \`--option 'i18n.locales=["en","es"]'\`.`);
375
+ rerunnable = false;
376
+ }
377
+ }
378
+ const mcpOAuthSetup = "Include `mcpOAuth()` from `vite-hub/auth/mcp` in the `plugins` of `defineAuth()` in the Auth Definition";
379
+ let needsMcpOAuth = false;
380
+ if (inputFeatures.includes("mcp") && site?.keys.mcp?.kind !== "expression") {
381
+ const configuredAuth = site?.keys.auth;
382
+ const authStatus = status.features.find((item) => item.id === "auth");
383
+ const discoveredAuth = authStatus?.enabled === "on" && authStatus.reason === "default";
384
+ const selectedAuth = args.features.includes("auth") && (!configuredAuth || configuredAuth.kind === "expression" || configuredAuth.value === false);
385
+ const authEnabled = !args.options.auth && (selectedAuth || configuredAuth?.kind === "literal" && configuredAuth.value === true || discoveredAuth);
386
+ const mcp = valueFor("mcp");
387
+ const mode = isRecord$1(mcp) && Object.hasOwn(mcp, "auth") ? mcp.auth : void 0;
388
+ const publicRoute = isRecord$1(mcp) && typeof mcp.publicRoute === "string" ? mcp.publicRoute : void 0;
389
+ if ((typeof mode === "boolean" || mode === "optional") && mcpPublicRouteNeedsSignedAuth(publicRoute, mode)) {
390
+ missing.push({ field: "mcp.publicRoute" });
391
+ inputFixes.push("Remove `mcp.publicRoute`, or enable Auth, set `mcp.auth=true`, and add `mcpOAuth()` to the Auth Definition.");
392
+ rerunnable = false;
393
+ } else if (!authEnabled && authStatus?.enabled === "unknown" && (mode === void 0 || mode === true || mode === "optional")) {
394
+ const file = project.configFile ?? "vite.config.ts";
395
+ const snippet = `mcp: ${toSource(isRecord$1(mcp) ? mcp : true)},`;
396
+ const fix = `Confirm Auth is enabled in the app. ${mcpOAuthSetup}. Add this key to the vitehub() options by hand:\n${snippet}`;
397
+ throw setupFailure(cliErrorDiagnostics.SETUP_CONFIG_MANUAL({
398
+ file,
399
+ fix,
400
+ reason: "Auth cannot be determined statically"
401
+ }), setupExitCodes.conflict, { data: { snippet } });
402
+ } else if (mode === true || mode === "optional" || mode === void 0 && authEnabled) {
403
+ if (authEnabled) needsMcpOAuth = true;
404
+ else {
405
+ missing.push({ field: "auth" });
406
+ inputFixes.push(`Select the \`auth\` feature or enable Auth in the app config. ${mcpOAuthSetup}.`);
407
+ rerunnable = false;
408
+ }
409
+ } else if (mode !== false) {
410
+ missing.push({
411
+ choices: [
412
+ "true",
413
+ "optional",
414
+ "false"
415
+ ],
416
+ field: "mcp.auth"
417
+ });
418
+ inputFixes.push("Enable Auth for signed requests and use `mcp.auth=true` or `mcp.auth=optional`, or omit `mcp.auth` to require sign-in by default. Pass `--option mcp.auth=false` only when anyone may call every tool.");
419
+ rerunnable = false;
420
+ }
421
+ }
354
422
  if (missing.length) {
355
423
  const fields = missing.map((item) => `\`${item.field}\``).join(", ");
356
- throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.` }), setupExitCodes.inputNeeded, {
424
+ const fix = inputFixes.length ? inputFixes.join(" ") : void 0;
425
+ throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({
426
+ fix,
427
+ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.`
428
+ }), setupExitCodes.inputNeeded, {
357
429
  missing,
358
430
  ...rerunnable ? { rerun: rerun(args, defaults, requires) } : {}
359
431
  });
360
432
  }
361
433
  const edits = [];
362
434
  let expression = false;
363
- const site = project.config?.ok ? project.config.site : void 0;
364
435
  const addedFeatures = [...args.features, ...requires];
365
436
  for (const id of /* @__PURE__ */ new Set([...addedFeatures, ...inputFeatures.filter((id) => args.options[id])])) {
366
437
  const next = nextValue(id, status, project, args.options[id]);
@@ -461,11 +532,27 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
461
532
  const command = installCommand(project.packageManager, install.prod, install.dev);
462
533
  const restartRequired = addsDiscovery && !configFile;
463
534
  const nextSteps = restartRequired ? ["Restart the dev server to load the new feature configuration."] : [];
535
+ if (needsMcpOAuth) {
536
+ const [appServerDir, ...layers] = project.serverDirs ?? [];
537
+ const authFiles = features.auth.enabledByDiscovery ?? [];
538
+ const appFiles = appServerDir ? authFiles.map((name) => join(appServerDir, name)) : [];
539
+ const definition = appServerDir && [
540
+ ...appFiles,
541
+ ...authFiles.map((name) => join(definitionRoot, `server.${name}`)),
542
+ ...layers.flatMap((dir) => authFiles.map((name) => join(dir, name)))
543
+ ].find(existsSync);
544
+ const target = definition ? ` in \`${relative(project.root, definition)}\`` : "";
545
+ if (!definition && appServerDir) nextSteps.push(`Create an Auth Definition at \`${join(serverDir, "auth.ts")}\` if the app has none.`);
546
+ nextSteps.push(`${mcpOAuthSetup}${target}. https://vitehub.dev/docs/mcp/configure#sign-in-with-mcp-oauth`);
547
+ }
464
548
  if (command && !args.install) nextSteps.push(`Install the packages: ${command}`);
465
549
  for (const id of implied) {
466
550
  const support = featureSupport(id, host);
467
551
  if (support.level === "unsupported") nextSteps.push(`${id} is turned on by ${args.features.join(", ")} but is not supported on ${host}: ${support.detail} Set \`${id}: false\` to turn it off.`);
468
- else if (support.level === "explicit" && !setsOption(project, support.option) && !(args.options[id] && support.option.slice(id.length + 1) in args.options[id])) nextSteps.push(`${id} is turned on by ${args.features.join(", ")}. Set \`${support.option}\` on ${host}, or set \`${id}: false\`. ${support.detail}`);
552
+ else if (support.level === "explicit") {
553
+ const option = missingProviderOption(project, support.option, valueFor(id));
554
+ if (option) nextSteps.push(`${id} is turned on by ${args.features.join(", ")}. Set \`${option}\` on ${host}, or set \`${id}: false\`. ${support.detail}`);
555
+ }
469
556
  }
470
557
  for (const id of [...addedFeatures, ...implied]) {
471
558
  if (selectsProvider(id, valueFor(id))) continue;
@@ -509,7 +596,7 @@ async function applySetupAdd(project, planned, args, context) {
509
596
  stdout: "stderr"
510
597
  });
511
598
  if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
512
- command: [project.packageManager, ...commandArgs].join(" "),
599
+ command: formatInstallCommand(project.packageManager, commandArgs),
513
600
  exitCode: result.exitCode ?? result.signal
514
601
  }), setupExitCodes.error);
515
602
  }
@@ -601,8 +688,7 @@ const addCommand = {
601
688
  run: runAdd,
602
689
  usage: usage$3
603
690
  };
604
- //#endregion
605
- //#region src/setup/catalog.ts
691
+ // src/setup/catalog.ts
606
692
  /** Every feature of `vitehub({...})` and how each host supports it. Needs no project. */
607
693
  function setupCatalog() {
608
694
  return {
@@ -611,10 +697,165 @@ function setupCatalog() {
611
697
  schemaVersion: 1
612
698
  };
613
699
  }
614
- //#endregion
615
- //#region src/setup/init.ts
700
+ // src/setup/stack.ts
701
+ function replayOption(id, keys, value) {
702
+ if (keys.some((key) => !key || /[.=\0]/u.test(key) || [
703
+ "__proto__",
704
+ "constructor",
705
+ "prototype"
706
+ ].includes(key))) return;
707
+ const raw = typeof value === "object" ? JSON.stringify(value) : String(value);
708
+ if (raw.includes("\0")) return;
709
+ const flag = `${id}.${keys.join(".")}=${raw}`;
710
+ try {
711
+ const parsed = readAddArgs([
712
+ id,
713
+ "--option",
714
+ flag
715
+ ]).options[id];
716
+ const expected = keys.reduceRight((child, key) => ({ [key]: child }), value);
717
+ if (isDeepStrictEqual(parsed, expected)) return flag;
718
+ } catch {
719
+ return;
720
+ }
721
+ }
722
+ function credentialKey(key) {
723
+ return /(?:token|secret|password|passphrase|apikey|privatekey|accesskey(?:id)?|connectionstring|credentials?|authorization|cookie|dsn)$/iu.test(key.replaceAll(/[-_]/gu, "")) || /^(?:pass|auth|headers)$/iu.test(key);
724
+ }
725
+ function containsCredentials(value) {
726
+ if (typeof value === "string") {
727
+ const url = URL.parse(value.startsWith("//") ? `https:${value}` : value);
728
+ return !!(url && (url.username || url.password || url.search || url.hash));
729
+ }
730
+ if (Array.isArray(value)) return value.some(containsCredentials);
731
+ return isRecord$1(value) && Object.entries(value).some(([key, child]) => credentialKey(key) || containsCredentials(child));
732
+ }
733
+ function setupStackLabels(stack) {
734
+ return {
735
+ command: stack.command ?? "Unavailable",
736
+ omissions: stack.omits.map(({ path, reason }) => `${path} (${reason})`).join(", ")
737
+ };
738
+ }
739
+ async function deriveSetupStack(project, status, validate) {
740
+ const site = project.config?.ok ? project.config.site : void 0;
741
+ const omits = [];
742
+ const options = [];
743
+ const selected = [];
744
+ const collect = (id, keys, value) => {
745
+ const path = [id, ...keys].join(".");
746
+ if (!(path === "mcp.auth" && keys.length === 1 && (typeof value === "boolean" || value === "optional")) && keys.some(credentialKey)) {
747
+ omits.push({
748
+ path,
749
+ reason: "credential-option"
750
+ });
751
+ return;
752
+ }
753
+ if (isRecord$1(value) && Object.keys(value).length) {
754
+ for (const [key, child] of Object.entries(value)) collect(id, [...keys, key], child);
755
+ return;
756
+ }
757
+ if (containsCredentials(value)) {
758
+ omits.push({
759
+ path,
760
+ reason: "credential-option"
761
+ });
762
+ return;
763
+ }
764
+ const flag = keys.length ? replayOption(id, keys, value) : void 0;
765
+ if (flag === void 0) omits.push({
766
+ path,
767
+ reason: "non-replayable-option"
768
+ });
769
+ else options.push(flag);
770
+ };
771
+ if (!site) omits.push({
772
+ path: "config",
773
+ reason: "opaque-config"
774
+ });
775
+ if (site?.spread) omits.push({
776
+ path: "config",
777
+ reason: "spread"
778
+ });
779
+ if (status.host.name === "unknown") omits.push({
780
+ path: "host",
781
+ reason: "unresolved-host"
782
+ });
783
+ for (const { id, enabled, support } of status.features) {
784
+ const setting = site?.keys[id];
785
+ if (setting?.kind === "expression") {
786
+ omits.push({
787
+ path: id,
788
+ reason: "expression"
789
+ });
790
+ continue;
791
+ }
792
+ if (enabled === "unknown" && site && !site.spread) omits.push({
793
+ path: id,
794
+ reason: "unresolved-feature"
795
+ });
796
+ if (enabled !== "on") continue;
797
+ if (support.level === "unsupported") {
798
+ omits.push({
799
+ path: id,
800
+ reason: "unsupported-feature"
801
+ });
802
+ continue;
803
+ }
804
+ const value = setting?.value;
805
+ if (features[id].enabledByDefault && (value === void 0 || value === true || isRecord$1(value) && !Object.keys(value).length)) continue;
806
+ selected.push(id);
807
+ if (value !== void 0 && value !== true) collect(id, [], value);
808
+ }
809
+ const implied = impliedFeatures(selected);
810
+ for (const { id, enabled, reason } of status.features) if (enabled === "off" && reason === "config" && (features[id].enabledByDefault || implied.includes(id))) omits.push({
811
+ path: id,
812
+ reason: "disabled-feature"
813
+ });
814
+ const name = basename(project.root);
815
+ const args = [
816
+ name.startsWith("-") ? `./${name}` : name || "vitehub-app",
817
+ "--host",
818
+ status.host.name === "unknown" ? "<host>" : status.host.name,
819
+ "--features",
820
+ selected.join(","),
821
+ ...options.flatMap((option) => ["--option", option]),
822
+ "--framework",
823
+ status.framework === "nuxt" ? "nuxt" : "vite",
824
+ "--pm",
825
+ status.packageManager,
826
+ "--yes"
827
+ ];
828
+ if (status.host.name !== "unknown") try {
829
+ await validate(args);
830
+ } catch (error) {
831
+ if (!isSetupFailure(error)) throw error;
832
+ const missing = error.details.missing;
833
+ if (missing?.length) omits.push(...missing.map(({ field }) => ({
834
+ path: field,
835
+ reason: "required-option"
836
+ })));
837
+ else omits.push({
838
+ path: "features",
839
+ reason: "unplannable-stack"
840
+ });
841
+ return {
842
+ command: null,
843
+ omits
844
+ };
845
+ }
846
+ return {
847
+ command: [
848
+ "pnpm",
849
+ "dlx",
850
+ "vite-hub",
851
+ "init",
852
+ ...args.map(shellQuote)
853
+ ].join(" "),
854
+ omits
855
+ };
856
+ }
857
+ // src/setup/init.ts
616
858
  const usage$2 = "vitehub init <dir> --host <host> --features <id,id,...> [--option <feature.key=value>]... [--framework vite|nuxt] [--pm pnpm|npm|yarn|bun] [--no-install] [--dry-run] --yes [--json]";
617
- /** The command that starts a project. It runs from the `vite-hub` package, so it needs no install. */
618
859
  const initCommandPrefix = "pnpm dlx vite-hub init";
619
860
  const initHosts = [
620
861
  "cloudflare",
@@ -632,8 +873,8 @@ const packageManagers = [
632
873
  ];
633
874
  /**
634
875
  * The packages of a new app, as `getting-started/installation.md` installs them. The Nitro and H3 versions match the
635
- * server integration of ViteHub. Nuxt 5 supplies Nitro 3, and its tutorials import H3 2. Valibot validates request
636
- * bodies in the docs' route examples.
876
+ * server integration of ViteHub. Nuxt 5 supplies Nitro 3, and a Nuxt 4.7 app also gets `nuxtNitroPackage`. The
877
+ * tutorials import H3 2. Valibot validates request bodies in the docs' route examples.
637
878
  */
638
879
  const initPackages = {
639
880
  nuxt: {
@@ -652,19 +893,17 @@ const initPackages = {
652
893
  ],
653
894
  prod: [
654
895
  "vite-hub",
655
- "nitro@3.0.261102-rc",
896
+ "nitro@3.0.261103-rc",
656
897
  "h3@2.0.8",
657
898
  "valibot"
658
899
  ]
659
900
  }
660
901
  };
902
+ const nuxtNitroRange = "^3.0.261103-rc";
903
+ const nuxtNitroPackage = `nitro@${nuxtNitroRange}`;
661
904
  /** The pinned Nuxt CLI that creates a new Nuxt app. */
662
905
  const nuxiPackage = "nuxi@3.37.0";
663
- /** Pin the starter files and select Nuxt 5 explicitly instead of the live minimal registry entry. */
664
906
  const nuxtTemplate = "gh:nuxt/starter#db01806fcb37f2e369fb09443c72cac696b31548";
665
- /** Where the reproducing command lives in README.md. */
666
- const stackStart = "<!-- vitehub:stack -->";
667
- const stackEnd = "<!-- /vitehub:stack -->";
668
907
  function isRecord(value) {
669
908
  return !!value && typeof value === "object" && !Array.isArray(value);
670
909
  }
@@ -712,7 +951,6 @@ function readInitArgs(args) {
712
951
  if (features !== void 0) parsed.features = readAddArgs(features.split(",").map((item) => item.trim()).filter(Boolean)).features;
713
952
  return parsed;
714
953
  }
715
- /** The `vitehub add` arguments for the features and options of `init`. */
716
954
  function addArgsOf(args) {
717
955
  return {
718
956
  ...readAddArgs([...args.features, ...args.options.flatMap((option) => ["--option", option])]),
@@ -726,20 +964,15 @@ function initCommand(parts, extra) {
726
964
  initCommandPrefix,
727
965
  shellQuote(parts.dir),
728
966
  "--host",
729
- parts.host ?? "<host>",
967
+ shellQuote(parts.host ?? "<host>"),
730
968
  "--features",
731
- parts.features ? parts.features.join(",") || "''" : "<id,id,...>",
969
+ shellQuote(parts.features?.join(",") ?? "<id,id,...>"),
732
970
  ...options.flatMap((option) => ["--option", shellQuote(option)]),
733
971
  ...parts.framework === "nuxt" ? ["--framework", "nuxt"] : [],
734
972
  ...parts.pm && parts.pm !== "pnpm" ? ["--pm", parts.pm] : [],
735
973
  ...extra
736
974
  ].join(" ");
737
975
  }
738
- /** The command that creates the same stack, for README.md and `vitehub status`. */
739
- function stackCommand(parts) {
740
- return initCommand(parts, ["--yes"]);
741
- }
742
- /** The `rerun` command: the same request with `--yes`. */
743
976
  function rerunInit(args, parts) {
744
977
  return initCommand(parts, [
745
978
  ...args.install ? [] : ["--no-install"],
@@ -747,37 +980,9 @@ function rerunInit(args, parts) {
747
980
  ...args.json ? ["--json"] : []
748
981
  ]);
749
982
  }
750
- function stackBlock(command) {
751
- return `${stackStart}\nCreate the same stack with:\n\n\`\`\`sh\n${command}\n\`\`\`\n${stackEnd}\n`;
752
- }
753
- /** README.md with the stack block, or undefined when it already holds the same block. */
754
- function readmeWithStack(readme, name, command) {
755
- const block = stackBlock(command);
756
- if (readme === void 0) return `# ${name}\n\n${block}`;
757
- const from = readme.indexOf(stackStart);
758
- const to = readme.indexOf(stackEnd, from);
759
- if (from !== -1 && to !== -1) {
760
- const after = readme.slice(to + 23).replace(/^\r?\n/u, "");
761
- return `${readme.slice(0, from)}${block}${after}`;
762
- }
763
- return `${readme}${readme === "" || readme.endsWith("\n") ? "" : "\n"}\n${block}`;
764
- }
765
- /** The stack command in the README.md block of `root`, for `vitehub status`. `null` when there is no block. */
766
- async function readSetupStack(root) {
767
- const file = join(root, "README.md");
768
- if (!existsSync(file)) return null;
769
- const readme = await readFile(file, "utf8");
770
- const from = readme.indexOf(stackStart);
771
- const to = readme.indexOf(stackEnd, from);
772
- if (from === -1 || to === -1) return null;
773
- const command = readme.slice(from, to).split(/\r?\n/u).map((line) => line.trim()).find((line) => line.startsWith(initCommandPrefix));
774
- return command ? { command } : null;
775
- }
776
- /** The deployment name rules of `vitehub({ name })`, for the package.json name of a new app. */
777
983
  function packageNameOf(root) {
778
984
  return basename(root).trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || "vitehub-app";
779
985
  }
780
- /** The files of a new Vite app, as `fixtures/docs-hosts/installation` has them. */
781
986
  function viteAppFiles(name, host) {
782
987
  return {
783
988
  ".gitignore": "node_modules\n.output\n.vitehub\n.env*\n!.env.example\n",
@@ -809,7 +1014,6 @@ function viteAppFiles(name, host) {
809
1014
  "vite.config.ts": `import { defineConfig } from "vite"\nimport { vitehub } from "vite-hub"\n\nexport default defineConfig({\n plugins: [vitehub({ host: "${host}" })],\n})\n`
810
1015
  };
811
1016
  }
812
- /** The config that `nuxi init` and the adoption would give, to plan a new Nuxt app before `nuxi init` runs. */
813
1017
  function nuxtAppFiles(name, host) {
814
1018
  return {
815
1019
  "nuxt.config.ts": `import viteHubNuxt from "vite-hub/nuxt"\n\nexport default defineNuxtConfig({\n modules: [\n [viteHubNuxt, { host: "${host}" }],\n ],\n})\n`,
@@ -881,7 +1085,6 @@ function manualConfig(file, reason, host, framework) {
881
1085
  snippet
882
1086
  }), setupExitCodes.conflict, { data: { snippet } });
883
1087
  }
884
- /** The config of an existing app with ViteHub registered on `host`. */
885
1088
  function adoptConfig(project, host, framework) {
886
1089
  const file = project.configFile ?? (framework === "nuxt" ? "nuxt.config.ts" : "vite.config.ts");
887
1090
  const config = project.config;
@@ -923,7 +1126,6 @@ function adoptConfig(project, host, framework) {
923
1126
  file
924
1127
  };
925
1128
  }
926
- /** Plans `vitehub init` without writing anything. Throws `SetupFailure` when the change needs input or is not possible. */
927
1129
  async function planInit(args, root, state, context) {
928
1130
  const name = packageNameOf(root);
929
1131
  const found = state.kind === "adopt" ? state.project.framework : void 0;
@@ -933,7 +1135,7 @@ async function planInit(args, root, state, context) {
933
1135
  found,
934
1136
  framework
935
1137
  }), setupExitCodes.conflict);
936
- if (state.kind === "adopt" && framework === "nuxt") await validateNuxtVersion(root);
1138
+ const nuxtNeedsNitro = state.kind === "adopt" && framework === "nuxt" && (await checkNuxtVersion(root)).needsNitro;
937
1139
  const detected = state.kind === "adopt" ? state.project : detectPackageManager(root, void 0, context.env);
938
1140
  const packageManager = args.pm ?? (detected.packageManagerSource === "default" ? "pnpm" : detected.packageManager);
939
1141
  const base = /* @__PURE__ */ new Map();
@@ -961,6 +1163,7 @@ async function planInit(args, root, state, context) {
961
1163
  dev: basePackages.dev.filter((spec) => !declared(packageName$1(spec), true)),
962
1164
  prod: basePackages.prod.filter((spec) => !declared(packageName$1(spec), false))
963
1165
  };
1166
+ if (nuxtNeedsNitro) install.prod.push(nuxtNitroPackage);
964
1167
  const willInstall = new Set([...install.prod, ...install.dev].map(packageName$1));
965
1168
  const configSource = base.get(configFile).after;
966
1169
  const planned = {
@@ -973,7 +1176,7 @@ async function planInit(args, root, state, context) {
973
1176
  packageManager,
974
1177
  packageManagerSource: args.pm ? "manifest" : detected.packageManagerSource,
975
1178
  root,
976
- serverDirs: state.kind === "adopt" ? state.project.serverDirs : [join(root, "server")]
1179
+ serverDirs: state.kind === "adopt" ? state.project.serverDirs : []
977
1180
  };
978
1181
  const addArgs = addArgsOf(args);
979
1182
  const parts = (extra = {}, extraFeatures = []) => {
@@ -1001,12 +1204,6 @@ async function planInit(args, root, state, context) {
1001
1204
  ...base.get(configFile),
1002
1205
  after: added.configFile.after
1003
1206
  });
1004
- const stack = stackCommand(parts());
1005
- const readme = state.kind === "create" ? void 0 : await readOptional(join(root, "README.md"));
1006
- base.set("README.md", {
1007
- ...readme === void 0 ? {} : { before: readme },
1008
- after: readmeWithStack(readme, name, stack)
1009
- });
1010
1207
  if (state.kind === "adopt") {
1011
1208
  const gitignore = await readOptional(join(root, ".gitignore"));
1012
1209
  base.set(".gitignore", {
@@ -1040,6 +1237,13 @@ async function planInit(args, root, state, context) {
1040
1237
  `Start the dev server: ${runScript(packageManager, "dev")}`,
1041
1238
  ...added.plan.nextSteps
1042
1239
  ];
1240
+ const finalConfig = base.get(configFile).after;
1241
+ const stackProject = {
1242
+ ...planned,
1243
+ config: locateViteHubConfig(configFile, finalConfig),
1244
+ configSource: finalConfig,
1245
+ packageManager: args.install && (command || scaffold) ? packageManager : detected.packageManager
1246
+ };
1043
1247
  return {
1044
1248
  install,
1045
1249
  plan: {
@@ -1058,14 +1262,27 @@ async function planInit(args, root, state, context) {
1058
1262
  packageManager,
1059
1263
  root,
1060
1264
  ...scaffold ? { scaffold: { command: [scaffold[0], ...scaffold[1]].join(" ") } } : {},
1061
- stack: { command: stack },
1062
1265
  status: writes.length || scaffold || command && args.install ? "planned" : "unchanged"
1063
1266
  },
1064
1267
  rerun: rerunInit(args, parts()),
1268
+ stackProject,
1065
1269
  writes,
1066
1270
  ...scaffold ? { scaffold } : {}
1067
1271
  };
1068
1272
  }
1273
+ function setupStack(project, status) {
1274
+ return deriveSetupStack(project, status, async (args) => {
1275
+ const inputs = await readInputs(readInitArgs(args));
1276
+ const rootDir = dirname(project.root);
1277
+ await planInit(inputs, resolve(rootDir, inputs.dir), {
1278
+ exists: false,
1279
+ kind: "create"
1280
+ }, {
1281
+ env: {},
1282
+ rootDir
1283
+ });
1284
+ });
1285
+ }
1069
1286
  async function applyInit(planned, install, context, scaffolded = false) {
1070
1287
  const { plan } = planned;
1071
1288
  const runInstall = async () => {
@@ -1079,7 +1296,7 @@ async function applyInit(planned, install, context, scaffolded = false) {
1079
1296
  stdout: "stderr"
1080
1297
  });
1081
1298
  if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
1082
- command: [plan.packageManager, ...commandArgs].join(" "),
1299
+ command: formatInstallCommand(plan.packageManager, commandArgs),
1083
1300
  exitCode: result.exitCode ?? result.signal,
1084
1301
  filesWritten: scaffolded || plan.mode === "create"
1085
1302
  }), setupExitCodes.error);
@@ -1102,7 +1319,6 @@ async function applyInit(planned, install, context, scaffolded = false) {
1102
1319
  }
1103
1320
  if (plan.mode === "create") await runInstall();
1104
1321
  }
1105
- /** Runs `nuxi init` for a new Nuxt app. ViteHub then adopts the app that it created. */
1106
1322
  async function scaffoldNuxt(planned, context) {
1107
1323
  const [command, commandArgs] = planned.scaffold;
1108
1324
  await mkdir(dirname(planned.plan.root), { recursive: true });
@@ -1116,25 +1332,34 @@ async function scaffoldNuxt(planned, context) {
1116
1332
  exitCode: result.exitCode ?? result.signal,
1117
1333
  filesWritten: "possible"
1118
1334
  }), setupExitCodes.error);
1119
- await validateNuxtVersion(planned.plan.root, true);
1335
+ await checkNuxtVersion(planned.plan.root, true);
1120
1336
  }
1121
- /** Accept nonempty ranges confined to Nuxt 5, including its prereleases and nightly aliases. */
1122
- function supportsNuxt5(nuxt) {
1123
- if (typeof nuxt !== "string") return false;
1337
+ function nuxtReleases(nuxt) {
1338
+ if (typeof nuxt !== "string") return void 0;
1124
1339
  const range = validRange(nuxt.replace(/^npm:nuxt(?:-nightly)?@/u, ""));
1125
- if (!range || !minVersion(range)) return false;
1126
- const releases = new Range(range).set.map((comparators) => comparators.map(({ operator, semver, value }) => typeof semver !== "symbol" && semver.major === 5 && semver.prerelease.length > 0 ? `${operator}5.${semver.minor}.${semver.patch}` : value).join(" ")).join(" || ");
1127
- return subset(releases, ">=5.0.0 <6.0.0");
1340
+ if (!range || !minVersion(range)) return void 0;
1341
+ return new Range(range).set.map((comparators) => comparators.map(({ operator, semver, value }) => typeof semver !== "symbol" && semver.major === 5 && semver.prerelease.length > 0 ? `${operator}5.${semver.minor}.${semver.patch}` : value).join(" ")).join(" || ");
1128
1342
  }
1129
- /** Validate both existing apps and scaffold output before planning adoption or installing packages. */
1130
- async function validateNuxtVersion(root, scaffolded = false) {
1343
+ async function checkNuxtVersion(root, scaffolded = false) {
1131
1344
  const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
1132
1345
  const dependencies = isRecord(manifest) && isRecord(manifest.dependencies) ? manifest.dependencies : {};
1133
1346
  const devDependencies = isRecord(manifest) && isRecord(manifest.devDependencies) ? manifest.devDependencies : {};
1134
- if (!supportsNuxt5(dependencies.nuxt ?? devDependencies.nuxt)) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_NUXT_VERSION({
1347
+ const releases = nuxtReleases(dependencies.nuxt ?? devDependencies.nuxt);
1348
+ if (!releases || !subset(releases, ">=4.7.0 <6.0.0")) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_NUXT_VERSION({
1135
1349
  dir: root,
1136
1350
  scaffolded
1137
1351
  }), setupExitCodes.conflict);
1352
+ if (subset(releases, ">=5.0.0 <6.0.0")) return { needsNitro: false };
1353
+ const nitroDeclarations = [dependencies.nitro, devDependencies.nitro].filter((spec) => spec !== void 0);
1354
+ for (const spec of nitroDeclarations) {
1355
+ const range = typeof spec === "string" ? validRange(spec.replace(/^npm:nitro@/u, "")) : null;
1356
+ if (!range || !minVersion(range) || !range.split("||").every((branch) => satisfies(branch, nuxtNitroRange) || subset(branch, nuxtNitroRange))) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_NITRO_VERSION({
1357
+ dir: root,
1358
+ range: nuxtNitroRange,
1359
+ scaffolded
1360
+ }), setupExitCodes.conflict);
1361
+ }
1362
+ return { needsNitro: nitroDeclarations.length === 0 };
1138
1363
  }
1139
1364
  function interactive(args) {
1140
1365
  return !args.json && !!process.stdin.isTTY && !!process.stderr.isTTY;
@@ -1150,7 +1375,6 @@ async function ask(question) {
1150
1375
  terminal.close();
1151
1376
  }
1152
1377
  }
1153
- /** Asks for missing inputs in a terminal. Without one, fails with the flag and its choices. */
1154
1378
  async function readInputs(args) {
1155
1379
  if (interactive(args)) {
1156
1380
  const dir = args.dir ?? (await ask("Folder of the app: ") || ".");
@@ -1201,13 +1425,22 @@ function writePlan$1(plan, context) {
1201
1425
  if (plan.scaffold) context.stdout.write(`Run: ${plan.scaffold.command}\n`);
1202
1426
  for (const change of plan.changes) if (change.kind === "create") context.stdout.write(`create ${change.path}\n`);
1203
1427
  else context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
1204
- const lines = [...plan.install.command ? [`Install: ${plan.install.command}`] : [], ...plan.implied.length ? [`Also turns on: ${plan.implied.join(", ")}`] : []];
1205
- if (lines.length) context.stdout.write(`${lines.join("\n")}\n`);
1428
+ const lines = [
1429
+ ...plan.install.command ? [`Install: ${plan.install.command}`] : [],
1430
+ ...plan.implied.length ? [`Also turns on: ${plan.implied.join(", ")}`] : [],
1431
+ ...stackLines(plan.stack)
1432
+ ];
1433
+ context.stdout.write(`${lines.join("\n")}\n`);
1434
+ }
1435
+ function stackLines(stack) {
1436
+ const { command, omissions } = setupStackLabels(stack);
1437
+ return [`Stack: ${command}`, ...omissions ? [`Stack omissions: ${omissions}`] : []];
1206
1438
  }
1207
1439
  function writeResult$1(plan, context) {
1208
1440
  const features = plan.features.length ? ` with ${plan.features.join(", ")}` : "";
1209
1441
  if (plan.status === "unchanged") context.stdout.write(`${plan.root} already has this stack. Nothing to change.\n`);
1210
1442
  else context.stdout.write(`${plan.mode === "create" ? "Created" : "Set up"} ${plan.root} for ${plan.host}${features}.\n`);
1443
+ context.stdout.write(`${stackLines(plan.stack).join("\n")}\n`);
1211
1444
  context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
1212
1445
  }
1213
1446
  async function runInit(rawArgs, context) {
@@ -1222,7 +1455,10 @@ async function runInit(rawArgs, context) {
1222
1455
  const args = await readInputs(parsed);
1223
1456
  const root = resolve(context.rootDir, args.dir);
1224
1457
  let planned = await planInit(args, root, await readDir(root, context.env), context);
1225
- const { plan } = planned;
1458
+ const plan = {
1459
+ ...planned.plan,
1460
+ stack: await setupStack(planned.stackProject, setupStatus(planned.stackProject, context.env))
1461
+ };
1226
1462
  if (plan.status === "unchanged" || args.dryRun) {
1227
1463
  if (args.json) writeSetupJson(context, plan);
1228
1464
  else if (plan.status === "unchanged") writeResult$1(plan, context);
@@ -1248,9 +1484,11 @@ async function runInit(rawArgs, context) {
1248
1484
  }, root, await readDir(root, context.env), context);
1249
1485
  }
1250
1486
  await applyInit(planned, args.install, context, !!plan.scaffold);
1487
+ const project = await readSetupProject(root, context.env);
1251
1488
  const applied = {
1252
1489
  ...planned.plan,
1253
1490
  mode: plan.mode,
1491
+ stack: await setupStack(project, setupStatus(project, context.env)),
1254
1492
  status: "applied",
1255
1493
  ...plan.scaffold ? { scaffold: plan.scaffold } : {}
1256
1494
  };
@@ -1267,8 +1505,7 @@ const initCommandDefinition = {
1267
1505
  run: runInit,
1268
1506
  usage: usage$2
1269
1507
  };
1270
- //#endregion
1271
- //#region src/setup/remove.ts
1508
+ // src/setup/remove.ts
1272
1509
  const usage$1 = "vitehub remove <feature...> [--dry-run] [--yes] [--keep-files] [--force] [--no-uninstall] [--json]";
1273
1510
  function invalid$1(message) {
1274
1511
  return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$1}` });
@@ -1310,11 +1547,9 @@ function rerunCommand(args) {
1310
1547
  ...args.json ? ["--json"] : []
1311
1548
  ].join(" ");
1312
1549
  }
1313
- /** The `vite-hub` subpath of a feature, such as `vite-hub/rate-limit`. */
1314
1550
  function runtimeModule(id) {
1315
1551
  return `vite-hub/${id === "sandboxTask" ? "sandbox/task" : id.replace(/[A-Z]/gu, (char) => `-${char.toLowerCase()}`)}`;
1316
1552
  }
1317
- /** The package of an import, such as `@vite-hub/schedule` for `@vite-hub/schedule/vite`. */
1318
1553
  function packageName(specifier) {
1319
1554
  const parts = specifier.split("/");
1320
1555
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
@@ -1322,7 +1557,6 @@ function packageName(specifier) {
1322
1557
  function importsModule(specifier, module) {
1323
1558
  return specifier === module || specifier.startsWith(`${module}/`);
1324
1559
  }
1325
- /** Imports (including static template literals), re-exports, module augmentations, and triple-slash type references. Comments can match, which only makes `remove` stricter. */
1326
1560
  const specifierPattern = /(?:\b(?:from|import|require|declare\s+module)(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*(?:\((?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*)?|\/\/\/\s*<reference\s+types\s*=\s*)(?:(["'])([^"'\r\n]+)\1|`((?:[^`$\r\n]|\$(?!\{))+)`)/gu;
1327
1561
  const sourceFile = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|mdx?|html?)$/iu;
1328
1562
  function lineAt(content, index) {
@@ -1330,7 +1564,6 @@ function lineAt(content, index) {
1330
1564
  for (let cursor = content.indexOf("\n"); cursor !== -1 && cursor < index; cursor = content.indexOf("\n", cursor + 1)) line++;
1331
1565
  return line;
1332
1566
  }
1333
- /** True when `content` equals the current or an earlier starter template for the Definition at `path`. */
1334
1567
  function isStarter(starter, path, content) {
1335
1568
  const parts = path.replace(/\.[^./]+$/u, "").split("/");
1336
1569
  const name = [
@@ -1340,7 +1573,6 @@ function isStarter(starter, path, content) {
1340
1573
  ].find((candidate) => candidate && starter.file(candidate) === path);
1341
1574
  return name !== void 0 && [starter.template, ...starter.previousTemplates ?? []].some((template) => template(name) === content);
1342
1575
  }
1343
- /** Features required by selected options. Unknown options can select any supported prerequisite. */
1344
1576
  function optionPrerequisites(id, value, unknown) {
1345
1577
  const options = isRecord$1(value) ? value : void 0;
1346
1578
  if (id === "cache" && (unknown || options?.driver === "kv")) return ["kv"];
@@ -1593,7 +1825,6 @@ async function planSetupRemove(project, args, env) {
1593
1825
  ...configPatch ? { configFile: configPatch } : {}
1594
1826
  };
1595
1827
  }
1596
- /** Deletes `path` and then each folder that is empty after it, such as the `server/queues` that `add` created. */
1597
1828
  async function deleteStarter(root, path) {
1598
1829
  await rm(join(root, path));
1599
1830
  for (let folder = dirname(join(root, path)); folder !== root && folder.startsWith(`${root}/`); folder = dirname(folder)) {
@@ -1691,8 +1922,7 @@ const removeCommand = {
1691
1922
  run: runRemove,
1692
1923
  usage: usage$1
1693
1924
  };
1694
- //#endregion
1695
- //#region src/setup/update.ts
1925
+ // src/setup/update.ts
1696
1926
  const usage = "vitehub update [--preview <commit>] [--dry-run] [--no-install] [--json]";
1697
1927
  const previewBase = "https://pkg.pr.new/vite-hub/vitehub";
1698
1928
  const defaultRegistry = "https://registry.npmjs.org/";
@@ -1701,14 +1931,9 @@ const dependencyFields = [
1701
1931
  "devDependencies",
1702
1932
  "optionalDependencies"
1703
1933
  ];
1704
- /** `vite-hub` and every `@vite-hub/*` package. */
1705
1934
  function isViteHubPackage(name) {
1706
1935
  return name === "vite-hub" || /^@vite-hub\/[a-z0-9][\w.-]*$/u.test(name);
1707
1936
  }
1708
- /**
1709
- * The package that an override or resolution key targets, such as `@vite-hub/env` for `foo>@vite-hub/env@0.1.0` or
1710
- * `**\/@vite-hub/env`. Undefined when it is not a ViteHub package.
1711
- */
1712
1937
  function overrideTarget(key) {
1713
1938
  let part = key.split(">").at(-1).replace(/^\*\*\//u, "");
1714
1939
  const scoped = part.lastIndexOf("/@");
@@ -1717,11 +1942,9 @@ function overrideTarget(key) {
1717
1942
  const name = part.replace(/(?<=.)@.*$/u, "");
1718
1943
  return isViteHubPackage(name) ? name : void 0;
1719
1944
  }
1720
- /** True for a specifier that names a release or a pkg.pr.new build, not `workspace:`, `catalog:`, a link, or git. */
1721
1945
  function isReplaceable(specifier) {
1722
1946
  return specifier.startsWith(`${previewBase}/`) || specifier === "latest" || specifier === "next" || semver.validRange(specifier) !== null;
1723
1947
  }
1724
- /** The new specifier for `name`, from the resolved npm version or preview URL. */
1725
1948
  function nextSpecifier(name, current, place, target) {
1726
1949
  if ("preview" in target) return target.url(name);
1727
1950
  const version = target.versions.get(name);
@@ -1731,7 +1954,6 @@ function nextSpecifier(name, current, place, target) {
1731
1954
  function isObject(value) {
1732
1955
  return !!value && typeof value === "object" && !Array.isArray(value);
1733
1956
  }
1734
- /** Calls `visit` for every ViteHub specifier in the update fields of a package.json. */
1735
1957
  function visitManifest(manifest, visit) {
1736
1958
  const entries = (holder, place, nameOf) => {
1737
1959
  if (!isObject(holder)) return;
@@ -1771,7 +1993,6 @@ function unquote(text) {
1771
1993
  value: text
1772
1994
  };
1773
1995
  }
1774
- /** A `key: value` line inside a block, such as ` "@vite-hub/env": 0.1.0 # pinned`. Undefined for other lines. */
1775
1996
  function readYamlEntry(line) {
1776
1997
  const match = /^(\s+)("[^"]+"|'[^']+'|[^\s#'"][^:#]*?):\s+(.+?)(\s+#.*)?$/u.exec(line);
1777
1998
  if (!match) return;
@@ -1785,12 +2006,10 @@ function readYamlEntry(line) {
1785
2006
  value
1786
2007
  };
1787
2008
  }
1788
- /** The top-level key of a line without indentation, such as `overrides` for `overrides:`. */
1789
2009
  function topLevelKey(line) {
1790
2010
  if (!line || /^\s/u.test(line) || line.startsWith("#") || line.startsWith("-")) return;
1791
2011
  return /^("[^"]+"|'[^']+'|[^:#\s]+):/u.exec(line)?.[1]?.replace(/^["']|["']$/gu, "");
1792
2012
  }
1793
- /** The line ranges of each top-level block of a YAML file. */
1794
2013
  function yamlBlocks(lines) {
1795
2014
  const blocks = /* @__PURE__ */ new Map();
1796
2015
  let current;
@@ -1806,7 +2025,6 @@ function yamlBlocks(lines) {
1806
2025
  }
1807
2026
  return blocks;
1808
2027
  }
1809
- /** The items of a top-level YAML list, such as `packages`, with their line numbers. */
1810
2028
  function yamlList(lines, range) {
1811
2029
  if (!range) return [];
1812
2030
  const inline = /^[^:]+:\s*\[(.*)\]\s*(#.*)?$/u.exec(lines[range.start]);
@@ -1822,14 +2040,11 @@ function yamlList(lines, range) {
1822
2040
  }] : [];
1823
2041
  });
1824
2042
  }
1825
- /** The name of a `minimumReleaseAgeExclude` entry that pins versions, such as `@vite-hub/env` for `@vite-hub/env@0.1.0`. */
1826
2043
  function pinnedName(entry) {
1827
2044
  const at = entry.indexOf("@", entry.startsWith("@") ? 1 : 0);
1828
2045
  return at > 0 ? entry.slice(0, at) : void 0;
1829
2046
  }
1830
- /** The patterns that let a fresh ViteHub release through pnpm's `minimumReleaseAge`. */
1831
2047
  const releaseAgePatterns = ["vite-hub", "@vite-hub/*"];
1832
- /** Calls `edit` for each ViteHub entry of the `overrides`, `catalog`, and `catalogs` blocks, and returns the removed lines. */
1833
2048
  function editYamlEntries(lines, edit) {
1834
2049
  const blocks = yamlBlocks(lines);
1835
2050
  const removed = /* @__PURE__ */ new Set();
@@ -1851,7 +2066,6 @@ function editYamlEntries(lines, edit) {
1851
2066
  }
1852
2067
  return removed;
1853
2068
  }
1854
- /** Rewrites the ViteHub entries of pnpm-workspace.yaml, and the settings that the target needs. */
1855
2069
  function updateWorkspaceYaml(text, edit, options) {
1856
2070
  const lines = text.split("\n");
1857
2071
  const removed = editYamlEntries(lines, edit);
@@ -1877,7 +2091,6 @@ function updateWorkspaceYaml(text, edit, options) {
1877
2091
  const after = lines.filter((_, index) => !removed.has(index)).join("\n");
1878
2092
  return after.endsWith("\n") || !after ? after : `${after}\n`;
1879
2093
  }
1880
- /** The workspace package folders that `patterns` select, relative to `root`. */
1881
2094
  async function workspaceFolders(root, patterns) {
1882
2095
  const find = async (selected) => {
1883
2096
  if (!selected.length) return /* @__PURE__ */ new Set();
@@ -1893,7 +2106,6 @@ async function workspaceFolders(root, patterns) {
1893
2106
  const excluded = await find(patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1)));
1894
2107
  return [...included].filter((folder) => !excluded.has(folder)).sort();
1895
2108
  }
1896
- /** The workspace patterns of a root: `packages` of pnpm-workspace.yaml, else `workspaces` of package.json. */
1897
2109
  function workspacePatterns(yaml, manifest) {
1898
2110
  if (yaml !== void 0) {
1899
2111
  const lines = yaml.split("\n");
@@ -1902,11 +2114,6 @@ function workspacePatterns(yaml, manifest) {
1902
2114
  const workspaces = manifest.workspaces;
1903
2115
  return (Array.isArray(workspaces) ? workspaces : isObject(workspaces) && Array.isArray(workspaces.packages) ? workspaces.packages : []).filter((item) => typeof item === "string");
1904
2116
  }
1905
- /**
1906
- * The root of the workspace that `start` belongs to: the nearest pnpm-workspace.yaml above, like pnpm finds it, or the
1907
- * nearest package.json whose `workspaces` list `start`, like npm, Yarn, and Bun. `start` itself when it has a lockfile
1908
- * or no workspace lists it.
1909
- */
1910
2117
  async function workspaceRoot(start) {
1911
2118
  if (setupLockfiles.some(([file]) => existsSync(join(start, file)))) return start;
1912
2119
  for (let folder = dirname(start), last = start; folder !== last; last = folder, folder = dirname(folder)) {
@@ -1961,7 +2168,6 @@ function readUpdateArgs(args) {
1961
2168
  }
1962
2169
  return parsed;
1963
2170
  }
1964
- /** Asks npm for the `latest` version of each package, or pkg.pr.new whether the build has it. Undefined when it has not. */
1965
2171
  async function resolvePackages(names, preview, context) {
1966
2172
  const request = context.fetch ?? fetch;
1967
2173
  const registry = (context.env.npm_config_registry || defaultRegistry).replace(/\/?$/u, "/");
@@ -2151,8 +2357,7 @@ const updateCommand = {
2151
2357
  run: runUpdate,
2152
2358
  usage
2153
2359
  };
2154
- //#endregion
2155
- //#region src/setup/commands.ts
2360
+ // src/setup/commands.ts
2156
2361
  var commands_exports = /* @__PURE__ */ __exportAll({ setupCommands: () => setupCommands });
2157
2362
  function supportLabel(support) {
2158
2363
  if (support.level === "unknown") return "unknown";
@@ -2163,7 +2368,6 @@ function writeHelp(command, context) {
2163
2368
  context.stdout.write(`Usage: ${command.usage}\n\n${command.description}\n`);
2164
2369
  return setupExitCodes.done;
2165
2370
  }
2166
- /** Runs `body` and reports any error in the setup envelope. */
2167
2371
  async function runSetupCommand(command, args, context, body) {
2168
2372
  const json = args.includes("--json");
2169
2373
  try {
@@ -2207,6 +2411,7 @@ function credentialsLabel(credentials) {
2207
2411
  function writeStatus(status, context) {
2208
2412
  const shown = status.features.filter((feature) => feature.enabled !== "off");
2209
2413
  const off = status.features.length - shown.length;
2414
+ const stack = status.stack ? setupStackLabels(status.stack) : void 0;
2210
2415
  context.stdout.write(`${table([
2211
2416
  ["root", status.root],
2212
2417
  ["framework", status.framework],
@@ -2216,7 +2421,8 @@ function writeStatus(status, context) {
2216
2421
  ["link", linkLabel(status)],
2217
2422
  ["credentials", credentialsLabel(status.credentials)],
2218
2423
  ["live", liveLabel(status)],
2219
- ...status.stack ? [["stack", status.stack.command]] : []
2424
+ ...stack ? [["stack", stack.command]] : [],
2425
+ ...stack?.omissions ? [["stack omissions", stack.omissions]] : []
2220
2426
  ])}\n\n`);
2221
2427
  if (shown.length) context.stdout.write(`${table([[
2222
2428
  "feature",
@@ -2234,10 +2440,6 @@ function writeStatus(status, context) {
2234
2440
  function isCheckoutStatusModule(value) {
2235
2441
  return Object(value) === value && typeof Reflect.get(Object(value), "formatWorkspaceStatus") === "function" && typeof Reflect.get(Object(value), "localCheckoutStatus") === "function";
2236
2442
  }
2237
- /**
2238
- * The checkout folders of `vitehub.lock`, read by the Workspace package that the project installs. Undefined without a
2239
- * lock file. The Workspace package reads only local files here; it never calls the app.
2240
- */
2241
2443
  async function readCheckouts(root) {
2242
2444
  if (!existsSync(join$1(root, "vitehub.lock"))) return void 0;
2243
2445
  const require = createRequire(join$1(root, "package.json"));
@@ -2281,7 +2483,7 @@ const statusCommand = {
2281
2483
  offline,
2282
2484
  signal
2283
2485
  }),
2284
- stack: await readSetupStack(project.root)
2486
+ stack: "manual" in features.config && features.config.manual === "no-vitehub" ? null : await setupStack(project, features)
2285
2487
  };
2286
2488
  const checkouts = await readCheckouts(status.root);
2287
2489
  if (json) {
@@ -2428,5 +2630,4 @@ const setupCommands = [
2428
2630
  logoutCommand,
2429
2631
  whoamiCommand
2430
2632
  ];
2431
- //#endregion
2432
- export { addCommand as _, updateCommand as a, readAddArgs as b, planSetupRemove as c, initCommandDefinition as d, initPackages as f, setupCatalog as g, readSetupStack as h, readUpdateArgs as i, readRemoveArgs as l, readInitArgs as m, setupCommands as n, updateInstallArgs as o, nuxiPackage as p, planSetupUpdate as r, applySetupRemove as s, commands_exports as t, removeCommand as u, applySetupAdd as v, shellQuote as x, planSetupAdd as y };
2633
+ export { applySetupAdd as _, updateCommand as a, planSetupRemove as c, initCommandDefinition as d, initPackages as f, addCommand as g, setupCatalog as h, readUpdateArgs as i, readRemoveArgs as l, readInitArgs as m, setupCommands as n, updateInstallArgs as o, nuxiPackage as p, planSetupUpdate as r, applySetupRemove as s, commands_exports as t, removeCommand as u, planSetupAdd as v, readAddArgs as y };