@vite-hub/cli 0.6.0 → 0.7.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.
@@ -1,18 +1,18 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
- import { C as installArgs, D as shellQuote, E as setupStatus, G as setupFailure, H as isSetupFailure, J as writeSetupJson, K as table, M as listMatchingFiles, O as uninstallArgs, R as loginCommand, S as formatInstallCommand, St as installSpecifier, T as missingProviderOption, U as readSetupArgs, V as whoamiCommand, W as setupExitCodes, Y as cliErrorDiagnostics, _t as featureIds, bt as features, gt as featureHosts, j as hasDefinitionFiles, m as appsCommand, q as writeSetupError, vt as featurePackages, w as installCommand, xt as impliedFeatures, yt as featureSupport, z as logoutCommand } from "./provision-akHsvf-B.js";
3
- import { B as insertViteHubConfig, I as detectPackageManager, L as readSetupProject, R as setupLockfiles, V as locateViteHubConfig, d as readSetupLinkState, h as unlinkSetupProject, i as SETUP_LINK_FILE, l as linkSetupProject, s as gitignoreWithViteHub, u as readLinkHostOption, z as editViteHubConfig } from "./env-BiVwma4a.js";
4
- import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-DwNjKrHq.js";
1
+ import { r as __exportAll } from "./console-env-MPzeOLqu.js";
2
+ import { At as insertViteHubConfig, Bt as hasDefinitionFiles, Ct as declaresNuxt5, Dt as readSetupProject, Et as pnpmWorkspaceFile, Ft as setupFailure, It as table, Lt as writeSetupError, Mt as isSetupFailure, Nt as readSetupArgs, Ot as setupLockfiles, Pt as setupExitCodes, Rt as writeSetupJson, St as whoamiCommand, Tt as nuxtReleases, Vt as listMatchingFiles, Y as appsCommand, at as missingProviderOption, cn as featureHosts, ct as setupStatus, dn as features, f as ignoredFolders, fn as impliedFeatures, h as readSetupLinkState, it as installCommand, jt as locateViteHubConfig, kt as editViteHubConfig, ln as featureIds, lt as shellQuote, m as readLinkHostOption, nt as formatInstallCommand, ot as rateLimitUsesVercelKV, p as linkSetupProject, pn as installSpecifier, rt as installArgs, s as SETUP_LINK_FILE, st as setupFeaturePackages, u as gitignoreWith, un as featureSupport, ut as uninstallArgs, vt as loginCommand, wn as isRecord$2, wt as detectPackageManager, y as unlinkSetupProject, yt as logoutCommand, zt as cliErrorDiagnostics } from "./provision-DWEZYLWJ.js";
3
+ import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-CGRf9Pq-.js";
5
4
  import { createRequire } from "node:module";
6
5
  import { existsSync, readFileSync } from "node:fs";
7
6
  import process from "node:process";
8
7
  import { basename, dirname, join, relative, resolve } from "pathe";
9
8
  import { glob, mkdir, readFile, readdir, rm, rmdir, writeFile } from "node:fs/promises";
10
- import { join as join$1 } from "node:path";
9
+ import { join as join$1, matchesGlob } from "node:path";
11
10
  import { createInterface } from "node:readline/promises";
12
11
  import { pathToFileURL } from "node:url";
13
- import { isDeepStrictEqual, parseArgs } from "node:util";
12
+ import { isDeepStrictEqual, parseArgs, stripVTControlCharacters } from "node:util";
13
+ import semver, { minVersion, satisfies, subset, validRange } from "semver";
14
+ import { isMap, parseDocument } from "yaml";
14
15
  import { createTwoFilesPatch } from "diff";
15
- import semver, { Range, minVersion, satisfies, subset, validRange } from "semver";
16
16
  // ../internal/dist/feature-inputs.js
