@vite-hub/cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3104 @@
1
+ import { A as readDeployCommit, B as featureIds, C as denoOrganization, D as build, E as listCloudflareDeployments, F as uninstallArgs, G as impliedInline, H as featureSupport, I as hostFromNitroPreset, J as locateViteHubConfig, K as editViteHubConfig, L as detectPackageManager, M as installCommand, N as setsOption, O as readBuildOutput, P as setupStatus, R as readSetupProject, S as denoAdapter, T as cloudflareAdapter, U as features, V as featurePackages, W as impliedFeatures, Y as __exportAll, _ as listVercelDeployments, a as ensureViteHubGitignore, b as netlifyAdapter, c as linkSetupProject, f as readSetupLinks, g as hasVercelLogin, h as writeSeparateResourcesNote, i as addSetupLink, j as installArgs, k as createDeployRun, l as readLinkHostOption, m as unlinkSetupProject, o as gitignoreWithViteHub, p as selectSetupLink, q as insertViteHubConfig, r as SETUP_LINK_FILE, s as hostRequired, t as checkDeployEnv, u as readSetupLinkState, v as vercelAdapter, w as listDenoDeployments, x as abortable, y as listNetlifyDeployments, z as featureHosts } from "./env-DzoVtVJO.js";
2
+ import { C as callOperationFromCli, _ as readProvisionState, a as writeProvisionActions, d as planProvisionSteps, f as resolveHostCredentials, g as mergeProvisionState, h as PROVISION_STATE_FILE, i as provisionEnv, m as cliErrorDiagnostics, n as isProvisionHost, r as provisionActionStatus, y as writeProvisionState } from "./provision-D8OvBBzi.js";
3
+ import { a as table, i as setupFailure, n as readSetupArgs, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-Cf56AJLa.js";
4
+ import { l as whoamiCommand, o as loginCommand, s as logoutCommand } from "./console-auth-xl7kLQNt.js";
5
+ import { createRequire } from "node:module";
6
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
7
+ import process from "node:process";
8
+ import { basename, dirname, join, relative, resolve } from "pathe";
9
+ import { mkdir, readFile, readdir, rm, rmdir, writeFile } from "node:fs/promises";
10
+ import { join as join$1 } from "node:path";
11
+ import { createInterface } from "node:readline/promises";
12
+ import { pathToFileURL } from "node:url";
13
+ import { createTwoFilesPatch } from "diff";
14
+ import { parseArgs } from "node:util";
15
+ import { Range, minVersion, subset, validRange } from "semver";
16
+ //#region src/setup/add.ts
17
+ const usage$4 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
18
+ /**
19
+ * Values that `--option` can choose for an `explicit` host, first the one that `rerun` uses, and the feature that the
20
+ * value needs. Options without an entry, such as `database.connection`, need a value that only the developer knows.
21
+ */
22
+ const optionChoices = {
23
+ "cache.driver": {
24
+ requires: "kv",
25
+ values: ["kv"]
26
+ },
27
+ "email.driver": { values: ["resend", "log"] },
28
+ "kv.driver": { values: ["upstash"] },
29
+ "realtime.driver": { values: ["memory"] },
30
+ "sandboxTask.driver": { values: ["vercel"] },
31
+ "workflow.driver": { values: ["openworkflow"] }
32
+ };
33
+ /** Option keys that select a provider or a store. A feature that sets one does not use the host default. */
34
+ const providerKeys = ["driver", "store"];
35
+ function selectsProvider(id, value, host) {
36
+ if (!isRecord$1(value)) return false;
37
+ if (id === "workflow" && host !== "netlify") {
38
+ const configured = (storage, key) => isRecord$1(storage) && (typeof storage[key] === "string" ? !!storage[key].trim() : isRecord$1(storage[key]));
39
+ if (configured(value.postgres, "url") || configured(value.sqlite, "path")) return true;
40
+ }
41
+ return providerKeys.some((key) => value[key] !== void 0);
42
+ }
43
+ /** How `host` supports `id`, with the override that `env` selects, such as BLOB_READ_WRITE_TOKEN for the Vercel Workspace. */
44
+ function hostSupport(id, host, env) {
45
+ const support = featureSupport(id, host);
46
+ if (support.level !== "native") return support;
47
+ return support.envOverrides?.find((override) => env[override.env]?.trim())?.support ?? support;
48
+ }
49
+ /** The value that turns a feature on, when `true` is not valid for its key. */
50
+ const enabledValues = { env: {} };
51
+ /** Keep owner packages on the running CLI's pkg.pr.new preview. */
52
+ function installSpecifiers(packages) {
53
+ const manifest = JSON.parse(readFileSync(new URL(import.meta.resolve("@vite-hub/cli/package.json")), "utf8"));
54
+ const dependencies = isRecord$1(manifest) && isRecord$1(manifest.dependencies) ? manifest.dependencies : {};
55
+ const preview = Object.entries(dependencies).flatMap(([name, specifier]) => {
56
+ if (!name.startsWith("@vite-hub/") || typeof specifier !== "string" || !specifier.startsWith("https://pkg.pr.new/")) return [];
57
+ const [base, ref] = specifier.split(`/${name}@`);
58
+ return base && ref ? [{
59
+ base,
60
+ ref
61
+ }] : [];
62
+ })[0];
63
+ return packages.map((name) => preview && name.startsWith("@vite-hub/") ? `${preview.base}/${name}@${preview.ref}` : name);
64
+ }
65
+ function invalid$2(message, commandUsage = usage$4) {
66
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${commandUsage}` });
67
+ }
68
+ /** The feature id of a command argument, such as `rate-limit` for `rateLimit`. Throws `CLI_R0003` for an unknown feature. */
69
+ function readFeatureId(value, commandUsage = usage$4) {
70
+ const key = value.replaceAll("-", "").toLowerCase();
71
+ const id = featureIds.find((item) => item.toLowerCase() === key);
72
+ if (!id) throw invalid$2(`Unknown feature ${JSON.stringify(value)}. Run \`vitehub catalog\` to list the features.`, commandUsage);
73
+ return id;
74
+ }
75
+ function optionValue(value) {
76
+ if (value === "true" || value === "false" || value === "null" || /^-?\d+(?:\.\d+)?$/u.test(value)) return JSON.parse(value);
77
+ return value;
78
+ }
79
+ function setPath(target, path, value) {
80
+ const [key, ...rest] = path;
81
+ if (!rest.length) {
82
+ target[key] = value;
83
+ return;
84
+ }
85
+ const child = target[key];
86
+ const next = isRecord$1(child) ? { ...child } : {};
87
+ setPath(next, rest, value);
88
+ target[key] = next;
89
+ }
90
+ function isRecord$1(value) {
91
+ return !!value && typeof value === "object" && !Array.isArray(value);
92
+ }
93
+ /** Reads the arguments. Throws `CLI_R0003` for an unknown flag, feature, or option. */
94
+ function readAddArgs(args) {
95
+ const parsed = {
96
+ dryRun: false,
97
+ features: [],
98
+ help: false,
99
+ install: true,
100
+ json: false,
101
+ options: {},
102
+ yes: false
103
+ };
104
+ const rawOptions = [];
105
+ for (let index = 0; index < args.length; index++) {
106
+ const arg = args[index];
107
+ const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, void 0];
108
+ const value = () => {
109
+ const next = inline ?? args[++index];
110
+ if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$2(`${flag} needs a value.`);
111
+ return next;
112
+ };
113
+ if (flag === "--json") parsed.json = true;
114
+ else if (flag === "--dry-run") parsed.dryRun = true;
115
+ else if (flag === "--yes" || flag === "-y") parsed.yes = true;
116
+ else if (flag === "--no-install") parsed.install = false;
117
+ else if (flag === "-h" || flag === "--help") parsed.help = true;
118
+ else if (flag === "--name") parsed.name = value();
119
+ else if (flag === "--option") rawOptions.push(value());
120
+ else if (arg.startsWith("-")) throw invalid$2(`Unknown argument ${JSON.stringify(arg)}.`);
121
+ else if (!parsed.features.includes(readFeatureId(arg))) parsed.features.push(readFeatureId(arg));
122
+ }
123
+ if (parsed.name !== void 0 && !/^[a-z0-9][a-z0-9-]*$/u.test(parsed.name)) throw invalid$2(`--name ${JSON.stringify(parsed.name)} must use lowercase letters, digits, and dashes, such as \`welcome-email\`.`);
124
+ for (const option of rawOptions) {
125
+ const separator = option.indexOf("=");
126
+ if (separator <= 0) throw invalid$2(`--option ${JSON.stringify(option)} must be key=value, such as \`email.driver=resend\`.`);
127
+ const path = option.slice(0, separator).split(".");
128
+ const head = featureIds.find((id) => id === path[0]);
129
+ const id = head ?? (parsed.features.length === 1 ? parsed.features[0] : void 0);
130
+ const keys = head ? path.slice(1) : path;
131
+ if (!id || !keys.length || keys.some((key) => !key)) throw invalid$2(`--option ${JSON.stringify(option)} must start with one of the features, such as \`${parsed.features[0] ?? "email"}.driver=resend\`.`);
132
+ setPath(parsed.options[id] ??= {}, keys, optionValue(option.slice(separator + 1)));
133
+ }
134
+ return parsed;
135
+ }
136
+ /** Quotes `value` for a POSIX shell when it needs quotes. */
137
+ function shellQuote(value) {
138
+ return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
139
+ }
140
+ /** `value` as `--option` values under `prefix`, such as `["email.driver=resend"]`. */
141
+ function flattenOptions(prefix, value, out = []) {
142
+ if (isRecord$1(value)) for (const [key, child] of Object.entries(value)) flattenOptions(`${prefix}.${key}`, child, out);
143
+ else out.push(`${prefix}=${value === null || typeof value !== "object" ? String(value) : JSON.stringify(value)}`);
144
+ return out;
145
+ }
146
+ /** The `vitehub add` command for `args`, with `extra` options and `--yes` unless it is a dry run. */
147
+ function rerunCommand$2(args, extra = {}, extraFeatures = []) {
148
+ const ids = [...args.features, ...extraFeatures.filter((id) => !args.features.includes(id))];
149
+ const options = [.../* @__PURE__ */ new Set([
150
+ ...ids,
151
+ ...Object.keys(args.options),
152
+ ...Object.keys(extra)
153
+ ])].flatMap((id) => {
154
+ const merged = mergeValue(args.options[id], extra[id]);
155
+ return isRecord$1(merged) ? flattenOptions(id, merged) : [];
156
+ });
157
+ return [
158
+ "vitehub add",
159
+ ...ids,
160
+ ...args.name ? ["--name", args.name] : [],
161
+ ...options.flatMap((option) => ["--option", shellQuote(option)]),
162
+ ...args.install ? [] : ["--no-install"],
163
+ ...args.dryRun ? ["--dry-run"] : ["--yes"],
164
+ ...args.json ? ["--json"] : []
165
+ ].join(" ");
166
+ }
167
+ /** Merges `patch` into `base`, object key by object key. */
168
+ function mergeValue(base, patch) {
169
+ if (patch === void 0) return base;
170
+ if (!isRecord$1(base) || !isRecord$1(patch)) return patch;
171
+ const merged = { ...base };
172
+ for (const [key, value] of Object.entries(patch)) merged[key] = mergeValue(base[key], value);
173
+ return merged;
174
+ }
175
+ function sameValue(left, right) {
176
+ if (isRecord$1(left) && isRecord$1(right)) return [.../* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])].every((key) => sameValue(left[key], right[key]));
177
+ return JSON.stringify(left) === JSON.stringify(right);
178
+ }
179
+ function toSource(value) {
180
+ if (Array.isArray(value)) return `[${value.map(toSource).join(", ")}]`;
181
+ if (isRecord$1(value)) {
182
+ const entries = Object.entries(value).map(([key, child]) => `${/^[A-Z_$][\w$]*$/iu.test(key) ? key : JSON.stringify(key)}: ${toSource(child)}`);
183
+ return entries.length ? `{ ${entries.join(", ")} }` : "{}";
184
+ }
185
+ return JSON.stringify(value);
186
+ }
187
+ /** A unified diff of `path`. Empty `before` creates a file; empty `after` deletes it. */
188
+ function setupDiff(path, before, after) {
189
+ return createTwoFilesPatch(before ? `a/${path}` : "/dev/null", after ? `b/${path}` : "/dev/null", before, after, void 0, void 0, { context: 3 }).replace(/^=+\n/u, "");
190
+ }
191
+ /**
192
+ * The config value that `add` writes for `id`, `undefined` when the config already turns it on, or `expression` when
193
+ * the key is an expression that only a person can edit.
194
+ */
195
+ function nextValue(id, status, project, options) {
196
+ const current = project.config?.ok ? project.config.site.keys[id] : void 0;
197
+ if (current?.kind === "expression") return "expression";
198
+ const literal = current?.value;
199
+ if (!options) return status.features.find((item) => item.id === id).enabled === "on" ? void 0 : { value: enabledValues[id] ?? true };
200
+ const merged = mergeValue(isRecord$1(literal) ? literal : {}, options);
201
+ return sameValue(literal, merged) ? void 0 : { value: merged };
202
+ }
203
+ /** Plans `vitehub add` without writing anything. Throws `SetupFailure` when the change needs input or is not possible. */
204
+ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
205
+ const status = setupStatus(project, env);
206
+ const host = status.host.name;
207
+ if (host === "unknown") {
208
+ const file = project.configFile ?? "vite.config.ts";
209
+ const reason = project.config && !project.config.ok ? project.config.reason : "dynamic-options";
210
+ const snippet = args.features.map((id) => `${id}: ${toSource(mergeValue(true, args.options[id]))},`).join("\n");
211
+ throw setupFailure(cliErrorDiagnostics.SETUP_CONFIG_MANUAL({
212
+ file,
213
+ reason,
214
+ snippet
215
+ }), setupExitCodes.conflict, { data: { snippet } });
216
+ }
217
+ for (const id of args.features) {
218
+ const support = featureSupport(id, host);
219
+ const current = project.config?.ok ? project.config.site.keys[id] : void 0;
220
+ const driver = args.options[id]?.driver ?? (current?.kind === "literal" && isRecord$1(current.value) ? current.value.driver : void 0);
221
+ if (id === "email" && driver === "cloudflare" && host !== "cloudflare") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
222
+ detail: "The cloudflare driver requires Cloudflare. Choose email.driver=resend, or email.driver=log to print each message and send nothing.",
223
+ feature: id,
224
+ host
225
+ }), setupExitCodes.conflict);
226
+ if (support.level === "unsupported") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
227
+ detail: support.detail,
228
+ feature: id,
229
+ host
230
+ }), setupExitCodes.conflict);
231
+ }
232
+ const missing = [];
233
+ const defaults = {};
234
+ const requires = [];
235
+ let rerunnable = true;
236
+ const keep = status.features.filter((item) => item.enabled === "off" && item.reason === "config" && !args.features.includes(item.id)).map((item) => item.id);
237
+ const valueFor = (id) => {
238
+ const current = project.config?.ok ? project.config.site.keys[id] : void 0;
239
+ return mergeValue(current?.kind === "literal" ? current.value : void 0, args.options[id]);
240
+ };
241
+ const inputFeatures = [...args.features, ...impliedFeatures(args.features, host, keep.filter((id) => id !== "database"))];
242
+ if (inputFeatures.includes("database") && keep.includes("database")) requires.push("database");
243
+ const requireFeature = (required) => {
244
+ for (const id of [required, ...impliedFeatures([required], host, keep.filter((id) => id !== "database"))]) {
245
+ if (!inputFeatures.includes(id)) inputFeatures.push(id);
246
+ if ((id === required || keep.includes(id)) && !args.features.includes(id) && !requires.includes(id) && status.features.find((item) => item.id === id)?.enabled !== "on") requires.push(id);
247
+ }
248
+ };
249
+ for (const id of inputFeatures) {
250
+ const support = featureSupport(id, host);
251
+ const options = args.options[id];
252
+ const current = project.config?.ok ? project.config.site.keys[id] : void 0;
253
+ const value = valueFor(id);
254
+ if (id === "observability" && isRecord$1(value) && value.papercuts) {
255
+ const agent = valueFor("agent");
256
+ if (host === "netlify" || isRecord$1(agent) && agent.runtime === "deno") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
257
+ detail: "observability.papercuts requires Nitro-hosted Agents. Netlify and the Agent Deno runtime are not supported.",
258
+ feature: id,
259
+ host
260
+ }), setupExitCodes.conflict);
261
+ requireFeature("agent");
262
+ requireFeature("console");
263
+ }
264
+ if (id === "observability" && isRecord$1(value) && value.posthog) requireFeature("env");
265
+ if (id === "realtime" && args.name !== void 0) requireFeature("workspace");
266
+ if (id === "agent" && host === "deno" && isRecord$1(value) && value.runtime === "deno") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
267
+ detail: "The Deno host cannot deploy the Agent Deno runtime outside its Nitro entrypoint. Use the host's Nitro runtime instead.",
268
+ feature: id,
269
+ host
270
+ }), setupExitCodes.conflict);
271
+ if (id === "realtime" && isRecord$1(value) && value.driver !== void 0) {
272
+ const choices = host === "cloudflare" ? ["cloudflare", "auto"] : host === "node" ? [
273
+ "auto",
274
+ "postgres",
275
+ "redis",
276
+ "memory"
277
+ ] : ["memory"];
278
+ if (typeof value.driver !== "string" || !choices.includes(value.driver)) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
279
+ detail: `realtime.driver must be ${choices.join(" or ")} on this host. ${support.detail}`,
280
+ feature: id,
281
+ host
282
+ }), setupExitCodes.conflict);
283
+ }
284
+ if (id === "cache" && isRecord$1(value) && value.driver !== void 0) {
285
+ const nativeDriver = {
286
+ cloudflare: "cloudflare",
287
+ deno: "deno-kv",
288
+ netlify: void 0,
289
+ node: "fs-lite",
290
+ vercel: "vercel"
291
+ }[host];
292
+ if (value.driver !== "kv" && value.driver !== nativeDriver) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
293
+ detail: `cache.driver must be ${nativeDriver ? `${nativeDriver} or ` : ""}kv on this host. ${support.detail}`,
294
+ feature: id,
295
+ host
296
+ }), setupExitCodes.conflict);
297
+ }
298
+ const invocations = id === "agent" && isRecord$1(value) ? value.invocations : void 0;
299
+ if (host === "netlify" && invocations !== void 0 && invocations !== false) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
300
+ detail: "agent.invocations requires Nitro-hosted Agents. Set invocations on each Agent Definition instead, or use agent.invocations=false.",
301
+ feature: id,
302
+ host
303
+ }), setupExitCodes.conflict);
304
+ if (invocations === "database" || isRecord$1(invocations) && invocations.store === "database") requireFeature("database");
305
+ const inlineOnly = !args.features.includes(id) && !requires.includes(id) && impliedInline(id, inputFeatures, host);
306
+ const storageSelected = id === "workflow" && host !== "netlify" && selectsProvider(id, value, host);
307
+ if (support.level === "explicit" && !inlineOnly && !storageSelected) {
308
+ const key = support.option.slice(id.length + 1);
309
+ if (!(options && key in options) && !setsOption(project, support.option)) {
310
+ const choices = optionChoices[support.option];
311
+ missing.push({
312
+ field: support.option,
313
+ ...choices ? { choices: choices.values } : {}
314
+ });
315
+ if (choices) setPath(defaults[id] ??= {}, [key], choices.values[0]);
316
+ else rerunnable = false;
317
+ }
318
+ }
319
+ for (const [field, choice] of Object.entries(optionChoices)) {
320
+ if (!choice?.requires || !field.startsWith(`${id}.`)) continue;
321
+ const key = field.slice(id.length + 1);
322
+ const selected = (isRecord$1(value) ? value[key] : void 0) ?? defaults[id]?.[key];
323
+ if (typeof selected !== "string" || !choice.values.includes(selected)) continue;
324
+ requireFeature(choice.requires);
325
+ }
326
+ if (id === "schedule" && host === "node" && current?.kind !== "expression" && !(isRecord$1(value) && value.providerOutput === false)) {
327
+ if (isRecord$1(value) && (value.providerOutput === "nitro" || value.providerOutput === "standalone")) {
328
+ missing.push({
329
+ choices: ["auto"],
330
+ field: "schedule.providerOutput"
331
+ });
332
+ setPath(defaults.schedule ??= {}, ["providerOutput"], "auto");
333
+ }
334
+ if (!isRecord$1(value) || !isRecord$1(value.runtime) || value.runtime.driver !== "process") {
335
+ missing.push({
336
+ choices: ["process"],
337
+ field: "schedule.runtime.driver"
338
+ });
339
+ setPath(defaults.schedule ??= {}, ["runtime", "driver"], "process");
340
+ }
341
+ }
342
+ }
343
+ const enabledAfter = (id) => inputFeatures.includes(id) || status.features.find((item) => item.id === id)?.enabled === "on";
344
+ const agent = valueFor("agent");
345
+ const observabilityValue = valueFor("observability");
346
+ const telemetry = isRecord$1(observabilityValue) && typeof observabilityValue.service === "string";
347
+ if (inputFeatures.some((id) => id === "agent" || id === "observability") && enabledAfter("observability") && telemetry && enabledAfter("agent") && (host === "netlify" || isRecord$1(agent) && agent.runtime === "deno")) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
348
+ detail: "Observability requires Nitro-hosted Agents. Netlify and the Agent Deno runtime are not supported.",
349
+ feature: "observability",
350
+ host
351
+ }), setupExitCodes.conflict);
352
+ for (const id of Object.keys(args.options)) if (!inputFeatures.includes(id)) throw invalid$2(`${id} is not requested or required by ${args.features.join(", ")}.`);
353
+ if (missing.length) {
354
+ const fields = missing.map((item) => `\`${item.field}\``).join(", ");
355
+ throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.` }), setupExitCodes.inputNeeded, {
356
+ missing,
357
+ ...rerunnable ? { rerun: rerun(args, defaults, requires) } : {}
358
+ });
359
+ }
360
+ const edits = [];
361
+ let expression = false;
362
+ const addedFeatures = [...args.features, ...requires];
363
+ for (const id of /* @__PURE__ */ new Set([...addedFeatures, ...inputFeatures.filter((id) => args.options[id])])) {
364
+ const next = nextValue(id, status, project, args.options[id]);
365
+ expression ||= next === "expression";
366
+ if (next !== void 0) edits.push({
367
+ key: id,
368
+ op: "set",
369
+ value: next === "expression" ? mergeValue(true, args.options[id]) : next.value
370
+ });
371
+ }
372
+ const changes = [];
373
+ const files = [];
374
+ let configFile;
375
+ const serverDir = relative(project.root, project.serverDirs?.[0] ?? join(project.root, "server"));
376
+ const nuxtRoot = project.config?.ok ? project.config.site.nuxt?.keys.rootDir : void 0;
377
+ const definitionRoot = nuxtRoot?.kind === "literal" && typeof nuxtRoot.value === "string" ? resolve(project.root, nuxtRoot.value) : project.root;
378
+ if (args.name !== void 0) {
379
+ const withStarter = args.features.filter((id) => features[id].definition);
380
+ if (!withStarter.length) throw invalid$2(`${args.features.join(", ")} has no Definition files, so --name has no effect. Features with Definitions: ${featureIds.filter((id) => features[id].definition).join(", ")}.`);
381
+ if (project.framework === "nuxt" && !project.serverDirs?.length) throw setupFailure(cliErrorDiagnostics.SETUP_SERVER_DIR_MANUAL(), setupExitCodes.conflict);
382
+ for (const id of withStarter) {
383
+ const starter = features[id].definition;
384
+ const path = join(serverDir, relative("server", starter.file(args.name)));
385
+ const content = starter.template(args.name);
386
+ const file = join(project.root, path);
387
+ if (existsSync(file)) {
388
+ if (await readFile(file, "utf8") === content) continue;
389
+ throw setupFailure(cliErrorDiagnostics.SETUP_FILE_EXISTS({ file: path }), setupExitCodes.conflict);
390
+ }
391
+ const conflict = starter.conflicts(args.name).flatMap((other) => other.startsWith("server/") ? (project.serverDirs ?? [join(project.root, "server")]).map((directory) => relative(project.root, join(directory, relative("server", other)))) : [relative(project.root, join(definitionRoot, other))]).find((other) => existsSync(join(project.root, other)));
392
+ if (conflict) throw setupFailure(cliErrorDiagnostics.SETUP_FILE_EXISTS({
393
+ definition: features[id].title,
394
+ file: conflict,
395
+ starter: path
396
+ }), setupExitCodes.conflict);
397
+ files.push({
398
+ content,
399
+ path
400
+ });
401
+ changes.push({
402
+ after: content,
403
+ diff: setupDiff(path, "", content),
404
+ kind: "create",
405
+ path
406
+ });
407
+ }
408
+ }
409
+ if (edits.length) {
410
+ const manualReason = !project.config ? "no-vitehub" : !project.config.ok ? project.config.reason : expression ? "dynamic-options" : void 0;
411
+ const file = project.configFile ?? (project.framework === "nuxt" ? "nuxt.config.ts" : "vite.config.ts");
412
+ const snippet = edits.map((edit) => edit.op === "set" ? `${edit.key}: ${toSource(edit.value)},` : "").join("\n");
413
+ const manual = (reason) => setupFailure(cliErrorDiagnostics.SETUP_CONFIG_MANUAL({
414
+ file,
415
+ reason,
416
+ snippet
417
+ }), setupExitCodes.conflict, { data: { snippet } });
418
+ if (manualReason || !project.configFile) throw manual(manualReason ?? "no-vitehub");
419
+ const before = project.configSource ?? await readFile(join(project.root, project.configFile), "utf8");
420
+ const result = editViteHubConfig(project.configFile, before, edits);
421
+ if (!result.ok) throw manual(result.reason);
422
+ configFile = {
423
+ after: result.code,
424
+ before,
425
+ path: project.configFile
426
+ };
427
+ changes.push({
428
+ after: result.code,
429
+ before,
430
+ diff: setupDiff(project.configFile, before, result.code),
431
+ kind: "patch",
432
+ path: project.configFile
433
+ });
434
+ }
435
+ const alreadyOn = new Set(status.features.filter((item) => item.enabled === "on").map((item) => item.id));
436
+ const implied = impliedFeatures([.../* @__PURE__ */ new Set([...alreadyOn, ...addedFeatures])], host, keep.filter((id) => !requires.includes(id))).filter((id) => !addedFeatures.includes(id));
437
+ const enabled = /* @__PURE__ */ new Set([
438
+ ...alreadyOn,
439
+ ...addedFeatures,
440
+ ...implied
441
+ ]);
442
+ const packageFeatures = [.../* @__PURE__ */ new Set([
443
+ ...addedFeatures,
444
+ ...implied,
445
+ ...inputFeatures,
446
+ ...enabled.has("console") ? ["console"] : []
447
+ ])];
448
+ const packages = packageFeatures.flatMap((id) => featurePackages(id, valueFor(id), host, [...enabled]));
449
+ const install = {
450
+ dev: [...new Set(packageFeatures.flatMap((id) => features[id].devPackages))].filter((name) => !project.declared(name, true)),
451
+ prod: [...new Set(packages)].filter((name) => !project.declared(name, false))
452
+ };
453
+ install.prod = installSpecifiers(install.prod);
454
+ install.dev = installSpecifiers(install.dev);
455
+ const command = installCommand(project.packageManager, install.prod, install.dev);
456
+ const nextSteps = [];
457
+ if (command && !args.install) nextSteps.push(`Install the packages: ${command}`);
458
+ for (const id of implied) {
459
+ const support = featureSupport(id, host);
460
+ if (support.level === "unsupported") nextSteps.push(`${id} is turned on by ${args.features.join(", ")} but is not supported on ${host}: ${support.detail} Set \`${id}: false\` to turn it off.`);
461
+ else if (support.level === "explicit" && impliedInline(id, [...enabled], host)) {
462
+ if (!selectsProvider(id, valueFor(id), host) && !setsOption(project, support.option)) nextSteps.push(`${features[id].title} that ${args.features.join(", ")} turns on runs inline in the request process on ${host}, and a restart loses its runs. Set \`${support.option}\` for durable runs. ${support.detail}`);
463
+ } else if (support.level === "explicit" && !setsOption(project, support.option) && !(args.options[id] && support.option.slice(id.length + 1) in args.options[id])) nextSteps.push(`${id} is turned on by ${args.features.join(", ")}. Set \`${support.option}\` on ${host}, or set \`${id}: false\`. ${support.detail}`);
464
+ }
465
+ for (const id of [...addedFeatures, ...implied]) {
466
+ if (selectsProvider(id, valueFor(id))) continue;
467
+ const support = hostSupport(id, host, env);
468
+ if (support.level === "native" && support.guarantee === "process-local") nextSteps.push(`${features[id].title} on ${host} uses ${support.display} by default. ${support.detail}`);
469
+ }
470
+ if (args.name !== void 0 && args.features.includes("workflow") && host === "vercel" && !selectsProvider("workflow", valueFor("workflow"))) nextSteps.push(`${join(serverDir, "workflows", `${args.name}.ts`)} has no \`native\` entry, so Vercel runs it inline. Add one for durable runs: https://vitehub.dev/docs/workflows/configure#add-a-durable-vercel-entry`);
471
+ 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`)}.`);
472
+ for (const id of args.features) nextSteps.push(`${features[id].title}: https://vitehub.dev${features[id].docs}`);
473
+ nextSteps.push("Run `vitehub status` to check the result.");
474
+ return {
475
+ files,
476
+ install,
477
+ plan: {
478
+ changes,
479
+ features: addedFeatures,
480
+ host: status.host,
481
+ implied,
482
+ install: {
483
+ devPackages: install.dev,
484
+ packages: install.prod,
485
+ ...command ? { command } : {}
486
+ },
487
+ nextSteps,
488
+ root: project.root,
489
+ status: changes.length || command && args.install ? "planned" : "unchanged"
490
+ },
491
+ ...configFile ? { configFile } : {}
492
+ };
493
+ }
494
+ /** Applies a `vitehub add` plan: installs the packages, writes the starter Definitions, and writes the config last. */
495
+ async function applySetupAdd(project, planned, args, context) {
496
+ const { dev, prod } = planned.install;
497
+ if (args.install) for (const [packages, isDev] of [[prod, false], [dev, true]]) {
498
+ if (!packages.length) continue;
499
+ const commandArgs = installArgs(project.packageManager, packages, isDev);
500
+ const result = await context.spawn(project.packageManager, commandArgs, {
501
+ cwd: project.root,
502
+ env: context.env,
503
+ stdout: "stderr"
504
+ });
505
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
506
+ command: [project.packageManager, ...commandArgs].join(" "),
507
+ exitCode: result.exitCode ?? result.signal
508
+ }), setupExitCodes.error);
509
+ }
510
+ 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);
511
+ for (const file of planned.files) {
512
+ await mkdir(dirname(join(project.root, file.path)), { recursive: true });
513
+ try {
514
+ await writeFile(join(project.root, file.path), file.content, { flag: "wx" });
515
+ } catch {
516
+ throw setupFailure(cliErrorDiagnostics.SETUP_FILE_EXISTS({ file: file.path }), setupExitCodes.conflict);
517
+ }
518
+ }
519
+ if (planned.configFile) {
520
+ const path = join(project.root, planned.configFile.path);
521
+ if (await readFile(path, "utf8") !== planned.configFile.before) throw setupFailure(cliErrorDiagnostics.SETUP_STALE_PLAN({ file: planned.configFile.path }), setupExitCodes.stalePlan);
522
+ await writeFile(path, planned.configFile.after);
523
+ }
524
+ }
525
+ function writePlan$2(plan, context) {
526
+ for (const change of plan.changes) context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
527
+ const lines = [...plan.install.command ? [`Install: ${plan.install.command}`] : [], ...plan.implied.length ? [`Also turns on: ${plan.implied.join(", ")}`] : []];
528
+ if (lines.length) context.stdout.write(`${lines.join("\n")}\n`);
529
+ }
530
+ function writeResult$2(plan, context) {
531
+ if (plan.status === "unchanged") context.stdout.write(`${plan.features.join(", ")} already on. Nothing to change.\n`);
532
+ else context.stdout.write(`Added ${plan.features.join(", ")}.${plan.changes.length ? ` Changed ${plan.changes.map((change) => change.path).join(", ")}.` : ""}\n`);
533
+ context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
534
+ }
535
+ /** Asks on the terminal whether to apply the changes. */
536
+ async function confirmSetupChange() {
537
+ const terminal = createInterface({
538
+ input: process.stdin,
539
+ output: process.stderr
540
+ });
541
+ try {
542
+ return /^y(?:es)?$/iu.test((await terminal.question("Apply these changes? [y/N] ")).trim());
543
+ } finally {
544
+ terminal.close();
545
+ }
546
+ }
547
+ async function runAdd(args, context) {
548
+ let parsed;
549
+ try {
550
+ parsed = readAddArgs(args);
551
+ if (parsed.help) {
552
+ context.stdout.write(`Usage: ${usage$4}\n\n${addCommand.description}\n`);
553
+ return setupExitCodes.done;
554
+ }
555
+ if (!parsed.features.length) throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: "[vitehub] Name at least one feature, such as `vitehub add kv`." }), setupExitCodes.inputNeeded, { missing: [{
556
+ choices: featureIds,
557
+ field: "feature"
558
+ }] });
559
+ const project = await readSetupProject(context.rootDir, context.env);
560
+ const planned = await planSetupAdd(project, parsed, context.env);
561
+ const { plan } = planned;
562
+ if (plan.status === "unchanged" || parsed.dryRun) {
563
+ if (parsed.json) writeSetupJson(context, plan);
564
+ else if (plan.status === "unchanged") writeResult$2(plan, context);
565
+ else writePlan$2(plan, context);
566
+ return setupExitCodes.done;
567
+ }
568
+ if (!parsed.yes) {
569
+ if (!(!parsed.json && !!process.stdin.isTTY && !!process.stderr.isTTY)) {
570
+ if (!parsed.json) writePlan$2(plan, context);
571
+ throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub add` changes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
572
+ data: plan,
573
+ rerun: rerunCommand$2(parsed)
574
+ });
575
+ }
576
+ writePlan$2(plan, context);
577
+ if (!await confirmSetupChange()) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The change was not confirmed. Nothing was written." }), setupExitCodes.error);
578
+ }
579
+ await applySetupAdd(project, planned, parsed, context);
580
+ const applied = {
581
+ ...plan,
582
+ status: "applied"
583
+ };
584
+ if (parsed.json) writeSetupJson(context, applied);
585
+ else writeResult$2(applied, context);
586
+ return setupExitCodes.done;
587
+ } catch (error) {
588
+ const json = parsed?.json ?? args.includes("--json");
589
+ return writeSetupError(context, json, error);
590
+ }
591
+ }
592
+ const addCommand = {
593
+ description: "Turn on features: edit vitehub() options, install packages, and create starter Definitions. Reads the config without running it.",
594
+ name: "add",
595
+ run: runAdd,
596
+ usage: usage$4
597
+ };
598
+ //#endregion
599
+ //#region src/setup/catalog.ts
600
+ /** Every feature of `vitehub({...})` and how each host supports it. Needs no project. */
601
+ function setupCatalog() {
602
+ return {
603
+ features: featureIds.map((id) => features[id]),
604
+ hosts: featureHosts,
605
+ schemaVersion: 1
606
+ };
607
+ }
608
+ //#endregion
609
+ //#region src/setup/deploy/after.ts
610
+ /** Waits between the attempts of one path: a new version can take a few seconds to reach every edge location. */
611
+ const checkRetryDelaysMs = [
612
+ 1e3,
613
+ 2e3,
614
+ 4e3
615
+ ];
616
+ const checkTimeoutMs = 1e4;
617
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
618
+ function reason(error) {
619
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `no answer within ${checkTimeoutMs / 1e3} seconds`;
620
+ return error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
621
+ }
622
+ /**
623
+ * Requests each path on the deployed URL until it answers with a 2xx status, with a few retries. Redirects are
624
+ * followed, so the final answer counts. The request asks the cache to skip, so a cached answer of the previous version
625
+ * does not pass the check.
626
+ */
627
+ async function runDeployChecks(baseUrl, paths, fetchImpl, delays = checkRetryDelaysMs) {
628
+ const origin = new URL(baseUrl);
629
+ return await Promise.all(paths.map(async (path) => {
630
+ const url = new URL(path, origin).href;
631
+ let last = {
632
+ ok: false,
633
+ path,
634
+ url
635
+ };
636
+ for (let attempt = 0; attempt <= delays.length; attempt++) {
637
+ if (attempt) await sleep(delays[attempt - 1]);
638
+ try {
639
+ const response = await fetchImpl(url, {
640
+ cache: "no-store",
641
+ headers: {
642
+ "cache-control": "no-cache",
643
+ "user-agent": "vitehub-deploy-check"
644
+ },
645
+ redirect: "follow",
646
+ signal: AbortSignal.timeout(checkTimeoutMs)
647
+ });
648
+ await response.body?.cancel();
649
+ last = {
650
+ ok: response.ok,
651
+ path,
652
+ status: response.status,
653
+ url
654
+ };
655
+ } catch (error) {
656
+ last = {
657
+ error: reason(error),
658
+ ok: false,
659
+ path,
660
+ url
661
+ };
662
+ }
663
+ if (last.ok) break;
664
+ }
665
+ return last;
666
+ }));
667
+ }
668
+ /** One line per failed check, such as `/api/health: 503` or `/: fetch failed`. */
669
+ function formatFailedChecks(checks) {
670
+ return checks.filter((check) => !check.ok).map((check) => `${check.path}: ${check.status ?? check.error ?? "no answer"}`).join(", ");
671
+ }
672
+ function quote(value) {
673
+ return /^[\w./:@=-]+$/u.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
674
+ }
675
+ /**
676
+ * The rollback of each host, from its CLI help in test/fixtures/host-cli-help/:
677
+ * - Wrangler 4.158 `wrangler rollback <version-id> --name <worker> --yes`.
678
+ * - Vercel CLI 65.16 `vercel rollback <deployment> --yes`.
679
+ * - Netlify CLI 27.11 `netlify api restoreSiteDeploy`, the `POST /sites/{site_id}/deploys/{deploy_id}/restore` API.
680
+ * - Deno Deploy CLI 0.0.9909 has no rollback command.
681
+ */
682
+ function rollbackFor(host, input) {
683
+ const { previous } = input;
684
+ if (!previous) return { note: input.lookupFailed ? `The previous production deployment is not known: ${input.lookupFailed} Run \`vitehub deployments\` to find it.` : "This was the first production deploy, so there is no earlier deployment to roll back to." };
685
+ const described = {
686
+ deploymentId: previous.id,
687
+ ...previous.version ? { version: previous.version } : {}
688
+ };
689
+ switch (host) {
690
+ case "cloudflare": return {
691
+ command: `npx wrangler rollback ${quote(previous.version ?? previous.id)} --name ${quote(input.projectName)} --yes`,
692
+ previous: described
693
+ };
694
+ case "vercel": return {
695
+ command: `npx vercel rollback ${quote(previous.id)} --yes`,
696
+ previous: described
697
+ };
698
+ case "netlify": return input.siteId ? {
699
+ command: `npx netlify api restoreSiteDeploy --data ${quote(JSON.stringify({
700
+ deploy_id: previous.id,
701
+ site_id: input.siteId
702
+ }))}`,
703
+ previous: described
704
+ } : {
705
+ note: `Publish deploy ${previous.id} again in the Netlify dashboard, under Deploys.`,
706
+ previous: described
707
+ };
708
+ case "deno": return {
709
+ note: `The Deno Deploy CLI has no rollback command. Promote revision ${previous.id} to production in the Deno Deploy dashboard.`,
710
+ previous: described
711
+ };
712
+ }
713
+ }
714
+ const xmlEntities = {
715
+ amp: "&",
716
+ apos: "'",
717
+ gt: ">",
718
+ lt: "<",
719
+ quot: "\""
720
+ };
721
+ /** Text of an XML element: CDATA kept as it is, named and numeric character references decoded. */
722
+ function decodeXml(text) {
723
+ return text.split(/(<!\[CDATA\[[\s\S]*?\]\]>)/u).map((part) => part.startsWith("<![CDATA[") ? part.slice(9, -3) : part.replace(/&(?:#x([\da-f]+)|#(\d+)|(amp|lt|gt|quot|apos));/giu, (match, hex, decimal, name) => {
724
+ if (name) return xmlEntities[name];
725
+ const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
726
+ return code <= 1114111 ? String.fromCodePoint(code) : match;
727
+ })).join("").trim();
728
+ }
729
+ function locations(xml) {
730
+ return [...xml.matchAll(/<loc>([\s\S]*?)<\/loc>/gu)].map((match) => decodeXml(match[1])).filter(Boolean);
731
+ }
732
+ /** IndexNow takes at most 10,000 URLs in one request. */
733
+ const indexNowBatch = 1e4;
734
+ /** A sitemap index may list sitemaps on other paths. Read at most this many. */
735
+ const nestedSitemapLimit = 50;
736
+ /**
737
+ * Reads `<url>/sitemap.xml`, one level of a sitemap index included, and sends every URL of the site to IndexNow.
738
+ * https://www.indexnow.org/documentation: 200 and 202 accept the URLs, 403 means the key file was not found.
739
+ */
740
+ async function submitIndexNow(indexNow, fetchImpl) {
741
+ const origin = new URL(indexNow.url);
742
+ const read = async (url) => {
743
+ const response = await fetchImpl(url, {
744
+ headers: { "user-agent": "vitehub-deploy" },
745
+ signal: AbortSignal.timeout(checkTimeoutMs)
746
+ });
747
+ if (!response.ok) throw Object.assign(/* @__PURE__ */ new Error(`${url} answered ${response.status}.`), { status: response.status });
748
+ return await response.text();
749
+ };
750
+ const sameSite = (url) => URL.canParse(url) && new URL(url).origin === origin.origin;
751
+ let urls;
752
+ try {
753
+ const sitemap = await read(new URL("/sitemap.xml", origin).href);
754
+ urls = /<sitemapindex[\s>]/u.test(sitemap) ? (await Promise.all(locations(sitemap).filter(sameSite).slice(0, nestedSitemapLimit).map(read))).flatMap(locations) : locations(sitemap);
755
+ } catch (error) {
756
+ const status = error instanceof Error ? Reflect.get(error, "status") : void 0;
757
+ return {
758
+ error: `The sitemap could not be read: ${reason(error)}`,
759
+ ...typeof status === "number" ? { status } : {}
760
+ };
761
+ }
762
+ const urlList = [...new Set(urls.filter(sameSite))];
763
+ if (!urlList.length) return { error: `${origin.origin}/sitemap.xml lists no URL of ${origin.host}.` };
764
+ let status = 0;
765
+ for (let start = 0; start < urlList.length; start += indexNowBatch) {
766
+ const response = await fetchImpl("https://api.indexnow.org/indexnow", {
767
+ body: JSON.stringify({
768
+ host: origin.host,
769
+ key: indexNow.key,
770
+ keyLocation: `${origin.origin}/${indexNow.key}.txt`,
771
+ urlList: urlList.slice(start, start + indexNowBatch)
772
+ }),
773
+ headers: { "content-type": "application/json; charset=utf-8" },
774
+ method: "POST",
775
+ signal: AbortSignal.timeout(checkTimeoutMs)
776
+ }).catch((error) => error instanceof Error ? error : new Error(String(error)));
777
+ if (response instanceof Error) return { error: `IndexNow did not answer: ${reason(response)}` };
778
+ await response.body?.cancel();
779
+ status = response.status;
780
+ if (status === 403) return {
781
+ error: `IndexNow did not find the key file at ${origin.origin}/${indexNow.key}.txt.`,
782
+ status
783
+ };
784
+ if (!response.ok) return {
785
+ error: `IndexNow answered ${status}.`,
786
+ status
787
+ };
788
+ }
789
+ return {
790
+ status,
791
+ submitted: urlList.length
792
+ };
793
+ }
794
+ //#endregion
795
+ //#region src/setup/deploy/checkouts.ts
796
+ /** The lock file of `vitehub pull` and `vitehub push`, at the project root. */
797
+ const lockFile = "vitehub.lock";
798
+ function isCheckoutModule(value) {
799
+ return Object(value) === value && typeof Reflect.get(Object(value), "localCheckoutStatus") === "function" && typeof Reflect.get(Object(value), "pullWorkspaces") === "function" && typeof Reflect.get(Object(value), "pushWorkspaces") === "function";
800
+ }
801
+ /** The checkout module of the Workspace package. */
802
+ const checkoutSpecifiers = ["@vite-hub/workspace/checkout", "vite-hub/workspace/checkout"];
803
+ /** True when `specifier` itself does not resolve: the package is not installed, or it has no `./checkout` export. */
804
+ function isNotInstalled(error, specifier) {
805
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
806
+ if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED") return true;
807
+ return code === "MODULE_NOT_FOUND" && error instanceof Error && error.message.includes(`'${specifier}'`);
808
+ }
809
+ /**
810
+ * The checkout module of the Workspace package that the project installs. Undefined only when no specifier resolves.
811
+ * A module that resolves but does not load stops the deploy, because a silent skip would deploy without the push.
812
+ */
813
+ async function importCheckoutModule(root) {
814
+ const require = createRequire(join(root, "package.json"));
815
+ for (const specifier of checkoutSpecifiers) {
816
+ let file;
817
+ try {
818
+ file = require.resolve(specifier);
819
+ } catch (error) {
820
+ if (isNotInstalled(error, specifier)) continue;
821
+ throw moduleFailure(specifier, specifier, error);
822
+ }
823
+ let module;
824
+ try {
825
+ module = await import(pathToFileURL(file).href);
826
+ } catch (error) {
827
+ throw moduleFailure(specifier, file, error);
828
+ }
829
+ if (!isCheckoutModule(module)) throw moduleFailure(specifier, file, /* @__PURE__ */ new TypeError("It does not export localCheckoutStatus, pullWorkspaces and pushWorkspaces."));
830
+ return module;
831
+ }
832
+ }
833
+ function moduleFailure(specifier, file, error) {
834
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
835
+ return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CHECKOUT_MODULE_FAILED({
836
+ file,
837
+ message,
838
+ specifier
839
+ }), setupExitCodes.error);
840
+ }
841
+ /**
842
+ * True when `vitehub.lock` lists at least one checkout folder. False without a lock. A lock that is not JSON, such as
843
+ * one with a Git conflict, counts, so the checkout module reports it.
844
+ */
845
+ async function lockHasCheckouts(root) {
846
+ let source;
847
+ try {
848
+ source = await readFile(join(root, lockFile), "utf8");
849
+ } catch (error) {
850
+ if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return false;
851
+ throw error;
852
+ }
853
+ let lock;
854
+ try {
855
+ lock = JSON.parse(source);
856
+ } catch {
857
+ return true;
858
+ }
859
+ const workspaces = Object(lock) === lock ? Reflect.get(Object(lock), "workspaces") : void 0;
860
+ return Object(workspaces) === workspaces && Object.keys(Object(workspaces)).length > 0;
861
+ }
862
+ /**
863
+ * Pulls the checkout folders of `vitehub.lock` before the build. Undefined when the project has no lock file,
864
+ * no checkout, or no Workspace package to read them: then deploy does not push. Without a checkout, deploy does not
865
+ * load the Workspace package. Without the package, a lock with checkouts gets one warning on `stderr`. Throws when the
866
+ * package does not load, the pull fails, or a checkout has an open conflict before or after the pull.
867
+ */
868
+ async function prepareDeployCheckouts(root, context) {
869
+ if (!await lockHasCheckouts(root)) return void 0;
870
+ const module = await importCheckoutModule(root);
871
+ if (!module) {
872
+ context.stderr.write("[vitehub] vitehub.lock has checkout folders, but the deploy does not push them because the Workspace package is not installed. Install @vite-hub/workspace or vite-hub.\n");
873
+ return;
874
+ }
875
+ const statuses = await module.localCheckoutStatus(root);
876
+ if (!statuses?.length) return void 0;
877
+ assertNoConflicts(statuses);
878
+ const before = await readLock(root);
879
+ const pulled = await module.pullWorkspaces(checkoutContext(root, context));
880
+ assertNoConflicts(await module.localCheckoutStatus(root) ?? []);
881
+ return {
882
+ before,
883
+ module,
884
+ pulls: new Map(pulled.map((result) => [result.workspace, result])),
885
+ root,
886
+ statuses
887
+ };
888
+ }
889
+ function assertNoConflicts(statuses) {
890
+ const conflicts = statuses.flatMap((status) => status.local.conflicted.map((path) => `${status.dir}/${path}`));
891
+ if (conflicts.length) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CHECKOUT_CONFLICT({ files: conflicts.join(", ") }), setupExitCodes.error);
892
+ }
893
+ async function readLock(root) {
894
+ return await readFile(join(root, lockFile), "utf8").catch(() => void 0);
895
+ }
896
+ function checkoutContext(root, context) {
897
+ const call = async (operation, input, remote) => await callOperationFromCli({
898
+ env: context.env,
899
+ ...context.fetch ? { fetch: context.fetch } : {},
900
+ rootDir: root,
901
+ timeout: 12e4,
902
+ ...remote ? { url: remote } : {}
903
+ }, operation, input);
904
+ return {
905
+ call,
906
+ rootDir: root
907
+ };
908
+ }
909
+ /**
910
+ * Pushes every checkout folder, as `vitehub push` does. The `remote` of each lock entry decides where it goes. Returns
911
+ * the results and the files changed since the pre-build pull: `vitehub.lock`, and the files that either pull wrote.
912
+ */
913
+ async function pushDeployCheckouts(checkouts, context) {
914
+ const results = (await checkouts.module.pushWorkspaces(checkoutContext(checkouts.root, context))).map((result) => {
915
+ const before = checkouts.pulls.get(result.workspace);
916
+ return before ? {
917
+ ...result,
918
+ pull: {
919
+ ...result.pull,
920
+ files: [...before.files, ...result.pull.files],
921
+ from: before.from
922
+ }
923
+ } : result;
924
+ });
925
+ const dirs = new Map(checkouts.statuses.map((status) => [status.workspace, status.dir]));
926
+ const pulled = results.flatMap((result) => [...result.pull.files, ...result.after?.files ?? []].filter((file) => file.action !== "kept").map((file) => `${dirs.get(result.workspace) ?? result.workspace}/${file.path}`));
927
+ return {
928
+ changed: [.../* @__PURE__ */ new Set([...checkouts.before === await readLock(checkouts.root) ? [] : [lockFile], ...pulled])],
929
+ results
930
+ };
931
+ }
932
+ /** The code, message, and fix of a failed push, as `vitehub push --json` prints them. */
933
+ function checkoutPushError(error) {
934
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
935
+ const fix = error instanceof Error ? Reflect.get(error, "fix") : void 0;
936
+ return {
937
+ code: typeof code === "string" ? code : "WORKSPACE_CHECKOUT_FAILED",
938
+ message: error instanceof Error ? error.message : String(error),
939
+ ...typeof fix === "string" ? { fix } : {}
940
+ };
941
+ }
942
+ function formatPull(result, workspace) {
943
+ if (result.from === result.head && !result.files.length) return "";
944
+ const lines = [`${workspace}: pulled ${result.ref} ${result.from ?? "(empty)"} -> ${result.head ?? "(empty)"}`];
945
+ for (const file of result.files) lines.push(` ${file.action.padEnd(8)} ${file.path}${file.note ? `\n ${file.note}` : ""}`);
946
+ return `${lines.join("\n")}\n`;
947
+ }
948
+ /** The text of `vitehub push`, then the files to commit. */
949
+ function formatDeployCheckouts(pushed) {
950
+ const text = pushed.results.map((result) => {
951
+ const pulled = formatPull(result.pull, result.workspace);
952
+ if (!result.revision) return `${pulled}${result.workspace}: nothing to push.\n`;
953
+ return `${pulled}${result.workspace}: pushed ${result.pushed.length} ${result.pushed.length === 1 ? "file" : "files"} to ${result.ref} (${result.revision})\n${result.pushed.map((path) => ` ${path}`).join("\n")}\n${result.after ? formatPull(result.after, result.workspace) : ""}`;
954
+ }).join("");
955
+ if (!pushed.changed.length) return text;
956
+ return `${text}The push changed these files. Commit them:\n${pushed.changed.map((path) => ` ${path}`).join("\n")}\n`;
957
+ }
958
+ //#endregion
959
+ //#region src/setup/deployments.ts
960
+ const usage$3 = "vitehub deployments [--host <host>] [--limit <n>] [--json]";
961
+ const listers = {
962
+ cloudflare: listCloudflareDeployments,
963
+ deno: listDenoDeployments,
964
+ netlify: listNetlifyDeployments,
965
+ vercel: listVercelDeployments
966
+ };
967
+ /** How long `vitehub deployments` waits for the host. */
968
+ const DEPLOYMENTS_TIMEOUT_MS = 3e4;
969
+ /** How long `vitehub status` waits for the host before it reports `liveReason: "timeout"`. */
970
+ const STATUS_HOST_TIMEOUT_MS = 5e3;
971
+ /** A fetch that gives up after `ms`, so a slow host cannot hold the command. */
972
+ function fetchWithTimeout(fetchImpl, ms, signal) {
973
+ return async (input, init) => {
974
+ signal?.throwIfAborted();
975
+ return await fetchImpl(input, {
976
+ ...init,
977
+ signal: signal ?? AbortSignal.timeout(ms)
978
+ });
979
+ };
980
+ }
981
+ function deploymentsContext(root, link, credentials, context, run, timeoutMs, signal) {
982
+ return {
983
+ credentials,
984
+ env: context.env,
985
+ fetch: fetchWithTimeout(context.fetch ?? globalThis.fetch, timeoutMs, signal),
986
+ link,
987
+ root,
988
+ run: signal ? (command, args, options) => run(command, args, {
989
+ ...options,
990
+ signal
991
+ }) : run,
992
+ timeoutMs
993
+ };
994
+ }
995
+ function readLimit(value) {
996
+ if (value === void 0) return 10;
997
+ const limit = Number(value);
998
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --limit must be a whole number from 1 to 100, not ${JSON.stringify(value)}. Usage: ${usage$3}` });
999
+ return limit;
1000
+ }
1001
+ function readDeploymentsArgs(args) {
1002
+ try {
1003
+ const { values } = parseArgs({
1004
+ args: [...args],
1005
+ options: {
1006
+ help: {
1007
+ short: "h",
1008
+ type: "boolean",
1009
+ default: false
1010
+ },
1011
+ host: { type: "string" },
1012
+ json: {
1013
+ type: "boolean",
1014
+ default: false
1015
+ },
1016
+ limit: { type: "string" }
1017
+ },
1018
+ strict: true
1019
+ });
1020
+ return {
1021
+ help: values.help,
1022
+ host: readLinkHostOption(values.host),
1023
+ json: values.json,
1024
+ limit: readLimit(values.limit)
1025
+ };
1026
+ } catch (error) {
1027
+ if (isSetupFailure(error) || error instanceof Error && "why" in error) throw error;
1028
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage$3}` });
1029
+ }
1030
+ }
1031
+ function shortCommit(commit) {
1032
+ return commit ? `${commit.sha.slice(0, 7)}${commit.dirty ? " (dirty)" : ""}` : "-";
1033
+ }
1034
+ function writeDeployments(output, context) {
1035
+ if (!output.deployments.length) {
1036
+ context.stdout.write(`${output.project.name} on ${output.host} has no deployments.\n`);
1037
+ return;
1038
+ }
1039
+ context.stdout.write(`${table([[
1040
+ "",
1041
+ "id",
1042
+ "target",
1043
+ "state",
1044
+ "commit",
1045
+ "created",
1046
+ "url"
1047
+ ], ...output.deployments.map((item) => [
1048
+ item.live ? "live" : "",
1049
+ item.id,
1050
+ item.target,
1051
+ item.state,
1052
+ shortCommit(item.commit),
1053
+ item.createdAt,
1054
+ item.url ?? "-"
1055
+ ])])}\n`);
1056
+ }
1057
+ async function runDeployments(host, limit, json, context) {
1058
+ const project = await readSetupProject(context.rootDir, context.env);
1059
+ const selected = selectSetupLink(await readSetupLinks(project.root), host);
1060
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, "vitehub deployments");
1061
+ const link = selected.link;
1062
+ if (!link) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_NOT_LINKED({ host }), setupExitCodes.inputNeeded, {
1063
+ missing: [{ field: "link" }],
1064
+ rerun: host ? `vitehub link --host ${host}` : "vitehub link"
1065
+ });
1066
+ const credentials = await resolveHostCredentials(link.host, {
1067
+ cwd: project.root,
1068
+ env: context.env,
1069
+ ...context.runHostCli ? { run: context.runHostCli } : {}
1070
+ });
1071
+ if (!credentials.ok) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_CREDENTIALS_MISSING({
1072
+ fix: credentials.fix,
1073
+ host: link.host
1074
+ }), setupExitCodes.inputNeeded, { missing: credentials.missing.map((field) => ({ field })) });
1075
+ const run = createDeployRun(context.stderr, []);
1076
+ const output = {
1077
+ deployments: await listers[link.host](deploymentsContext(project.root, link, credentials, context, run, DEPLOYMENTS_TIMEOUT_MS), { limit }),
1078
+ host: link.host,
1079
+ project: link.project
1080
+ };
1081
+ if (json) writeSetupJson(context, output);
1082
+ else writeDeployments(output, context);
1083
+ return setupExitCodes.done;
1084
+ }
1085
+ const deploymentsCommand = {
1086
+ description: "List the deployments of the linked project, read from the host each time. Marks the one that receives production traffic. --host picks a linked host other than the default.",
1087
+ name: "deployments",
1088
+ run: async (args, context) => {
1089
+ const json = args.includes("--json");
1090
+ try {
1091
+ const parsed = readDeploymentsArgs(args);
1092
+ if (parsed.help) {
1093
+ context.stdout.write(`Usage: ${usage$3}\n\n${deploymentsCommand.description}\n`);
1094
+ return setupExitCodes.done;
1095
+ }
1096
+ return await runDeployments(parsed.host, parsed.limit, parsed.json, context);
1097
+ } catch (error) {
1098
+ return writeSetupError(context, json, error);
1099
+ }
1100
+ },
1101
+ usage: usage$3
1102
+ };
1103
+ /**
1104
+ * Compares the live commit with HEAD: `git rev-list --left-right --count <sha>...HEAD` prints the commits that only
1105
+ * the deployment has, then the commits that only HEAD has.
1106
+ */
1107
+ async function compareWithHead(run, root, env, sha) {
1108
+ const git = async (args) => {
1109
+ try {
1110
+ return await run("git", args, {
1111
+ cwd: root,
1112
+ env,
1113
+ timeoutMs: STATUS_HOST_TIMEOUT_MS
1114
+ });
1115
+ } catch {
1116
+ return;
1117
+ }
1118
+ };
1119
+ const inside = await git(["rev-parse", "--is-inside-work-tree"]);
1120
+ if (inside?.exitCode !== 0 || inside.stdout.trim() !== "true") return { unknownReason: "no-git" };
1121
+ if ((await git([
1122
+ "cat-file",
1123
+ "-e",
1124
+ `${sha}^{commit}`
1125
+ ]))?.exitCode !== 0) return { unknownReason: "commit-not-local" };
1126
+ const counts = await git([
1127
+ "rev-list",
1128
+ "--left-right",
1129
+ "--count",
1130
+ `${sha}...HEAD`
1131
+ ]);
1132
+ const match = counts?.exitCode === 0 ? /^(\d+)\s+(\d+)/u.exec(counts.stdout.trim()) : void 0;
1133
+ if (!match) return { unknownReason: "no-git" };
1134
+ return {
1135
+ ahead: Number(match[1]),
1136
+ behind: Number(match[2])
1137
+ };
1138
+ }
1139
+ function isTimeout(error) {
1140
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return true;
1141
+ return error instanceof Error && error.cause instanceof Error && isTimeout(error.cause);
1142
+ }
1143
+ /**
1144
+ * The deployment that receives production traffic, for `vitehub status`. It asks the host only when the project is
1145
+ * linked and the credentials resolved. The signal shares status's deadline with credential discovery; standalone
1146
+ * callers get `STATUS_HOST_TIMEOUT_MS`. It never throws: a failure is a `liveReason`.
1147
+ */
1148
+ async function readSetupLive(root, link, credentials, context, options) {
1149
+ if (options.offline) return {
1150
+ live: null,
1151
+ liveReason: "offline"
1152
+ };
1153
+ if (!link) return {
1154
+ live: null,
1155
+ liveReason: "not-linked"
1156
+ };
1157
+ const signal = options.signal ?? AbortSignal.timeout(5e3);
1158
+ if (signal.aborted) return {
1159
+ live: null,
1160
+ liveReason: "timeout"
1161
+ };
1162
+ if (!credentials?.ok || credentials.host !== link.host) return {
1163
+ live: null,
1164
+ liveReason: "no-credentials"
1165
+ };
1166
+ const run = createDeployRun(context.stderr, []);
1167
+ try {
1168
+ const deployment = (await abortable(signal, "Host deployment lookup timed out", () => listers[link.host](deploymentsContext(root, link, credentials, context, run, STATUS_HOST_TIMEOUT_MS, signal), {
1169
+ includeLive: true,
1170
+ limit: 10
1171
+ }))).find((item) => item.live);
1172
+ if (!deployment) return {
1173
+ live: null,
1174
+ liveReason: "no-live-deployment"
1175
+ };
1176
+ const base = {
1177
+ deploymentId: deployment.id,
1178
+ ...deployment.url ? { url: deployment.url } : {}
1179
+ };
1180
+ if (!deployment.commit) return {
1181
+ live: {
1182
+ ...base,
1183
+ unknownReason: "no-marker"
1184
+ },
1185
+ liveReason: null
1186
+ };
1187
+ const commit = {
1188
+ dirty: deployment.commit.dirty,
1189
+ sha: deployment.commit.sha
1190
+ };
1191
+ return {
1192
+ live: {
1193
+ ...base,
1194
+ commit,
1195
+ ...await compareWithHead(run, root, context.env, commit.sha)
1196
+ },
1197
+ liveReason: null
1198
+ };
1199
+ } catch (error) {
1200
+ return {
1201
+ live: null,
1202
+ liveReason: isTimeout(error) ? "timeout" : "host-error"
1203
+ };
1204
+ }
1205
+ }
1206
+ /** How long `vitehub deploy` waits for the host when it reads the deployment that a failed check rolls back to. */
1207
+ const DEPLOY_PREVIOUS_TIMEOUT_MS = 1e4;
1208
+ /**
1209
+ * The deployment that receives production traffic now, read before `vitehub deploy` replaces it. It throws when the
1210
+ * host request fails, so the caller can say why the rollback target is not known.
1211
+ */
1212
+ async function readLiveDeployment(root, link, credentials, context, run) {
1213
+ const signal = AbortSignal.timeout(DEPLOY_PREVIOUS_TIMEOUT_MS);
1214
+ return (await abortable(signal, "Host deployment lookup timed out", () => listers[link.host](deploymentsContext(root, link, credentials, context, run, DEPLOY_PREVIOUS_TIMEOUT_MS, signal), {
1215
+ includeLive: true,
1216
+ limit: 1
1217
+ }))).find((item) => item.live);
1218
+ }
1219
+ const reasonLabels = {
1220
+ "host-error": "unknown (the host request failed; run `vitehub deployments` for the error)",
1221
+ "no-credentials": "unknown (no host credentials)",
1222
+ "no-live-deployment": "none (nothing receives production traffic)",
1223
+ "not-linked": "unknown (not linked)",
1224
+ "offline": "not checked (--offline)",
1225
+ "timeout": "unknown (the host did not answer in time)"
1226
+ };
1227
+ const unknownLabels = {
1228
+ "commit-not-local": "commit not in this repository",
1229
+ "no-git": "no git repository",
1230
+ "no-marker": "no commit marker"
1231
+ };
1232
+ function plural(count, word) {
1233
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
1234
+ }
1235
+ /** The `live` line of `vitehub status`, such as `abc1234 (3 commits behind)`. */
1236
+ function liveLabel(status) {
1237
+ const { live } = status;
1238
+ if (!live) return reasonLabels[status.liveReason ?? "no-live-deployment"];
1239
+ const name = live.commit ? live.commit.sha.slice(0, 7) : live.deploymentId;
1240
+ const notes = [];
1241
+ if (live.unknownReason) notes.push(unknownLabels[live.unknownReason]);
1242
+ else if (live.ahead || live.behind) notes.push([live.behind ? `${plural(live.behind, "commit")} behind` : "", live.ahead ? `${plural(live.ahead, "commit")} ahead` : ""].filter(Boolean).join(", "));
1243
+ else notes.push("up to date");
1244
+ if (live.commit?.dirty) notes.push("with uncommitted changes");
1245
+ return `${name} (${notes.join(", ")})${live.url ? ` ${live.url}` : ""}`;
1246
+ }
1247
+ //#endregion
1248
+ //#region src/setup/deploy/provision.ts
1249
+ /** A step whose recorded state declares nothing has no resource to create, so deploy does not ask the host. */
1250
+ function declaresResources(step, env) {
1251
+ const described = step.recordedState?.({ env });
1252
+ return described === void 0 || described.some((category) => category.declared.length > 0);
1253
+ }
1254
+ /** Says which credential the steps miss, for the reason of SETUP_DEPLOY_PROVISION_UNCHECKED. */
1255
+ function missingCredential(host, env) {
1256
+ if (host === "cloudflare" && !env.CLOUDFLARE_ACCOUNT_ID?.trim()) return "Set CLOUDFLARE_ACCOUNT_ID, or run `vitehub link --host cloudflare --account <id>`. A `wrangler login` with several accounts does not say which one to use.";
1257
+ if (host === "vercel" && !env.VERCEL_TOKEN?.trim()) return "A saved `vercel login` cannot create Vercel resources. Set VERCEL_TOKEN to a token from https://vercel.com/account/tokens.";
1258
+ if (host === "vercel" && !env.VERCEL_PROJECT_ID?.trim()) return "Run `vitehub link --host vercel` to store the project id, or set VERCEL_PROJECT_ID.";
1259
+ return "Fix the cause of the warnings.";
1260
+ }
1261
+ async function confirmProvision(count, host) {
1262
+ const terminal = createInterface({
1263
+ input: process.stdin,
1264
+ output: process.stderr
1265
+ });
1266
+ try {
1267
+ return /^y(?:es)?$/iu.test((await terminal.question(`Create or change ${count} ${count === 1 ? "resource" : "resources"} on ${host}? [y/N] `)).trim());
1268
+ } finally {
1269
+ terminal.close();
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Runs the Provision Steps of `host` before the build, with the credentials that deploy resolved, such as a
1274
+ * `wrangler login`. It creates missing resources and records their ids in `.vitehub/provision.json`, so the build
1275
+ * binds them and a second deploy creates nothing. Returns undefined when the host has no step with a resource.
1276
+ */
1277
+ async function provisionForDeploy(input, context) {
1278
+ const { host } = input;
1279
+ if (!isProvisionHost(host) || !context.loadProvision) return;
1280
+ const env = provisionEnv(context.env, input.credentials, {
1281
+ ...input.link?.account?.id ? { accountId: input.link.account.id } : {},
1282
+ ...input.link?.project.id ? { projectId: input.link.project.id } : {}
1283
+ });
1284
+ const loaded = await context.loadProvision(host);
1285
+ const steps = loaded.steps.filter((step) => step.provider === host && declaresResources(step, env));
1286
+ if (!steps.length) return;
1287
+ const root = loaded.rootDir;
1288
+ await readProvisionState(root);
1289
+ const plan = await planProvisionSteps(host, steps, {
1290
+ env,
1291
+ fetch: context.fetch ?? globalThis.fetch,
1292
+ logger: {
1293
+ log: (message) => context.stderr.write(`${message}\n`),
1294
+ warn: (message) => context.stderr.write(`${message}\n`)
1295
+ }
1296
+ });
1297
+ if (!plan.checked) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PROVISION_UNCHECKED({
1298
+ host,
1299
+ missing: missingCredential(host, env),
1300
+ warnings: plan.warnings.join(" ")
1301
+ }), setupExitCodes.inputNeeded, { rerun: input.rerun });
1302
+ const changes = plan.actions.flatMap((planned) => {
1303
+ const status = provisionActionStatus(planned);
1304
+ return status === "exists" ? [] : [{
1305
+ planned,
1306
+ status
1307
+ }];
1308
+ });
1309
+ if (changes.length && !input.build) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PROVISION_NEEDS_BUILD({
1310
+ count: changes.length,
1311
+ host
1312
+ }), setupExitCodes.conflict);
1313
+ if (changes.length) {
1314
+ if (!input.json) {
1315
+ context.stdout.write(`Provision on ${host}:\n`);
1316
+ writeProvisionActions(changes.map((change) => change.planned), context.stdout);
1317
+ }
1318
+ if (!input.yes && !await confirmProvision(changes.length, host)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The resources were not confirmed. Nothing was created or deployed." }), setupExitCodes.error);
1319
+ }
1320
+ let state = {};
1321
+ try {
1322
+ for (const { action } of plan.actions) {
1323
+ const result = await action.apply();
1324
+ if (result.ids) state = mergeProvisionState(state, result.ids);
1325
+ }
1326
+ } finally {
1327
+ if (Object.keys(state).length) await writeProvisionState(root, state);
1328
+ }
1329
+ if (changes.length && !input.json) context.stdout.write(`Provisioned ${changes.length} ${changes.length === 1 ? "resource" : "resources"} on ${host}. Ids are in ${PROVISION_STATE_FILE}.\n`);
1330
+ return {
1331
+ changed: changes.map(({ planned, status }) => ({
1332
+ kind: planned.action.kind,
1333
+ name: planned.action.name,
1334
+ status,
1335
+ step: planned.step
1336
+ })),
1337
+ ids: state[host] ?? {}
1338
+ };
1339
+ }
1340
+ //#endregion
1341
+ //#region src/setup/deploy.ts
1342
+ const deployHosts = [
1343
+ "cloudflare",
1344
+ "vercel",
1345
+ "netlify",
1346
+ "deno"
1347
+ ];
1348
+ const temporaryHosts = ["cloudflare", "vercel"];
1349
+ const usage$2 = "vitehub deploy [--host <host>] [--preview] [--push-env] [--no-build] [--no-provision] [--no-push] [--no-check] [--no-index-now] [--temporary] [--yes] [--json]";
1350
+ const help = `--host picks a host target of .vitehub/link.json. Without it, deploy uses the default target. The build runs
1351
+ with VITEHUB_HOST set to that host, which wins over \`host\` in vitehub(). Each host has its own resources, such as D1,
1352
+ KV, R2, and libSQL.
1353
+
1354
+ On Cloudflare and Vercel, deploy first creates the missing resources of the app, such as D1, KV, R2, Queues, and Vercel
1355
+ Blob, with the same login, and records their ids in .vitehub/provision.json. The build binds those ids, and a second
1356
+ deploy creates nothing. It lists what it creates and asks first, unless you pass --yes. --no-provision skips it.
1357
+
1358
+ With checkout folders in vitehub.lock, a production deploy pulls them and checks for conflicts before the build, and
1359
+ pushes them after the deploy, as \`vitehub push\` does. A --preview deploy does not push, so a preview never writes
1360
+ the shared Workspace ref. --no-push skips the pull, the check and the push.
1361
+
1362
+ After the build, deploy checks the env names that the build lists. A production deploy reads stage production, a
1363
+ --preview deploy stage preview: the shell, then .env.<stage> files. Each required name must be on the host or have a
1364
+ local value, or nothing is deployed. Deploy sets the names that the host lacks from their local values; --push-env
1365
+ also replaces the names that the host has. Cloudflare gets the values with the new version through --secrets-file.
1366
+ Cloudflare always re-supplies local stage values and needs a local value for every existing Worker secret, so an
1367
+ omitted secret cannot inherit from another stage. With --yes, a missing VITEHUB_SECRET is generated and set.
1368
+
1369
+ After the upload, deploy requests the paths of \`deploy.check\` in vitehub(), and the health route with \`health\`, on
1370
+ the deployed URL. When one does not answer with a 2xx status, deploy exits with 1 and prints the command that rolls
1371
+ production back to the deployment it replaced. --no-check skips the checks. With \`deploy.indexNow\`, a production
1372
+ deploy that passed its checks then sends the URLs of /sitemap.xml to IndexNow. --no-index-now skips it.
1373
+ `;
1374
+ function readDeployArgs(args) {
1375
+ try {
1376
+ const { values } = parseArgs({
1377
+ args: [...args],
1378
+ options: {
1379
+ "help": {
1380
+ short: "h",
1381
+ type: "boolean",
1382
+ default: false
1383
+ },
1384
+ "host": { type: "string" },
1385
+ "json": {
1386
+ type: "boolean",
1387
+ default: false
1388
+ },
1389
+ "no-build": {
1390
+ type: "boolean",
1391
+ default: false
1392
+ },
1393
+ "no-check": {
1394
+ type: "boolean",
1395
+ default: false
1396
+ },
1397
+ "no-index-now": {
1398
+ type: "boolean",
1399
+ default: false
1400
+ },
1401
+ "no-provision": {
1402
+ type: "boolean",
1403
+ default: false
1404
+ },
1405
+ "no-push": {
1406
+ type: "boolean",
1407
+ default: false
1408
+ },
1409
+ "preview": {
1410
+ type: "boolean",
1411
+ default: false
1412
+ },
1413
+ "push-env": {
1414
+ type: "boolean",
1415
+ default: false
1416
+ },
1417
+ "temporary": {
1418
+ type: "boolean",
1419
+ default: false
1420
+ },
1421
+ "yes": {
1422
+ short: "y",
1423
+ type: "boolean",
1424
+ default: false
1425
+ }
1426
+ },
1427
+ strict: true
1428
+ });
1429
+ return {
1430
+ build: !values["no-build"],
1431
+ check: !values["no-check"],
1432
+ help: values.help,
1433
+ indexNow: !values["no-index-now"],
1434
+ ...values.host === void 0 ? {} : { host: values.host },
1435
+ json: values.json,
1436
+ preview: values.preview,
1437
+ pushEnv: values["push-env"],
1438
+ provision: !values["no-provision"],
1439
+ push: !values["no-push"],
1440
+ temporary: values.temporary,
1441
+ yes: values.yes
1442
+ };
1443
+ } catch (error) {
1444
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage$2}` });
1445
+ }
1446
+ }
1447
+ function rerunCommand$1(args, extra = {}) {
1448
+ return [
1449
+ "vitehub deploy",
1450
+ ...args.host ? [`--host ${args.host}`] : [],
1451
+ ...args.preview ? ["--preview"] : [],
1452
+ ...args.pushEnv ? ["--push-env"] : [],
1453
+ ...args.build ? [] : ["--no-build"],
1454
+ ...args.provision && extra.provision !== false ? [] : ["--no-provision"],
1455
+ ...args.push ? [] : ["--no-push"],
1456
+ ...args.check ? [] : ["--no-check"],
1457
+ ...args.indexNow ? [] : ["--no-index-now"],
1458
+ ...args.temporary || extra.temporary ? ["--temporary"] : [],
1459
+ "--yes",
1460
+ ...args.json ? ["--json"] : []
1461
+ ].join(" ");
1462
+ }
1463
+ function supportedHost(host) {
1464
+ const found = deployHosts.find((item) => item === host);
1465
+ if (!found) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_HOST_UNSUPPORTED({ host }), setupExitCodes.conflict);
1466
+ return found;
1467
+ }
1468
+ /** `--host`, else the default target, else the only target, else the config host. The CLI host wins over the config. */
1469
+ function deployTarget(project, links, option, env) {
1470
+ if (option !== void 0) {
1471
+ const named = hostFromNitroPreset(option);
1472
+ if (!named) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown host ${JSON.stringify(option)}. Use cloudflare, vercel, netlify, or deno. Usage: ${usage$2}` });
1473
+ const host = supportedHost(named);
1474
+ return {
1475
+ host,
1476
+ link: links.targets.find((target) => target.host === host)
1477
+ };
1478
+ }
1479
+ const selected = selectSetupLink(links);
1480
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, "vitehub deploy");
1481
+ if (selected.link) return {
1482
+ host: selected.link.host,
1483
+ link: selected.link
1484
+ };
1485
+ return {
1486
+ host: supportedHost(setupStatus(project, env).host.name),
1487
+ link: void 0
1488
+ };
1489
+ }
1490
+ function temporaryUnsupported(reason) {
1491
+ return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_TEMPORARY_UNSUPPORTED({ reason }), setupExitCodes.conflict);
1492
+ }
1493
+ /** Cloudflare: Wrangler refuses `--temporary` with a login. Vercel: the CLI refuses it in CI and in a linked folder. */
1494
+ function assertTemporary(host, args, credentials, project, env) {
1495
+ if (!temporaryHosts.includes(host)) throw temporaryUnsupported(`${host} has no temporary deploy. Only cloudflare and vercel have one.`);
1496
+ if (args.preview) throw temporaryUnsupported("A temporary deploy always goes to production, so --preview does not apply.");
1497
+ if (credentials.ok) throw temporaryUnsupported(`It is for a machine without a ${host} login, and credentials were found (${credentials.source}).`);
1498
+ if (host === "vercel") {
1499
+ if (env.CI && env.CI !== "0" && env.CI !== "false") throw temporaryUnsupported("The Vercel CLI refuses temporary deploys in CI.");
1500
+ if (existsSync(join(project.root, ".vercel", "project.json"))) throw temporaryUnsupported("The folder is linked to a Vercel project in .vercel/project.json.");
1501
+ }
1502
+ }
1503
+ function credentialsMissing(host, credentials, args) {
1504
+ const temporary = temporaryHosts.includes(host);
1505
+ const offer = temporary ? ` Or deploy without an account: run \`${rerunCommand$1(args, { temporary: true })}\`${host === "cloudflare" ? " and claim the Worker within 60 minutes" : " and claim the deployment with the link that it prints"}.` : "";
1506
+ return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CREDENTIALS_MISSING({
1507
+ fix: `${credentials.fix}${offer}`,
1508
+ host
1509
+ }), setupExitCodes.inputNeeded, {
1510
+ missing: credentials.missing.map((field) => ({ field })),
1511
+ ...temporary ? { rerun: rerunCommand$1(args, { temporary: true }) } : {}
1512
+ });
1513
+ }
1514
+ async function confirmDeploy(name, host, preview) {
1515
+ const terminal = createInterface({
1516
+ input: process.stdin,
1517
+ output: process.stderr
1518
+ });
1519
+ try {
1520
+ return /^y(?:es)?$/iu.test((await terminal.question(`Deploy ${name} to ${host}${preview ? " as a preview" : " production"}? [y/N] `)).trim());
1521
+ } finally {
1522
+ terminal.close();
1523
+ }
1524
+ }
1525
+ async function hostAdapter(host, context) {
1526
+ switch (host) {
1527
+ case "cloudflare": return await cloudflareAdapter(context);
1528
+ case "vercel": return vercelAdapter(context);
1529
+ case "netlify": return netlifyAdapter(context);
1530
+ case "deno": return await denoAdapter(context, denoOrganization(context.link, context.env));
1531
+ }
1532
+ }
1533
+ /** Records the host project after a first deploy, so `status` finds it. It stays unverified until `vitehub link`. */
1534
+ async function recordLink(root, host, result, fallbackName) {
1535
+ const project = result.project ?? { name: fallbackName };
1536
+ await addSetupLink(root, {
1537
+ host,
1538
+ ...project.accountId ? { account: { id: project.accountId } } : {},
1539
+ project: {
1540
+ ...project.id ? { id: project.id } : {},
1541
+ name: project.name
1542
+ },
1543
+ verified: false,
1544
+ linkedAt: (/* @__PURE__ */ new Date()).toISOString()
1545
+ });
1546
+ await ensureViteHubGitignore(root);
1547
+ }
1548
+ function writeDeployed(output, name, context) {
1549
+ context.stdout.write(`Deployed ${name} to ${output.host}: ${output.url}\n`);
1550
+ if (output.deploymentId) context.stdout.write(`Deployment: ${output.deploymentId}\n`);
1551
+ if (output.version) context.stdout.write(`Version: ${output.version}\n`);
1552
+ if (output.commit) context.stdout.write(`Commit: ${output.commit.sha}${output.commit.dirty ? " (with uncommitted changes)" : ""}\n`);
1553
+ for (const check of output.checks ?? []) context.stdout.write(`Checked ${check.path}: ${check.status ?? check.error}\n`);
1554
+ if (output.temporary) {
1555
+ const window = output.host === "cloudflare" ? "within 60 minutes" : output.temporary.expiresAt ? `before ${output.temporary.expiresAt}` : "soon";
1556
+ context.stdout.write(`This is a temporary deploy. Claim it ${window}, or the host deletes it. Do not share the claim link:\n${output.temporary.claimUrl}\n`);
1557
+ }
1558
+ }
1559
+ /** Pushes the checkout folders after the deploy. A failed push does not undo the deploy, so it exits with 1 and says so. */
1560
+ async function pushCheckouts(checkouts, deployed, args, context) {
1561
+ try {
1562
+ const pushed = await pushDeployCheckouts(checkouts, context);
1563
+ if (!args.json) context.stdout.write(formatDeployCheckouts(pushed));
1564
+ return {
1565
+ ...deployed,
1566
+ checkouts: pushed
1567
+ };
1568
+ } catch (error) {
1569
+ const failure = checkoutPushError(error);
1570
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PUSH_FAILED({
1571
+ fix: failure.fix,
1572
+ message: `${failure.code}: ${failure.message}`,
1573
+ url: deployed.url
1574
+ }), setupExitCodes.error, {
1575
+ data: {
1576
+ ...deployed,
1577
+ checkouts: { error: failure }
1578
+ },
1579
+ rerun: "vitehub push"
1580
+ });
1581
+ }
1582
+ }
1583
+ async function runDeploy(args, context) {
1584
+ const project = await readSetupProject(context.rootDir, context.env);
1585
+ const links = await readSetupLinks(project.root);
1586
+ const { host, link } = deployTarget(project, links, args.host, context.env);
1587
+ if (args.preview && host === "deno") throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PREVIEW_UNSUPPORTED({ host }), setupExitCodes.conflict);
1588
+ const credentials = await resolveHostCredentials(host, {
1589
+ cwd: project.root,
1590
+ env: context.env,
1591
+ ...context.runHostCli ? { run: context.runHostCli } : {}
1592
+ });
1593
+ const vercelLogin = host === "vercel" && !credentials.ok && await hasVercelLogin(project.root, context);
1594
+ if (args.temporary && vercelLogin) throw temporaryUnsupported("It is for a machine without a vercel login, and a saved CLI login was found.");
1595
+ if (args.temporary) assertTemporary(host, args, credentials, project, context.env);
1596
+ else if (!credentials.ok && !vercelLogin) throw credentialsMissing(host, credentials, args);
1597
+ const interactive = !args.json && !!process.stdin.isTTY && !!process.stderr.isTTY;
1598
+ if (!args.yes) {
1599
+ if (!interactive) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub deploy` publishes the app and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, { rerun: rerunCommand$1(args) });
1600
+ if (!await confirmDeploy(link?.project.name ?? basename(project.root), host, args.preview)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The deploy was not confirmed. Nothing was deployed." }), setupExitCodes.error);
1601
+ }
1602
+ const provisioned = args.provision && !args.temporary ? await provisionForDeploy({
1603
+ build: args.build,
1604
+ credentials,
1605
+ host,
1606
+ json: args.json,
1607
+ link,
1608
+ rerun: rerunCommand$1(args, { provision: false }),
1609
+ yes: args.yes
1610
+ }, context) : void 0;
1611
+ const checkouts = args.push && !args.preview ? await prepareDeployCheckouts(project.root, context) : void 0;
1612
+ if (!link && !args.temporary) writeSeparateResourcesNote(context, host, links);
1613
+ if (args.build) await build(project, host, context);
1614
+ const output = await readBuildOutput(project.root, host);
1615
+ const projectName = link?.project.name ?? output.identityName;
1616
+ if (!projectName) throw setupFailure(cliErrorDiagnostics.SETUP_LINK_NAME_REQUIRED(), setupExitCodes.inputNeeded, {
1617
+ missing: [{ field: "project" }],
1618
+ rerun: "vitehub link --project <name>"
1619
+ });
1620
+ const secrets = credentials.ok ? [credentials.token] : [];
1621
+ const run = createDeployRun(context.stderr, secrets);
1622
+ const env = await checkDeployEnv({
1623
+ context,
1624
+ entries: output.env,
1625
+ envDir: output.envDir,
1626
+ host,
1627
+ interactive,
1628
+ link: args.temporary ? void 0 : link,
1629
+ outputDir: output.outputDir,
1630
+ preview: args.preview,
1631
+ pushEnv: args.pushEnv,
1632
+ root: project.root,
1633
+ run,
1634
+ secrets,
1635
+ yes: args.yes
1636
+ });
1637
+ const deployContext = {
1638
+ commit: await readDeployCommit(run, project.root, context.env),
1639
+ credentials,
1640
+ env: context.env,
1641
+ fetch: context.fetch ?? globalThis.fetch,
1642
+ link,
1643
+ outputDir: output.outputDir,
1644
+ preview: args.preview,
1645
+ projectName,
1646
+ root: project.root,
1647
+ run,
1648
+ secrets,
1649
+ temporary: args.temporary,
1650
+ upload: env.upload
1651
+ };
1652
+ const adapter = await hostAdapter(host, deployContext);
1653
+ await env.apply();
1654
+ const checkPaths = args.check ? output.deploy.check : [];
1655
+ const previous = checkPaths.length && !args.preview && !args.temporary ? await previousDeployment(project.root, link, credentials, context, run) : void 0;
1656
+ const result = await adapter.deploy();
1657
+ if (!link && !args.temporary) await recordLink(project.root, host, result, projectName);
1658
+ const checks = checkPaths.length ? await runDeployChecks(result.url, checkPaths, deployContext.fetch) : void 0;
1659
+ const deployed = {
1660
+ host,
1661
+ url: result.url,
1662
+ ...result.deploymentId ? { deploymentId: result.deploymentId } : {},
1663
+ ...result.version ? { version: result.version } : {},
1664
+ ...result.claim ? { temporary: {
1665
+ claimUrl: result.claim.url,
1666
+ ...result.claim.expiresAt ? { expiresAt: result.claim.expiresAt } : {}
1667
+ } } : {},
1668
+ ...deployContext.commit ? { commit: deployContext.commit } : {},
1669
+ env: env.output,
1670
+ ...provisioned ? { provision: provisioned } : {},
1671
+ ...checks ? { checks } : {}
1672
+ };
1673
+ if (checks?.some((check) => !check.ok)) throw checkFailed(deployed, host, previous, projectName, link, result, args.preview);
1674
+ if (!args.json) writeDeployed(deployed, projectName, context);
1675
+ const pushed = checkouts ? await pushCheckouts(checkouts, deployed, args, context) : deployed;
1676
+ const indexNow = output.deploy.indexNow && args.indexNow && !args.preview && !args.temporary ? await submitIndexNow(output.deploy.indexNow, deployContext.fetch) : void 0;
1677
+ if (indexNow && !args.json) context.stderr.write("submitted" in indexNow ? `IndexNow: sent ${indexNow.submitted} URLs (${indexNow.status}).\n` : `IndexNow: nothing was sent. ${indexNow.error} The deploy is done.\n`);
1678
+ const final = indexNow ? {
1679
+ ...pushed,
1680
+ indexNow
1681
+ } : pushed;
1682
+ if (args.json) writeSetupJson(context, final);
1683
+ return setupExitCodes.done;
1684
+ }
1685
+ /** The deployment that serves production before this deploy. Without a link or a token there is nothing to read. */
1686
+ async function previousDeployment(root, link, credentials, context, run) {
1687
+ if (!link) return { failed: "the project was not linked before this deploy." };
1688
+ if (!credentials.ok) return { failed: `deploy used the saved ${link.host} CLI login, which gives no API token.` };
1689
+ try {
1690
+ return { deployment: await readLiveDeployment(root, link, credentials, context, run) };
1691
+ } catch (error) {
1692
+ return { failed: error instanceof Error ? error.message : String(error) };
1693
+ }
1694
+ }
1695
+ /** A deployed app that failed a check. Production now serves it, so the error says how to roll back. */
1696
+ function checkFailed(deployed, host, previous, projectName, link, result, preview) {
1697
+ const rollback = preview ? { note: "This was a preview deploy, so production did not change." } : rollbackFor(host, {
1698
+ previous: previous && "deployment" in previous ? previous.deployment : void 0,
1699
+ projectName: link?.project.name ?? result.project?.name ?? projectName,
1700
+ ...previous && "failed" in previous ? { lookupFailed: previous.failed } : {},
1701
+ ...host === "netlify" && (link?.project.id ?? result.project?.id) ? { siteId: link?.project.id ?? result.project?.id } : {}
1702
+ });
1703
+ const failure = cliErrorDiagnostics.SETUP_DEPLOY_CHECK_FAILED({
1704
+ failed: formatFailedChecks(deployed.checks ?? []),
1705
+ rollback: rollback.command ? `Run \`${rollback.command}\` to put the previous deployment back on production.` : rollback.note,
1706
+ url: deployed.url
1707
+ });
1708
+ return setupFailure(failure, setupExitCodes.error, { data: {
1709
+ ...deployed,
1710
+ rollback
1711
+ } });
1712
+ }
1713
+ const deployCommand = {
1714
+ description: "Create the missing host resources, build the app for a linked host, check its env, and deploy it with your local login. --host picks the host. Pushes the checkout folders of vitehub.lock.",
1715
+ name: "deploy",
1716
+ run: async (args, context) => {
1717
+ const json = args.includes("--json");
1718
+ try {
1719
+ const parsed = readDeployArgs(args);
1720
+ if (parsed.help) {
1721
+ context.stdout.write(`Usage: ${usage$2}\n\n${deployCommand.description}\n\n${help}`);
1722
+ return setupExitCodes.done;
1723
+ }
1724
+ return await runDeploy(parsed, context);
1725
+ } catch (error) {
1726
+ return writeSetupError(context, json, error);
1727
+ }
1728
+ },
1729
+ usage: usage$2
1730
+ };
1731
+ //#endregion
1732
+ //#region src/setup/init.ts
1733
+ const usage$1 = "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]";
1734
+ /** The command that starts a project. It runs from the `vite-hub` package, so it needs no install. */
1735
+ const initCommandPrefix = "pnpm dlx vite-hub init";
1736
+ const initHosts = [
1737
+ "cloudflare",
1738
+ "vercel",
1739
+ "netlify",
1740
+ "deno",
1741
+ "node"
1742
+ ];
1743
+ const frameworks = ["vite", "nuxt"];
1744
+ const packageManagers = [
1745
+ "pnpm",
1746
+ "npm",
1747
+ "yarn",
1748
+ "bun"
1749
+ ];
1750
+ /**
1751
+ * The packages of a new app, as `getting-started/installation.md` installs them. The Nitro and H3 versions match the
1752
+ * server integration of ViteHub. Nuxt 5 supplies Nitro 3, and its tutorials import H3 2. Valibot validates request
1753
+ * bodies in the docs' route examples.
1754
+ */
1755
+ const initPackages = {
1756
+ nuxt: {
1757
+ dev: [],
1758
+ prod: [
1759
+ "vite-hub",
1760
+ "h3@^2.0.8",
1761
+ "valibot"
1762
+ ]
1763
+ },
1764
+ vite: {
1765
+ dev: [
1766
+ "vite@^8",
1767
+ "typescript@^6",
1768
+ "@types/node@^24"
1769
+ ],
1770
+ prod: [
1771
+ "vite-hub",
1772
+ "nitro@3.0.261102-rc",
1773
+ "h3@2.0.8",
1774
+ "valibot"
1775
+ ]
1776
+ }
1777
+ };
1778
+ /** The pinned Nuxt CLI that creates a new Nuxt app. */
1779
+ const nuxiPackage = "nuxi@3.37.0";
1780
+ /** Pin the starter files and select Nuxt 5 explicitly instead of the live minimal registry entry. */
1781
+ const nuxtTemplate = "gh:nuxt/starter#db01806fcb37f2e369fb09443c72cac696b31548";
1782
+ /** Where the reproducing command lives in README.md. */
1783
+ const stackStart = "<!-- vitehub:stack -->";
1784
+ const stackEnd = "<!-- /vitehub:stack -->";
1785
+ function isRecord(value) {
1786
+ return !!value && typeof value === "object" && !Array.isArray(value);
1787
+ }
1788
+ function invalid$1(message) {
1789
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$1}` });
1790
+ }
1791
+ function oneOf(flag, value, choices) {
1792
+ const found = choices.find((choice) => choice === value);
1793
+ if (!found) throw invalid$1(`${flag} must be one of ${choices.join(", ")}, not ${JSON.stringify(value)}.`);
1794
+ return found;
1795
+ }
1796
+ /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or value. */
1797
+ function readInitArgs(args) {
1798
+ const parsed = {
1799
+ dryRun: false,
1800
+ help: false,
1801
+ install: true,
1802
+ json: false,
1803
+ options: [],
1804
+ yes: false
1805
+ };
1806
+ let features;
1807
+ for (let index = 0; index < args.length; index++) {
1808
+ const arg = args[index];
1809
+ const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, void 0];
1810
+ const value = () => {
1811
+ const next = inline ?? args[++index];
1812
+ if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$1(`${flag} needs a value.`);
1813
+ return next;
1814
+ };
1815
+ if (flag === "--json") parsed.json = true;
1816
+ else if (flag === "--dry-run") parsed.dryRun = true;
1817
+ else if (flag === "--yes" || flag === "-y") parsed.yes = true;
1818
+ else if (flag === "--no-install") parsed.install = false;
1819
+ else if (flag === "-h" || flag === "--help") parsed.help = true;
1820
+ else if (flag === "--host") parsed.host = oneOf("--host", value(), initHosts);
1821
+ else if (flag === "--features") features = value();
1822
+ else if (flag === "--option") parsed.options.push(value());
1823
+ else if (flag === "--framework") parsed.framework = oneOf("--framework", value(), frameworks);
1824
+ else if (flag === "--pm") parsed.pm = oneOf("--pm", value(), packageManagers);
1825
+ else if (arg.startsWith("-")) throw invalid$1(`Unknown argument ${JSON.stringify(arg)}.`);
1826
+ else if (parsed.dir === void 0) parsed.dir = arg;
1827
+ else throw invalid$1(`Pass one folder, not ${JSON.stringify(parsed.dir)} and ${JSON.stringify(arg)}.`);
1828
+ }
1829
+ if (features !== void 0) parsed.features = readAddArgs(features.split(",").map((item) => item.trim()).filter(Boolean)).features;
1830
+ return parsed;
1831
+ }
1832
+ /** The `vitehub add` arguments for the features and options of `init`. */
1833
+ function addArgsOf(args) {
1834
+ return {
1835
+ ...readAddArgs([...args.features, ...args.options.flatMap((option) => ["--option", option])]),
1836
+ install: true,
1837
+ yes: true
1838
+ };
1839
+ }
1840
+ function initCommand(parts, extra) {
1841
+ const options = parts.options ?? [];
1842
+ return [
1843
+ initCommandPrefix,
1844
+ shellQuote(parts.dir),
1845
+ "--host",
1846
+ parts.host ?? "<host>",
1847
+ "--features",
1848
+ parts.features ? parts.features.join(",") || "''" : "<id,id,...>",
1849
+ ...options.flatMap((option) => ["--option", shellQuote(option)]),
1850
+ ...parts.framework === "nuxt" ? ["--framework", "nuxt"] : [],
1851
+ ...parts.pm && parts.pm !== "pnpm" ? ["--pm", parts.pm] : [],
1852
+ ...extra
1853
+ ].join(" ");
1854
+ }
1855
+ /** The command that creates the same stack, for README.md and `vitehub status`. */
1856
+ function stackCommand(parts) {
1857
+ return initCommand(parts, ["--yes"]);
1858
+ }
1859
+ /** The `rerun` command: the same request with `--yes`. */
1860
+ function rerunInit(args, parts) {
1861
+ return initCommand(parts, [
1862
+ ...args.install ? [] : ["--no-install"],
1863
+ "--yes",
1864
+ ...args.json ? ["--json"] : []
1865
+ ]);
1866
+ }
1867
+ function stackBlock(command) {
1868
+ return `${stackStart}\nCreate the same stack with:\n\n\`\`\`sh\n${command}\n\`\`\`\n${stackEnd}\n`;
1869
+ }
1870
+ /** README.md with the stack block, or undefined when it already holds the same block. */
1871
+ function readmeWithStack(readme, name, command) {
1872
+ const block = stackBlock(command);
1873
+ if (readme === void 0) return `# ${name}\n\n${block}`;
1874
+ const from = readme.indexOf(stackStart);
1875
+ const to = readme.indexOf(stackEnd, from);
1876
+ if (from !== -1 && to !== -1) {
1877
+ const after = readme.slice(to + 23).replace(/^\r?\n/u, "");
1878
+ return `${readme.slice(0, from)}${block}${after}`;
1879
+ }
1880
+ return `${readme}${readme === "" || readme.endsWith("\n") ? "" : "\n"}\n${block}`;
1881
+ }
1882
+ /** The stack command in the README.md block of `root`, for `vitehub status`. `null` when there is no block. */
1883
+ async function readSetupStack(root) {
1884
+ const file = join(root, "README.md");
1885
+ if (!existsSync(file)) return null;
1886
+ const readme = await readFile(file, "utf8");
1887
+ const from = readme.indexOf(stackStart);
1888
+ const to = readme.indexOf(stackEnd, from);
1889
+ if (from === -1 || to === -1) return null;
1890
+ const command = readme.slice(from, to).split(/\r?\n/u).map((line) => line.trim()).find((line) => line.startsWith(initCommandPrefix));
1891
+ return command ? { command } : null;
1892
+ }
1893
+ /** The deployment name rules of `vitehub({ name })`, for the package.json name of a new app. */
1894
+ function packageNameOf(root) {
1895
+ return basename(root).trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || "vitehub-app";
1896
+ }
1897
+ /** The files of a new Vite app, as `fixtures/docs-hosts/installation` has them. */
1898
+ function viteAppFiles(name, host) {
1899
+ return {
1900
+ ".gitignore": "node_modules\n.output\n.vitehub\n.env*\n!.env.example\n",
1901
+ "package.json": `${JSON.stringify({
1902
+ name,
1903
+ private: true,
1904
+ type: "module",
1905
+ scripts: {
1906
+ dev: "vite --port 3000 --strictPort",
1907
+ build: "vite build",
1908
+ start: "node .output/server/index.mjs"
1909
+ }
1910
+ }, null, 2)}\n`,
1911
+ "server/api/health.get.ts": "import { defineEventHandler } from \"h3\"\n\nexport default defineEventHandler(() => ({ ok: true }))\n",
1912
+ "tsconfig.json": `{
1913
+ "extends": ["vite-hub/tsconfig"],
1914
+ "compilerOptions": {
1915
+ "target": "ES2022",
1916
+ "module": "ESNext",
1917
+ "moduleResolution": "Bundler",
1918
+ "strict": true,
1919
+ "noEmit": true,
1920
+ "skipLibCheck": true,
1921
+ "types": ["node"]
1922
+ },
1923
+ "include": ["server/**/*.ts", "vite.config.ts"]
1924
+ }
1925
+ `,
1926
+ "vite.config.ts": `import { defineConfig } from "vite"\nimport { vitehub } from "vite-hub"\n\nexport default defineConfig({\n plugins: [vitehub({ host: "${host}" })],\n})\n`
1927
+ };
1928
+ }
1929
+ /** The config that `nuxi init` and the adoption would give, to plan a new Nuxt app before `nuxi init` runs. */
1930
+ function nuxtAppFiles(name, host) {
1931
+ return {
1932
+ "nuxt.config.ts": `import viteHubNuxt from "vite-hub/nuxt"\n\nexport default defineNuxtConfig({\n modules: [\n [viteHubNuxt, { host: "${host}" }],\n ],\n})\n`,
1933
+ "package.json": `${JSON.stringify({
1934
+ name,
1935
+ private: true,
1936
+ type: "module"
1937
+ }, null, 2)}\n`
1938
+ };
1939
+ }
1940
+ function packageName$1(spec) {
1941
+ const at = spec.indexOf("@", 1);
1942
+ return at === -1 ? spec : spec.slice(0, at);
1943
+ }
1944
+ function dlx(packageManager, spec, args) {
1945
+ if (packageManager === "npm" || packageManager === "yarn") return ["npx", [
1946
+ "--yes",
1947
+ spec,
1948
+ ...args
1949
+ ]];
1950
+ if (packageManager === "bun") return ["bunx", [spec, ...args]];
1951
+ return [packageManager, [
1952
+ "dlx",
1953
+ spec,
1954
+ ...args
1955
+ ]];
1956
+ }
1957
+ function runScript(packageManager, script) {
1958
+ return packageManager === "npm" || packageManager === "bun" ? `${packageManager} run ${script}` : `${packageManager} ${script}`;
1959
+ }
1960
+ async function readDir(root, env) {
1961
+ if (!existsSync(root)) return {
1962
+ exists: false,
1963
+ kind: "create"
1964
+ };
1965
+ if (!(await readdir(root)).filter((entry) => entry !== ".git").length) return {
1966
+ exists: true,
1967
+ kind: "create"
1968
+ };
1969
+ const project = await readSetupProject(root, env).catch(() => void 0);
1970
+ if (!project || project.framework === "none") throw setupFailure(cliErrorDiagnostics.SETUP_INIT_DIR_NOT_EMPTY({ dir: root }), setupExitCodes.conflict);
1971
+ return {
1972
+ kind: "adopt",
1973
+ project
1974
+ };
1975
+ }
1976
+ function changeOf(path, before, after) {
1977
+ return before === void 0 ? {
1978
+ after,
1979
+ diff: setupDiff(path, "", after),
1980
+ kind: "create",
1981
+ path
1982
+ } : {
1983
+ after,
1984
+ before,
1985
+ diff: setupDiff(path, before, after),
1986
+ kind: "patch",
1987
+ path
1988
+ };
1989
+ }
1990
+ async function readOptional(file) {
1991
+ return existsSync(file) ? await readFile(file, "utf8") : void 0;
1992
+ }
1993
+ function manualConfig(file, reason, host, framework) {
1994
+ const snippet = framework === "nuxt" ? `[viteHubNuxt, { host: "${host}" }],` : `vitehub({ host: "${host}" }),`;
1995
+ return setupFailure(cliErrorDiagnostics.SETUP_CONFIG_MANUAL({
1996
+ file,
1997
+ reason,
1998
+ snippet
1999
+ }), setupExitCodes.conflict, { data: { snippet } });
2000
+ }
2001
+ /** The config of an existing app with ViteHub registered on `host`. */
2002
+ function adoptConfig(project, host, framework) {
2003
+ const file = project.configFile ?? (framework === "nuxt" ? "nuxt.config.ts" : "vite.config.ts");
2004
+ const config = project.config;
2005
+ if (config && !config.ok && config.reason !== "no-vitehub") throw manualConfig(file, config.reason, host, framework);
2006
+ if (!project.configFile) {
2007
+ const name = packageNameOf(project.root);
2008
+ return {
2009
+ after: (framework === "nuxt" ? nuxtAppFiles(name, host) : viteAppFiles(name, host))[file],
2010
+ file
2011
+ };
2012
+ }
2013
+ const before = project.configSource;
2014
+ if (before === void 0) throw manualConfig(file, "no-vitehub", host, framework);
2015
+ if (!config?.ok) {
2016
+ if (config?.reason !== "no-vitehub") throw manualConfig(file, config?.reason ?? "no-vitehub", host, framework);
2017
+ const inserted = insertViteHubConfig(file, before, { host });
2018
+ if (!inserted.ok) throw manualConfig(file, inserted.reason, host, framework);
2019
+ return {
2020
+ after: inserted.code,
2021
+ before,
2022
+ file
2023
+ };
2024
+ }
2025
+ const configuredHost = config.site.keys.host;
2026
+ if (configuredHost?.kind === "literal" && configuredHost.value === host) return {
2027
+ after: before,
2028
+ before,
2029
+ file
2030
+ };
2031
+ const edited = editViteHubConfig(file, before, [{
2032
+ key: "host",
2033
+ op: "set",
2034
+ value: host
2035
+ }]);
2036
+ if (!edited.ok) throw manualConfig(file, edited.reason, host, framework);
2037
+ return {
2038
+ after: edited.code,
2039
+ before,
2040
+ file
2041
+ };
2042
+ }
2043
+ /** Plans `vitehub init` without writing anything. Throws `SetupFailure` when the change needs input or is not possible. */
2044
+ async function planInit(args, root, state, context) {
2045
+ const name = packageNameOf(root);
2046
+ const found = state.kind === "adopt" ? state.project.framework : void 0;
2047
+ const framework = args.framework ?? (found === "nuxt" ? "nuxt" : "vite");
2048
+ if (found && found !== framework) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_FRAMEWORK_MISMATCH({
2049
+ dir: root,
2050
+ found,
2051
+ framework
2052
+ }), setupExitCodes.conflict);
2053
+ if (state.kind === "adopt" && framework === "nuxt") await validateNuxtVersion(root);
2054
+ const detected = state.kind === "adopt" ? state.project : detectPackageManager(root, void 0, context.env);
2055
+ const packageManager = args.pm ?? (detected.packageManagerSource === "default" ? "pnpm" : detected.packageManager);
2056
+ const base = /* @__PURE__ */ new Map();
2057
+ let configFile;
2058
+ if (state.kind === "create") {
2059
+ const files = framework === "vite" ? viteAppFiles(name, args.host) : nuxtAppFiles(name, args.host);
2060
+ for (const [path, after] of Object.entries(files)) base.set(path, { after });
2061
+ configFile = framework === "vite" ? "vite.config.ts" : "nuxt.config.ts";
2062
+ } else {
2063
+ const status = setupStatus(state.project, context.env);
2064
+ 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);
2065
+ const config = adoptConfig(state.project, args.host, framework);
2066
+ base.set(config.file, config);
2067
+ configFile = config.file;
2068
+ }
2069
+ const manifestText = base.get("package.json")?.after ?? await readOptional(join(root, "package.json"));
2070
+ const manifest = manifestText ? JSON.parse(manifestText) : {};
2071
+ const dependencies = (key) => {
2072
+ const value = manifest && typeof manifest === "object" ? Reflect.get(manifest, key) : void 0;
2073
+ return value && typeof value === "object" ? value : {};
2074
+ };
2075
+ const declared = (name, dev) => Object.hasOwn(dependencies("dependencies"), name) || dev && Object.hasOwn(dependencies("devDependencies"), name);
2076
+ const basePackages = initPackages[framework];
2077
+ const install = {
2078
+ dev: basePackages.dev.filter((spec) => !declared(packageName$1(spec), true)),
2079
+ prod: basePackages.prod.filter((spec) => !declared(packageName$1(spec), false))
2080
+ };
2081
+ const willInstall = new Set([...install.prod, ...install.dev].map(packageName$1));
2082
+ const configSource = base.get(configFile).after;
2083
+ const planned = {
2084
+ config: locateViteHubConfig(configFile, configSource),
2085
+ configFile,
2086
+ configSource,
2087
+ declared: (name, dev) => declared(name, dev) || willInstall.has(name),
2088
+ framework,
2089
+ installed: state.kind === "adopt" ? state.project.installed : () => false,
2090
+ packageManager,
2091
+ packageManagerSource: args.pm ? "manifest" : detected.packageManagerSource,
2092
+ root,
2093
+ serverDirs: state.kind === "adopt" ? state.project.serverDirs : [join(root, "server")]
2094
+ };
2095
+ const addArgs = addArgsOf(args);
2096
+ const parts = (extra = {}, extraFeatures = []) => {
2097
+ const optionIds = [.../* @__PURE__ */ new Set([...Object.keys(addArgs.options), ...Object.keys(extra)])].filter((id) => featureIds.some((item) => item === id));
2098
+ const options = {};
2099
+ for (const id of optionIds) {
2100
+ const merged = mergeValue(addArgs.options[id], extra[id]);
2101
+ if (isRecord(merged)) options[id] = { ...merged };
2102
+ }
2103
+ return {
2104
+ dir: args.dir,
2105
+ features: [...args.features, ...extraFeatures.filter((id) => !args.features.includes(id))],
2106
+ framework,
2107
+ host: args.host,
2108
+ options: Object.entries(options).flatMap(([id, value]) => value ? flattenOptions(id, value) : []),
2109
+ pm: packageManager
2110
+ };
2111
+ };
2112
+ const rerun = (_args, extra, extraFeatures) => rerunInit(args, parts(extra, extraFeatures));
2113
+ const added = await planSetupAdd(planned, addArgs, context.env, rerun);
2114
+ for (const name of added.install.prod) if (!install.prod.includes(name)) install.prod.push(name);
2115
+ for (const name of added.install.dev) if (!install.dev.includes(name)) install.dev.push(name);
2116
+ for (const file of added.files) base.set(file.path, { after: file.content });
2117
+ if (added.configFile) base.set(configFile, {
2118
+ ...base.get(configFile),
2119
+ after: added.configFile.after
2120
+ });
2121
+ const stack = stackCommand(parts());
2122
+ const readme = state.kind === "create" ? void 0 : await readOptional(join(root, "README.md"));
2123
+ base.set("README.md", {
2124
+ ...readme === void 0 ? {} : { before: readme },
2125
+ after: readmeWithStack(readme, name, stack)
2126
+ });
2127
+ if (state.kind === "adopt") {
2128
+ const gitignore = await readOptional(join(root, ".gitignore"));
2129
+ base.set(".gitignore", {
2130
+ ...gitignore === void 0 ? {} : { before: gitignore },
2131
+ after: gitignore === void 0 ? ".vitehub\n" : gitignoreWithViteHub(gitignore) ?? gitignore
2132
+ });
2133
+ }
2134
+ const scaffolded = state.kind === "create" && framework === "nuxt";
2135
+ 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]) => ({
2136
+ path,
2137
+ ...file
2138
+ }));
2139
+ const command = installCommand(packageManager, install.prod, install.dev);
2140
+ const scaffold = scaffolded ? dlx(packageManager, nuxiPackage, [
2141
+ "init",
2142
+ basename(root),
2143
+ "--template",
2144
+ nuxtTemplate,
2145
+ "--nightly",
2146
+ "5x",
2147
+ "--packageManager",
2148
+ packageManager,
2149
+ "--no-install",
2150
+ "--no-gitInit",
2151
+ "--no-modules",
2152
+ ...state.exists ? ["--force"] : []
2153
+ ]) : void 0;
2154
+ const nextSteps = [
2155
+ ...root === resolve(context.rootDir) ? [] : [`cd ${shellQuote(args.dir)}`],
2156
+ ...command && !args.install ? [`Install the packages: ${command}`] : [],
2157
+ `Start the dev server: ${runScript(packageManager, "dev")}`,
2158
+ ...added.plan.nextSteps
2159
+ ];
2160
+ return {
2161
+ install,
2162
+ plan: {
2163
+ changes: writes.map((write) => changeOf(write.path, write.before, write.after)),
2164
+ features: added.plan.features,
2165
+ framework,
2166
+ host: args.host,
2167
+ implied: added.plan.implied,
2168
+ install: {
2169
+ devPackages: install.dev,
2170
+ packages: install.prod,
2171
+ ...command ? { command } : {}
2172
+ },
2173
+ mode: state.kind,
2174
+ nextSteps,
2175
+ packageManager,
2176
+ root,
2177
+ ...scaffold ? { scaffold: { command: [scaffold[0], ...scaffold[1]].join(" ") } } : {},
2178
+ stack: { command: stack },
2179
+ status: writes.length || scaffold || command && args.install ? "planned" : "unchanged"
2180
+ },
2181
+ rerun: rerunInit(args, parts()),
2182
+ writes,
2183
+ ...scaffold ? { scaffold } : {}
2184
+ };
2185
+ }
2186
+ async function applyInit(planned, install, context, scaffolded = false) {
2187
+ const { plan } = planned;
2188
+ const runInstall = async () => {
2189
+ if (!install) return;
2190
+ for (const [packages, dev] of [[planned.install.prod, false], [planned.install.dev, true]]) {
2191
+ if (!packages.length) continue;
2192
+ const commandArgs = installArgs(plan.packageManager, packages, dev);
2193
+ const result = await context.spawn(plan.packageManager, commandArgs, {
2194
+ cwd: plan.root,
2195
+ env: context.env,
2196
+ stdout: "stderr"
2197
+ });
2198
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
2199
+ command: [plan.packageManager, ...commandArgs].join(" "),
2200
+ exitCode: result.exitCode ?? result.signal,
2201
+ filesWritten: scaffolded || plan.mode === "create"
2202
+ }), setupExitCodes.error);
2203
+ }
2204
+ };
2205
+ if (plan.mode === "adopt") await runInstall();
2206
+ for (const write of planned.writes) {
2207
+ const file = join(plan.root, write.path);
2208
+ await mkdir(dirname(file), { recursive: true });
2209
+ if (write.before === void 0) {
2210
+ try {
2211
+ await writeFile(file, write.after, { flag: "wx" });
2212
+ } catch {
2213
+ throw setupFailure(cliErrorDiagnostics.SETUP_FILE_EXISTS({ file: write.path }), setupExitCodes.conflict);
2214
+ }
2215
+ continue;
2216
+ }
2217
+ if (await readFile(file, "utf8") !== write.before) throw setupFailure(cliErrorDiagnostics.SETUP_STALE_PLAN({ file: write.path }), setupExitCodes.stalePlan);
2218
+ await writeFile(file, write.after);
2219
+ }
2220
+ if (plan.mode === "create") await runInstall();
2221
+ }
2222
+ /** Runs `nuxi init` for a new Nuxt app. ViteHub then adopts the app that it created. */
2223
+ async function scaffoldNuxt(planned, context) {
2224
+ const [command, commandArgs] = planned.scaffold;
2225
+ await mkdir(dirname(planned.plan.root), { recursive: true });
2226
+ const result = await context.spawn(command, commandArgs, {
2227
+ cwd: dirname(planned.plan.root),
2228
+ env: context.env,
2229
+ stdout: "stderr"
2230
+ });
2231
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
2232
+ command: [command, ...commandArgs].join(" "),
2233
+ exitCode: result.exitCode ?? result.signal,
2234
+ filesWritten: "possible"
2235
+ }), setupExitCodes.error);
2236
+ await validateNuxtVersion(planned.plan.root, true);
2237
+ }
2238
+ /** Accept nonempty ranges confined to Nuxt 5, including its prereleases and nightly aliases. */
2239
+ function supportsNuxt5(nuxt) {
2240
+ if (typeof nuxt !== "string") return false;
2241
+ const range = validRange(nuxt.replace(/^npm:nuxt(?:-nightly)?@/u, ""));
2242
+ if (!range || !minVersion(range)) return false;
2243
+ const releases = new Range(range).set.map((comparators) => comparators.map(({ operator, semver, value }) => typeof semver !== "symbol" && semver.major === 5 && semver.prerelease.length > 0 ? `${operator}5.${semver.minor}.${semver.patch}` : value).join(" ")).join(" || ");
2244
+ return subset(releases, ">=5.0.0 <6.0.0");
2245
+ }
2246
+ /** Validate both existing apps and scaffold output before planning adoption or installing packages. */
2247
+ async function validateNuxtVersion(root, scaffolded = false) {
2248
+ const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
2249
+ const dependencies = isRecord(manifest) && isRecord(manifest.dependencies) ? manifest.dependencies : {};
2250
+ const devDependencies = isRecord(manifest) && isRecord(manifest.devDependencies) ? manifest.devDependencies : {};
2251
+ if (!supportsNuxt5(dependencies.nuxt ?? devDependencies.nuxt)) throw setupFailure(cliErrorDiagnostics.SETUP_INIT_NUXT_VERSION({
2252
+ dir: root,
2253
+ scaffolded
2254
+ }), setupExitCodes.conflict);
2255
+ }
2256
+ function interactive(args) {
2257
+ return !args.json && !!process.stdin.isTTY && !!process.stderr.isTTY;
2258
+ }
2259
+ async function ask(question) {
2260
+ const terminal = createInterface({
2261
+ input: process.stdin,
2262
+ output: process.stderr
2263
+ });
2264
+ try {
2265
+ return (await terminal.question(question)).trim();
2266
+ } finally {
2267
+ terminal.close();
2268
+ }
2269
+ }
2270
+ /** Asks for missing inputs in a terminal. Without one, fails with the flag and its choices. */
2271
+ async function readInputs(args) {
2272
+ if (interactive(args)) {
2273
+ const dir = args.dir ?? (await ask("Folder of the app: ") || ".");
2274
+ const host = args.host ?? oneOf("--host", await ask(`Host (${initHosts.join(", ")}): `), initHosts);
2275
+ 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;
2276
+ return {
2277
+ ...args,
2278
+ dir,
2279
+ features,
2280
+ host
2281
+ };
2282
+ }
2283
+ const missing = [];
2284
+ if (args.dir === void 0) missing.push({
2285
+ field: "dir",
2286
+ sentence: "Pass the app folder, such as `vitehub init my-app`,"
2287
+ });
2288
+ if (args.host === void 0) missing.push({
2289
+ choices: initHosts,
2290
+ field: "host",
2291
+ sentence: `Pass --host (${initHosts.join(", ")})`
2292
+ });
2293
+ if (args.features === void 0) missing.push({
2294
+ choices: featureIds,
2295
+ field: "features",
2296
+ sentence: "Pass --features with feature ids separated by commas, such as `--features kv,queue` (run `vitehub catalog` to list them),"
2297
+ });
2298
+ if (!missing.length) return {
2299
+ ...args,
2300
+ dir: args.dir,
2301
+ features: args.features,
2302
+ host: args.host
2303
+ };
2304
+ const message = missing.map((item) => `${item.sentence} when running without an interactive terminal.`).join(" ");
2305
+ throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] ${message}` }), setupExitCodes.inputNeeded, {
2306
+ missing: missing.map(({ sentence: _sentence, ...item }) => item),
2307
+ rerun: rerunInit(args, {
2308
+ dir: args.dir ?? "<dir>",
2309
+ options: args.options,
2310
+ ...args.features ? { features: args.features } : {},
2311
+ ...args.host ? { host: args.host } : {},
2312
+ ...args.framework ? { framework: args.framework } : {},
2313
+ ...args.pm ? { pm: args.pm } : {}
2314
+ })
2315
+ });
2316
+ }
2317
+ function writePlan$1(plan, context) {
2318
+ if (plan.scaffold) context.stdout.write(`Run: ${plan.scaffold.command}\n`);
2319
+ for (const change of plan.changes) if (change.kind === "create") context.stdout.write(`create ${change.path}\n`);
2320
+ else context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
2321
+ const lines = [...plan.install.command ? [`Install: ${plan.install.command}`] : [], ...plan.implied.length ? [`Also turns on: ${plan.implied.join(", ")}`] : []];
2322
+ if (lines.length) context.stdout.write(`${lines.join("\n")}\n`);
2323
+ }
2324
+ function writeResult$1(plan, context) {
2325
+ const features = plan.features.length ? ` with ${plan.features.join(", ")}` : "";
2326
+ if (plan.status === "unchanged") context.stdout.write(`${plan.root} already has this stack. Nothing to change.\n`);
2327
+ else context.stdout.write(`${plan.mode === "create" ? "Created" : "Set up"} ${plan.root} for ${plan.host}${features}.\n`);
2328
+ context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
2329
+ }
2330
+ async function runInit(rawArgs, context) {
2331
+ let json = rawArgs.includes("--json");
2332
+ try {
2333
+ const parsed = readInitArgs(rawArgs);
2334
+ json = parsed.json;
2335
+ if (parsed.help) {
2336
+ context.stdout.write(`Usage: ${usage$1}\n\n${initCommandDefinition.description}\n`);
2337
+ return setupExitCodes.done;
2338
+ }
2339
+ const args = await readInputs(parsed);
2340
+ const root = resolve(context.rootDir, args.dir);
2341
+ let planned = await planInit(args, root, await readDir(root, context.env), context);
2342
+ const { plan } = planned;
2343
+ if (plan.status === "unchanged" || args.dryRun) {
2344
+ if (args.json) writeSetupJson(context, plan);
2345
+ else if (plan.status === "unchanged") writeResult$1(plan, context);
2346
+ else writePlan$1(plan, context);
2347
+ return setupExitCodes.done;
2348
+ }
2349
+ if (!args.yes) {
2350
+ if (!interactive(args)) {
2351
+ if (!args.json) writePlan$1(plan, context);
2352
+ throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub init` writes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
2353
+ data: plan,
2354
+ rerun: planned.rerun
2355
+ });
2356
+ }
2357
+ writePlan$1(plan, context);
2358
+ if (!await confirmSetupChange()) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The change was not confirmed. Nothing was written." }), setupExitCodes.error);
2359
+ }
2360
+ if (planned.scaffold) {
2361
+ await scaffoldNuxt(planned, context);
2362
+ planned = await planInit({
2363
+ ...args,
2364
+ pm: plan.packageManager
2365
+ }, root, await readDir(root, context.env), context);
2366
+ }
2367
+ await applyInit(planned, args.install, context, !!plan.scaffold);
2368
+ const applied = {
2369
+ ...planned.plan,
2370
+ mode: plan.mode,
2371
+ status: "applied",
2372
+ ...plan.scaffold ? { scaffold: plan.scaffold } : {}
2373
+ };
2374
+ if (args.json) writeSetupJson(context, applied);
2375
+ else writeResult$1(applied, context);
2376
+ return setupExitCodes.done;
2377
+ } catch (error) {
2378
+ return writeSetupError(context, json, error);
2379
+ }
2380
+ }
2381
+ const initCommandDefinition = {
2382
+ description: "Create a ViteHub app in a folder, or set up an existing Vite or Nuxt app, with a host and features.",
2383
+ name: "init",
2384
+ run: runInit,
2385
+ usage: usage$1
2386
+ };
2387
+ //#endregion
2388
+ //#region ../internal/dist/definition-catalog.js
2389
+ const ignoredDirs = /* @__PURE__ */ new Set([
2390
+ "node_modules",
2391
+ "dist",
2392
+ ".output",
2393
+ ".nuxt",
2394
+ ".vercel",
2395
+ ".git",
2396
+ ".vitehub"
2397
+ ]);
2398
+ function readDirEntries(root) {
2399
+ try {
2400
+ return readdirSync(root, { withFileTypes: true });
2401
+ } catch (error) {
2402
+ if (error.code === "ENOENT") return [];
2403
+ throw error;
2404
+ }
2405
+ }
2406
+ function isGitRepositoryDirectory(directory) {
2407
+ return existsSync(resolve(directory, ".git"));
2408
+ }
2409
+ function listMatchingFiles(root, predicate, options = {}) {
2410
+ const files = [];
2411
+ for (const entry of readDirEntries(root)) {
2412
+ const absolute = resolve(root, entry.name);
2413
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
2414
+ if (isGitRepositoryDirectory(absolute)) continue;
2415
+ if (entry.name.startsWith(".")) continue;
2416
+ if (ignoredDirs.has(entry.name)) continue;
2417
+ files.push(...listMatchingFiles(absolute, predicate, options));
2418
+ continue;
2419
+ }
2420
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
2421
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
2422
+ }
2423
+ return files.sort();
2424
+ }
2425
+ //#endregion
2426
+ //#region src/setup/remove.ts
2427
+ const usage = "vitehub remove <feature...> [--dry-run] [--yes] [--keep-files] [--force] [--no-uninstall] [--json]";
2428
+ function invalid(message) {
2429
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage}` });
2430
+ }
2431
+ /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or feature. */
2432
+ function readRemoveArgs(args) {
2433
+ const parsed = {
2434
+ dryRun: false,
2435
+ features: [],
2436
+ force: false,
2437
+ help: false,
2438
+ json: false,
2439
+ keepFiles: false,
2440
+ uninstall: true,
2441
+ yes: false
2442
+ };
2443
+ for (const arg of args) if (arg === "--json") parsed.json = true;
2444
+ else if (arg === "--dry-run") parsed.dryRun = true;
2445
+ else if (arg === "--yes" || arg === "-y") parsed.yes = true;
2446
+ else if (arg === "--keep-files") parsed.keepFiles = true;
2447
+ else if (arg === "--force") parsed.force = true;
2448
+ else if (arg === "--no-uninstall") parsed.uninstall = false;
2449
+ else if (arg === "-h" || arg === "--help") parsed.help = true;
2450
+ else if (arg.startsWith("-")) throw invalid(`Unknown argument ${JSON.stringify(arg)}.`);
2451
+ else {
2452
+ const id = readFeatureId(arg, usage);
2453
+ if (!parsed.features.includes(id)) parsed.features.push(id);
2454
+ }
2455
+ return parsed;
2456
+ }
2457
+ function rerunCommand(args) {
2458
+ return [
2459
+ "vitehub remove",
2460
+ ...args.features,
2461
+ ...args.keepFiles ? ["--keep-files"] : [],
2462
+ ...args.force ? ["--force"] : [],
2463
+ ...args.uninstall ? [] : ["--no-uninstall"],
2464
+ "--yes",
2465
+ ...args.json ? ["--json"] : []
2466
+ ].join(" ");
2467
+ }
2468
+ /** The `vite-hub` subpath of a feature, such as `vite-hub/rate-limit`. */
2469
+ function runtimeModule(id) {
2470
+ return `vite-hub/${id === "sandboxTask" ? "sandbox/task" : id.replace(/[A-Z]/gu, (char) => `-${char.toLowerCase()}`)}`;
2471
+ }
2472
+ /** The package of an import, such as `@vite-hub/schedule` for `@vite-hub/schedule/vite`. */
2473
+ function packageName(specifier) {
2474
+ const parts = specifier.split("/");
2475
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
2476
+ }
2477
+ function importsModule(specifier, module) {
2478
+ return specifier === module || specifier.startsWith(`${module}/`);
2479
+ }
2480
+ /** Imports (including static template literals), re-exports, module augmentations, and triple-slash type references. Comments can match, which only makes `remove` stricter. */
2481
+ const specifierPattern = /(?:\b(?:from|import|require|declare\s+module)(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*(?:\((?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*)?|\/\/\/\s*<reference\s+types\s*=\s*)(?:(["'])([^"'\r\n]+)\1|`((?:[^`$\r\n]|\$(?!\{))+)`)/gu;
2482
+ const sourceFile = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|mdx?|html?)$/iu;
2483
+ function lineAt(content, index) {
2484
+ let line = 1;
2485
+ for (let cursor = content.indexOf("\n"); cursor !== -1 && cursor < index; cursor = content.indexOf("\n", cursor + 1)) line++;
2486
+ return line;
2487
+ }
2488
+ /** True when `content` equals the current or an earlier starter template for the Definition at `path`. */
2489
+ function isStarter(starter, path, content) {
2490
+ const parts = path.replace(/\.[^./]+$/u, "").split("/");
2491
+ const name = [
2492
+ parts.at(-1),
2493
+ parts.at(-2),
2494
+ "default"
2495
+ ].find((candidate) => candidate && starter.file(candidate) === path);
2496
+ return name !== void 0 && [starter.template, ...starter.previousTemplates ?? []].some((template) => template(name) === content);
2497
+ }
2498
+ /** Features required by selected options. Unknown options can select any supported prerequisite. */
2499
+ function optionPrerequisites(id, value, unknown) {
2500
+ const options = isRecord$1(value) ? value : void 0;
2501
+ if (id === "cache" && (unknown || options?.driver === "kv")) return ["kv"];
2502
+ if (id === "observability") return [...unknown || options?.posthog ? ["env"] : [], ...unknown || options?.papercuts ? ["agent", "console"] : []];
2503
+ const invocations = options?.invocations;
2504
+ if (id === "agent" && (unknown || invocations === "database" || isRecord$1(invocations) && invocations.store === "database")) return ["database"];
2505
+ return [];
2506
+ }
2507
+ /** Plans `vitehub remove` without writing anything. Throws `SetupFailure` when the change is not safe or not possible. */
2508
+ async function planSetupRemove(project, args, env) {
2509
+ const status = setupStatus(project, env);
2510
+ const configFile = project.configFile ?? (project.framework === "nuxt" ? "nuxt.config.ts" : "vite.config.ts");
2511
+ const manual = (reason) => {
2512
+ const snippet = args.features.map((id) => `${id}: false,`).join("\n");
2513
+ return setupFailure(cliErrorDiagnostics.SETUP_CONFIG_MANUAL({
2514
+ file: configFile,
2515
+ reason,
2516
+ snippet
2517
+ }), setupExitCodes.conflict, { data: { snippet } });
2518
+ };
2519
+ const host = status.host.name;
2520
+ if (host === "unknown") throw manual(project.config && !project.config.ok ? project.config.reason : "dynamic-options");
2521
+ const keys = project.config?.ok ? project.config.site.keys : {};
2522
+ const before = project.configFile ? await readFile(join(project.root, project.configFile), "utf8") : "";
2523
+ const simulate = (edits) => {
2524
+ if (!edits.length) return { status };
2525
+ if (!project.config?.ok || !project.configFile) throw manual(project.config && !project.config.ok ? project.config.reason : "no-vitehub");
2526
+ const result = editViteHubConfig(project.configFile, before, edits);
2527
+ if (!result.ok) throw manual(result.reason);
2528
+ return {
2529
+ code: result.code,
2530
+ status: setupStatus({
2531
+ ...project,
2532
+ config: locateViteHubConfig(project.configFile, result.code)
2533
+ }, env)
2534
+ };
2535
+ };
2536
+ const enabled = (state, id) => state.features.find((item) => item.id === id);
2537
+ const edits = /* @__PURE__ */ new Map();
2538
+ for (const id of args.features) {
2539
+ const current = keys[id];
2540
+ if (current?.kind === "expression") throw manual("dynamic-options");
2541
+ if (current && current.value !== false) edits.set(id, {
2542
+ key: id,
2543
+ op: "delete"
2544
+ });
2545
+ }
2546
+ const deleted = simulate([...edits.values()]).status;
2547
+ const blocking = [];
2548
+ const directories = project.serverDirs ?? [];
2549
+ for (const id of args.features) {
2550
+ const state = enabled(deleted, id);
2551
+ if (state.enabled === "off") continue;
2552
+ if (state.reason === "implied" && !args.force) {
2553
+ const disabled = deleted.features.filter((item) => item.enabled === "off" && item.reason === "config").map((item) => item.id);
2554
+ const by = deleted.features.filter((item) => item.enabled === "on" && item.reason !== "implied" && impliedFeatures([item.id], host, disabled).includes(id)).map((item) => item.id);
2555
+ throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_IMPLIED({
2556
+ by: by.join(", "),
2557
+ feature: id
2558
+ }), setupExitCodes.conflict, { data: { impliedBy: by } });
2559
+ }
2560
+ if (state.reason === "default" && !features[id].enabledByDefault && state.enabled === "on") {
2561
+ for (const directory of directories) for (const name of features[id].enabledByDiscovery ?? []) if (existsSync(join(directory, name))) blocking.push({
2562
+ feature: id,
2563
+ file: relative(project.root, join(directory, name))
2564
+ });
2565
+ }
2566
+ edits.set(id, {
2567
+ key: id,
2568
+ op: "set",
2569
+ value: false
2570
+ });
2571
+ }
2572
+ const after = simulate([...edits.values()]);
2573
+ const turnedOff = featureIds.filter((id) => enabled(status, id).enabled === "on" && enabled(after.status, id).enabled !== "on");
2574
+ const needsDirectories = [...args.features, ...turnedOff].some((id) => enabled(status, id).enabled !== "off" && (features[id].definition || features[id].enabledByDiscovery));
2575
+ if (!args.force && project.framework === "nuxt" && !project.serverDirs?.length && needsDirectories) throw setupFailure(cliErrorDiagnostics.SETUP_SERVER_DIR_MANUAL({ command: "remove" }), setupExitCodes.conflict);
2576
+ const remaining = featureIds.filter((id) => enabled(after.status, id).enabled !== "off");
2577
+ const wasEnabled = featureIds.filter((id) => enabled(status, id).enabled !== "off");
2578
+ const afterKeys = after.code && project.configFile ? locateViteHubConfig(project.configFile, after.code) : project.config;
2579
+ const valueOf = (source, id) => {
2580
+ const key = source?.ok ? source.site.keys[id] : void 0;
2581
+ return key?.kind === "literal" ? key.value : void 0;
2582
+ };
2583
+ for (const id of turnedOff) {
2584
+ const by = remaining.filter((dependent) => optionPrerequisites(dependent, valueOf(afterKeys, dependent), enabled(after.status, dependent).enabled === "unknown").includes(id));
2585
+ if (by.length) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_REQUIRED({
2586
+ by: by.join(", "),
2587
+ feature: id
2588
+ }), setupExitCodes.conflict, { data: { impliedBy: by } });
2589
+ }
2590
+ const packagesOf = (id, value, active = wasEnabled) => {
2591
+ return [...featurePackages(id, value, host, active), ...features[id].devPackages];
2592
+ };
2593
+ const stillNeeded = new Set(remaining.flatMap((id) => packagesOf(id, valueOf(afterKeys, id), remaining)));
2594
+ const starters = /* @__PURE__ */ new Map();
2595
+ const edited = [];
2596
+ for (const id of turnedOff) {
2597
+ const starter = features[id].definition;
2598
+ if (!starter) continue;
2599
+ for (const directory of directories) {
2600
+ const folder = join(directory, relative("server", starter.dir));
2601
+ if (!existsSync(folder)) continue;
2602
+ for (const file of listMatchingFiles(folder, () => true)) {
2603
+ const path = relative(project.root, file);
2604
+ const content = await readFile(file, "utf8");
2605
+ if (isStarter(starter, join("server", relative(directory, file)), content)) starters.set(path, content);
2606
+ else {
2607
+ blocking.push({
2608
+ feature: id,
2609
+ file: path
2610
+ });
2611
+ edited.push(path);
2612
+ }
2613
+ }
2614
+ }
2615
+ }
2616
+ const modules = /* @__PURE__ */ new Map();
2617
+ for (const id of turnedOff) {
2618
+ modules.set(runtimeModule(id), id);
2619
+ for (const name of packagesOf(id, valueOf(project.config, id))) if (!stillNeeded.has(name) && !modules.has(name)) modules.set(name, id);
2620
+ }
2621
+ const imported = /* @__PURE__ */ new Set();
2622
+ for (const file of listMatchingFiles(project.root, (name) => sourceFile.test(name))) {
2623
+ const path = relative(project.root, file);
2624
+ if (starters.has(path) && !args.keepFiles) continue;
2625
+ const content = await readFile(file, "utf8");
2626
+ for (const match of content.matchAll(specifierPattern)) {
2627
+ const specifier = match[2] ?? match[3];
2628
+ imported.add(packageName(specifier));
2629
+ for (const id of featureIds) if (importsModule(specifier, runtimeModule(id))) for (const name of features[id].packages) imported.add(name);
2630
+ if (starters.has(path) || edited.includes(path)) continue;
2631
+ for (const [module, id] of modules) if (importsModule(specifier, module)) blocking.push({
2632
+ feature: id,
2633
+ file: path,
2634
+ line: lineAt(content, match.index),
2635
+ module: specifier
2636
+ });
2637
+ }
2638
+ }
2639
+ if (blocking.length && !args.force) {
2640
+ const list = blocking.map((item) => ` ${item.file}${item.line ? `:${item.line}` : ""}${item.module ? ` imports ${item.module}` : ""}`).join("\n");
2641
+ const used = [...new Set(blocking.map((item) => item.feature))].join(", ");
2642
+ throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_IN_USE({
2643
+ features: used,
2644
+ references: list
2645
+ }), setupExitCodes.conflict, { data: { references: blocking } });
2646
+ }
2647
+ const prod = [];
2648
+ const dev = [];
2649
+ for (const id of wasEnabled) {
2650
+ if (enabled(status, id).enabled !== "on") continue;
2651
+ const packages = featurePackages(id, valueOf(project.config, id), host, wasEnabled);
2652
+ const removable = (name) => !stillNeeded.has(name) && !imported.has(name) && !prod.includes(name) && !dev.includes(name);
2653
+ for (const name of packages) if (removable(name) && project.declared(name, true)) prod.push(name);
2654
+ for (const name of features[id].devPackages) if (removable(name) && project.declared(name, true)) dev.push(name);
2655
+ }
2656
+ const uninstall = [...prod, ...dev];
2657
+ const command = uninstall.length ? [project.packageManager, ...uninstallArgs(project.packageManager, uninstall)].join(" ") : void 0;
2658
+ const changes = [];
2659
+ if (after.code !== void 0 && after.code !== before) changes.push({
2660
+ after: after.code,
2661
+ before,
2662
+ diff: setupDiff(project.configFile, before, after.code),
2663
+ kind: "patch",
2664
+ path: project.configFile
2665
+ });
2666
+ const deletes = [];
2667
+ const kept = [];
2668
+ for (const [path, content] of starters) {
2669
+ if (args.keepFiles) {
2670
+ kept.push({
2671
+ path,
2672
+ reason: "keep-files"
2673
+ });
2674
+ continue;
2675
+ }
2676
+ deletes.push({
2677
+ content,
2678
+ path
2679
+ });
2680
+ changes.push({
2681
+ after: "",
2682
+ before: content,
2683
+ diff: setupDiff(path, content, ""),
2684
+ kind: "delete",
2685
+ path
2686
+ });
2687
+ }
2688
+ for (const path of edited) kept.push({
2689
+ path,
2690
+ reason: "edited"
2691
+ });
2692
+ const nextSteps = [];
2693
+ if (command && !args.uninstall) nextSteps.push(`Uninstall the packages: ${command}`);
2694
+ if (edited.length) nextSteps.push(`${edited.join(", ")} stayed because ${edited.length === 1 ? "it differs" : "they differ"} from the starter. Delete or move ${edited.length === 1 ? "it" : "them"} by hand.`);
2695
+ const hosted = host === "node" ? [] : turnedOff.flatMap((id) => {
2696
+ const support = featureSupport(id, host);
2697
+ return support.level === "native" && support.guarantee === "native" ? [`${features[id].title} (${support.display})`] : [];
2698
+ });
2699
+ if (hosted.length) nextSteps.push(`ViteHub does not delete host resources. Delete the resources of ${hosted.join(", ")} on ${host} by hand when you no longer need them.`);
2700
+ if (existsSync(join(project.root, ".vitehub/data"))) nextSteps.push("Local data in .vitehub/data stays. Delete it by hand when you no longer need it.");
2701
+ if (existsSync(join(project.root, ".vitehub/link.json"))) nextSteps.push("The host credentials and .vitehub/link.json stay unchanged.");
2702
+ nextSteps.push("Run `vitehub status` to check the result.");
2703
+ return {
2704
+ deletes,
2705
+ plan: {
2706
+ changes,
2707
+ features: args.features,
2708
+ host: status.host,
2709
+ kept,
2710
+ nextSteps,
2711
+ references: blocking,
2712
+ root: project.root,
2713
+ status: changes.length || command && args.uninstall ? "planned" : "unchanged",
2714
+ turnedOff,
2715
+ uninstall: {
2716
+ devPackages: dev,
2717
+ packages: prod,
2718
+ ...command ? { command } : {}
2719
+ }
2720
+ },
2721
+ uninstall,
2722
+ ...after.code !== void 0 && after.code !== before ? { configFile: {
2723
+ after: after.code,
2724
+ before,
2725
+ path: project.configFile
2726
+ } } : {}
2727
+ };
2728
+ }
2729
+ /** Deletes `path` and then each folder that is empty after it, such as the `server/queues` that `add` created. */
2730
+ async function deleteStarter(root, path) {
2731
+ await rm(join(root, path));
2732
+ for (let folder = dirname(join(root, path)); folder !== root && folder.startsWith(`${root}/`); folder = dirname(folder)) {
2733
+ if ((await readdir(folder)).length) return;
2734
+ await rmdir(folder);
2735
+ }
2736
+ }
2737
+ /** Applies a removal. In-server sessions defer the restart-triggering config until cleanup finishes. */
2738
+ async function applySetupRemove(project, planned, args, context, options = {}) {
2739
+ 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);
2740
+ for (const file of planned.deletes) if (await readFile(join(project.root, file.path), "utf8").catch(() => void 0) !== file.content) throw setupFailure(cliErrorDiagnostics.SETUP_STALE_PLAN({ file: file.path }), setupExitCodes.stalePlan);
2741
+ if (planned.configFile && !options.configLast) await writeFile(join(project.root, planned.configFile.path), planned.configFile.after);
2742
+ for (const file of planned.deletes) await deleteStarter(project.root, file.path);
2743
+ if (args.uninstall && planned.uninstall.length) {
2744
+ const commandArgs = uninstallArgs(project.packageManager, planned.uninstall);
2745
+ const result = await context.spawn(project.packageManager, commandArgs, {
2746
+ cwd: project.root,
2747
+ env: context.env,
2748
+ stdout: "stderr"
2749
+ });
2750
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_UNINSTALL_FAILED({
2751
+ command: [project.packageManager, ...commandArgs].join(" "),
2752
+ configWritten: !options.configLast,
2753
+ exitCode: result.exitCode ?? result.signal
2754
+ }), setupExitCodes.error);
2755
+ }
2756
+ if (planned.configFile && options.configLast) {
2757
+ const file = join(project.root, planned.configFile.path);
2758
+ if (await readFile(file, "utf8").catch(() => void 0) !== planned.configFile.before) throw setupFailure(cliErrorDiagnostics.SETUP_STALE_PLAN({ file: planned.configFile.path }), setupExitCodes.stalePlan);
2759
+ await writeFile(file, planned.configFile.after);
2760
+ }
2761
+ }
2762
+ function writePlan(plan, context) {
2763
+ for (const change of plan.changes) context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
2764
+ const extra = plan.turnedOff.filter((id) => !plan.features.includes(id));
2765
+ const lines = [
2766
+ ...plan.uninstall.command ? [`Uninstall: ${plan.uninstall.command}`] : [],
2767
+ ...extra.length ? [`Also turns off: ${extra.join(", ")}`] : [],
2768
+ ...plan.kept.map((file) => `Keeps: ${file.path} (${file.reason === "edited" ? "differs from the starter" : "--keep-files"})`)
2769
+ ];
2770
+ if (lines.length) context.stdout.write(`${lines.join("\n")}\n`);
2771
+ }
2772
+ function writeResult(plan, context) {
2773
+ if (plan.status === "unchanged") context.stdout.write(`${plan.features.join(", ")} already off. Nothing to change.\n`);
2774
+ else context.stdout.write(`Removed ${plan.features.join(", ")}.${plan.changes.length ? ` Changed ${plan.changes.map((change) => change.path).join(", ")}.` : ""}\n`);
2775
+ context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
2776
+ }
2777
+ async function runRemove(args, context) {
2778
+ let parsed;
2779
+ try {
2780
+ parsed = readRemoveArgs(args);
2781
+ if (parsed.help) {
2782
+ context.stdout.write(`Usage: ${usage}\n\n${removeCommand.description}\n`);
2783
+ return setupExitCodes.done;
2784
+ }
2785
+ if (!parsed.features.length) throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: "[vitehub] Name at least one feature, such as `vitehub remove kv`." }), setupExitCodes.inputNeeded, { missing: [{
2786
+ choices: featureIds,
2787
+ field: "feature"
2788
+ }] });
2789
+ const project = await readSetupProject(context.rootDir, context.env);
2790
+ const planned = await planSetupRemove(project, parsed, context.env);
2791
+ const { plan } = planned;
2792
+ if (plan.status === "unchanged" || parsed.dryRun) {
2793
+ if (parsed.json) writeSetupJson(context, plan);
2794
+ else if (plan.status === "unchanged") writeResult(plan, context);
2795
+ else writePlan(plan, context);
2796
+ return setupExitCodes.done;
2797
+ }
2798
+ if (!parsed.yes) {
2799
+ if (!(!parsed.json && !!process.stdin.isTTY && !!process.stderr.isTTY)) {
2800
+ if (!parsed.json) writePlan(plan, context);
2801
+ throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub remove` changes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
2802
+ data: plan,
2803
+ rerun: rerunCommand(parsed)
2804
+ });
2805
+ }
2806
+ writePlan(plan, context);
2807
+ if (!await confirmSetupChange()) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The change was not confirmed. Nothing was written." }), setupExitCodes.error);
2808
+ }
2809
+ await applySetupRemove(project, planned, parsed, context);
2810
+ const applied = {
2811
+ ...plan,
2812
+ status: "applied"
2813
+ };
2814
+ if (parsed.json) writeSetupJson(context, applied);
2815
+ else writeResult(applied, context);
2816
+ return setupExitCodes.done;
2817
+ } catch (error) {
2818
+ return writeSetupError(context, parsed?.json ?? args.includes("--json"), error);
2819
+ }
2820
+ }
2821
+ const removeCommand = {
2822
+ description: "Turn off features: edit vitehub() options, delete unchanged starter Definitions, and uninstall unused packages. Reads the config without running it.",
2823
+ name: "remove",
2824
+ run: runRemove,
2825
+ usage
2826
+ };
2827
+ //#endregion
2828
+ //#region src/setup/commands.ts
2829
+ var commands_exports = /* @__PURE__ */ __exportAll({ setupCommands: () => setupCommands });
2830
+ function supportLabel(support) {
2831
+ if (support.level === "unknown") return "unknown";
2832
+ if (support.level === "unsupported") return "-";
2833
+ return support.level === "explicit" ? `${support.display} (set ${support.option})` : support.display;
2834
+ }
2835
+ function writeHelp(command, context) {
2836
+ context.stdout.write(`Usage: ${command.usage}\n\n${command.description}\n`);
2837
+ return setupExitCodes.done;
2838
+ }
2839
+ /** Runs `body` and reports any error in the setup envelope. */
2840
+ async function runSetupCommand(command, args, context, body) {
2841
+ const json = args.includes("--json");
2842
+ try {
2843
+ const parsed = readSetupArgs(args, command.usage);
2844
+ if (parsed.help) return writeHelp(command, context);
2845
+ return await body(parsed.json);
2846
+ } catch (error) {
2847
+ return writeSetupError(context, json, error);
2848
+ }
2849
+ }
2850
+ const catalogCommand = {
2851
+ description: "List every ViteHub feature and how each host supports it. Needs no project.",
2852
+ name: "catalog",
2853
+ run: (args, context) => runSetupCommand(catalogCommand, args, context, async (json) => {
2854
+ const catalog = setupCatalog();
2855
+ if (json) {
2856
+ writeSetupJson(context, catalog);
2857
+ return setupExitCodes.done;
2858
+ }
2859
+ context.stdout.write(`${table([["feature", ...catalog.hosts], ...catalog.features.map((feature) => [feature.id, ...catalog.hosts.map((host) => supportLabel(feature.hosts[host]))])])}\n\n"-" is unsupported. Run \`vitehub catalog --json\` for packages, docs, and details.\n`);
2860
+ return setupExitCodes.done;
2861
+ }),
2862
+ usage: "vitehub catalog [--json]"
2863
+ };
2864
+ function configLabel(config) {
2865
+ if ("form" in config) return `${config.file} (${config.form})`;
2866
+ return `${config.file ? `${config.file}${config.line === void 0 ? "" : `:${config.line}`}: ` : ""}manual (${config.manual})`;
2867
+ }
2868
+ function linkLabel(status) {
2869
+ if (!status.targets.length) return "none (run `vitehub link`)";
2870
+ return status.targets.map((link) => {
2871
+ const account = link.account ? ` in ${link.account.name ?? link.account.id}` : "";
2872
+ const notes = [...status.targets.length > 1 && link.host === status.default ? ["default"] : [], ...link.verified ? [] : ["not verified"]];
2873
+ return `${link.project.name} on ${link.host}${account}${notes.length ? ` (${notes.join(", ")})` : ""}`;
2874
+ }).join("; ");
2875
+ }
2876
+ function credentialsLabel(credentials) {
2877
+ if (!credentials) return "not needed";
2878
+ return credentials.ok ? `${credentials.host} (${credentials.source})` : `missing: ${credentials.fix}`;
2879
+ }
2880
+ function writeStatus(status, context) {
2881
+ const shown = status.features.filter((feature) => feature.enabled !== "off");
2882
+ const off = status.features.length - shown.length;
2883
+ context.stdout.write(`${table([
2884
+ ["root", status.root],
2885
+ ["framework", status.framework],
2886
+ ["config", configLabel(status.config)],
2887
+ ["host", `${status.host.name} (${status.host.source})`],
2888
+ ["packages", status.packageManager],
2889
+ ["link", linkLabel(status)],
2890
+ ["credentials", credentialsLabel(status.credentials)],
2891
+ ["live", liveLabel(status)],
2892
+ ...status.stack ? [["stack", status.stack.command]] : []
2893
+ ])}\n\n`);
2894
+ if (shown.length) context.stdout.write(`${table([[
2895
+ "feature",
2896
+ "state",
2897
+ "support",
2898
+ "fix"
2899
+ ], ...shown.map((feature) => [
2900
+ feature.id,
2901
+ feature.reason === "config" ? feature.enabled : `${feature.enabled} (${feature.reason})`,
2902
+ supportLabel(feature.support),
2903
+ feature.fix ?? ""
2904
+ ])])}\n\n`);
2905
+ context.stdout.write(`${off} features are off. Run \`vitehub catalog\` to list them.\n`);
2906
+ }
2907
+ function isCheckoutStatusModule(value) {
2908
+ return Object(value) === value && typeof Reflect.get(Object(value), "formatWorkspaceStatus") === "function" && typeof Reflect.get(Object(value), "localCheckoutStatus") === "function";
2909
+ }
2910
+ /**
2911
+ * The checkout folders of `vitehub.lock`, read by the Workspace package that the project installs. Undefined without a
2912
+ * lock file. The Workspace package reads only local files here; it never calls the app.
2913
+ */
2914
+ async function readCheckouts(root) {
2915
+ if (!existsSync(join$1(root, "vitehub.lock"))) return void 0;
2916
+ const require = createRequire(join$1(root, "package.json"));
2917
+ for (const specifier of ["@vite-hub/workspace/checkout", "vite-hub/workspace/checkout"]) {
2918
+ let module;
2919
+ try {
2920
+ module = await import(pathToFileURL(require.resolve(specifier)).href);
2921
+ } catch {
2922
+ continue;
2923
+ }
2924
+ if (!isCheckoutStatusModule(module)) continue;
2925
+ try {
2926
+ const statuses = await module.localCheckoutStatus(root) ?? [];
2927
+ return {
2928
+ statuses,
2929
+ text: statuses.map((status) => module.formatWorkspaceStatus(status)).join("")
2930
+ };
2931
+ } catch (error) {
2932
+ return { error: error instanceof Error ? error.message : String(error) };
2933
+ }
2934
+ }
2935
+ return { error: "vitehub.lock lists checkout folders, but the project does not install vite-hub or @vite-hub/workspace to read them." };
2936
+ }
2937
+ const statusCommand = {
2938
+ description: "Show the host, the enabled features, what each one still needs, the live deployment, and the checkout folders of vitehub.lock. Reads the config without running it. --offline skips the host request.",
2939
+ name: "status",
2940
+ run: (args, context) => {
2941
+ const offline = args.includes("--offline");
2942
+ return runSetupCommand(statusCommand, args.filter((arg) => arg !== "--offline"), context, async (json) => {
2943
+ const project = await readSetupProject(context.rootDir, context.env);
2944
+ const features = setupStatus(project, context.env);
2945
+ const signal = offline ? void 0 : AbortSignal.timeout(STATUS_HOST_TIMEOUT_MS);
2946
+ const state = await readSetupLinkState(project, features.host.name, context, {
2947
+ offline,
2948
+ signal
2949
+ });
2950
+ const status = {
2951
+ ...features,
2952
+ ...state.status,
2953
+ ...await readSetupLive(project.root, state.link, state.credentials, context, {
2954
+ offline,
2955
+ signal
2956
+ }),
2957
+ stack: await readSetupStack(project.root)
2958
+ };
2959
+ const checkouts = await readCheckouts(status.root);
2960
+ if (json) {
2961
+ writeSetupJson(context, checkouts === void 0 ? status : {
2962
+ ...status,
2963
+ checkouts: "error" in checkouts ? { error: checkouts.error } : checkouts.statuses
2964
+ });
2965
+ return setupExitCodes.done;
2966
+ }
2967
+ writeStatus(status, context);
2968
+ if (checkouts) context.stdout.write(`\nCheckouts (vitehub.lock):\n${"error" in checkouts ? `${checkouts.error}\n` : checkouts.text}`);
2969
+ return setupExitCodes.done;
2970
+ });
2971
+ },
2972
+ usage: "vitehub status [--offline] [--json]"
2973
+ };
2974
+ const linkUsage = "vitehub link [--host <host>] [--project <name>] [--account <id>] [--create] [--default] [--json]";
2975
+ function readLinkArgs(args) {
2976
+ try {
2977
+ return parseArgs({
2978
+ args,
2979
+ options: {
2980
+ account: { type: "string" },
2981
+ create: {
2982
+ type: "boolean",
2983
+ default: false
2984
+ },
2985
+ default: {
2986
+ type: "boolean",
2987
+ default: false
2988
+ },
2989
+ help: {
2990
+ short: "h",
2991
+ type: "boolean",
2992
+ default: false
2993
+ },
2994
+ host: { type: "string" },
2995
+ json: {
2996
+ type: "boolean",
2997
+ default: false
2998
+ },
2999
+ project: { type: "string" }
3000
+ },
3001
+ strict: true
3002
+ }).values;
3003
+ } catch (error) {
3004
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${linkUsage}` });
3005
+ }
3006
+ }
3007
+ function writeLinked(result, context) {
3008
+ const { link } = result;
3009
+ const account = link.account ? ` in account ${link.account.name ?? link.account.id}` : "";
3010
+ context.stdout.write(`${result.created ? "Created and linked" : "Linked"} ${link.project.name} on ${link.host}${account}.\n`);
3011
+ if (!link.verified) context.stdout.write(`The ${link.host} API was not asked, so the project is not verified.\n`);
3012
+ if (result.hosts.length > 1) context.stdout.write(`Linked hosts: ${result.hosts.join(", ")}. ${result.default ? `\`vitehub deploy\` uses ${result.default} without --host.` : "None is the default, so `vitehub deploy` needs --host."}\n`);
3013
+ context.stdout.write(`Wrote ${result.file}. It holds no secret.\n`);
3014
+ if (result.gitignore === "added") context.stdout.write("Added .vitehub to .gitignore.\n");
3015
+ if (result.gitignore === "no-gitignore") context.stderr.write("[vitehub] The project has no .gitignore. Do not commit the .vitehub folder.\n");
3016
+ }
3017
+ const linkCommand = {
3018
+ description: "Link this project to a project on a host. Each host is one target in .vitehub/link.json, which holds no secret. Linking another host keeps the others. The first host is the default, and --default makes this one the default.",
3019
+ name: "link",
3020
+ run: async (args, context) => {
3021
+ const json = args.includes("--json");
3022
+ try {
3023
+ const values = readLinkArgs(args);
3024
+ if (values.help) return writeHelp(linkCommand, context);
3025
+ const project = await readSetupProject(context.rootDir, context.env);
3026
+ const result = await linkSetupProject(project, {
3027
+ account: values.account,
3028
+ create: values.create,
3029
+ default: values.default,
3030
+ host: values.host,
3031
+ project: values.project
3032
+ }, context);
3033
+ if (json) writeSetupJson(context, result);
3034
+ else writeLinked(result, context);
3035
+ return setupExitCodes.done;
3036
+ } catch (error) {
3037
+ return writeSetupError(context, json, error);
3038
+ }
3039
+ },
3040
+ usage: linkUsage
3041
+ };
3042
+ const unlinkUsage = "vitehub unlink [--host <host>] [--json]";
3043
+ const unlinkCommand = {
3044
+ description: "Remove the link to the host project, or only the target of --host. The project on the host does not change.",
3045
+ name: "unlink",
3046
+ run: async (args, context) => {
3047
+ const json = args.includes("--json");
3048
+ try {
3049
+ let values;
3050
+ try {
3051
+ values = parseArgs({
3052
+ args,
3053
+ options: {
3054
+ help: {
3055
+ short: "h",
3056
+ type: "boolean",
3057
+ default: false
3058
+ },
3059
+ host: { type: "string" },
3060
+ json: {
3061
+ type: "boolean",
3062
+ default: false
3063
+ }
3064
+ },
3065
+ strict: true
3066
+ }).values;
3067
+ } catch (error) {
3068
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${unlinkUsage}` });
3069
+ }
3070
+ if (values.help) return writeHelp(unlinkCommand, context);
3071
+ const host = readLinkHostOption(values.host);
3072
+ const project = await readSetupProject(context.rootDir, context.env);
3073
+ const removed = await unlinkSetupProject(project.root, host);
3074
+ if (json) writeSetupJson(context, {
3075
+ file: SETUP_LINK_FILE,
3076
+ ...host ? { host } : {},
3077
+ removed
3078
+ });
3079
+ else if (host) context.stdout.write(removed ? `Removed the ${host} target from ${SETUP_LINK_FILE}.\n` : `The project has no ${host} target.\n`);
3080
+ else context.stdout.write(removed ? `Removed ${SETUP_LINK_FILE}.\n` : "The project is not linked.\n");
3081
+ return setupExitCodes.done;
3082
+ } catch (error) {
3083
+ return writeSetupError(context, json, error);
3084
+ }
3085
+ },
3086
+ usage: unlinkUsage
3087
+ };
3088
+ /** The setup commands. They run before the CLI loads the project config. */
3089
+ const setupCommands = [
3090
+ initCommandDefinition,
3091
+ addCommand,
3092
+ removeCommand,
3093
+ catalogCommand,
3094
+ statusCommand,
3095
+ linkCommand,
3096
+ unlinkCommand,
3097
+ deployCommand,
3098
+ deploymentsCommand,
3099
+ loginCommand,
3100
+ logoutCommand,
3101
+ whoamiCommand
3102
+ ];
3103
+ //#endregion
3104
+ export { shellQuote as S, setupCatalog as _, readRemoveArgs as a, planSetupAdd as b, initPackages as c, readSetupStack as d, deployCommand as f, readSetupLive as g, deploymentsCommand as h, planSetupRemove as i, nuxiPackage as l, STATUS_HOST_TIMEOUT_MS as m, setupCommands as n, removeCommand as o, readDeployArgs as p, applySetupRemove as r, initCommandDefinition as s, commands_exports as t, readInitArgs as u, addCommand as v, readAddArgs as x, applySetupAdd as y };