@vite-hub/cli 0.6.1 → 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-YzxNsbhs.js";
3
- import { B as readSetupProject, H as editViteHubConfig, I as declaresNuxt5, L as detectPackageManager, R as nuxtReleases, U as insertViteHubConfig, V as setupLockfiles, W as locateViteHubConfig, d as readSetupLinkState, h as unlinkSetupProject, i as SETUP_LINK_FILE, l as linkSetupProject, s as gitignoreWithViteHub, u as readLinkHostOption, z as pnpmWorkspaceFile } from "./env-DzYHxq9A.js";
4
- import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-DDen0JC0.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";
14
- import { createTwoFilesPatch } from "diff";
12
+ import { isDeepStrictEqual, parseArgs, stripVTControlCharacters } from "node:util";
15
13
  import semver, { minVersion, satisfies, subset, validRange } from "semver";
14
+ import { isMap, parseDocument } from "yaml";
15
+ import { createTwoFilesPatch } from "diff";
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) || [
@@ -909,11 +1128,6 @@ const initPackages = {
909
1128
  const nuxtNitroRange = "^3.0.261103-rc";
910
1129
  const nuxtNitroPackage = `nitro@${nuxtNitroRange}`;
911
1130
  const nuxt47ViteHub = "vite-hub@>=0.5.1 <1";
912
- /**
913
- * Nuxt 4 installs esbuild, and pnpm 11 and later fail the install while the esbuild build script waits for
914
- * approval. esbuild runs without that script, so a new Nuxt 4.7 app declines it.
915
- */
916
- const nuxtPnpmWorkspace = "allowBuilds:\n esbuild: false\n";
917
1131
  /** The pinned Nuxt CLI that creates a new Nuxt app. */
918
1132
  const nuxiPackage = "nuxi@3.37.0";
919
1133
  const nuxtTemplate = "gh:nuxt/starter#d4367031fe43d93d4e2a339f73b519ec35e78b38";
@@ -1001,9 +1215,18 @@ function rerunInit(args, parts) {
1001
1215
  function packageNameOf(root) {
1002
1216
  return basename(root).trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || "vitehub-app";
1003
1217
  }
1218
+ function appGitignore(host) {
1219
+ return [
1220
+ "node_modules",
1221
+ ".output",
1222
+ ...ignoredFolders(host),
1223
+ ".env*",
1224
+ "!.env.example"
1225
+ ];
1226
+ }
1004
1227
  function viteAppFiles(name, host) {
1005
1228
  return {
1006
- ".gitignore": "node_modules\n.output\n.vitehub\n.env*\n!.env.example\n",
1229
+ ".gitignore": [...appGitignore(host), ""].join("\n"),
1007
1230
  "package.json": `${JSON.stringify({
1008
1231
  name,
1009
1232
  private: true,
@@ -1062,12 +1285,18 @@ function dlx(packageManager, spec, args) {
1062
1285
  function runScript(packageManager, script) {
1063
1286
  return packageManager === "npm" || packageManager === "bun" ? `${packageManager} run ${script}` : `${packageManager} ${script}`;
1064
1287
  }
1288
+ function hasErrorCode(error, code) {
1289
+ return error instanceof Error && "code" in error && error.code === code;
1290
+ }
1065
1291
  async function readDir(root, env) {
1066
- if (!existsSync(root)) return {
1292
+ const entries = await readdir(root).catch((error) => {
1293
+ if (!hasErrorCode(error, "ENOENT")) throw error;
1294
+ });
1295
+ if (!entries) return {
1067
1296
  exists: false,
1068
1297
  kind: "create"
1069
1298
  };
1070
- if (!(await readdir(root)).filter((entry) => entry !== ".git").length) return {
1299
+ if (entries.every((entry) => entry === ".git")) return {
1071
1300
  exists: true,
1072
1301
  kind: "create"
1073
1302
  };
@@ -1078,6 +1307,11 @@ async function readDir(root, env) {
1078
1307
  project
1079
1308
  };
1080
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
+ }
1081
1315
  function changeOf(path, before, after) {
1082
1316
  return before === void 0 ? {
1083
1317
  after,
@@ -1165,8 +1399,8 @@ async function planInit(args, root, state, context) {
1165
1399
  for (const [path, after] of Object.entries(files)) base.set(path, { after });
1166
1400
  configFile = framework === "vite" ? "vite.config.ts" : "nuxt.config.ts";
1167
1401
  } else {
1168
- const status = setupStatus(state.project, context.env);
1169
- 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);
1170
1404
  const config = adoptConfig(state.project, args.host, framework);
1171
1405
  base.set(config.file, config);
1172
1406
  configFile = config.file;
@@ -1230,17 +1464,16 @@ async function planInit(args, root, state, context) {
1230
1464
  const gitignore = await readOptional(join(root, ".gitignore"));
1231
1465
  base.set(".gitignore", {
1232
1466
  ...gitignore === void 0 ? {} : { before: gitignore },
1233
- after: gitignore === void 0 ? ".vitehub\n" : gitignoreWithViteHub(gitignore) ?? gitignore
1467
+ after: gitignoreWith(gitignore ?? "", appGitignore(args.host)) ?? gitignore ?? ""
1234
1468
  });
1235
1469
  }
1236
- const workspaceFile = allowsNuxt4 && packageManager === "pnpm" ? pnpmWorkspaceFile(root) : void 0;
1237
- if (state.kind === "create" && allowsNuxt4 && packageManager === "pnpm" && !workspaceFile) base.set("pnpm-workspace.yaml", { after: nuxtPnpmWorkspace });
1238
1470
  const scaffolded = state.kind === "create" && framework === "nuxt";
1239
1471
  const writes = [...base.entries()].filter(([path]) => !scaffolded || !Object.hasOwn(nuxtAppFiles(name, args.host), path)).sort(([left], [right]) => Number(left === configFile) - Number(right === configFile)).filter(([, file]) => file.before !== file.after).map(([path, file]) => ({
1240
1472
  path,
1241
1473
  ...file
1242
1474
  }));
1243
1475
  const command = installCommand(packageManager, install.prod, install.dev);
1476
+ const workspace = command ? planPnpmBuilds(planned, declinedBuilds(planned, args.host, added.enabled)) : void 0;
1244
1477
  const scaffold = scaffolded ? dlx(packageManager, nuxiPackage, [
1245
1478
  "init",
1246
1479
  basename(root),
@@ -1270,7 +1503,7 @@ async function planInit(args, root, state, context) {
1270
1503
  return {
1271
1504
  install,
1272
1505
  plan: {
1273
- 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))],
1274
1507
  features: added.plan.features,
1275
1508
  framework,
1276
1509
  host: args.host,
@@ -1285,13 +1518,13 @@ async function planInit(args, root, state, context) {
1285
1518
  packageManager,
1286
1519
  root,
1287
1520
  ...scaffold ? { scaffold: { command: [scaffold[0], ...scaffold[1]].join(" ") } } : {},
1288
- status: writes.length || scaffold || command && args.install ? "planned" : "unchanged"
1521
+ status: writes.length || workspace || scaffold || command && args.install ? "planned" : "unchanged"
1289
1522
  },
1290
1523
  rerun: rerunInit(args, parts()),
1291
1524
  stackProject,
1292
1525
  writes,
1293
1526
  ...scaffold ? { scaffold } : {},
1294
- ...workspaceFile ? { workspaceFile } : {}
1527
+ ...workspace ? { workspace } : {}
1295
1528
  };
1296
1529
  }
1297
1530
  function setupStack(project, status) {
@@ -1311,22 +1544,12 @@ async function applyInit(planned, install, context, scaffolded = false) {
1311
1544
  const { plan } = planned;
1312
1545
  const runInstall = async () => {
1313
1546
  if (!install) return;
1314
- for (const [packages, dev] of [[planned.install.prod, false], [planned.install.dev, true]]) {
1315
- if (!packages.length) continue;
1316
- const commandArgs = installArgs(plan.packageManager, packages, dev);
1317
- const result = await context.spawn(plan.packageManager, commandArgs, {
1318
- cwd: plan.root,
1319
- env: context.env,
1320
- stdout: "stderr"
1321
- });
1322
- if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
1323
- command: formatInstallCommand(plan.packageManager, commandArgs),
1324
- exitCode: result.exitCode ?? result.signal,
1325
- filesWritten: scaffolded || plan.mode === "create",
1326
- workspaceFile: planned.workspaceFile
1327
- }), setupExitCodes.error);
1328
- }
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
+ });
1329
1551
  };
1552
+ if (planned.workspace) await writePnpmBuilds(planned.workspace);
1330
1553
  if (plan.mode === "adopt") await runInstall();
1331
1554
  for (const write of planned.writes) {
1332
1555
  const file = join(plan.root, write.path);
@@ -1380,32 +1603,110 @@ async function checkNuxtVersion(root, scaffolded = false) {
1380
1603
  }
1381
1604
  return { needsNitro: nitroDeclarations.length === 0 };
1382
1605
  }
1383
- function interactive(args) {
1384
- 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
+ });
1385
1669
  }
1386
- async function ask(question) {
1387
- const terminal = createInterface({
1388
- input: process.stdin,
1389
- 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
+ }))
1390
1691
  });
1391
- try {
1392
- return (await terminal.question(question)).trim();
1393
- } finally {
1394
- terminal.close();
1395
- }
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
+ };
1396
1701
  }
1397
- async function readInputs(args) {
1398
- if (interactive(args)) {
1399
- const dir = args.dir ?? (await ask("Folder of the app: ") || ".");
1400
- const host = args.host ?? oneOf("--host", await ask(`Host (${initHosts.join(", ")}): `), initHosts);
1401
- 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;
1402
- return {
1403
- ...args,
1404
- dir,
1405
- features,
1406
- host
1407
- };
1408
- }
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);
1409
1710
  const missing = [];
1410
1711
  if (args.dir === void 0) missing.push({
1411
1712
  field: "dir",
@@ -1427,7 +1728,7 @@ async function readInputs(args) {
1427
1728
  features: args.features,
1428
1729
  host: args.host
1429
1730
  };
1430
- 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)}`;
1431
1732
  throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] ${message}` }), setupExitCodes.inputNeeded, {
1432
1733
  missing: missing.map(({ sentence: _sentence, ...item }) => item),
1433
1734
  rerun: rerunInit(args, {
@@ -1463,7 +1764,8 @@ function writeResult$1(plan, context) {
1463
1764
  context.stdout.write(`${stackLines(plan.stack).join("\n")}\n`);
1464
1765
  context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
1465
1766
  }
1466
- 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) {
1467
1769
  let json = rawArgs.includes("--json");
1468
1770
  try {
1469
1771
  const parsed = readInitArgs(rawArgs);
@@ -1472,9 +1774,10 @@ async function runInit(rawArgs, context) {
1472
1774
  context.stdout.write(`Usage: ${usage$2}\n\n${initCommandDefinition.description}\n`);
1473
1775
  return setupExitCodes.done;
1474
1776
  }
1475
- const args = await readInputs(parsed);
1777
+ const prompts = parsed.json ? void 0 : await wizard();
1778
+ const args = await readInputs(parsed, prompts, context);
1476
1779
  const root = resolve(context.rootDir, args.dir);
1477
- 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);
1478
1781
  const plan = {
1479
1782
  ...planned.plan,
1480
1783
  stack: await setupStack(planned.stackProject, setupStatus(planned.stackProject, context.env))
@@ -1486,19 +1789,24 @@ async function runInit(rawArgs, context) {
1486
1789
  return setupExitCodes.done;
1487
1790
  }
1488
1791
  if (!args.yes) {
1489
- if (!interactive(args)) {
1792
+ if (!prompts) {
1490
1793
  if (!args.json) writePlan$1(plan, context);
1491
1794
  throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub init` writes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
1492
1795
  data: plan,
1493
1796
  rerun: planned.rerun
1494
1797
  });
1495
1798
  }
1496
- writePlan$1(plan, context);
1497
- 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);
1498
1807
  }