17
17
  function isLocaleTag(value) {
18
18
  try {
@@ -33,6 +33,129 @@ function i18nLocaleListProblem(locales) {
33
33
  function mcpPublicRouteNeedsSignedAuth(publicRoute, auth) {
34
34
  return !!publicRoute && auth !== true;
35
35
  }
36
+ // src/setup/install.ts
37
+ /**
38
+ * The packages with build scripts that a ViteHub app installs: Nuxt 4 and Workflow install esbuild, Workflow installs
39
+ * `@swc/core` and cbor-extract, and Wrangler on Cloudflare installs esbuild and workerd. pnpm 11 and later stop the
40
+ * install while a build script waits for approval. Each of these packages runs without its build script: esbuild,
41
+ * workerd, and `@swc/core` load the binary of their platform package, and cbor-extract loads its prebuilt addon, so the
42
+ * app declines every one of them.
43
+ */
44
+ function declinedBuilds(project, host, features) {
45
+ const workflow = features.includes("workflow");
46
+ const cloudflare = host === "cloudflare";
47
+ return [
48
+ ...project.framework === "nuxt" && !declaresNuxt5(project.nuxt) || workflow || cloudflare ? ["esbuild"] : [],
49
+ ...cloudflare ? ["workerd"] : [],
50
+ ...workflow ? ["@swc/core", "cbor-extract"] : []
51
+ ];
52
+ }
53
+ function named(policy, name) {
54
+ if (!isRecord$2(policy)) return false;
55
+ if (policy.dangerouslyAllowAllBuilds === true) return true;
56
+ const matches = (key) => typeof key === "string" && (key === name || key.startsWith(`${name}@`));
57
+ if (isRecord$2(policy.allowBuilds) && Object.keys(policy.allowBuilds).some(matches)) return true;
58
+ return [
59
+ "onlyBuiltDependencies",
60
+ "ignoredBuiltDependencies",
61
+ "neverBuiltDependencies"
62
+ ].some((key) => {
63
+ const list = policy[key];
64
+ return Array.isArray(list) && list.some(matches);
65
+ });
66
+ }
67
+ function pnpmBuildPolicyFile(root) {
68
+ const local = join(root, "pnpm-workspace.yaml");
69
+ const workspace = pnpmWorkspaceFile(root);
70
+ if (!workspace || workspace === local) return local;
71
+ const document = parseDocument(readFileSync(workspace, "utf8"));
72
+ if (document.errors.length) return workspace;
73
+ const policy = document.toJS();
74
+ if (!isRecord$2(policy) || !Array.isArray(policy.packages)) return workspace;
75
+ const path = relative(dirname(workspace), root);
76
+ const patterns = policy.packages.filter((pattern) => typeof pattern === "string");
77
+ const includes = (pattern) => matchesGlob(path, pattern.replace(/^\.\//u, "").replace(/\/$/u, ""));
78
+ return patterns.some((pattern) => !pattern.startsWith("!") && includes(pattern)) && !patterns.some((pattern) => pattern.startsWith("!") && includes(pattern.slice(1))) ? workspace : local;
79
+ }
80
+ /**
81
+ * Adds `allowBuilds: { <name>: false }` for each of `names` that the pnpm build policy does not name yet. It edits the
82
+ * `pnpm-workspace.yaml` of the project or of its pnpm workspace, or creates one in the project. Undefined when the
83
+ * package manager is not pnpm, or when the policy already names every package.
84
+ */
85
+ function planPnpmBuilds(project, names) {
86
+ if (project.packageManager !== "pnpm" || !names.length) return;
87
+ const file = pnpmBuildPolicyFile(project.root);
88
+ const before = existsSync(file) ? readFileSync(file, "utf8") : void 0;
89
+ const document = parseDocument(before ?? "");
90
+ if (document.errors.length || document.contents !== null && !isMap(document.contents)) return;
91
+ const policy = document.toJS();
92
+ const missing = names.filter((name) => !named(policy, name));
93
+ if (!missing.length) return;
94
+ if (document.has("allowBuilds") && !isMap(document.get("allowBuilds", true))) return;
95
+ for (const name of missing) document.setIn(["allowBuilds", name], false);
96
+ return {
97
+ after: document.toString(),
98
+ file,
99
+ path: relative(project.root, file),
100
+ ...before === void 0 ? {} : { before }
101
+ };
102
+ }
103
+ /** Writes a planned build policy change. Throws when the file changed after the plan. */
104
+ async function writePnpmBuilds(change) {
105
+ if (change.before === void 0) {
106
+ await mkdir(dirname(change.file), { recursive: true });
107
+ try {
108
+ await writeFile(change.file, change.after, { flag: "wx" });
109
+ } catch {
110
+ throw setupFailure(cliErrorDiagnostics.SETUP_FILE_EXISTS({ file: change.path }), setupExitCodes.conflict);
111
+ }
112
+ return;
113
+ }
114
+ if (await readFile(change.file, "utf8") !== change.before) throw setupFailure(cliErrorDiagnostics.SETUP_STALE_PLAN({ file: change.path }), setupExitCodes.stalePlan);
115
+ await writeFile(change.file, change.after);
116
+ }
117
+ function ignoredBuilds(output) {
118
+ const list = output.match(/Ignored build scripts:\s*((?:@[^\s/,]+\/)?[\w.-]+(?:@[^\s,]+)?(?:,\s*(?:@[^\s/,]+\/)?[\w.-]+(?:@[^\s,]+)?)*)/u)?.[1];
119
+ return list ? list.split(",").map((spec) => spec.trim().replace(/(?<=.)@[^@]*$/u, "")) : [];
120
+ }
121
+ /**
122
+ * Installs `packages` with the package manager. The package manager's error output still reaches the terminal, and a
123
+ * failure throws `SETUP_INSTALL_FAILED` with that output, so `--json` shows the real error too.
124
+ */
125
+ async function installPackages(context, packageManager, packages, dev, failure) {
126
+ const commandArgs = installArgs(packageManager, packages, dev);
127
+ const tails = {
128
+ stderr: "",
129
+ stdout: ""
130
+ };
131
+ const onOutput = (text, stream) => {
132
+ context.stderr?.write(text);
133
+ tails[stream] = (tails[stream] + text).slice(-16384);
134
+ };
135
+ const result = await context.spawn(packageManager, commandArgs, {
136
+ cwd: failure.root,
137
+ env: context.env,
138
+ onOutput,
139
+ stderr: "pipe",
140
+ stdout: "pipe"
141
+ });
142
+ if (result.stdout && !tails.stdout) onOutput(result.stdout, "stdout");
143
+ if (result.stderr && !tails.stderr) onOutput(result.stderr, "stderr");
144
+ if (result.exitCode === 0) return;
145
+ const streams = [tails.stdout, tails.stderr].map(stripVTControlCharacters);
146
+ const output = streams.map((text) => text.trim().split("\n").map((line) => line.trimEnd()).filter(Boolean).slice(-20).join("\n")).filter(Boolean).join("\n");
147
+ const ignored = packageManager === "pnpm" ? [...new Set(streams.flatMap(ignoredBuilds))] : [];
148
+ throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
149
+ command: formatInstallCommand(packageManager, commandArgs),
150
+ exitCode: result.exitCode ?? result.signal,
151
+ filesWritten: failure.filesWritten,
152
+ ...output ? { output } : {},
153
+ ...ignored.length ? {
154
+ ignored,
155
+ workspaceFile: pnpmBuildPolicyFile(failure.root)
156
+ } : {}
157
+ }), setupExitCodes.error);
158
+ }
36
159
  // src/setup/add.ts
37
160
  const usage$3 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
38
161
  const optionChoices = {
@@ -46,6 +169,11 @@ const optionChoices = {
46
169
  "sandboxTask.driver": { values: ["vercel"] },
47
170
  "workflow.driver": { values: ["openworkflow"] }
48
171
  };
172
+ const optionExamples = {
173
+ "blob.driver": ["blob.driver=s3", "blob.bucket=<bucket>"],
174
+ "database.connection": ["database.connection.url=libsql://<host>"],
175
+ "workspace.store": ["workspace.store.driver=github", "workspace.store.repo=<owner>/<repo>"]
176
+ };
49
177
  const providerKeys = ["driver", "store"];
50
178
  function selectsProvider(id, value, host) {
51
179
  if (!isRecord$1(value)) return false;
@@ -326,7 +454,11 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
326
454
  ...choices ? { choices: choices.values } : {}
327
455
  });
328
456
  if (choices) setPath(defaults[id] ??= {}, field.split(".").slice(1), choices.values[0]);
329
- else rerunnable = false;
457
+ else {
458
+ const example = optionExamples[field];
459
+ inputFixes.push(`${example ? `Pass ${example.map((option) => `\`--option ${option}\``).join(" ")}, or set \`${field}\` in the config.` : `Set \`${field}\` with --option or in the config.`} ${support.detail}`);
460
+ rerunnable = false;
461
+ }
330
462
  }
331
463
  }
332
464
  for (const [field, choice] of Object.entries(optionChoices)) {
@@ -417,15 +549,22 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
417
549
  rerunnable = false;
418
550
  }
419
551
  }
552
+ if (inputFeatures.includes("rateLimit") && keep.includes("kv") && !requires.includes("kv") && site?.keys.rateLimit?.kind !== "expression" && rateLimitUsesVercelKV(host, valueFor("rateLimit"))) {
553
+ missing.push({ field: "kv" });
554
+ inputFixes.push("Add `kv` to the command for shared counts, or pass `--option rateLimit.driver=memory` for counts in one function instance.");
555
+ rerunnable = false;
556
+ }
420
557
  if (missing.length) {
421
558
  const fields = missing.map((item) => `\`${item.field}\``).join(", ");
422
559
  const fix = inputFixes.length ? inputFixes.join(" ") : void 0;
560
+ const command = rerunnable ? rerun(args, defaults, requires) : void 0;
423
561
  throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({
424
562
  fix,
425
- message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.`
563
+ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.`,
564
+ rerun: command
426
565
  }), setupExitCodes.inputNeeded, {
427
566
  missing,
428
- ...rerunnable ? { rerun: rerun(args, defaults, requires) } : {}
567
+ ...command ? { rerun: command } : {}
429
568
  });
430
569
  }
