@vite-hub/cli 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,16 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawn } from "node:child_process";
3
- import { existsSync, readFileSync, statSync } from "node:fs";
4
- import { dirname, resolve } from "pathe";
3
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
+ import { dirname, join, resolve } from "pathe";
5
5
  import { defineDiagnostics } from "nostics";
6
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
6
+ import { chmod, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
7
7
  import { basename as basename$1, dirname as dirname$1, join as join$1, parse, resolve as resolve$1 } from "node:path";
8
8
  import "node:readline/promises";
9
9
  import "node:url";
10
- import { tmpdir } from "node:os";
10
+ import { homedir, hostname, tmpdir } from "node:os";
11
11
  import { createBirpc } from "birpc";
12
12
  import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
13
+ import { parseArgs } from "node:util";
13
14
  // ../internal/dist/error-diagnostics-B5oT1e3D.js
14
15
  const dynamicError$1 = { why: ({ message }) => message === void 0 ? "" : String(message) };
15
16
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
@@ -551,7 +552,7 @@ function explicit(option, display, detail) {
551
552
  option
552
553
  };
553
554
  }
554
- function unsupported(detail) {
555
+ function unsupported$1(detail) {
555
556
  return {
556
557
  detail,
557
558
  level: "unsupported"
@@ -668,11 +669,11 @@ export default defineAgent({
668
669
  enabledByDiscovery: ["browsers"],
669
670
  hosts: {
670
671
  cloudflare: native("cloudflare", "Browser Run", "Cloudflare Browser Run binding and provider output."),
671
- deno: unsupported("Browser Definitions do not have a Deno provider."),
672
- dev: unsupported("Browser Definitions need the Cloudflare host. Use createBrowser({ driver: localBrowser({ executablePath }) }) from code for a trusted local process."),
673
- netlify: unsupported("Browser Definitions do not have a Netlify provider."),
674
- node: unsupported("The Node host has no built-in Browser Provider. Use localBrowser() from code for a trusted process."),
675
- vercel: unsupported("Browser Definitions do not have a Vercel provider.")
672
+ deno: unsupported$1("Browser Definitions do not have a Deno provider."),
673
+ dev: unsupported$1("Browser Definitions need the Cloudflare host. Use createBrowser({ driver: localBrowser({ executablePath }) }) from code for a trusted local process."),
674
+ netlify: unsupported$1("Browser Definitions do not have a Netlify provider."),
675
+ node: unsupported$1("The Node host has no built-in Browser Provider. Use localBrowser() from code for a trusted process."),
676
+ vercel: unsupported$1("Browser Definitions do not have a Vercel provider.")
676
677
  },
677
678
  id: "browser",
678
679
  packages: ["@vite-hub/browser"],
@@ -877,9 +878,9 @@ export default defineQueue<{ id: string }>({
877
878
  enabledByDiscovery: ["queues"],
878
879
  hosts: {
879
880
  cloudflare: native("cloudflare", "Queues", "Cloudflare Queues bindings and consumers."),
880
- deno: unsupported("No Deno Queue driver is provided."),
881
+ deno: unsupported$1("No Deno Queue driver is provided."),
881
882
  dev: native("local", "Local driver", "The local driver stores jobs in .vitehub/data/queue and runs them in the dev server process.", "single-host"),
882
- netlify: unsupported("Netlify has no Queue driver, so `vitehub({ queue })` fails on Netlify."),
883
+ netlify: unsupported$1("Netlify has no Queue driver, so `vitehub({ queue })` fails on Netlify."),
883
884
  node: native("local", "Postgres / local driver", "With a Postgres Default Database, the postgres driver keeps jobs in Postgres and every instance runs them. Else the local driver keeps jobs on the disk of one host.", "single-host"),
884
885
  vercel: native("vercel", "Vercel Queues", "Vercel Queues callbacks and runtime client.")
885
886
  },
@@ -895,11 +896,11 @@ export default defineQueue<{ id: string }>({
895
896
  docs: "/docs/rate-limit",
896
897
  hosts: {
897
898
  cloudflare: native("cloudflare", "Cloudflare", "Native Cloudflare Rate Limiting binding."),
898
- deno: unsupported("ViteHub has no native Deno Rate Limit driver."),
899
+ deno: unsupported$1("ViteHub has no native Deno Rate Limit driver."),
899
900
  dev: native("memory", "memory", "Process-local memory driver for development and tests.", "process-local"),
900
- netlify: unsupported("ViteHub has no native Netlify Rate Limit driver."),
901
+ netlify: unsupported$1("ViteHub has no native Netlify Rate Limit driver."),
901
902
  node: native("memory", "memory, or KV", "Without KV, each process counts alone. With KV on, ViteHub selects the kv provider, which shares the counts when KV uses Redis or a Postgres Database.", "process-local"),
902
- vercel: unsupported("ViteHub has no native Vercel Rate Limit driver.")
903
+ vercel: unsupported$1("ViteHub has no native Vercel Rate Limit driver.")
903
904
  },
904
905
  id: "rateLimit",
905
906
  packages: ["@vite-hub/rate-limit"],
@@ -925,11 +926,11 @@ export default defineRealtime({
925
926
  enabledByDiscovery: ["realtime"],
926
927
  hosts: {
927
928
  cloudflare: native("cloudflare", "Durable Objects", "Cloudflare Durable Objects run the production rooms."),
928
- deno: unsupported("Realtime has no distributed Deno driver, and process memory is rejected for the Deno host."),
929
+ deno: unsupported$1("Realtime has no distributed Deno driver, and process memory is rejected for the Deno host."),
929
930
  dev: native("memory", "memory", "Process-memory driver for local development.", "process-local"),
930
- netlify: unsupported("Realtime has no distributed Netlify driver, and process memory is rejected for the Netlify host."),
931
+ netlify: unsupported$1("Realtime has no distributed Netlify driver, and process memory is rejected for the Netlify host."),
931
932
  node: native("node", "Postgres or Redis", "Each instance keeps its rooms in memory and shares them through Redis with REDIS_URL, else Postgres on a Postgres Default Database. Without either, rooms stay in one process."),
932
- vercel: unsupported("Realtime has no distributed Vercel driver, and process memory is rejected for the Vercel host.")
933
+ vercel: unsupported$1("Realtime has no distributed Vercel driver, and process memory is rejected for the Vercel host.")
933
934
  },
934
935
  id: "realtime",
935
936
  packages: ["@vite-hub/realtime"],
@@ -941,8 +942,8 @@ export default defineRealtime({
941
942
  docs: "/docs/sandbox",
942
943
  hosts: {
943
944
  cloudflare: native("cloudflare", "CF Sandbox", "Cloudflare Sandbox execution provider."),
944
- deno: unsupported("No Deno Sandbox driver is provided."),
945
- dev: unsupported("The default Node host has no Sandbox Provider. With the Cloudflare or Vercel host, `vite dev` runs each Sandbox Task as a process on this machine, with no isolation and no provider account. `sandboxTask: { remote: true }` uses the host's Sandbox instead."),
945
+ deno: unsupported$1("No Deno Sandbox driver is provided."),
946
+ dev: unsupported$1("The default Node host has no Sandbox Provider. With the Cloudflare or Vercel host, `vite dev` runs each Sandbox Task as a process on this machine, with no isolation and no provider account. `sandboxTask: { remote: true }` uses the host's Sandbox instead."),
946
947
  netlify: explicit("sandboxTask.driver", "Vercel Sandbox", "The Netlify host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
947
948
  node: explicit("sandboxTask.driver", "Vercel Sandbox", "The Node host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
948
949
  vercel: native("vercel", "Vercel Sandbox", "Vercel Sandbox execution provider.")
@@ -1129,7 +1130,7 @@ function impliedFeatures(enabled, disabled = []) {
1129
1130
  }
1130
1131
  return implied;
1131
1132
  }
1132
- // ../internal/dist/vite-CELQZdD3.js
1133
+ // ../internal/dist/vite-D86Q14G4.js
1133
1134
  const projectRootDirectoryMarkers = [
1134
1135
  ["server", "agents"],
1135
1136
  ["server", "channels"],
@@ -1484,7 +1485,8 @@ const setupCommandNames = [
1484
1485
  "login",
1485
1486
  "logout",
1486
1487
  "update",
1487
- "whoami"
1488
+ "whoami",
1489
+ "apps"
1488
1490
  ];
1489
1491
  /** CLI namespaces owned by built-in commands. */
1490
1492
  const reservedOperationNamespaces = [
@@ -1714,7 +1716,7 @@ async function callOperation(target, name, input) {
1714
1716
  const url = new URL(operationRpcPath.slice(1), base);
1715
1717
  origin = url.origin;
1716
1718
  const env = target.roots?.length ? {} : target.env;
1717
- try {
1719
+ if (!target.authorization) try {
1718
1720
  readConsoleSigningKey(env);
1719
1721
  } catch (error) {
1720
1722
  return {
@@ -1726,15 +1728,18 @@ async function callOperation(target, name, input) {
1726
1728
  };
1727
1729
  }
1728
1730
  const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
1729
- const headers = await signedOperationHeaders(env, url, body);
1731
+ const signal = target.signal ?? AbortSignal.timeout(target.timeout ?? 3e4);
1732
+ const headers = target.authorization ? operationHeaders() : await signedOperationHeaders(env, url, body);
1733
+ if (target.authorization) headers.set("authorization", target.authorization);
1730
1734
  if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
1731
1735
  if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
1736
+ signal.throwIfAborted();
1732
1737
  const response = await (target.fetch ?? fetch)(url.href, {
1733
1738
  body,
1734
1739
  headers,
1735
1740
  method: "POST",
1736
1741
  redirect: "manual",
1737
- signal: AbortSignal.timeout(target.timeout ?? 3e4)
1742
+ signal
1738
1743
  });
1739
1744
  const text = await response.text();
1740
1745
  let json;
@@ -1771,7 +1776,7 @@ async function callOperation(target, name, input) {
1771
1776
  } : void 0);
1772
1777
  if (failure) {
1773
1778
  if (target.roots?.length && failure.status === 401) failure.fix = `Pass --url ${base.href.slice(0, -1)} to send credentials. A command sends none to the dev server that it finds. ${failure.fix ?? "Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key that `vitehub secret console-key` printed, and its public key in VITEHUB_CONSOLE_KEY_<NAME> on the app."}`;
1774
- if ((failure.status === 401 || failure.status === 403) && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
1779
+ if ((failure.status === 401 || failure.status === 403) && !target.authorization && !hasCredentials(env) && !failure.fix) failure.fix = target.roots?.length ? `Pass --url <origin> to send deployment credentials. ${operationCredentialHint}` : operationCredentialHint;
1775
1780
  return {
1776
1781
  ok: false,
1777
1782
  ...failure
@@ -1936,6 +1941,10 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1936
1941
  fix: "Run `vitehub login` again, and approve the code in the browser within 15 minutes. Pass --console <url> for a self-hosted Console.",
1937
1942
  why: ({ console, message }) => `Sign-in to ${String(console)} did not finish. ${String(message)}`
1938
1943
  },
1944
+ CLI_CONSOLE_REQUEST_FAILED: {
1945
+ fix: ({ fix }) => typeof fix === "string" ? fix : "Check that you are an owner or admin of the team, and that the key opens the app. Run `vitehub whoami` to see both.",
1946
+ why: ({ code, console, message }) => `${String(console)} refused the request (${String(code)}). ${String(message)}`
1947
+ },
1939
1948
  CLI_CONSOLE_SIGNED_OUT: {
1940
1949
  fix: "Run `vitehub login`, or set VITEHUB_CONSOLE_TOKEN to an API key from Account settings in the Console.",
1941
1950
  why: ({ console }) => `There is no valid API key for ${String(console)}. The key is missing, expired, or revoked.`
@@ -2025,7 +2034,7 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
2025
2034
  why: ({ message }) => message === void 0 ? "" : String(message)
2026
2035
  },
2027
2036
  SETUP_INSTALL_FAILED: {
2028
- fix: ({ filesWritten }) => `Run the install command by hand to see the error, then run the command again. ${filesWritten === "possible" ? "Scaffolding may have left new app files on disk; inspect the target folder before retrying." : filesWritten ? "The new app files were written before installation failed; keep them when retrying." : "ViteHub did not write starter or config files; the package manager may have changed package manifests or lockfiles."}`,
2037
+ fix: ({ filesWritten, workspaceFile }) => `Run the install command by hand to see the error, then run the command again. ${filesWritten === "possible" ? "Scaffolding may have left new app files on disk; inspect the target folder before retrying." : filesWritten ? "The new app files were written before installation failed; keep them when retrying." : "ViteHub did not write starter or config files; the package manager may have changed package manifests or lockfiles."}${workspaceFile ? ` If pnpm reports an ignored esbuild build script, set \`allowBuilds: { esbuild: false }\` in \`${workspaceFile}\` before retrying.` : ""}`,
2029
2038
  why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
2030
2039
  },
2031
2040
  SETUP_FEATURE_IMPLIED: {
@@ -2141,7 +2150,7 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
2141
2150
  why: ({ command }) => `The build output names a deploy command that ViteHub did not write, so it does not run it: ${String(command)}`
2142
2151
  },
2143
2152
  SETUP_DEPLOY_ENV_MISSING: {
2144
- fix: ({ firstDeploy, host }) => firstDeploy ? `Set each name in the shell or in .env.<stage>, then deploy again. If the ${String(host)} project already exists, run \`vitehub link --host ${String(host)}\` first, so deploy reads its variables.` : `Run \`vitehub env push --host ${String(host)}\`, set the names in the ${String(host)} dashboard, or set them in the shell or in .env.<stage> and deploy again.`,
2153
+ fix: ({ console, firstDeploy, host }) => (console === true ? "For VITEHUB_CONSOLE_KEY_*, run `vitehub login`, and deploy links the app in the Console and sets its key. " : "") + (firstDeploy ? `Set each name in the shell or in .env.<stage>, then deploy again. If the ${String(host)} project already exists, run \`vitehub link --host ${String(host)}\` first, so deploy reads its variables.` : `Run \`vitehub env push --host ${String(host)}\`, set the names in the ${String(host)} dashboard, or set them in the shell or in .env.<stage> and deploy again.`),
2145
2154
  why: ({ firstDeploy, host, names, stage }) => firstDeploy ? `The app needs ${String(names)}, and no value was found. This is the first deploy to ${String(host)}: the project is not linked, so the host has no variables yet and every required name needs a local value for the ${String(stage)} stage. Nothing was deployed.` : `The app needs ${String(names)}, and neither ${String(host)} nor a local value for the ${String(stage)} stage has one. Nothing was deployed.`
2146
2155
  },
2147
2156
  SETUP_DEPLOY_ENV_NOT_LINKED: {
@@ -2150,7 +2159,7 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
2150
2159
  },
2151
2160
  SETUP_DEPLOY_ENV_STAGE_UNSAFE: {
2152
2161
  why: ({ names, stage }) => `These existing Cloudflare secrets have no local value for stage ${String(stage)}: ${String(names)}. The latest uploaded version may belong to another stage, so inheriting its values is unsafe. Nothing was deployed.`,
2153
- fix: ({ stage }) => `Set every listed name in the shell or an untracked .env.${String(stage)} file and deploy again. Cloudflare deploys re-supply all existing secrets with the version to preserve stage isolation.`
2162
+ fix: ({ console, stage }) => `Set every listed name in the shell or an untracked .env.${String(stage)} file and deploy again. Cloudflare deploys re-supply all existing secrets with the version to preserve stage isolation.${console ? " For a Console key, copy the public value of the existing link, or restore the Console connection with `vitehub login`." : ""}`
2154
2163
  },
2155
2164
  SETUP_DEPLOY_FAILED: {
2156
2165
  fix: "Read the host output above, fix the cause, and run the command again.",
@@ -2190,7 +2199,7 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
2190
2199
  },
2191
2200
  SETUP_DEPLOY_PUSH_FAILED: {
2192
2201
  fix: ({ fix }) => `${fix ? `${String(fix)} ` : ""}Then run \`vitehub push\`. Do not deploy again.`,
2193
- why: ({ message, url }) => `The app is deployed to ${String(url)}, but the Workspace push failed: ${String(message)}`
2202
+ why: ({ message, url }) => `The app is deployed${url === void 0 ? "" : ` to ${String(url)}`}, but the Workspace push failed: ${String(message)}`
2194
2203
  },
2195
2204
  CLI_R0004: {
2196
2205
  fix: "Run it again with --yes, or check the change first with a dry run when the command has one.",
@@ -2242,6 +2251,1101 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
2242
2251
  }
2243
2252
  }
2244
2253
  });
2254
+ // src/setup/envelope.ts
2255
+ /** Exit codes of the setup commands. */
2256
+ const setupExitCodes = {
2257
+ done: 0,
2258
+ error: 1,
2259
+ inputNeeded: 2,
2260
+ conflict: 3,
2261
+ stalePlan: 4
2262
+ };
2263
+ function isDiagnostic(error) {
2264
+ return error instanceof Error && typeof Reflect.get(error, "code") === "string" && typeof Reflect.get(error, "why") === "string";
2265
+ }
2266
+ function toSetupError(error) {
2267
+ const diagnostic = isDiagnostic(error) ? error : cliErrorDiagnostics.CLI_SETUP_FAILED({ message: error instanceof Error ? error.message : String(error) });
2268
+ const why = diagnostic.why.replace(/^\[vitehub\] /u, "");
2269
+ return {
2270
+ code: diagnostic.code,
2271
+ message: /^.*?[.!?](?=\s|$)/u.exec(why)?.[0] ?? why,
2272
+ why,
2273
+ ...diagnostic.fix ? { fix: diagnostic.fix } : {},
2274
+ ...diagnostic.docs ? { docs: diagnostic.docs } : {}
2275
+ };
2276
+ }
2277
+ /** Prints one JSON document with `schemaVersion: 1` on stdout. */
2278
+ function writeSetupJson(context, data) {
2279
+ context.stdout.write(`${JSON.stringify({
2280
+ schemaVersion: 1,
2281
+ ...data
2282
+ })}\n`);
2283
+ }
2284
+ /** Adds the exit code and the missing input of a setup command to its diagnostic. */
2285
+ function setupFailure(diagnostic, exitCode, details = {}) {
2286
+ return Object.assign(diagnostic, {
2287
+ details,
2288
+ exitCode
2289
+ });
2290
+ }
2291
+ /** Whether `error` is a diagnostic that `setupFailure()` gave an exit code. */
2292
+ function isSetupFailure(error) {
2293
+ if (!(error instanceof Error)) return false;
2294
+ const details = Reflect.get(error, "details");
2295
+ return typeof Reflect.get(error, "exitCode") === "number" && typeof details === "object" && details !== null;
2296
+ }
2297
+ function formatMissing(missing) {
2298
+ return missing.map((item) => {
2299
+ const choices = item.choices ?? [];
2300
+ if (choices.every((choice) => typeof choice === "string")) return `Missing: ${item.field}${choices.length ? ` (${choices.join(", ")})` : ""}\n`;
2301
+ return `Missing: ${item.field}\n${choices.map((choice) => typeof choice === "string" ? ` ${choice}\n` : ` ${choice.id}${choice.name ? ` ${choice.name}` : ""}\n`).join("")}`;
2302
+ }).join("");
2303
+ }
2304
+ /**
2305
+ * Reports `error` as one JSON document on stdout with `--json`, else on stderr, and returns its exit code.
2306
+ * A `SetupFailure` adds `missing`, `rerun`, and its `data` to the document. Any other error exits with 1.
2307
+ */
2308
+ function writeSetupError(context, json, error) {
2309
+ if (isSetupFailure(error)) {
2310
+ const { data, missing, rerun } = error.details;
2311
+ if (json) writeSetupJson(context, {
2312
+ ...data,
2313
+ error: toSetupError(error),
2314
+ ...missing ? { missing } : {},
2315
+ ...rerun ? { rerun } : {}
2316
+ });
2317
+ else context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n${formatMissing(missing ?? [])}${rerun ? `Run: ${rerun}\n` : ""}`);
2318
+ return error.exitCode;
2319
+ }
2320
+ if (json) writeSetupJson(context, { error: toSetupError(error) });
2321
+ else context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
2322
+ return setupExitCodes.error;
2323
+ }
2324
+ /** Reads `--json` and `--help`. Throws `CLI_R0003` for any other argument. */
2325
+ function readSetupArgs(args, usage) {
2326
+ const unknown = args.find((arg) => arg !== "--json" && arg !== "-h" && arg !== "--help");
2327
+ if (unknown !== void 0) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown argument ${JSON.stringify(unknown)}. Usage: ${usage}` });
2328
+ return {
2329
+ help: args.includes("-h") || args.includes("--help"),
2330
+ json: args.includes("--json")
2331
+ };
2332
+ }
2333
+ /** Rows as plain text columns, two spaces apart. */
2334
+ function table(rows) {
2335
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
2336
+ return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()).join("\n");
2337
+ }
2338
+ // src/setup/console-auth.ts
2339
+ /** The hosted Console. `--console` and `VITEHUB_CONSOLE_URL` name a self-hosted one. */
2340
+ const defaultConsoleUrl = "https://console.vitehub.dev";
2341
+ /** An API key for CI. It wins over the saved key, and `vitehub logout` does not remove it. */
2342
+ const consoleTokenVariable = "VITEHUB_CONSOLE_TOKEN";
2343
+ const consoleUrlVariable = "VITEHUB_CONSOLE_URL";
2344
+ const clientId = "vitehub-cli";
2345
+ /** `$XDG_CONFIG_HOME/vitehub/credentials.json`, else `~/.config/vitehub/credentials.json`. */
2346
+ function consoleCredentialsFile(env) {
2347
+ const base = env.XDG_CONFIG_HOME || join$1(env.HOME || env.USERPROFILE || homedir(), ".config");
2348
+ return join$1(base, "vitehub", "credentials.json");
2349
+ }
2350
+ async function readCredentials(file, signal) {
2351
+ const text = await readFile(file, {
2352
+ encoding: "utf8",
2353
+ signal
2354
+ }).catch((error) => {
2355
+ if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return void 0;
2356
+ throw error;
2357
+ });
2358
+ if (text === void 0) return {
2359
+ version: 1,
2360
+ consoles: {}
2361
+ };
2362
+ const parsed = JSON.parse(text);
2363
+ const consoles = parsed instanceof Object ? Reflect.get(parsed, "consoles") : void 0;
2364
+ return {
2365
+ version: 1,
2366
+ consoles: consoles instanceof Object ? consoles : {}
2367
+ };
2368
+ }
2369
+ async function writeCredentials(file, value) {
2370
+ await mkdir(dirname$1(file), {
2371
+ mode: 448,
2372
+ recursive: true
2373
+ });
2374
+ const temporary = `${file}.${process.pid}.tmp`;
2375
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
2376
+ await chmod(temporary, 384);
2377
+ await rename(temporary, file);
2378
+ }
2379
+ /** The origin of a Console URL. Plain `http` is accepted only for a Console on this machine. */
2380
+ function consoleOrigin(value) {
2381
+ let url;
2382
+ try {
2383
+ url = new URL(value);
2384
+ } catch {
2385
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be a URL, such as ${defaultConsoleUrl}. Got ${JSON.stringify(value)}.` });
2386
+ }
2387
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
2388
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --console must be an https:// URL. Plain http:// is only for a Console on localhost. Got ${url.origin}.` });
2389
+ return url.origin;
2390
+ }
2391
+ /**
2392
+ * The key that a command sends to a Console, and where it came from: `VITEHUB_CONSOLE_TOKEN`, else the key that
2393
+ * `vitehub login` saved for the Console. Without `console`, the Console is `VITEHUB_CONSOLE_URL`, else the only saved
2394
+ * Console, else console.vitehub.dev. `undefined` when there is no key.
2395
+ */
2396
+ async function readConsoleCredential(env, console, signal) {
2397
+ const file = await readCredentials(consoleCredentialsFile(env), signal);
2398
+ const named = console ?? env["VITEHUB_CONSOLE_URL"];
2399
+ const saved = Object.keys(file.consoles);
2400
+ const origin = consoleOrigin(named ?? (saved.length === 1 ? saved[0] : "https://console.vitehub.dev"));
2401
+ const token = env[consoleTokenVariable];
2402
+ if (token) return {
2403
+ origin,
2404
+ source: "env",
2405
+ token
2406
+ };
2407
+ const credential = file.consoles[origin];
2408
+ return credential ? {
2409
+ origin,
2410
+ saved: credential,
2411
+ source: "file",
2412
+ token: credential.token
2413
+ } : void 0;
2414
+ }
2415
+ function readArgs(args, usage, extra = {}) {
2416
+ try {
2417
+ return parseArgs({
2418
+ args,
2419
+ options: {
2420
+ ...extra.console ? { console: { type: "string" } } : {},
2421
+ help: {
2422
+ short: "h",
2423
+ type: "boolean",
2424
+ default: false
2425
+ },
2426
+ json: {
2427
+ type: "boolean",
2428
+ default: false
2429
+ }
2430
+ },
2431
+ strict: true
2432
+ }).values;
2433
+ } catch (error) {
2434
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
2435
+ }
2436
+ }
2437
+ async function postJson(context, url, body) {
2438
+ const response = await (context.fetch ?? fetch)(url, {
2439
+ body: JSON.stringify(body),
2440
+ headers: {
2441
+ accept: "application/json",
2442
+ "content-type": "application/json"
2443
+ },
2444
+ method: "POST"
2445
+ });
2446
+ const data = await response.json().catch(() => ({}));
2447
+ return {
2448
+ data: data instanceof Object ? data : {},
2449
+ headers: response.headers,
2450
+ status: response.status
2451
+ };
2452
+ }
2453
+ function loginFailed(origin, message) {
2454
+ return cliErrorDiagnostics.CLI_CONSOLE_LOGIN_FAILED({
2455
+ console: origin,
2456
+ message
2457
+ });
2458
+ }
2459
+ const wait = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
2460
+ const dateFormat = new Intl.DateTimeFormat("en-GB", {
2461
+ day: "numeric",
2462
+ month: "short",
2463
+ year: "numeric",
2464
+ timeZone: "UTC"
2465
+ });
2466
+ function groupCode(code) {
2467
+ return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
2468
+ }
2469
+ async function deviceLogin(origin, context, prompt) {
2470
+ const started = await postJson(context, `${origin}/api/auth/device/code`, {
2471
+ client_id: clientId,
2472
+ client_name: `vitehub CLI on ${hostname()}`
2473
+ }).catch((error) => {
2474
+ throw loginFailed(origin, `The Console did not answer: ${error instanceof Error ? error.message : String(error)}`);
2475
+ });
2476
+ if (started.status !== 200 || typeof started.data.device_code !== "string") throw loginFailed(origin, `The Console answered ${started.status} to the device code request${typeof started.data.error === "string" ? ` (${started.data.error})` : ""}. Is ${origin} a ViteHub Console?`);
2477
+ const code = started.data;
2478
+ prompt.write(`Open ${code.verification_uri} and enter the code ${groupCode(code.user_code)}\n`);
2479
+ if (code.verification_uri_complete) prompt.write(`Or open ${code.verification_uri_complete}\n`);
2480
+ prompt.write("Waiting for approval...\n");
2481
+ let interval = Number.isFinite(code.interval) ? code.interval : 5;
2482
+ const deadline = Date.now() + code.expires_in * 1e3;
2483
+ while (Date.now() < deadline) {
2484
+ await wait(interval);
2485
+ const answer = await postJson(context, `${origin}/api/auth/cli/token`, {
2486
+ client_id: clientId,
2487
+ device_code: code.device_code
2488
+ });
2489
+ if (answer.status === 200 && typeof answer.data.access_token === "string") return answer.data;
2490
+ if (answer.status === 429) {
2491
+ interval = Math.max(interval, Number(answer.headers.get("retry-after")) || 60);
2492
+ continue;
2493
+ }
2494
+ const error = answer.data.error;
2495
+ if (error === "authorization_pending") continue;
2496
+ if (error === "slow_down") {
2497
+ interval += 5;
2498
+ continue;
2499
+ }
2500
+ if (error === "access_denied") throw loginFailed(origin, "The sign-in was denied in the browser.");
2501
+ if (error === "expired_token") break;
2502
+ throw loginFailed(origin, `The Console answered ${answer.status}${typeof error === "string" ? ` (${error})` : ""}.`);
2503
+ }
2504
+ throw loginFailed(origin, "The code expired before anyone approved it.");
2505
+ }
2506
+ const loginUsage = "vitehub login [--console <url>] [--json]";
2507
+ const loginCommand = {
2508
+ description: `Sign in to a ViteHub Console with the device flow, and save an API key for this machine. The default Console is ${defaultConsoleUrl}; --console or ${consoleUrlVariable} names another.`,
2509
+ name: "login",
2510
+ usage: loginUsage,
2511
+ run: async (args, context) => {
2512
+ const json = args.includes("--json");
2513
+ try {
2514
+ const values = readArgs(args, loginUsage, { console: true });
2515
+ if (values.help) {
2516
+ context.stdout.write(`Usage: ${loginUsage}\n\n${loginCommand.description}\n`);
2517
+ return setupExitCodes.done;
2518
+ }
2519
+ const origin = consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev");
2520
+ const answer = await deviceLogin(origin, context, json ? context.stderr : context.stdout);
2521
+ const file = consoleCredentialsFile(context.env);
2522
+ const saved = await readCredentials(file);
2523
+ const credential = {
2524
+ expiresAt: Date.now() + answer.expires_in * 1e3,
2525
+ keyId: answer.key_id,
2526
+ team: answer.team,
2527
+ token: answer.access_token,
2528
+ user: answer.user
2529
+ };
2530
+ await writeCredentials(file, {
2531
+ version: 1,
2532
+ consoles: {
2533
+ ...saved.consoles,
2534
+ [origin]: credential
2535
+ }
2536
+ });
2537
+ const result = {
2538
+ console: origin,
2539
+ expiresAt: new Date(credential.expiresAt).toISOString(),
2540
+ file,
2541
+ team: credential.team,
2542
+ user: credential.user
2543
+ };
2544
+ if (json) writeSetupJson(context, result);
2545
+ else context.stdout.write(`Signed in to ${origin} as ${credential.user.name}${credential.user.email ? ` (${credential.user.email})` : ""} in team ${credential.team.name}.\nThe API key expires on ${dateFormat.format(new Date(credential.expiresAt))}. Saved in ${file}.\n`);
2546
+ if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is set, so commands use it instead of this key.\n`);
2547
+ return setupExitCodes.done;
2548
+ } catch (error) {
2549
+ return writeSetupError(context, json, error);
2550
+ }
2551
+ }
2552
+ };
2553
+ const whoamiUsage = "vitehub whoami [--console <url>] [--json]";
2554
+ const whoamiCommand = {
2555
+ description: `Show the person and the team of the Console API key: ${consoleTokenVariable}, else the key of \`vitehub login\`.`,
2556
+ name: "whoami",
2557
+ usage: whoamiUsage,
2558
+ run: async (args, context) => {
2559
+ const json = args.includes("--json");
2560
+ try {
2561
+ const values = readArgs(args, whoamiUsage, { console: true });
2562
+ if (values.help) {
2563
+ context.stdout.write(`Usage: ${whoamiUsage}\n\n${whoamiCommand.description}\n`);
2564
+ return setupExitCodes.done;
2565
+ }
2566
+ const credential = await readConsoleCredential(context.env, values.console);
2567
+ if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(values.console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
2568
+ const response = await (context.fetch ?? fetch)(`${credential.origin}/api/whoami`, { headers: {
2569
+ accept: "application/json",
2570
+ authorization: `Bearer ${credential.token}`
2571
+ } });
2572
+ if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
2573
+ if (!response.ok) throw cliErrorDiagnostics.CLI_R0001({ message: `[vitehub] ${credential.origin} answered ${response.status} to /api/whoami.` });
2574
+ const me = await response.json();
2575
+ const source = credential.source === "env" ? consoleTokenVariable : consoleCredentialsFile(context.env);
2576
+ if (json) writeSetupJson(context, {
2577
+ console: credential.origin,
2578
+ expiresAt: new Date(me.key.expiresAt).toISOString(),
2579
+ projectIds: me.projectIds,
2580
+ roles: me.roles,
2581
+ source,
2582
+ team: me.team,
2583
+ user: me.user
2584
+ });
2585
+ else {
2586
+ context.stdout.write(`${me.user.name}${me.user.email ? ` (${me.user.email})` : ""} in team ${me.team.name} (${me.roles.join(", ")}) on ${credential.origin}\n`);
2587
+ context.stdout.write(`Key from ${source}, for ${me.projectIds ? `${me.projectIds.length} project${me.projectIds.length === 1 ? "" : "s"}` : "every project of the team"}, expires on ${dateFormat.format(new Date(me.key.expiresAt))}.\n`);
2588
+ }
2589
+ return setupExitCodes.done;
2590
+ } catch (error) {
2591
+ return writeSetupError(context, json, error);
2592
+ }
2593
+ }
2594
+ };
2595
+ const logoutUsage = "vitehub logout [--console <url>] [--json]";
2596
+ const logoutCommand = {
2597
+ description: "Revoke the API key of `vitehub login` on the Console and remove it from this machine.",
2598
+ name: "logout",
2599
+ usage: logoutUsage,
2600
+ run: async (args, context) => {
2601
+ const json = args.includes("--json");
2602
+ try {
2603
+ const values = readArgs(args, logoutUsage, { console: true });
2604
+ if (values.help) {
2605
+ context.stdout.write(`Usage: ${logoutUsage}\n\n${logoutCommand.description}\n`);
2606
+ return setupExitCodes.done;
2607
+ }
2608
+ const file = consoleCredentialsFile(context.env);
2609
+ const saved = await readCredentials(file);
2610
+ const credential = await readConsoleCredential({
2611
+ ...context.env,
2612
+ [consoleTokenVariable]: void 0
2613
+ }, values.console);
2614
+ if (!credential) {
2615
+ if (json) writeSetupJson(context, { removed: false });
2616
+ else context.stdout.write("Not signed in.\n");
2617
+ return setupExitCodes.done;
2618
+ }
2619
+ const response = await (context.fetch ?? fetch)(`${credential.origin}/api/api-keys/current`, {
2620
+ headers: { authorization: `Bearer ${credential.token}` },
2621
+ method: "DELETE"
2622
+ }).catch(() => void 0);
2623
+ const revoked = response !== void 0 && (response.status === 204 || response.status === 401 || response.status === 404);
2624
+ const { [credential.origin]: _removed, ...consoles } = saved.consoles;
2625
+ await writeCredentials(file, {
2626
+ version: 1,
2627
+ consoles
2628
+ });
2629
+ if (json) writeSetupJson(context, {
2630
+ console: credential.origin,
2631
+ removed: true,
2632
+ revoked
2633
+ });
2634
+ else {
2635
+ context.stdout.write(`Signed out of ${credential.origin}.\n`);
2636
+ if (!revoked) context.stderr.write("[vitehub] The Console did not revoke the key. Revoke it in Account settings, under API keys.\n");
2637
+ }
2638
+ if (context.env["VITEHUB_CONSOLE_TOKEN"]) context.stderr.write(`[vitehub] ${consoleTokenVariable} is still set. Unset it to sign out completely.\n`);
2639
+ return setupExitCodes.done;
2640
+ } catch (error) {
2641
+ return writeSetupError(context, json, error);
2642
+ }
2643
+ }
2644
+ };
2645
+ // ../internal/dist/definition-catalog.js
2646
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
2647
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
2648
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
2649
+ const ignoredDirs = /* @__PURE__ */ new Set([
2650
+ "node_modules",
2651
+ "dist",
2652
+ ".output",
2653
+ ".nuxt",
2654
+ ".vercel",
2655
+ ".git",
2656
+ ".vitehub"
2657
+ ]);
2658
+ function readDirEntries(root) {
2659
+ try {
2660
+ return readdirSync(root, { withFileTypes: true });
2661
+ } catch (error) {
2662
+ if (error.code === "ENOENT") return [];
2663
+ throw error;
2664
+ }
2665
+ }
2666
+ function isGitRepositoryDirectory(directory) {
2667
+ return existsSync(resolve(directory, ".git"));
2668
+ }
2669
+ function listMatchingFiles(root, predicate, options = {}) {
2670
+ const files = [];
2671
+ for (const entry of readDirEntries(root)) {
2672
+ const absolute = resolve(root, entry.name);
2673
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
2674
+ if (isGitRepositoryDirectory(absolute)) continue;
2675
+ if (entry.name.startsWith(".")) continue;
2676
+ if (ignoredDirs.has(entry.name)) continue;
2677
+ files.push(...listMatchingFiles(absolute, predicate, options));
2678
+ continue;
2679
+ }
2680
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
2681
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
2682
+ }
2683
+ return files.sort();
2684
+ }
2685
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
2686
+ function isDefinitionSourceFile(name) {
2687
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
2688
+ }
2689
+ function listSourceFiles(root, options = {}) {
2690
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
2691
+ }
2692
+ /**
2693
+ * Whether `path` is a file, or a folder that holds a Definition source file. A Definition file in a server directory,
2694
+ * such as `server/auth.ts` or a file in `server/queues/`, turns its feature on without a key. An empty folder, which
2695
+ * Git does not keep, turns nothing on.
2696
+ */
2697
+ function hasDefinitionFiles(path) {
2698
+ if (!existsSync(path)) return false;
2699
+ return statSync(path).isFile() || listSourceFiles(path).length > 0;
2700
+ }
2701
+ // ../internal/dist/deployment.js
2702
+ const unsupported = (reason) => ({
2703
+ reason,
2704
+ supported: false
2705
+ });
2706
+ const plans = {
2707
+ cloudflare: {
2708
+ host: "cloudflare",
2709
+ nitroPreset: "cloudflare-module",
2710
+ output: {
2711
+ directory: ".output",
2712
+ entry: "server/index.mjs",
2713
+ packaging: "none"
2714
+ },
2715
+ runtime: "workerd",
2716
+ services: {
2717
+ blob: {
2718
+ driver: "cloudflare",
2719
+ guarantee: "native",
2720
+ supported: true
2721
+ },
2722
+ browser: {
2723
+ driver: "cloudflare",
2724
+ guarantee: "native",
2725
+ supported: true
2726
+ },
2727
+ queue: {
2728
+ driver: "cloudflare",
2729
+ guarantee: "native",
2730
+ supported: true
2731
+ },
2732
+ rateLimit: {
2733
+ driver: "cloudflare",
2734
+ guarantee: "native",
2735
+ supported: true
2736
+ },
2737
+ realtime: {
2738
+ driver: "cloudflare",
2739
+ guarantee: "native",
2740
+ supported: true
2741
+ },
2742
+ sandbox: {
2743
+ driver: "cloudflare",
2744
+ guarantee: "native",
2745
+ supported: true
2746
+ }
2747
+ }
2748
+ },
2749
+ deno: {
2750
+ host: "deno",
2751
+ nitroPreset: "deno-deploy",
2752
+ output: {
2753
+ directory: ".output",
2754
+ entry: "server/index.mjs",
2755
+ packaging: "deno-node-modules"
2756
+ },
2757
+ runtime: "deno",
2758
+ services: {
2759
+ blob: unsupported("Deno Deploy has no built-in durable Blob Store with ViteHub's object-storage contract."),
2760
+ browser: unsupported("Deno Deploy has no built-in Browser Provider."),
2761
+ queue: unsupported("Deno Deploy has no built-in Queue Provider with ViteHub's delivery contract."),
2762
+ rateLimit: unsupported("Deno Deploy has no built-in distributed Rate Limit driver."),
2763
+ realtime: unsupported("Deno Deploy has no shared room authority for Realtime."),
2764
+ sandbox: unsupported("Deno Deploy has no built-in isolated Sandbox Provider.")
2765
+ }
2766
+ },
2767
+ netlify: {
2768
+ host: "netlify",
2769
+ nitroPreset: "netlify",
2770
+ output: {
2771
+ directory: ".netlify",
2772
+ entry: "v1/functions/server/server.mjs",
2773
+ packaging: "none"
2774
+ },
2775
+ runtime: "node",
2776
+ services: {
2777
+ blob: {
2778
+ driver: "netlify-blobs",
2779
+ guarantee: "native",
2780
+ supported: true
2781
+ },
2782
+ browser: unsupported("Netlify has no built-in Browser Provider."),
2783
+ queue: unsupported("Netlify has no built-in Queue Provider with ViteHub's delivery contract."),
2784
+ rateLimit: unsupported("Netlify has no built-in distributed Rate Limit driver."),
2785
+ realtime: unsupported("Netlify has no shared room authority for Realtime."),
2786
+ sandbox: unsupported("Netlify has no built-in isolated Sandbox Provider.")
2787
+ }
2788
+ },
2789
+ node: {
2790
+ host: "node",
2791
+ nitroPreset: "node-server",
2792
+ output: {
2793
+ directory: ".output",
2794
+ entry: "server/index.mjs",
2795
+ packaging: "none"
2796
+ },
2797
+ runtime: "node",
2798
+ services: {
2799
+ blob: {
2800
+ driver: "fs",
2801
+ guarantee: "single-host",
2802
+ supported: true
2803
+ },
2804
+ browser: unsupported("The Node host has no built-in Browser Provider."),
2805
+ queue: {
2806
+ driver: "local",
2807
+ guarantee: "single-host",
2808
+ supported: true
2809
+ },
2810
+ rateLimit: {
2811
+ driver: "memory",
2812
+ guarantee: "process-local",
2813
+ supported: true
2814
+ },
2815
+ realtime: {
2816
+ driver: "node",
2817
+ guarantee: "native",
2818
+ supported: true
2819
+ },
2820
+ sandbox: unsupported("The Node host has no built-in isolated Sandbox Provider.")
2821
+ }
2822
+ },
2823
+ vercel: {
2824
+ host: "vercel",
2825
+ nitroPreset: "vercel",
2826
+ output: {
2827
+ directory: ".vercel/output",
2828
+ entry: "functions/__server.func/index.mjs",
2829
+ packaging: "none"
2830
+ },
2831
+ runtime: "node",
2832
+ services: {
2833
+ blob: {
2834
+ driver: "vercel",
2835
+ guarantee: "native",
2836
+ supported: true
2837
+ },
2838
+ browser: unsupported("Vercel has no built-in Browser Provider."),
2839
+ queue: {
2840
+ driver: "vercel",
2841
+ guarantee: "native",
2842
+ supported: true
2843
+ },
2844
+ rateLimit: unsupported("Vercel has no built-in distributed Rate Limit driver."),
2845
+ realtime: unsupported("Vercel has no shared room authority for Realtime."),
2846
+ sandbox: {
2847
+ driver: "vercel",
2848
+ guarantee: "native",
2849
+ supported: true
2850
+ }
2851
+ }
2852
+ }
2853
+ };
2854
+ function resolveDeploymentPlan(host) {
2855
+ const plan = plans[host];
2856
+ if (!plan) throw internalErrorDiagnostics.INTERNAL_R0001({ message: `Unknown ViteHub host: ${JSON.stringify(host)}.` });
2857
+ return plan;
2858
+ }
2859
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
2860
+ function hostFromNitroPreset(value) {
2861
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
2862
+ if (!normalized) return;
2863
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
2864
+ if (normalized.startsWith("deno")) return "deno";
2865
+ if (normalized.startsWith("netlify")) return "netlify";
2866
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
2867
+ if (normalized.startsWith("vercel")) return "vercel";
2868
+ }
2869
+ const providerHosts = [
2870
+ ["WORKERS_CI", "cloudflare"],
2871
+ ["NETLIFY", "netlify"],
2872
+ ["NOW_BUILDER", "vercel"],
2873
+ ["VERCEL", "vercel"],
2874
+ ["VERCEL_ENV", "vercel"],
2875
+ ["DENO_DEPLOY", "deno"],
2876
+ ["DENO_DEPLOYMENT_ID", "deno"]
2877
+ ];
2878
+ /**
2879
+ * Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
2880
+ * The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
2881
+ * `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
2882
+ * `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
2883
+ */
2884
+ function detectHost(env = process.env) {
2885
+ for (const name of [
2886
+ "VITEHUB_HOST",
2887
+ "NITRO_PRESET",
2888
+ "SERVER_PRESET"
2889
+ ]) {
2890
+ const host = hostFromNitroPreset(env[name]);
2891
+ if (host) return host;
2892
+ }
2893
+ return providerHosts.find(([name]) => env[name]?.trim())?.[1];
2894
+ }
2895
+ // src/setup/status.ts
2896
+ const addArgs = {
2897
+ bun: {
2898
+ dev: ["add", "-d"],
2899
+ prod: ["add"]
2900
+ },
2901
+ npm: {
2902
+ dev: ["install", "-D"],
2903
+ prod: ["install"]
2904
+ },
2905
+ pnpm: {
2906
+ dev: ["add", "-D"],
2907
+ prod: ["add"]
2908
+ },
2909
+ yarn: {
2910
+ dev: ["add", "-D"],
2911
+ prod: ["add"]
2912
+ }
2913
+ };
2914
+ /** Quotes `value` for a POSIX shell when it needs quotes. */
2915
+ function shellQuote(value) {
2916
+ return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
2917
+ }
2918
+ /** The arguments of the `packageManager` command that installs `packages`, such as `["add", "-D", "drizzle-kit"]`. */
2919
+ function installArgs(packageManager, packages, dev) {
2920
+ return [...addArgs[packageManager][dev ? "dev" : "prod"], ...packages];
2921
+ }
2922
+ const removeArgs = {
2923
+ bun: ["remove"],
2924
+ npm: ["uninstall"],
2925
+ pnpm: ["remove"],
2926
+ yarn: ["remove"]
2927
+ };
2928
+ /** The arguments of the `packageManager` command that uninstalls `packages`, such as `["remove", "@vite-hub/queue"]`. */
2929
+ function uninstallArgs(packageManager, packages) {
2930
+ return [...removeArgs[packageManager], ...packages];
2931
+ }
2932
+ function formatInstallCommand(command, args) {
2933
+ return [command, ...args].map(formatInstallArgument).join(" ");
2934
+ }
2935
+ function installCommand(packageManager, prod, dev) {
2936
+ const commands = [...prod.length ? [formatInstallCommand(packageManager, installArgs(packageManager, prod, false))] : [], ...dev.length ? [formatInstallCommand(packageManager, installArgs(packageManager, dev, true))] : []];
2937
+ return commands.length ? commands.join(" && ") : void 0;
2938
+ }
2939
+ function readHost(project, env) {
2940
+ const config = project.config;
2941
+ if (config && !config.ok && config.reason !== "no-vitehub") return {
2942
+ name: "unknown",
2943
+ source: "config"
2944
+ };
2945
+ const site = config?.ok ? config.site : void 0;
2946
+ const host = site?.keys.host;
2947
+ const fromConfig = host?.kind === "literal" && typeof host.value === "string" ? hostFromNitroPreset(host.value) : void 0;
2948
+ if (fromConfig) return {
2949
+ name: fromConfig,
2950
+ source: "config"
2951
+ };
2952
+ if (host || site?.spread) return {
2953
+ name: "unknown",
2954
+ source: "config"
2955
+ };
2956
+ const fromEnv = detectHost(env);
2957
+ return fromEnv ? {
2958
+ name: fromEnv,
2959
+ source: "env"
2960
+ } : {
2961
+ name: "node",
2962
+ source: "default"
2963
+ };
2964
+ }
2965
+ function readEnabled(project, id, withoutDefinitions) {
2966
+ const config = project.config;
2967
+ if (!config || !config.ok && config.reason === "no-vitehub") return {
2968
+ enabled: "off",
2969
+ reason: "default"
2970
+ };
2971
+ if (!config.ok) return {
2972
+ enabled: "unknown",
2973
+ reason: "config"
2974
+ };
2975
+ const value = config.site.keys[id];
2976
+ if (value?.kind === "expression") return {
2977
+ enabled: "unknown",
2978
+ reason: "config"
2979
+ };
2980
+ if (value) return {
2981
+ enabled: value.value === false ? "off" : "on",
2982
+ reason: "config"
2983
+ };
2984
+ if (config.site.spread) return {
2985
+ enabled: "unknown",
2986
+ reason: "config"
2987
+ };
2988
+ if (features[id].enabledByDefault) return {
2989
+ enabled: "on",
2990
+ reason: "default"
2991
+ };
2992
+ if (withoutDefinitions?.has(id)) return {
2993
+ enabled: "off",
2994
+ reason: "default"
2995
+ };
2996
+ const discovery = features[id].enabledByDiscovery;
2997
+ const directories = project.serverDirs ?? (project.framework === "nuxt" ? void 0 : [join(project.root, "server")]);
2998
+ if (discovery && !directories) return {
2999
+ enabled: "unknown",
3000
+ reason: "default"
3001
+ };
3002
+ return {
3003
+ enabled: discovery?.some((file) => directories?.some((directory) => hasDefinitionFiles(join(directory, file)))) ? "on" : "off",
3004
+ reason: "default"
3005
+ };
3006
+ }
3007
+ const kvDefaultStoreOption = "kv.stores.default.driver";
3008
+ function kvStores(value) {
3009
+ return isRecord(value) && isRecord(value.stores) ? value.stores : void 0;
3010
+ }
3011
+ function missingProviderOption(project, option, value) {
3012
+ const [id, key] = option.split(".");
3013
+ const configured = project.config?.ok ? project.config.site.keys[id] : void 0;
3014
+ if (configured?.kind === "expression") return;
3015
+ const options = value ?? configured?.value;
3016
+ const stores = option === "kv.driver" ? kvStores(options) : void 0;
3017
+ if (stores) {
3018
+ const store = stores.default;
3019
+ const driver = isRecord(store) ? store.driver : void 0;
3020
+ if (driver !== "upstash" && driver !== "redis" && driver !== "database") return kvDefaultStoreOption;
3021
+ return;
3022
+ }
3023
+ if (!isRecord(options) || !(key in options)) return option;
3024
+ }
3025
+ function featureFix(project, id, support, host, missing, providerChosen) {
3026
+ const install = installCommand(project.packageManager, missing.prod.map(installSpecifier), missing.dev.map(installSpecifier));
3027
+ if (install) return install;
3028
+ if (support.level === "unsupported") return `Set \`${id}: false\`, or build for another host than ${host}.`;
3029
+ if (support.level === "explicit" && !providerChosen) {
3030
+ const option = missingProviderOption(project, support.option);
3031
+ if (option) return `Set \`${option}\` in vitehub() to choose a provider on ${host}.`;
3032
+ }
3033
+ }
3034
+ /** What the project enables, on which host, and what each enabled feature still needs. Reads the config without running it. */
3035
+ function setupStatus(project, env, withoutDefinitions) {
3036
+ const host = readHost(project, env);
3037
+ const enabled = new Map(featureIds.map((id) => [id, readEnabled(project, id, withoutDefinitions)]));
3038
+ const on = featureIds.filter((id) => enabled.get(id).enabled === "on");
3039
+ const keep = featureIds.filter((id) => enabled.get(id).enabled !== "on" && enabled.get(id).reason === "config");
3040
+ const maybeOn = featureIds.filter((id) => enabled.get(id).enabled !== "off");
3041
+ const disabled = keep.filter((id) => enabled.get(id).enabled === "off");
3042
+ const definite = impliedFeatures(on, keep);
3043
+ for (const id of impliedFeatures(maybeOn, disabled)) {
3044
+ const state = enabled.get(id);
3045
+ if (state.enabled === "off" && state.reason === "default") enabled.set(id, {
3046
+ enabled: definite.includes(id) ? "on" : "unknown",
3047
+ reason: "implied"
3048
+ });
3049
+ }
3050
+ return {
3051
+ config: !project.config ? { manual: "no-vitehub" } : project.config.ok ? {
3052
+ file: project.configFile,
3053
+ form: project.config.site.form
3054
+ } : {
3055
+ file: project.configFile,
3056
+ manual: project.config.reason,
3057
+ ...project.config.line === void 0 ? {} : { line: project.config.line }
3058
+ },
3059
+ features: featureIds.map((id) => {
3060
+ const state = enabled.get(id);
3061
+ const support = host.name === "unknown" ? {
3062
+ level: "unknown",
3063
+ detail: "The config does not statically identify the deployment host."
3064
+ } : featureSupport(id, host.name);
3065
+ const definition = features[id];
3066
+ const value = project.config?.ok ? project.config.site.keys[id] : void 0;
3067
+ const literal = value?.kind === "literal" ? value.value : void 0;
3068
+ const packages = featurePackages(id, literal, host.name, featureIds.filter((feature) => enabled.get(feature)?.enabled === "on"));
3069
+ const missing = state.enabled === "on" ? {
3070
+ dev: definition.devPackages.filter((name) => !project.installed(name)),
3071
+ prod: packages.filter((name) => !project.installed(name))
3072
+ } : {
3073
+ dev: [],
3074
+ prod: []
3075
+ };
3076
+ const providerChosen = id === "workflow" && host.name !== "netlify" && packages.includes("openworkflow");
3077
+ const fix = state.enabled === "on" ? featureFix(project, id, support, host.name, missing, providerChosen) : void 0;
3078
+ const resolvedSupport = support.level === "explicit" && support.option === "kv.driver" && kvStores(literal) ? {
3079
+ ...support,
3080
+ option: kvDefaultStoreOption
3081
+ } : support;
3082
+ return {
3083
+ id,
3084
+ ...state,
3085
+ missingPackages: [...missing.prod, ...missing.dev],
3086
+ support: resolvedSupport,
3087
+ ...fix ? { fix } : {}
3088
+ };
3089
+ }),
3090
+ framework: project.framework,
3091
+ host,
3092
+ packageManager: project.packageManager,
3093
+ root: project.root,
3094
+ schemaVersion: 1
3095
+ };
3096
+ }
3097
+ // src/setup/console-apps.ts
3098
+ /** The Console of `--console`, else `VITEHUB_CONSOLE_URL`, else the only saved Console, else console.vitehub.dev. */
3099
+ async function openConsole(context, console) {
3100
+ const credential = await readConsoleCredential(context.env, console);
3101
+ if (!credential) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: consoleOrigin(console ?? context.env["VITEHUB_CONSOLE_URL"] ?? "https://console.vitehub.dev") });
3102
+ return consoleClient(context, credential);
3103
+ }
3104
+ function consoleClient(context, credential, signal) {
3105
+ return {
3106
+ origin: credential.origin,
3107
+ async request(path, init = {}) {
3108
+ const response = await (context.fetch ?? fetch)(`${credential.origin}${path}`, {
3109
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
3110
+ headers: {
3111
+ accept: "application/json",
3112
+ authorization: `Bearer ${credential.token}`,
3113
+ ...init.body === void 0 ? {} : { "content-type": "application/json" }
3114
+ },
3115
+ method: init.method ?? "GET",
3116
+ ...signal ? {
3117
+ redirect: "error",
3118
+ signal
3119
+ } : {}
3120
+ }).catch((error) => {
3121
+ throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
3122
+ code: "FETCH_FAILED",
3123
+ console: credential.origin,
3124
+ message: `The Console did not answer ${path}: ${error instanceof Error ? error.message : String(error)}`
3125
+ });
3126
+ });
3127
+ if (response.status === 401) throw cliErrorDiagnostics.CLI_CONSOLE_SIGNED_OUT({ console: credential.origin });
3128
+ const body = response.status === 204 ? {} : await response.json().catch(() => ({}));
3129
+ const record = body instanceof Object ? body : {};
3130
+ if (!response.ok) throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
3131
+ code: typeof record.code === "string" ? record.code : String(response.status),
3132
+ console: credential.origin,
3133
+ ...typeof record.fix === "string" ? { fix: record.fix } : {},
3134
+ message: typeof record.message === "string" ? record.message : `${credential.origin} answered ${response.status} to ${path}.`
3135
+ });
3136
+ return {
3137
+ body: record,
3138
+ status: response.status
3139
+ };
3140
+ }
3141
+ };
3142
+ }
3143
+ /** The apps of the team of the key. */
3144
+ async function listConsoleApps(client) {
3145
+ const { body } = await client.request("/api/projects");
3146
+ return Array.isArray(body.projects) ? body.projects : [];
3147
+ }
3148
+ /** Link an app, or register a site with `kind: "site"`. Linking a URL again returns the same link with `created: false`. */
3149
+ async function linkConsoleApp(client, input) {
3150
+ const { body, status } = await client.request("/api/projects", {
3151
+ body: input,
3152
+ method: "POST"
3153
+ });
3154
+ return {
3155
+ app: body.project,
3156
+ created: status === 201
3157
+ };
3158
+ }
3159
+ async function checkConsoleApp(client, id) {
3160
+ const { body } = await client.request(`/api/projects/${encodeURIComponent(id)}/check`, {
3161
+ body: {},
3162
+ method: "POST"
3163
+ });
3164
+ return {
3165
+ answer: body.answer,
3166
+ linked: body.linked === true,
3167
+ status: typeof body.status === "number" ? body.status : 0
3168
+ };
3169
+ }
3170
+ /** The Console page of an app. */
3171
+ function consoleAppUrl(origin, app) {
3172
+ return `${origin}/open?project=${encodeURIComponent(app.url)}`;
3173
+ }
3174
+ /** The text of a check that did not link, such as `401 CONSOLE_KEY_UNKNOWN: ...`. */
3175
+ function checkProblem(check) {
3176
+ const answer = Object(check.answer);
3177
+ const code = Reflect.get(answer, "code");
3178
+ const message = Reflect.get(answer, "message");
3179
+ return [check.status ? String(check.status) : "", typeof code === "string" ? code : ""].filter(Boolean).join(" ") + (typeof message === "string" ? `: ${message}` : "");
3180
+ }
3181
+ const usage = {
3182
+ check: "vitehub apps check <id> [--console <url>] [--json]",
3183
+ link: "vitehub apps link <url> [--label <name>] [--kind site] [--console <url>] [--json]",
3184
+ list: "vitehub apps list [--console <url>] [--json]",
3185
+ unlink: "vitehub apps unlink <id> --delete-hosted-comments [--console <url>] [--json]"
3186
+ };
3187
+ function readAppsArgs(command, args) {
3188
+ let parsed;
3189
+ try {
3190
+ parsed = parseArgs({
3191
+ allowPositionals: true,
3192
+ args,
3193
+ options: {
3194
+ "console": { type: "string" },
3195
+ "help": {
3196
+ default: false,
3197
+ short: "h",
3198
+ type: "boolean"
3199
+ },
3200
+ "json": {
3201
+ default: false,
3202
+ type: "boolean"
3203
+ },
3204
+ ...command === "link" ? {
3205
+ kind: { type: "string" },
3206
+ label: { type: "string" }
3207
+ } : {},
3208
+ ...command === "unlink" ? { "delete-hosted-comments": {
3209
+ default: false,
3210
+ type: "boolean"
3211
+ } } : {}
3212
+ },
3213
+ strict: true
3214
+ });
3215
+ } catch (error) {
3216
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage[command]}` });
3217
+ }
3218
+ const { positionals, values } = parsed;
3219
+ const expected = command === "list" ? 0 : 1;
3220
+ if (!values.help && positionals.length !== expected) {
3221
+ const message = expected ? `Pass one ${command === "link" ? "URL" : "app id"}.` : `Got ${JSON.stringify(positionals[0])}.`;
3222
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage[command]}` });
3223
+ }
3224
+ return {
3225
+ positionals,
3226
+ values: {
3227
+ "delete-hosted-comments": false,
3228
+ ...values
3229
+ }
3230
+ };
3231
+ }
3232
+ function appName(app) {
3233
+ return app.label ? `${app.label} (${app.url})` : app.url;
3234
+ }
3235
+ async function runApps(command, args, context) {
3236
+ const { positionals, values } = readAppsArgs(command, args);
3237
+ if (values.help) {
3238
+ context.stdout.write(`Usage: ${usage[command]}\n\n${appsHelp[command]}\n`);
3239
+ return setupExitCodes.done;
3240
+ }
3241
+ const client = await openConsole(context, values.console);
3242
+ const write = (result, text) => {
3243
+ if (values.json) writeSetupJson(context, {
3244
+ console: client.origin,
3245
+ ...result
3246
+ });
3247
+ else context.stdout.write(text);
3248
+ };
3249
+ if (command === "list") {
3250
+ const [apps, me] = await Promise.all([listConsoleApps(client), client.request("/api/whoami")]);
3251
+ const team = {
3252
+ ...me.body.team,
3253
+ role: me.body.roles.join(",")
3254
+ };
3255
+ const rows = apps.map((app) => [
3256
+ app.id,
3257
+ app.label ?? "",
3258
+ app.url,
3259
+ app.keyVariable ? "app" : "site"
3260
+ ]);
3261
+ write({
3262
+ apps,
3263
+ team
3264
+ }, apps.length ? `${table([[
3265
+ "id",
3266
+ "label",
3267
+ "url",
3268
+ "kind"
3269
+ ], ...rows])}\n` : `Team ${team.name} has no apps. Run \`vitehub apps link <url>\`, or \`vitehub deploy\` in the app folder.\n`);
3270
+ return setupExitCodes.done;
3271
+ }
3272
+ if (command === "link") {
3273
+ if (values.kind !== void 0 && values.kind !== "site") throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --kind takes only "site". Usage: ${usage.link}` });
3274
+ const { app, created } = await linkConsoleApp(client, {
3275
+ url: positionals[0],
3276
+ ...values.label ? { label: values.label } : {},
3277
+ ...values.kind === "site" ? { kind: "site" } : {}
3278
+ });
3279
+ const verb = created ? "Linked" : "Already linked";
3280
+ if (app.keyVariable === null) {
3281
+ const script = `<script type="module" src="${client.origin}/hosted-comments.js" data-vitehub-comments="${app.id}"><\/script>`;
3282
+ const next = `Add the script to the HTML of ${app.url} and of the pages to review, then open ${app.url}?vitehub and choose Comments.`;
3283
+ write({
3284
+ app,
3285
+ script,
3286
+ next
3287
+ }, `${verb} the site ${appName(app)} as ${app.id}.\n${script}\n${next}\n`);
3288
+ return setupExitCodes.done;
3289
+ }
3290
+ const variable = `${app.keyVariable}=${app.publicKey}`;
3291
+ const check = `vitehub apps check ${shellQuote(app.id)} --console ${shellQuote(client.origin)}`;
3292
+ const next = `Set ${app.keyVariable} in the environment of ${app.url} and enable console: true in its vitehub config. On Node, also set publicUrl: ${JSON.stringify(new URL(app.url).origin)} in that config. Deploy it, then run \`${check}\`.`;
3293
+ write({
3294
+ app,
3295
+ variable,
3296
+ next
3297
+ }, `${verb} ${appName(app)} as ${app.id}.\n${variable}\n${next}\n`);
3298
+ return setupExitCodes.done;
3299
+ }
3300
+ const id = positionals[0];
3301
+ if (command === "check") {
3302
+ const check = await checkConsoleApp(client, id);
3303
+ write(check, check.linked ? `The app answers signed requests of ${client.origin}.\n` : `The app does not accept the Console yet: ${checkProblem(check)}\n`);
3304
+ return check.linked ? setupExitCodes.done : setupExitCodes.error;
3305
+ }
3306
+ if (!values["delete-hosted-comments"]) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unlinking permanently deletes the hosted comment threads and replies of the app. Pass --delete-hosted-comments to confirm. Usage: ${usage.unlink}` });
3307
+ const app = (await listConsoleApps(client)).find((item) => item.id === id);
3308
+ const { status } = await client.request(`/api/projects/${encodeURIComponent(id)}?deleteHostedComments=true`, { method: "DELETE" });
3309
+ if (status !== 204) throw cliErrorDiagnostics.CLI_CONSOLE_REQUEST_FAILED({
3310
+ code: String(status),
3311
+ console: client.origin,
3312
+ fix: "Check that the Console and its proxy return the project API response, not a sign-in page. Run `vitehub apps list` to see if the app is still linked.",
3313
+ message: "The Console did not confirm the unlink (expected status 204)."
3314
+ });
3315
+ const next = app?.keyVariable ? `Remove ${app.keyVariable} from the environment of ${app.url}.` : "";
3316
+ write({
3317
+ unlinked: id,
3318
+ next
3319
+ }, `Unlinked ${app ? appName(app) : id}.${next ? ` ${next}` : ""}\n`);
3320
+ return setupExitCodes.done;
3321
+ }
3322
+ const appsHelp = {
3323
+ check: "Call project.get on a linked app with a signed request from the Console. Exits with 1 if the request fails.",
3324
+ link: "Link a deployed ViteHub app to your team, or register a site for Hosted Comments with --kind site. Linking a URL again returns the same link and key. Only owners and admins may link.",
3325
+ list: "List the apps of the team of your Console key, with the id that the other commands take.",
3326
+ unlink: "Unlink an app. This deletes the private key of the link and the hosted comment threads of the app. Only owners and admins may unlink."
3327
+ };
3328
+ const appsUsage = "vitehub apps <list|link|check|unlink> [args...]";
3329
+ /** `vitehub apps`: the CLI side of the `list_apps`, `link_app`, `check_app`, and `unlink_app` tools of the Console MCP. */
3330
+ const appsCommand = {
3331
+ description: "List, link, check, and unlink the apps of your team in the ViteHub Console. Each command matches a tool of the Console MCP. Needs `vitehub login`.",
3332
+ name: "apps",
3333
+ usage: appsUsage,
3334
+ run: async (args, context) => {
3335
+ const json = args.includes("--json");
3336
+ try {
3337
+ const [command, ...rest] = args;
3338
+ if (command === void 0 || command === "-h" || command === "--help") {
3339
+ context.stdout.write(`Usage: ${appsUsage}\n\n${appsCommand.description}\n\n${Object.keys(usage).map((name) => ` ${usage[name]}\n ${appsHelp[name]}`).join("\n")}\n`);
3340
+ return setupExitCodes.done;
3341
+ }
3342
+ if (!Object.hasOwn(usage, command)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown command \`vitehub apps ${command}\`. Usage: ${appsUsage}` });
3343
+ return await runApps(command, rest, context);
3344
+ } catch (error) {
3345
+ return writeSetupError(context, json, error);
3346
+ }
3347
+ }
3348
+ };
2245
3349
  // ../internal/dist/host-credentials.js
2246
3350
  const missingFixes = {
2247
3351
  cloudflare: {
@@ -2700,7 +3804,7 @@ function provisionEnv(env, credentials, link = {}) {
2700
3804
  }
2701
3805
  return env;
2702
3806
  }
2703
- function parseArgs(command, args) {
3807
+ function parseArgs$1(command, args) {
2704
3808
  const parsed = {
2705
3809
  dryRun: false,
2706
3810
  help: false,
@@ -2774,7 +3878,7 @@ async function resolveHost(command, parsed, context) {
2774
3878
  let host = parsed.host;
2775
3879
  let link;
2776
3880
  if (host === void 0) {
2777
- const { resolveDefaultDeployTarget } = await import("./deploy-BZ2iQjZL.js").then((n) => n.n);
3881
+ const { resolveDefaultDeployTarget } = await import("./deploy-DDen0JC0.js").then((n) => n.n);
2778
3882
  try {
2779
3883
  const target = await resolveDefaultDeployTarget(resolveViteHubProjectRoot(context.rootDir), context.env, `vitehub provision ${command}`);
2780
3884
  host = target.host;
@@ -2908,7 +4012,7 @@ function writeProvisionActions(actions, stdout) {
2908
4012
  }
2909
4013
  }
2910
4014
  async function runProvision(args, cliContext, load) {
2911
- const parsed = parseArgs("run", args);
4015
+ const parsed = parseArgs$1("run", args);
2912
4016
  const resolved = await resolveHost("run", parsed, cliContext);
2913
4017
  if ("exitCode" in resolved) return resolved.exitCode;
2914
4018
  const { host: provider } = resolved;
@@ -2960,7 +4064,7 @@ async function runProvision(args, cliContext, load) {
2960
4064
  return blocked ? 1 : 0;
2961
4065
  }
2962
4066
  async function runProvisionStatus(args, cliContext, load) {
2963
- const parsed = parseArgs("status", args);
4067
+ const parsed = parseArgs$1("status", args);
2964
4068
  const resolved = await resolveHost("status", parsed, cliContext);
2965
4069
  if ("exitCode" in resolved) return resolved.exitCode;
2966
4070
  const { host: provider } = resolved;
@@ -3032,4 +4136,4 @@ function createProvisionNamespace(load) {
3032
4136
  name: "provision"
3033
4137
  };
3034
4138
  }
3035
- export { internalErrorDiagnostics as $, parseOperationInput as A, formatInstallArgument as B, callOperationFromCli as C, operationCliOptions as D, operationCall as E, featureHosts as F, appUrlError as G, installSpecifier as H, featureIds as I, findViteHubDevServerUrl as J, collectViteHubCliContribution as K, featurePackages as L, reservedOperationNamespaces as M, setupCommandNames as N, operationCliPath as O, resolveViteHubProjectRoot as P, isRecord as Q, featureSupport as R, callOperation as S, createOperationRegistry as T, quoteSupportedInstallSpecifier as U, impliedFeatures as V, invariant as W, viteCliProjectConfig as X, getStableStdoutWrite as Y, withStdoutOnStderr as Z, readProvisionState as _, writeProvisionActions as a, loadAllEnv as b, createNetlifyApiClient as c, planProvisionSteps as d, resolveHostCredentials as f, mergeProvisionState as g, PROVISION_STATE_FILE as h, provisionEnv as i, operationInputJsonSchema as j, operationsOf as k, createVercelProvisionClient as l, cliErrorDiagnostics as m, isProvisionHost as n, createCloudflareApiClient as o, runHostCli as p, createCliDiscoveryNitroCloser as q, provisionActionStatus as r, createCloudflareProvisionClient as s, createProvisionNamespace as t, isProvisionRequestError as u, readProvisionStateSync as v, collectOperationContributions as w, withViteStageEnvironment as x, writeProvisionState as y, features as z };
4139
+ export { readProvisionStateSync as $, resolveDeploymentPlan as A, viteCliProjectConfig as At, readConsoleCredential as B, installArgs as C, quoteSupportedInstallSpecifier as Ct, shellQuote as D, createCliDiscoveryNitroCloser as Dt, setupStatus as E, collectViteHubCliContribution as Et, consoleTokenVariable as F, setupFailure as G, isSetupFailure as H, consoleUrlVariable as I, writeSetupJson as J, table as K, defaultConsoleUrl as L, listMatchingFiles as M, isRecord as Mt, consoleCredentialsFile as N, uninstallArgs as O, findViteHubDevServerUrl as Ot, consoleOrigin as P, readProvisionState as Q, loginCommand as R, formatInstallCommand as S, installSpecifier as St, missingProviderOption as T, appUrlError as Tt, readSetupArgs as U, whoamiCommand as V, setupExitCodes as W, PROVISION_STATE_FILE as X, cliErrorDiagnostics as Y, mergeProvisionState as Z, consoleAppUrl as _, featureIds as _t, writeProvisionActions as a, collectOperationContributions as at, listConsoleApps as b, features as bt, createNetlifyApiClient as c, operationCliOptions as ct, planProvisionSteps as d, parseOperationInput as dt, writeProvisionState as et, resolveHostCredentials as f, operationInputJsonSchema as ft, checkProblem as g, featureHosts as gt, checkConsoleApp as h, resolveViteHubProjectRoot as ht, provisionEnv as i, callOperationFromCli as it, hasDefinitionFiles as j, withStdoutOnStderr as jt, hostFromNitroPreset as k, getStableStdoutWrite as kt, createVercelProvisionClient as l, operationCliPath as lt, appsCommand as m, setupCommandNames as mt, isProvisionHost as n, withViteStageEnvironment as nt, createCloudflareApiClient as o, createOperationRegistry as ot, runHostCli as p, reservedOperationNamespaces as pt, writeSetupError as q, provisionActionStatus as r, callOperation as rt, createCloudflareProvisionClient as s, operationCall as st, createProvisionNamespace as t, loadAllEnv as tt, isProvisionRequestError as u, operationsOf as ut, consoleClient as v, featurePackages as vt, installCommand as w, invariant as wt, openConsole as x, impliedFeatures as xt, linkConsoleApp as y, featureSupport as yt, logoutCommand as z };