1499
1808
  if (planned.scaffold) {
1500
1809
  await scaffoldNuxt(planned, context);
1501
- for (const write of planned.writes.filter((write) => write.path === "pnpm-workspace.yaml")) await writeFile(join(root, write.path), write.after);
1502
1810
  planned = await planInit({
1503
1811
  ...args,
1504
1812
  pm: plan.packageManager
@@ -1523,7 +1831,7 @@ async function runInit(rawArgs, context) {
1523
1831
  const initCommandDefinition = {
1524
1832
  description: "Create a ViteHub app in a folder, or set up an existing Vite or Nuxt app, with a host and features.",
1525
1833
  name: "init",
1526
- run: runInit,
1834
+ run: (args, context) => runInit(args, context),
1527
1835
  usage: usage$2
1528
1836
  };
1529
1837
  // src/setup/remove.ts
@@ -1681,6 +1989,10 @@ async function planSetupRemove(project, args, env) {
1681
1989
  const key = source?.ok ? source.site.keys[id] : void 0;
1682
1990
  return key?.kind === "literal" ? key.value : void 0;
1683
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"] } });
1684
1996
  for (const id of turnedOff) {
1685
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));
1686
1998
  if (by.length) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_REQUIRED({
@@ -1688,10 +2000,10 @@ async function planSetupRemove(project, args, env) {
1688
2000
  feature: id
1689
2001
  }), setupExitCodes.conflict, { data: { impliedBy: by } });
1690
2002
  }
1691
- const packagesOf = (id, value, active = wasEnabled) => {
1692
- 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];
1693
2005
  };
1694
- 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)));
1695
2007
  const starters = /* @__PURE__ */ new Map();