431
570
  const edits = [];
@@ -520,7 +659,9 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
520
659
  ...inputFeatures,
521
660
  ...enabled.has("console") ? ["console"] : []
522
661
  ])];
523
- const packages = packageFeatures.flatMap((id) => featurePackages(id, valueFor(id), host, [...enabled]));
662
+ const plannedKV = edits.find((edit) => edit.key === "kv");
663
+ const packageValue = (id) => id === "kv" && plannedKV?.op === "set" ? plannedKV.value : valueFor(id);
664
+ const packages = packageFeatures.flatMap((id) => setupFeaturePackages(id, packageValue, host, [...enabled]));
524
665
  const install = {
525
666
  dev: [...new Set(packageFeatures.flatMap((id) => features[id].devPackages))].filter((name) => !project.declared(name, true)),
526
667
  prod: [...new Set(packages)].filter((name) => !project.declared(name, false))
@@ -528,6 +669,14 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
528
669
  install.prod = installSpecifiers(install.prod);
529
670
  install.dev = installSpecifiers(install.dev);
530
671
  const command = installCommand(project.packageManager, install.prod, install.dev);
672
+ const workspace = command ? planPnpmBuilds(project, declinedBuilds(project, host, [...enabled])) : void 0;
673
+ if (workspace) changes.unshift({
674
+ after: workspace.after,
675
+ diff: setupDiff(workspace.path, workspace.before ?? "", workspace.after),
676
+ kind: workspace.before === void 0 ? "create" : "patch",
677
+ path: workspace.path,
678
+ ...workspace.before === void 0 ? {} : { before: workspace.before }
679
+ });
531
680
  const restartRequired = addsDiscovery && !configFile;
532
681
  const nextSteps = restartRequired ? ["Restart the dev server to load the new feature configuration."] : [];
533
682
  if (needsMcpOAuth) {
@@ -561,42 +710,42 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
561
710
  if (args.name !== void 0 && args.features.includes("realtime")) nextSteps.push(`${join(serverDir, "realtime", `${args.name}.ts`)} stores documents in the Workspace "${args.name}". Add a Workspace Definition in ${join(serverDir, "workspaces", `${args.name}.ts`)}.`);
562
711
  for (const id of args.features) nextSteps.push(`${features[id].title}: https://vitehub.dev${features[id].docs}`);
563
712
  nextSteps.push("Run `vitehub status` to check the result.");
713
+ const plan = {
714
+ changes,
715
+ features: addedFeatures,
716
+ host: status.host,
717
+ implied,
718
+ install: {
719
+ devPackages: install.dev,
720
+ packages: install.prod,
721
+ ...command ? { command } : {}
722
+ },
723
+ nextSteps,
724
+ root: project.root,
725
+ status: changes.length || command && args.install ? "planned" : "unchanged"
726
+ };
564
727
  return {
728
+ enabled: [...enabled],
565
729
  files,
566
730
  install,
567
- plan: {
568
- changes,
569
- features: addedFeatures,
570
- host: status.host,
571
- implied,
572
- install: {
573
- devPackages: install.dev,
574
- packages: install.prod,
575
- ...command ? { command } : {}
576
- },
577
- nextSteps,
578
- root: project.root,
579
- status: changes.length || command && args.install ? "planned" : "unchanged"
580
- },
731
+ plan,
581
732
  restartRequired,
582
- ...configFile ? { configFile } : {}
733
+ ...configFile ? { configFile } : {},
734
+ ...workspace ? { workspace } : {}
583
735
  };
584
736
  }
585
- /** Applies a `vitehub add` plan: installs the packages, writes the starter Definitions, and writes the config last. */
737
+ /**
738
+ * Applies a `vitehub add` plan: writes the pnpm build policy, installs the packages, writes the starter Definitions,
739
+ * and writes the config last.
740
+ */
586
741
  async function applySetupAdd(project, planned, args, context) {
587
742
  const { dev, prod } = planned.install;
588
- if (args.install) for (const [packages, isDev] of [[prod, false], [dev, true]]) {
589
- if (!packages.length) continue;
590
- const commandArgs = installArgs(project.packageManager, packages, isDev);
591
- const result = await context.spawn(project.packageManager, commandArgs, {
592
- cwd: project.root,
593
- env: context.env,
594
- stdout: "stderr"
743
+ if (planned.workspace) await writePnpmBuilds(planned.workspace);
744
+ if (args.install) {
745
+ for (const [packages, isDev] of [[prod, false], [dev, true]]) if (packages.length) await installPackages(context, project.packageManager, packages, isDev, {
746
+ filesWritten: false,
747
+ root: project.root
595
748
  });
596
- if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
597
- command: formatInstallCommand(project.packageManager, commandArgs),
598
- exitCode: result.exitCode ?? result.signal
599
- }), setupExitCodes.error);
600
749
  }
601
750
  if (planned.configFile && await readFile(join(project.root, planned.configFile.path), "utf8") !== planned.configFile.before) throw setupFailure(cliErrorDiagnostics.SETUP_STALE_PLAN({ file: planned.configFile.path }), setupExitCodes.stalePlan);
602
751
  for (const file of planned.files) {
@@ -695,6 +844,76 @@ function setupCatalog() {
695
844
  schemaVersion: 1
696
845
  };
697
846
  }
847
+ // src/setup/init-wizard.ts
848
+ function cancelled() {
849
+ return setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The setup was cancelled. Nothing was written." }), setupExitCodes.error);
850
+ }
851
+ /** The wizard on the terminal, with `@clack/prompts`. It loads only when `vitehub init` runs interactively. */
852
+ async function terminalPrompts() {
853
+ const clack = await import("./dist-CEIUyD15.js");
854
+ const output = process.stderr;
855
+ const answer = (value) => {
856
+ if (clack.isCancel(value) || typeof value === "symbol") throw cancelled();
857
+ return value;
858
+ };
859
+ const pick = (options, value) => {
860
+ const found = options.find((option) => option.value === value);
861
+ if (!found) throw cancelled();
862
+ return found.value;
863
+ };
864
+ return {
865
+ confirm: async (options) => answer(await clack.confirm({
866
+ ...options,
867
+ output
868
+ })),
869
+ error: (message) => clack.log.error(message, { output }),
870
+ multiselect: async ({ message, options }) => answer(await clack.multiselect({
871
+ message,
872
+ options: [...options],
873
+ output,
874
+ required: false
875
+ })).map((value) => pick(options, value)),
876
+ select: async ({ initialValue, message, options }) => pick(options, answer(await clack.select({
877
+ message,
878
+ options: [...options],
879
+ output,
880
+ ...initialValue ? { initialValue } : {}
881
+ }))),
882
+ text: async ({ defaultValue, message }) => answer(await clack.text({
883
+ defaultValue,
884
+ message,
885
+ output,
886
+ placeholder: defaultValue
887
+ })) || defaultValue
888
+ };
889
+ }
890
+ /** The features that a picker offers on `host`: every feature that the host supports and that is not always on. */
891
+ function pickableFeatures(host) {
892
+ return featureIds.filter((id) => !features[id].enabledByDefault && featureSupport(id, host).level !== "unsupported").map((id) => ({
893
+ hint: features[id].summary.replaceAll("`", ""),
894
+ label: features[id].title,
895
+ value: id
896
+ }));
897
+ }
898
+ async function askOption(prompts, item) {
899
+ if (item.choices?.length) {
900
+ const options = item.choices.map((choice) => typeof choice === "string" ? {
901
+ label: choice,
902
+ value: choice
903
+ } : {
904
+ label: choice.name ?? choice.id,
905
+ value: choice.id
906
+ });
907
+ return await prompts.select({
908
+ message: `Choose ${item.field}`,
909
+ options
910
+ });
911
+ }
912
+ if (item.field === "i18n.locales") return await prompts.text({
913
+ defaultValue: "",
914
+ message: "Enter i18n.locales as a JSON array, such as [\"en\",\"es\"]"
915
+ });
916
+ }
698
917
  // src/setup/stack.ts
699
918
  function replayOption(id, keys, value) {
700
919
  if (keys.some((key) => !key || /[.=\0]/u.test(key) || [
@@ -809,6 +1028,14 @@ async function deriveSetupStack(project, status, validate) {
809
1028
  path: id,
810
1029
  reason: "disabled-feature"
811
1030
  });
1031
+ const nuxtNightly = status.framework === "nuxt" && declaresNuxt5(project.nuxt);
1032
+ if (status.framework === "nuxt" && !nuxtNightly) {
1033
+ const releases = nuxtReleases(project.nuxt);
1034
+ if (!releases || !subset(releases, ">=4.7.0 <5.0.0")) omits.push({
1035
+ path: "nuxt",
1036
+ reason: "unresolved-nuxt-version"
1037
+ });
1038
+ }
812
1039
  const name = basename(project.root);
813
1040
  const args = [
814
1041
  name.startsWith("-") ? `./${name}` : name || "vitehub-app",
@@ -819,6 +1046,7 @@ async function deriveSetupStack(project, status, validate) {
819
1046
  ...options.flatMap((option) => ["--option", option]),
820
1047
  "--framework",
821
1048
  status.framework === "nuxt" ? "nuxt" : "vite",
1049
+ ...nuxtNightly ? ["--nuxt-nightly"] : [],
822
1050
  "--pm",
823
1051
  status.packageManager,
824
1052
  "--yes"
@@ -853,7 +1081,7 @@ async function deriveSetupStack(project, status, validate) {
853
1081
  };
854
1082
  }
855
1083
  // src/setup/init.ts
856
- 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]";
1084
+ const usage$2 = "vitehub init <dir> --host <host> --features <id,id,...> [--option <feature.key=value>]... [--framework vite|nuxt] [--nuxt-nightly] [--pm pnpm|npm|yarn|bun] [--no-install] [--dry-run] --yes [--json]";
857
1085
  const initCommandPrefix = "pnpm dlx vite-hub init";
858
1086
  const initHosts = [
859
1087
  "cloudflare",
@@ -871,7 +1099,7 @@ const packageManagers = [
871
1099
  ];
872
1100
  /**
873
1101
  * The packages of a new app, as `getting-started/installation.md` installs them. The Nitro and H3 versions match the
874
- * server integration of ViteHub. Nuxt 5 supplies Nitro 3, and a Nuxt 4.7 app also gets `nuxtNitroPackage`. The
1102
+ * server integration of ViteHub. A new Nuxt app is Nuxt 4.7, so it also gets `nuxtNitroPackage`. Nuxt 5 supplies Nitro 3. The
875
1103
  * tutorials import H3 2. Valibot validates request bodies in the docs' route examples.
876
1104
  */
877
1105
  const initPackages = {
@@ -899,9 +1127,10 @@ const initPackages = {
899
1127
  };
900
1128
  const nuxtNitroRange = "^3.0.261103-rc";
901
1129
  const nuxtNitroPackage = `nitro@${nuxtNitroRange}`;
1130
+ const nuxt47ViteHub = "vite-hub@>=0.5.1 <1";
902
1131
  /** The pinned Nuxt CLI that creates a new Nuxt app. */
903
1132
  const nuxiPackage = "nuxi@3.37.0";
904
- const nuxtTemplate = "gh:nuxt/starter#db01806fcb37f2e369fb09443c72cac696b31548";
1133
+ const nuxtTemplate = "gh:nuxt/starter#d4367031fe43d93d4e2a339f73b519ec35e78b38";
905
1134
  function isRecord(value) {
906
1135
  return !!value && typeof value === "object" && !Array.isArray(value);
907
1136
  }
@@ -920,6 +1149,7 @@ function readInitArgs(args) {
920
1149
  help: false,
921
1150
  install: true,
922
1151
  json: false,
1152
+ nuxtNightly: false,
923
1153
  options: [],
924
1154
  yes: false
925
1155
  };
@@ -936,6 +1166,7 @@ function readInitArgs(args) {
936
1166
  else if (flag === "--dry-run") parsed.dryRun = true;
937
1167
  else if (flag === "--yes" || flag === "-y") parsed.yes = true;
938
1168
  else if (flag === "--no-install") parsed.install = false;
1169
+ else if (flag === "--nuxt-nightly") parsed.nuxtNightly = true;
939
1170
  else if (flag === "-h" || flag === "--help") parsed.help = true;
940
1171
  else if (flag === "--host") parsed.host = oneOf("--host", value(), initHosts);
941
1172
  else if (flag === "--features") features = value();
@@ -947,6 +1178,8 @@ function readInitArgs(args) {
947
1178
  else throw invalid$2(`Pass one folder, not ${JSON.stringify(parsed.dir)} and ${JSON.stringify(arg)}.`);
948
1179
  }
949
1180
  if (features !== void 0) parsed.features = readAddArgs(features.split(",").map((item) => item.trim()).filter(Boolean)).features;
1181
+ if (parsed.nuxtNightly && parsed.framework === "vite") throw invalid$2("--nuxt-nightly needs --framework nuxt.");
1182
+ if (parsed.nuxtNightly) parsed.framework = "nuxt";
950
1183
  return parsed;
951
1184
  }
952
1185
  function addArgsOf(args) {
@@ -967,6 +1200,7 @@ function initCommand(parts, extra) {
967
1200
  shellQuote(parts.features?.join(",") ?? "<id,id,...>"),
968
1201
  ...options.flatMap((option) => ["--option", shellQuote(option)]),
969
1202
  ...parts.framework === "nuxt" ? ["--framework", "nuxt"] : [],
1203
+ ...parts.nuxtNightly ? ["--nuxt-nightly"] : [],
970
1204
  ...parts.pm && parts.pm !== "pnpm" ? ["--pm", parts.pm] : [],
971
1205
  ...extra
972
1206
  ].join(" ");
@@ -981,9 +1215,18 @@ function rerunInit(args, parts) {
981
1215
  function packageNameOf(root) {
982
1216
  return basename(root).trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || "vitehub-app";
983
1217
  }
1218
+ function appGitignore(host) {
1219
+ return [
1220
+ "node_modules",
1221
+ ".output",
1222
+ ...ignoredFolders(host),
1223
+ ".env*",
1224
+ "!.env.example"
1225
+ ];
1226
+ }
984
1227
  function viteAppFiles(name, host) {
985
1228
  return {
986
- ".gitignore": "node_modules\n.output\n.vitehub\n.env*\n!.env.example\n",
1229
+ ".gitignore": [...appGitignore(host), ""].join("\n"),
987
1230
  "package.json": `${JSON.stringify({
988
1231
  name,
989
1232
  private: true,
@@ -1042,12 +1285,18 @@ function dlx(packageManager, spec, args) {
1042
1285
  function runScript(packageManager, script) {
1043
1286
  return packageManager === "npm" || packageManager === "bun" ? `${packageManager} run ${script}` : `${packageManager} ${script}`;
1044
1287
  }
1288
+ function hasErrorCode(error, code) {
1289
+ return error instanceof Error && "code" in error && error.code === code;
1290
+ }
1045
1291
  async function readDir(root, env) {
1046
- if (!existsSync(root)) return {
1292
+ const entries = await readdir(root).catch((error) => {
1293
+ if (!hasErrorCode(error, "ENOENT")) throw error;
1294
+ });
1295
+ if (!entries) return {
1047
1296
  exists: false,
1048
1297
  kind: "create"
1049
1298
  };
1050
- if (!(await readdir(root)).filter((entry) => entry !== ".git").length) return {
1299
+ if (entries.every((entry) => entry === ".git")) return {
1051
1300
  exists: true,
1052
1301
  kind: "create"
1053
1302
  };
@@ -1058,6 +1307,11 @@ async function readDir(root, env) {
1058
1307
  project
1059
1308
  };
1060
1309
  }
1310
+ function lockedHost(project, env) {
1311
+ if (!project.config?.ok) return;
1312
+ const status = setupStatus(project, env);
1313
+ if (status.features.some((feature) => feature.id !== "env" && feature.enabled !== "off")) return status.host.name;
1314
+ }
1061
1315
  function changeOf(path, before, after) {
1062
1316
  return before === void 0 ? {
1063
1317
  after,
@@ -1133,7 +1387,9 @@ async function planInit(args, root, state, context) {
1133
1387
  found,
1134
1388
  framework
1135
1389
  }), setupExitCodes.conflict);
1136
- const nuxtNeedsNitro = state.kind === "adopt" && framework === "nuxt" && (await checkNuxtVersion(root)).needsNitro;
1390
+ const nuxt = framework !== "nuxt" ? void 0 : state.kind === "adopt" ? state.project.nuxt : args.nuxtNightly ? "npm:nuxt-nightly@5x" : "^4.7.0";
1391
+ const nuxtNeedsNitro = framework === "nuxt" && (state.kind === "adopt" ? (await checkNuxtVersion(root)).needsNitro : !args.nuxtNightly);
1392
+ const allowsNuxt4 = framework === "nuxt" && !declaresNuxt5(nuxt);
1137
1393
  const detected = state.kind === "adopt" ? state.project : detectPackageManager(root, void 0, context.env);
1138
1394
  const packageManager = args.pm ?? (detected.packageManagerSource === "default" ? "pnpm" : detected.packageManager);
1139
1395
  const base = /* @__PURE__ */ new Map();
@@ -1143,8 +1399,8 @@ async function planInit(args, root, state, context) {
1143
1399
  for (const [path, after] of Object.entries(files)) base.set(path, { after });
1144
1400
  configFile = framework === "vite" ? "vite.config.ts" : "nuxt.config.ts";
1145
1401
  } else {
1146
- const status = setupStatus(state.project, context.env);
1147
- if (state.project.config?.ok && status.host.name !== args.host && status.features.some((feature) => feature.id !== "env" && feature.enabled !== "off")) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_HOST_MIGRATION({ host: args.host }), setupExitCodes.conflict);
1402
+ const currentHost = lockedHost(state.project, context.env);
1403
+ if (currentHost && currentHost !== args.host) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_HOST_MIGRATION({ host: args.host }), setupExitCodes.conflict);
1148
1404
  const config = adoptConfig(state.project, args.host, framework);
1149
1405
  base.set(config.file, config);
1150
1406
  configFile = config.file;
@@ -1159,7 +1415,7 @@ async function planInit(args, root, state, context) {
1159
1415
  const basePackages = initPackages[framework];
1160
1416
  const install = {
1161
1417
  dev: basePackages.dev.filter((spec) => !declared(packageName$1(spec), true)),
1162
- prod: basePackages.prod.filter((spec) => !declared(packageName$1(spec), false))
1418
+ prod: basePackages.prod.filter((spec) => !declared(packageName$1(spec), false)).map((spec) => allowsNuxt4 && spec === "vite-hub" ? nuxt47ViteHub : spec)
1163
1419
  };
1164
1420
  if (nuxtNeedsNitro) install.prod.push(nuxtNitroPackage);
1165
1421
  const willInstall = new Set([...install.prod, ...install.dev].map(packageName$1));
@@ -1171,6 +1427,7 @@ async function planInit(args, root, state, context) {
1171
1427
  declared: (name, dev) => declared(name, dev) || willInstall.has(name),
1172
1428
  framework,
1173
1429
  installed: state.kind === "adopt" ? state.project.installed : () => false,
1430
+ ...nuxt === void 0 ? {} : { nuxt },
1174
1431
  packageManager,
1175
1432
  packageManagerSource: args.pm ? "manifest" : detected.packageManagerSource,
1176
1433
  root,
@@ -1189,6 +1446,7 @@ async function planInit(args, root, state, context) {
1189
1446
  features: [...args.features, ...extraFeatures.filter((id) => !args.features.includes(id))],
1190
1447
  framework,
1191
1448
  host: args.host,
1449
+ nuxtNightly: args.nuxtNightly,
1192
1450
  options: Object.entries(options).flatMap(([id, value]) => value ? flattenOptions(id, value) : []),
1193
1451
  pm: packageManager
1194
1452
  };
@@ -1206,7 +1464,7 @@ async function planInit(args, root, state, context) {
1206
1464
  const gitignore = await readOptional(join(root, ".gitignore"));
1207
1465
  base.set(".gitignore", {
1208
1466
  ...gitignore === void 0 ? {} : { before: gitignore },
1209
- after: gitignore === void 0 ? ".vitehub\n" : gitignoreWithViteHub(gitignore) ?? gitignore
1467
+ after: gitignoreWith(gitignore ?? "", appGitignore(args.host)) ?? gitignore ?? ""
1210
1468
  });
1211
1469
  }
1212
1470
  const scaffolded = state.kind === "create" && framework === "nuxt";
@@ -1215,13 +1473,13 @@ async function planInit(args, root, state, context) {
1215
1473
  ...file
1216
1474
  }));
1217
1475
  const command = installCommand(packageManager, install.prod, install.dev);
1476
+ const workspace = command ? planPnpmBuilds(planned, declinedBuilds(planned, args.host, added.enabled)) : void 0;
1218
1477
  const scaffold = scaffolded ? dlx(packageManager, nuxiPackage, [
1219
1478
  "init",
1220
1479
  basename(root),
1221
1480
  "--template",
1222
1481
  nuxtTemplate,
1223
- "--nightly",
1224
- "5x",
1482
+ ...args.nuxtNightly ? ["--nightly", "5x"] : [],
1225
1483
  "--packageManager",
1226
1484
  packageManager,
1227
1485
  "--no-install",
@@ -1245,7 +1503,7 @@ async function planInit(args, root, state, context) {
1245
1503
  return {
1246
1504
  install,
1247
1505
  plan: {
1248
- changes: writes.map((write) => changeOf(write.path, write.before, write.after)),
1506
+ changes: [...workspace ? [changeOf(workspace.path, workspace.before, workspace.after)] : [], ...writes.map((write) => changeOf(write.path, write.before, write.after))],
1249
1507
  features: added.plan.features,
1250
1508
  framework,
1251
1509
  host: args.host,
@@ -1260,12 +1518,13 @@ async function planInit(args, root, state, context) {
1260
1518
  packageManager,
1261
1519
  root,
1262
1520
  ...scaffold ? { scaffold: { command: [scaffold[0], ...scaffold[1]].join(" ") } } : {},
1263
- status: writes.length || scaffold || command && args.install ? "planned" : "unchanged"
1521
+ status: writes.length || workspace || scaffold || command && args.install ? "planned" : "unchanged"
1264
1522
  },
1265
1523
  rerun: rerunInit(args, parts()),
1266
1524
  stackProject,
1267
1525
  writes,
1268
- ...scaffold ? { scaffold } : {}
1526
+ ...scaffold ? { scaffold } : {},
1527
+ ...workspace ? { workspace } : {}
1269
1528
  };
1270
1529
  }
1271
1530
  function setupStack(project, status) {
@@ -1285,21 +1544,12 @@ async function applyInit(planned, install, context, scaffolded = false) {
1285
1544
  const { plan } = planned;
1286
1545
  const runInstall = async () => {
1287
1546
  if (!install) return;
1288
- for (const [packages, dev] of [[planned.install.prod, false], [planned.install.dev, true]]) {
1289
- if (!packages.length) continue;
1290
- const commandArgs = installArgs(plan.packageManager, packages, dev);
1291
- const result = await context.spawn(plan.packageManager, commandArgs, {
1292
- cwd: plan.root,
1293
- env: context.env,
1294
- stdout: "stderr"
1295
- });
1296
- if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
1297
- command: formatInstallCommand(plan.packageManager, commandArgs),
1298
- exitCode: result.exitCode ?? result.signal,
1299
- filesWritten: scaffolded || plan.mode === "create"
1300
- }), setupExitCodes.error);
1301
- }
1547
+ for (const [packages, dev] of [[planned.install.prod, false], [planned.install.dev, true]]) if (packages.length) await installPackages(context, plan.packageManager, packages, dev, {
1548
+ filesWritten: scaffolded || plan.mode === "create",
1549
+ root: plan.root
1550
+ });
1302
1551
  };
1552
+ if (planned.workspace) await writePnpmBuilds(planned.workspace);
1303
1553
  if (plan.mode === "adopt") await runInstall();
1304
1554
  for (const write of planned.writes) {
1305
1555
  const file = join(plan.root, write.path);
@@ -1332,12 +1582,6 @@ async function scaffoldNuxt(planned, context) {
1332
1582
  }), setupExitCodes.error);
1333
1583
  await checkNuxtVersion(planned.plan.root, true);
1334
1584
  }
1335
- function nuxtReleases(nuxt) {
1336
- if (typeof nuxt !== "string") return void 0;
1337
- const range = validRange(nuxt.replace(/^npm:nuxt(?:-nightly)?@/u, ""));
1338
- if (!range || !minVersion(range)) return void 0;
1339
- 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(" || ");
1340
- }
1341
1585
  async function checkNuxtVersion(root, scaffolded = false) {
1342
1586
  const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
1343
1587
  const dependencies = isRecord(manifest) && isRecord(manifest.dependencies) ? manifest.dependencies : {};
@@ -1347,7 +1591,7 @@ async function checkNuxtVersion(root, scaffolded = false) {
1347
1591
  dir: root,
1348
1592
  scaffolded
1349
1593
  }), setupExitCodes.conflict);
1350
- if (subset(releases, ">=5.0.0 <6.0.0")) return { needsNitro: false };
1594
+ if (declaresNuxt5(dependencies.nuxt ?? devDependencies.nuxt)) return { needsNitro: false };
1351
1595
  const nitroDeclarations = [dependencies.nitro, devDependencies.nitro].filter((spec) => spec !== void 0);
1352
1596
  for (const spec of nitroDeclarations) {
1353
1597
  const range = typeof spec === "string" ? validRange(spec.replace(/^npm:nitro@/u, "")) : null;
@@ -1359,32 +1603,110 @@ async function checkNuxtVersion(root, scaffolded = false) {
1359
1603
  }
1360
1604
  return { needsNitro: nitroDeclarations.length === 0 };
1361
1605
  }
1362
- function interactive(args) {
1363
- return !args.json && !!process.stdin.isTTY && !!process.stderr.isTTY;
1606
+ async function planWithAnswers(args, root, state, context, prompts, canReviseFeatures) {
1607
+ const initialOptions = [...args.options];
1608
+ const asked = /* @__PURE__ */ new Set();
1609
+ for (;;) try {
1610
+ return await planInit(args, root, state, context);
1611
+ } catch (error) {
1612
+ if (!prompts || !isSetupFailure(error) || error.exitCode !== setupExitCodes.inputNeeded) throw error;
1613
+ const missing = error.details.missing ?? [];
1614
+ let answered = false;
1615
+ for (const item of missing) {
1616
+ if (asked.has(item.field)) continue;
1617
+ asked.add(item.field);
1618
+ if (item.field === "auth") {
1619
+ if (await prompts.confirm({
1620
+ initialValue: true,
1621
+ message: "Enable Auth for signed MCP requests?"
1622
+ })) {
1623
+ args.features = [...args.features, "auth"];
1624
+ answered = true;
1625
+ }
1626
+ continue;
1627
+ }
1628
+ const value = await askOption(prompts, item);
1629
+ if (value === void 0) continue;
1630
+ args.options.push(`${item.field}=${value}`);
1631
+ answered = true;
1632
+ }
1633
+ if (answered) continue;
1634
+ if (!canReviseFeatures || !missing.length) throw error;
1635
+ prompts.error(error.message.replace(/^\[vitehub\] /u, ""));
1636
+ args.features = await askFeatures(prompts, args.host);
1637
+ const selected = /* @__PURE__ */ new Set([...args.features, ...initialOptions.map((option) => option.split(".", 1)[0])]);
1638
+ args.options = args.options.filter((option) => selected.has(option.split(".", 1)[0]));
1639
+ asked.clear();
1640
+ }
1641
+ }
1642
+ async function terminalWizard() {
1643
+ return process.stdin.isTTY && process.stderr.isTTY ? await terminalPrompts() : void 0;
1644
+ }
1645
+ async function askDir(args, prompts, context) {
1646
+ for (;;) {
1647
+ const dir = args.dir ?? await prompts.text({
1648
+ defaultValue: "vitehub-app",
1649
+ message: "Folder of the app"
1650
+ });
1651
+ try {
1652
+ return {
1653
+ dir,
1654
+ state: await readDir(resolve(context.rootDir, dir), context.env)
1655
+ };
1656
+ } catch (error) {
1657
+ if (args.dir !== void 0) throw error;
1658
+ if (hasErrorCode(error, "ENOTDIR")) prompts.error(`${dir} is not a folder. Choose a folder.`);
1659
+ else if (isSetupFailure(error)) prompts.error(error.message.replace(/^\[vitehub\] /u, ""));
1660
+ else throw error;
1661
+ }
1662
+ }
1663
+ }
1664
+ function askFeatures(prompts, host) {
1665
+ return prompts.multiselect({
1666
+ message: "Features (space to select, enter for none)",
1667
+ options: pickableFeatures(host)
1668
+ });
1364
1669
  }
1365
- async function ask(question) {
1366
- const terminal = createInterface({
1367
- input: process.stdin,
1368
- output: process.stderr
1670
+ async function askInputs(args, prompts, context) {
1671
+ const { dir, state } = await askDir(args, prompts, context);
1672
+ const found = state.kind === "adopt" && state.project.framework !== "none" ? state.project.framework : void 0;
1673
+ const framework = args.framework ?? (found === "nuxt" || found === "vite" ? found : await prompts.select({
1674
+ initialValue: "vite",
1675
+ message: "Framework",
1676
+ options: [{
1677
+ label: "Vite",
1678
+ value: "vite"
1679
+ }, {
1680
+ label: "Nuxt",
1681
+ value: "nuxt"
1682
+ }]
1683
+ }));
1684
+ const currentHost = state.kind === "adopt" ? lockedHost(state.project, context.env) : void 0;
1685
+ const host = args.host ?? currentHost ?? await prompts.select({
1686
+ message: "Host",
1687
+ options: initHosts.map((value) => ({
1688
+ label: value,
1689
+ value
1690
+ }))
1369
1691
  });
1370
- try {
1371
- return (await terminal.question(question)).trim();
1372
- } finally {
1373
- terminal.close();
1374
- }
1692
+ if (host === "unknown") throw setupFailure(cliErrorDiagnostics.SETUP_INIT_HOST_MIGRATION({ host }), setupExitCodes.conflict);
1693
+ const features = args.features ?? await askFeatures(prompts, host);
1694
+ return {
1695
+ ...args,
1696
+ dir,
1697
+ features,
1698
+ framework,
1699
+ host
1700
+ };
1375
1701
  }
1376
- async function readInputs(args) {
1377
- if (interactive(args)) {
1378
- const dir = args.dir ?? (await ask("Folder of the app: ") || ".");
1379
- const host = args.host ?? oneOf("--host", await ask(`Host (${initHosts.join(", ")}): `), initHosts);
1380
- const features = args.features ?? readAddArgs((await ask("Features, separated by commas (none for no features): ")).split(",").map((item) => item.trim()).filter((item) => item && item !== "none")).features;
1381
- return {
1382
- ...args,
1383
- dir,
1384
- features,
1385
- host
1386
- };
1387
- }
1702
+ function npmCreateHint(env) {
1703
+ return env.npm_command === "init" || env.npm_command === "create" ? " With `npm create`, put `--` before the flags: `npm create vitehub@latest -- my-app --host node --features kv --yes`." : "";
1704
+ }
1705
+ async function readInputs(args, prompts, context = {
1706
+ env: {},
1707
+ rootDir: process.cwd()
1708
+ }) {
1709
+ if (prompts) return askInputs(args, prompts, context);
1388
1710
  const missing = [];
1389
1711
  if (args.dir === void 0) missing.push({
1390
1712
  field: "dir",
@@ -1406,11 +1728,12 @@ async function readInputs(args) {
1406
1728
  features: args.features,
1407
1729
  host: args.host
1408
1730
  };
1409
- const message = missing.map((item) => `${item.sentence} when running without an interactive terminal.`).join(" ");
1731
+ const message = `${missing.map((item) => `${item.sentence} when running without an interactive terminal.`).join(" ")}${npmCreateHint(context.env)}`;
1410
1732
  throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] ${message}` }), setupExitCodes.inputNeeded, {
1411
1733
  missing: missing.map(({ sentence: _sentence, ...item }) => item),
1412
1734
  rerun: rerunInit(args, {
1413
1735
  dir: args.dir ?? "<dir>",
1736
+ nuxtNightly: args.nuxtNightly,
1414
1737
  options: args.options,
1415
1738
  ...args.features ? { features: args.features } : {},
1416
1739
  ...args.host ? { host: args.host } : {},
@@ -1441,7 +1764,8 @@ function writeResult$1(plan, context) {
1441
1764
  context.stdout.write(`${stackLines(plan.stack).join("\n")}\n`);
1442
1765
  context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
1443
1766
  }
1444
- async function runInit(rawArgs, context) {
1767
+ /** Runs `vitehub init`. `wizard` gives the prompts for a person at a terminal; tests pass fake prompts. */
1768
+ async function runInit(rawArgs, context, wizard = terminalWizard) {
1445
1769
  let json = rawArgs.includes("--json");
1446
1770
  try {
1447
1771
  const parsed = readInitArgs(rawArgs);
@@ -1450,9 +1774,10 @@ async function runInit(rawArgs, context) {
1450
1774
  context.stdout.write(`Usage: ${usage$2}\n\n${initCommandDefinition.description}\n`);
1451
1775
  return setupExitCodes.done;
1452
1776
  }
1453
- const args = await readInputs(parsed);
1777
+ const prompts = parsed.json ? void 0 : await wizard();
1778
+ const args = await readInputs(parsed, prompts, context);
1454
1779
  const root = resolve(context.rootDir, args.dir);
1455
- let planned = await planInit(args, root, await readDir(root, context.env), context);
1780
+ let planned = await planWithAnswers(args, root, await readDir(root, context.env), context, prompts, parsed.features === void 0);
1456
1781
  const plan = {
1457
1782
  ...planned.plan,
1458
1783
  stack: await setupStack(planned.stackProject, setupStatus(planned.stackProject, context.env))
@@ -1464,15 +1789,21 @@ async function runInit(rawArgs, context) {
1464
1789
  return setupExitCodes.done;
1465
1790
  }
1466
1791
  if (!args.yes) {
1467
- if (!interactive(args)) {
1792
+ if (!prompts) {
1468
1793
  if (!args.json) writePlan$1(plan, context);
1469
1794
  throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub init` writes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
1470
1795
  data: plan,
1471
1796
  rerun: planned.rerun
1472
1797
  });
1473
1798
  }
1474
- writePlan$1(plan, context);
1475
- if (!await confirmSetupChange()) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The change was not confirmed. Nothing was written." }), setupExitCodes.error);
1799
+ writePlan$1(plan, {
1800
+ ...context,
1801
+ stdout: context.stderr
1802
+ });
1803
+ if (!await prompts.confirm({
1804
+ initialValue: plan.mode === "create",
1805
+ message: plan.mode === "create" ? "Create the app?" : "Apply these changes?"
1806
+ })) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The change was not confirmed. Nothing was written." }), setupExitCodes.error);
1476
1807
  }
1477
1808
  if (planned.scaffold) {
1478
1809
  await scaffoldNuxt(planned, context);
@@ -1500,7 +1831,7 @@ async function runInit(rawArgs, context) {
1500
1831
  const initCommandDefinition = {
1501
1832
  description: "Create a ViteHub app in a folder, or set up an existing Vite or Nuxt app, with a host and features.",
1502
1833
  name: "init",
1503
- run: runInit,
1834
+ run: (args, context) => runInit(args, context),
1504
1835
  usage: usage$2
1505
1836
  };
1506
1837
  // src/setup/remove.ts
@@ -1658,6 +1989,10 @@ async function planSetupRemove(project, args, env) {
1658
1989
  const key = source?.ok ? source.site.keys[id] : void 0;
1659
1990
  return key?.kind === "literal" ? key.value : void 0;
1660
1991
  };
1992
+ if (args.features.includes("kv") && remaining.includes("rateLimit") && valueOf(project.config, "kv") !== false && rateLimitUsesVercelKV(host, valueOf(afterKeys, "rateLimit"))) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_REQUIRED({
1993
+ by: "rateLimit",
1994
+ feature: "kv"
1995
+ }), setupExitCodes.conflict, { data: { impliedBy: ["rateLimit"] } });
1661
1996
  for (const id of turnedOff) {
1662
1997
  const by = remaining.filter((dependent) => optionPrerequisites(dependent, valueOf(afterKeys, dependent), enabled(after.status, dependent).enabled === "unknown" && enabled(after.status, dependent).reason === "config").includes(id));
1663
1998
  if (by.length) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_REQUIRED({
@@ -1665,10 +2000,10 @@ async function planSetupRemove(project, args, env) {
1665
2000
  feature: id
1666
2001
  }), setupExitCodes.conflict, { data: { impliedBy: by } });
1667
2002
  }
1668
- const packagesOf = (id, value, active = wasEnabled) => {
1669
- return [...featurePackages(id, value, host, active), ...features[id].devPackages];
2003
+ const packagesOf = (id, source, active = wasEnabled) => {
2004
+ return [...setupFeaturePackages(id, (feature) => valueOf(source, feature), host, active), ...features[id].devPackages];
1670
2005
  };
1671
- const stillNeeded = new Set(remaining.flatMap((id) => packagesOf(id, valueOf(afterKeys, id), remaining)));
2006
+ const stillNeeded = new Set(remaining.flatMap((id) => packagesOf(id, afterKeys, remaining)));
1672
2007
  const starters = /* @__PURE__ */ new Map();
1673
2008
  const edited = [];
1674
2009
  for (const id of turnedOff) {
@@ -1694,7 +2029,7 @@ async function planSetupRemove(project, args, env) {
1694
2029
  const modules = /* @__PURE__ */ new Map();
1695
2030
  for (const id of turnedOff) {
1696
2031
  modules.set(runtimeModule(id), id);
1697
- for (const name of packagesOf(id, valueOf(project.config, id))) if (!stillNeeded.has(name) && !modules.has(name)) modules.set(name, id);
2032
+ for (const name of packagesOf(id, project.config)) if (!stillNeeded.has(name) && !modules.has(name)) modules.set(name, id);
1698
2033
  }
1699
2034
  const imported = /* @__PURE__ */ new Set();
1700
2035
  for (const file of listMatchingFiles(project.root, (name) => sourceFile.test(name))) {
@@ -1742,7 +2077,7 @@ async function planSetupRemove(project, args, env) {
1742
2077
  const dev = [];
1743
2078
  for (const id of wasEnabled) {
1744
2079
  if (enabled(status, id).enabled !== "on") continue;
1745
- const packages = featurePackages(id, valueOf(project.config, id), host, wasEnabled);
2080
+ const packages = setupFeaturePackages(id, (feature) => valueOf(project.config, feature), host, wasEnabled);
1746
2081
  const removable = (name) => !stillNeeded.has(name) && !imported.has(name) && !prod.includes(name) && !dev.includes(name);
1747
2082
  for (const name of packages) if (removable(name) && project.declared(name, true)) prod.push(name);
1748
2083
  for (const name of features[id].devPackages) if (removable(name) && project.declared(name, true)) dev.push(name);
@@ -2404,7 +2739,9 @@ function linkLabel(status) {
2404
2739
  }
2405
2740
  function credentialsLabel(credentials) {
2406
2741
  if (!credentials) return "not needed";
2407
- return credentials.ok ? `${credentials.host} (${credentials.source})` : `missing: ${credentials.fix}`;
2742
+ if (credentials.ok && credentials.host === "vercel" && credentials.source === "host-cli") return "vercel (vercel login; deploy uses it. Set VERCEL_TOKEN for link checks, provision, and live status)";
2743
+ if (credentials.ok) return `${credentials.host} (${credentials.source})`;
2744
+ return "unknown" in credentials ? `unknown: ${credentials.fix}` : `missing: ${credentials.fix}`;
2408
2745
  }
2409
2746
  function writeStatus(status, context) {
2410
2747
  const shown = status.features.filter((feature) => feature.enabled !== "off");