1696
2008
  const edited = [];
1697
2009
  for (const id of turnedOff) {
@@ -1717,7 +2029,7 @@ async function planSetupRemove(project, args, env) {
1717
2029
  const modules = /* @__PURE__ */ new Map();
1718
2030
  for (const id of turnedOff) {
1719
2031
  modules.set(runtimeModule(id), id);
1720
- 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);
1721
2033
  }
1722
2034
  const imported = /* @__PURE__ */ new Set();
1723
2035
  for (const file of listMatchingFiles(project.root, (name) => sourceFile.test(name))) {
@@ -1765,7 +2077,7 @@ async function planSetupRemove(project, args, env) {
1765
2077
  const dev = [];
1766
2078
  for (const id of wasEnabled) {
1767
2079
  if (enabled(status, id).enabled !== "on") continue;
1768
- const packages = featurePackages(id, valueOf(project.config, id), host, wasEnabled);
2080
+ const packages = setupFeaturePackages(id, (feature) => valueOf(project.config, feature), host, wasEnabled);
1769
2081
  const removable = (name) => !stillNeeded.has(name) && !imported.has(name) && !prod.includes(name) && !dev.includes(name);
1770
2082
  for (const name of packages) if (removable(name) && project.declared(name, true)) prod.push(name);
1771
2083
  for (const name of features[id].devPackages) if (removable(name) && project.declared(name, true)) dev.push(name);
@@ -2427,7 +2739,9 @@ function linkLabel(status) {
2427
2739
  }
2428
2740
  function credentialsLabel(credentials) {
2429
2741
  if (!credentials) return "not needed";
2430
- 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}`;
2431
2745
  }
2432
2746
  function writeStatus(status, context) {
2433
2747
  const shown = status.features.filter((feature) => feature.enabled !== "off");