@vite-hub/cli 0.0.4 → 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,2262 @@
1
+ import { createRequire } from "node:module";
2
+ import { spawn } from "node:child_process";
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { dirname, resolve } from "pathe";
5
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
6
+ import { basename as basename$1, dirname as dirname$1, join as join$1, parse, resolve as resolve$1 } from "node:path";
7
+ import "node:readline/promises";
8
+ import { defineDiagnostics } from "nostics";
9
+ import "node:url";
10
+ import { tmpdir } from "node:os";
11
+ import { createBirpc } from "birpc";
12
+ //#region ../internal/dist/object.js
13
+ /** A non-null object that is not an array. Functions do not pass. */
14
+ function isRecord(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ /** A non-null object or a function that is not an array. */
18
+ function isRecordOrFunction(value) {
19
+ return Object(value) === value && !Array.isArray(value);
20
+ }
21
+ //#endregion
22
+ //#region ../internal/dist/cli.js
23
+ const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
24
+ const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
25
+ const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
26
+ const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
27
+ const stdoutRedirectGlobal = globalThis;
28
+ /**
29
+ * Sends `process.stdout` writes to stderr while `run` loads project config.
30
+ * Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
31
+ */
32
+ async function withStdoutOnStderr(run, stderr = process.stderr) {
33
+ getStableStdoutWrite();
34
+ const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
35
+ let release;
36
+ stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
37
+ release = resolve;
38
+ });
39
+ await previous;
40
+ const write = process.stdout.write;
41
+ if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
42
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
43
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
44
+ }
45
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
46
+ process.stdout.write = ((chunk, encoding, callback) => {
47
+ const done = typeof encoding === "function" ? encoding : callback;
48
+ let called = false;
49
+ const onComplete = (error) => {
50
+ if (called) return;
51
+ called = true;
52
+ done?.(error);
53
+ };
54
+ const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
55
+ if (done && !called) {
56
+ if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
57
+ else if (stderr.write.length < 2) onComplete();
58
+ }
59
+ return result;
60
+ });
61
+ try {
62
+ return await run();
63
+ } finally {
64
+ process.stdout.write = write;
65
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
66
+ release();
67
+ }
68
+ }
69
+ /**
70
+ * A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
71
+ * Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
72
+ * config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
73
+ * then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
74
+ */
75
+ function createCliDiscoveryNitroCloser() {
76
+ const instances = [];
77
+ return {
78
+ close: async () => {
79
+ await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
80
+ },
81
+ plugin: {
82
+ name: "vite-hub/cli-discovery-nitro",
83
+ nitro: { setup: (nitro) => {
84
+ instances.push(nitro);
85
+ } }
86
+ }
87
+ };
88
+ }
89
+ /** Returns the unredirected process stdout writer for payload output. */
90
+ function getStableStdoutWrite() {
91
+ const current = process.stdout.write;
92
+ if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
93
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
94
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
95
+ }
96
+ return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
97
+ }
98
+ async function resolveContributor(value) {
99
+ return typeof value === "function" ? await value() : value;
100
+ }
101
+ /** Resolves command namespaces and Provision Steps from one contribution per plugin. */
102
+ async function collectViteHubCliContribution(plugins) {
103
+ const namespaces = /* @__PURE__ */ new Map();
104
+ const steps = /* @__PURE__ */ new Map();
105
+ const seeds = /* @__PURE__ */ new Map();
106
+ let publicUrl;
107
+ for (const plugin of plugins) {
108
+ if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
109
+ const metadata = plugin.vitehub;
110
+ const contributor = await resolveContributor(metadata?.cli);
111
+ if (!contributor) continue;
112
+ publicUrl ??= contributor.publicUrl;
113
+ for (const namespace of contributor.namespaces) {
114
+ const existing = namespaces.get(namespace.name);
115
+ if (!existing) {
116
+ namespaces.set(namespace.name, {
117
+ ...namespace,
118
+ features: [...namespace.features]
119
+ });
120
+ continue;
121
+ }
122
+ const features = new Map(existing.features.map((feature) => [feature.name, feature]));
123
+ for (const feature of namespace.features) features.set(feature.name, feature);
124
+ existing.features = [...features.values()];
125
+ }
126
+ for (const step of contributor.provision ?? []) steps.set(step.id, step);
127
+ for (const seed of contributor.seeds ?? []) seeds.set(seed.name, seed);
128
+ }
129
+ return {
130
+ namespaces: [...namespaces.values()],
131
+ provision: [...steps.values()],
132
+ seeds: [...seeds.values()],
133
+ ...publicUrl ? { publicUrl } : {}
134
+ };
135
+ }
136
+ /** File in the project root where the running dev server tells commands where it listens. */
137
+ const viteHubDevServerFile = ".vitehub/dev-server.json";
138
+ /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
139
+ function readViteHubDevServerFile(root) {
140
+ try {
141
+ const value = JSON.parse(readFileSync(join$1(root, viteHubDevServerFile), "utf8"));
142
+ const url = isRecord(value) ? value.url : void 0;
143
+ const served = isRecord(value) ? value.root : void 0;
144
+ return typeof url === "string" && url && typeof served === "string" && served ? {
145
+ root: served,
146
+ url
147
+ } : void 0;
148
+ } catch {
149
+ return;
150
+ }
151
+ }
152
+ /**
153
+ * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
154
+ * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
155
+ */
156
+ function findViteHubDevServerUrl(roots, env) {
157
+ for (const root of roots) {
158
+ const file = readViteHubDevServerFile(root);
159
+ if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
160
+ }
161
+ return env["VITEHUB_DEV_SERVER_URL"] || void 0;
162
+ }
163
+ //#endregion
164
+ //#region ../internal/dist/error-diagnostics-NFLF9k-4.js
165
+ const dynamicError$1 = { why: ({ message }) => message === void 0 ? "" : String(message) };
166
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
167
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
168
+ codes: {
169
+ INTERNAL_R0012: {
170
+ ...dynamicError$1,
171
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
172
+ },
173
+ INTERNAL_R0013: {
174
+ ...dynamicError$1,
175
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
176
+ },
177
+ INTERNAL_R0014: {
178
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
179
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
180
+ },
181
+ INTERNAL_R0020: {
182
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
183
+ why: ({ message }) => message === void 0 ? "" : String(message)
184
+ },
185
+ INTERNAL_R0021: {
186
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
187
+ why: ({ message }) => message === void 0 ? "" : String(message)
188
+ },
189
+ INTERNAL_R0022: {
190
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
191
+ why: ({ message }) => message === void 0 ? "" : String(message)
192
+ },
193
+ INTERNAL_R0024: {
194
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
195
+ why: ({ message }) => message === void 0 ? "" : String(message)
196
+ },
197
+ INTERNAL_R0023: {
198
+ fix: "Ask for access to the section of this operation.",
199
+ why: ({ message }) => message === void 0 ? "" : String(message)
200
+ },
201
+ INTERNAL_B0001: {
202
+ ...dynamicError$1,
203
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
204
+ },
205
+ INTERNAL_B0015: {
206
+ ...dynamicError$1,
207
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
208
+ },
209
+ INTERNAL_B0016: {
210
+ ...dynamicError$1,
211
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
212
+ },
213
+ INTERNAL_B0017: {
214
+ ...dynamicError$1,
215
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
216
+ },
217
+ INTERNAL_B0018: {
218
+ ...dynamicError$1,
219
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
220
+ },
221
+ INTERNAL_B0019: {
222
+ ...dynamicError$1,
223
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
224
+ },
225
+ INTERNAL_B0020: {
226
+ ...dynamicError$1,
227
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
228
+ },
229
+ INTERNAL_B0021: {
230
+ ...dynamicError$1,
231
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
232
+ },
233
+ INTERNAL_B0022: {
234
+ ...dynamicError$1,
235
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
236
+ },
237
+ INTERNAL_B0025: {
238
+ ...dynamicError$1,
239
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
240
+ },
241
+ INTERNAL_B0026: {
242
+ ...dynamicError$1,
243
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
244
+ },
245
+ INTERNAL_B0027: {
246
+ ...dynamicError$1,
247
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
248
+ },
249
+ INTERNAL_B0028: {
250
+ ...dynamicError$1,
251
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
252
+ },
253
+ INTERNAL_B0029: {
254
+ ...dynamicError$1,
255
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
256
+ },
257
+ INTERNAL_B0031: {
258
+ ...dynamicError$1,
259
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
260
+ },
261
+ INTERNAL_B0032: {
262
+ ...dynamicError$1,
263
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
264
+ },
265
+ INTERNAL_B0035: {
266
+ ...dynamicError$1,
267
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
268
+ },
269
+ INTERNAL_B0039: {
270
+ ...dynamicError$1,
271
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
272
+ },
273
+ INTERNAL_B0040: {
274
+ ...dynamicError$1,
275
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
276
+ },
277
+ INTERNAL_B0043: {
278
+ ...dynamicError$1,
279
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
280
+ },
281
+ INTERNAL_B0046: {
282
+ ...dynamicError$1,
283
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
284
+ },
285
+ INTERNAL_B0047: {
286
+ ...dynamicError$1,
287
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
288
+ },
289
+ INTERNAL_B0048: {
290
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
291
+ why: ({ message }) => message === void 0 ? "" : String(message)
292
+ },
293
+ INTERNAL_B0049: {
294
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
295
+ why: ({ message }) => message === void 0 ? "" : String(message)
296
+ },
297
+ INTERNAL_B0050: {
298
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
299
+ why: ({ message }) => message === void 0 ? "" : String(message)
300
+ },
301
+ INTERNAL_B0051: {
302
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
303
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
304
+ },
305
+ INTERNAL_B0052: {
306
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
307
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
308
+ },
309
+ INTERNAL_R0025: {
310
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
311
+ why: ({ message }) => message === void 0 ? "" : String(message)
312
+ },
313
+ INTERNAL_R0026: {
314
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
315
+ fix: "Review the operation, then run it again with --yes to confirm the change."
316
+ },
317
+ INTERNAL_C0001: {
318
+ ...dynamicError$1,
319
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
320
+ },
321
+ INTERNAL_C0002: {
322
+ ...dynamicError$1,
323
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
324
+ },
325
+ INTERNAL_R0001: {
326
+ ...dynamicError$1,
327
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
328
+ },
329
+ INTERNAL_R0002: {
330
+ ...dynamicError$1,
331
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
332
+ },
333
+ INTERNAL_R0004: {
334
+ ...dynamicError$1,
335
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
336
+ },
337
+ INTERNAL_R0005: {
338
+ ...dynamicError$1,
339
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
340
+ },
341
+ INTERNAL_R0006: {
342
+ ...dynamicError$1,
343
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
344
+ },
345
+ INTERNAL_R0007: {
346
+ ...dynamicError$1,
347
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
348
+ },
349
+ INTERNAL_R0008: {
350
+ ...dynamicError$1,
351
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
352
+ },
353
+ INTERNAL_R0009: {
354
+ ...dynamicError$1,
355
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
356
+ },
357
+ INTERNAL_R0010: {
358
+ ...dynamicError$1,
359
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
360
+ },
361
+ INTERNAL_R0011: {
362
+ ...dynamicError$1,
363
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
364
+ },
365
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
366
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
367
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
368
+ },
369
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
370
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
371
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
372
+ },
373
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
374
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
375
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
376
+ },
377
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
378
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
379
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
380
+ },
381
+ INTERNAL_FORGE_NOT_INSTALLED: {
382
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
383
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
384
+ },
385
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
386
+ why: ({ detail }) => detail,
387
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
388
+ },
389
+ INTERNAL_MCP_METHOD_FAILED: {
390
+ why: ({ name }) => `${name} failed on the server.`,
391
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
392
+ },
393
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
394
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
395
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
396
+ },
397
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
398
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
399
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
400
+ },
401
+ INTERNAL_PRESET_TUPLE_INVALID: {
402
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
403
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
404
+ },
405
+ INTERNAL_SECRET_PURPOSE_MISSING: {
406
+ why: "[vitehub] A derived secret requires a purpose.",
407
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
408
+ },
409
+ INTERNAL_SECRET_TOO_SHORT: {
410
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
411
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
412
+ },
413
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
414
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
415
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
416
+ },
417
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
418
+ why: "Received integer which cannot be safely represented as a JavaScript number",
419
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
420
+ },
421
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
422
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
423
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
424
+ }
425
+ }
426
+ });
427
+ //#endregion
428
+ //#region ../internal/dist/console-signature.js
429
+ /**
430
+ * Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
431
+ * CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
432
+ * its env cannot sign a request. The module uses only Web Crypto, so it runs in Node, Workers, Deno, and browsers.
433
+ *
434
+ * The signature covers this text, one field per line:
435
+ *
436
+ * ```txt
437
+ * vitehub-signature-v1
438
+ * POST
439
+ * /_vitehub/rpc
440
+ * https://app.example.com
441
+ * 1794400000
442
+ * CONSOLE_3F9A12BC
443
+ * <SHA-256 of the body bytes, base64url>
444
+ * <the x-vitehub-caller header>
445
+ * ```
446
+ */
447
+ /** The signature header: `key=<NAME>, t=<seconds>, origin=<app origin>, body=<SHA-256>, v1=<signature>`. */
448
+ const consoleSignatureHeader = "x-vitehub-signature";
449
+ /** Who calls, as base64url JSON. The signature covers it. See {@link ConsoleCaller}. */
450
+ const consoleCallerHeader = "x-vitehub-caller";
451
+ /** The first line of the signed text. A new format gets a new tag. */
452
+ const consoleSignatureVersion = "vitehub-signature-v1";
453
+ /** The CLI reads its private key from `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. `<NAME>` is the key name that it signs with. */
454
+ const consolePrivateKeyPrefix = "VITEHUB_CONSOLE_PRIVATE_KEY_";
455
+ const keyNamePattern = /^[A-Z0-9_]{1,64}$/;
456
+ const encoder = new TextEncoder();
457
+ new TextDecoder();
458
+ const ed25519 = { name: "Ed25519" };
459
+ const pkcs8Prefix = Uint8Array.of(48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32);
460
+ function base64url(bytes) {
461
+ let binary = "";
462
+ for (const byte of bytes) binary += String.fromCharCode(byte);
463
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
464
+ }
465
+ /** The bytes of a base64url value, or `undefined` when it is not canonical base64url without padding. */
466
+ function fromBase64url(value) {
467
+ if (!/^[\w-]*$/.test(value) || value.length % 4 === 1) return void 0;
468
+ const bytes = Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
469
+ return base64url(bytes) === value ? bytes : void 0;
470
+ }
471
+ function bytesOf(body) {
472
+ if (typeof body === "string") return encoder.encode(body);
473
+ return body instanceof Uint8Array ? Uint8Array.from(body) : new Uint8Array(body);
474
+ }
475
+ /** The SHA-256 of the exact body bytes, base64url. A request without a body hashes zero bytes. */
476
+ async function consoleBodySha256(body = "") {
477
+ return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytesOf(body))));
478
+ }
479
+ /** The text that the signature covers. Fields are joined with `\n`. */
480
+ function consoleSignedText(fields) {
481
+ return [
482
+ consoleSignatureVersion,
483
+ fields.method.toUpperCase(),
484
+ fields.target,
485
+ fields.origin,
486
+ fields.timestamp,
487
+ fields.key,
488
+ fields.bodySha256,
489
+ fields.caller
490
+ ].join("\n");
491
+ }
492
+ /** The path and query of a URL, the part of the request target that the signature covers. */
493
+ function requestTarget(url) {
494
+ return `${url.pathname}${url.search}`;
495
+ }
496
+ /** Whether a name can be the `<NAME>` of `VITEHUB_CONSOLE_KEY_<NAME>`: up to 64 of `A-Z`, `0-9`, and `_`. */
497
+ function isConsoleKeyName(name) {
498
+ return keyNamePattern.test(name);
499
+ }
500
+ async function importPrivateKey(seed) {
501
+ const bytes = fromBase64url(seed.trim());
502
+ if (bytes?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_INVALID();
503
+ const der = new Uint8Array(pkcs8Prefix.length + 32);
504
+ der.set(pkcs8Prefix);
505
+ der.set(bytes, pkcs8Prefix.length);
506
+ return await crypto.subtle.importKey("pkcs8", der, ed25519, false, ["sign"]);
507
+ }
508
+ /** The `x-vitehub-caller` value of a caller: its JSON as base64url. */
509
+ function encodeConsoleCaller(caller) {
510
+ return base64url(encoder.encode(JSON.stringify(caller)));
511
+ }
512
+ /**
513
+ * Sign one request. `url` is the full URL that the request goes to, and `body` is the exact body that it sends. Returns
514
+ * the two headers to add: `x-vitehub-signature` and `x-vitehub-caller`.
515
+ */
516
+ async function signConsoleRequest(options) {
517
+ if (!isConsoleKeyName(options.key.name)) throw internalErrorDiagnostics.INTERNAL_CONSOLE_KEY_NAME_INVALID({ name: options.key.name });
518
+ const url = new URL(options.url);
519
+ const timestamp = String(Math.floor((options.now ?? Date.now()) / 1e3));
520
+ const bodySha256 = await consoleBodySha256(options.body);
521
+ const caller = encodeConsoleCaller(options.caller);
522
+ const text = consoleSignedText({
523
+ bodySha256,
524
+ caller,
525
+ key: options.key.name,
526
+ method: options.method,
527
+ origin: url.origin,
528
+ target: requestTarget(url),
529
+ timestamp
530
+ });
531
+ const signature = new Uint8Array(await crypto.subtle.sign(ed25519, await importPrivateKey(options.key.privateKey), encoder.encode(text)));
532
+ return {
533
+ [consoleCallerHeader]: caller,
534
+ [consoleSignatureHeader]: `key=${options.key.name}, t=${timestamp}, origin=${url.origin}, body=${bodySha256}, v1=${base64url(signature)}`
535
+ };
536
+ }
537
+ /**
538
+ * The signing key of a CLI from its env: the one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable. Returns `undefined`
539
+ * without one. Throws a coded error when there are several, or when the value is not a 32-byte seed.
540
+ */
541
+ function readConsoleSigningKey(env) {
542
+ const variables = Object.keys(env).filter((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && env[name]?.trim()).sort();
543
+ if (!variables.length) return void 0;
544
+ if (variables.length > 1) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE({
545
+ prefix: consolePrivateKeyPrefix,
546
+ variables: variables.join(", ")
547
+ });
548
+ const variable = variables[0];
549
+ const name = variable.slice(28);
550
+ const privateKey = env[variable].trim();
551
+ if (!isConsoleKeyName(name) || fromBase64url(privateKey)?.length !== 32) throw internalErrorDiagnostics.INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID({ variable });
552
+ return {
553
+ name,
554
+ privateKey
555
+ };
556
+ }
557
+ //#endregion
558
+ //#region ../internal/dist/build/vite.js
559
+ const projectRootDirectoryMarkers = [
560
+ ["server", "agents"],
561
+ ["server", "channels"],
562
+ ["server", "connections"],
563
+ ["server", "browsers"],
564
+ ["server", "emails"],
565
+ ["server", "schedules"],
566
+ ["server", "workspaces"]
567
+ ];
568
+ const projectRootFileMarkers = [
569
+ ["package.json"],
570
+ ["nuxt.config.ts"],
571
+ ["nuxt.config.mts"],
572
+ ["nuxt.config.js"],
573
+ ["nuxt.config.mjs"]
574
+ ];
575
+ function resolveViteHubProjectRoot(root, options = {}) {
576
+ const resolvedRoot = resolve$1(root);
577
+ const temporaryRoot = resolve$1(tmpdir());
578
+ const sharedTemporaryRoot = dirname$1(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
579
+ if (options.projectRoot) return resolve$1(resolvedRoot, options.projectRoot);
580
+ if (basename$1(resolvedRoot) === "app") {
581
+ const parent = dirname$1(resolvedRoot);
582
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
583
+ "nuxt.config.ts",
584
+ "nuxt.config.mts",
585
+ "nuxt.config.js",
586
+ "nuxt.config.mjs"
587
+ ]))) return parent;
588
+ }
589
+ let current = resolvedRoot;
590
+ while (true) {
591
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
592
+ if (hasProjectRootMarker(current)) return current;
593
+ const parent = dirname$1(current);
594
+ if (parent === current) return resolvedRoot;
595
+ current = parent;
596
+ }
597
+ }
598
+ function hasProjectRootDirectoryMarker(root) {
599
+ for (const marker of projectRootDirectoryMarkers) try {
600
+ if (statSync(resolve$1(root, ...marker)).isDirectory()) return true;
601
+ } catch (error) {
602
+ if (error.code !== "ENOENT") throw error;
603
+ }
604
+ return false;
605
+ }
606
+ function hasProjectRootMarker(root) {
607
+ if (hasProjectRootDirectoryMarker(root)) return true;
608
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
609
+ }
610
+ function hasProjectRootFileMarker(root, markers) {
611
+ for (const marker of markers) {
612
+ const path = Array.isArray(marker) ? marker : [marker];
613
+ try {
614
+ if (statSync(resolve$1(root, ...path)).isFile()) return true;
615
+ } catch (error) {
616
+ if (error.code !== "ENOENT") throw error;
617
+ }
618
+ }
619
+ return false;
620
+ }
621
+ //#endregion
622
+ //#region ../internal/dist/standard-schema.js
623
+ function readOwn(value, key) {
624
+ if (value === null || Object(value) !== value) return;
625
+ try {
626
+ return Reflect.get(Object(value), key);
627
+ } catch {
628
+ return;
629
+ }
630
+ }
631
+ /**
632
+ * Read a Standard JSON Schema projection without throwing.
633
+ *
634
+ * Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
635
+ * (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
636
+ */
637
+ function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
638
+ const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
639
+ const project = readOwn(jsonSchema, direction);
640
+ if (typeof project !== "function") return;
641
+ try {
642
+ const result = project.call(jsonSchema, libraryOptions ? {
643
+ target,
644
+ libraryOptions
645
+ } : { target });
646
+ return isRecordOrFunction(result) ? result : void 0;
647
+ } catch {
648
+ return;
649
+ }
650
+ }
651
+ //#endregion
652
+ //#region ../internal/dist/operation-definition.js
653
+ const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
654
+ const kinds = /* @__PURE__ */ new Set([
655
+ "read",
656
+ "write",
657
+ "destructive"
658
+ ]);
659
+ function invalidDefinition(name, reason) {
660
+ return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
661
+ }
662
+ function checkDefinition(definition) {
663
+ if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
664
+ const { name } = definition;
665
+ if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
666
+ if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
667
+ const { section } = definition;
668
+ if (section !== false && !(section instanceof Function) && !isSectionId(section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false; section ids cannot contain ':'.");
669
+ if (definition.scope !== void 0 && (!(definition.scope instanceof Function) || String(section) !== section)) throw invalidDefinition(name, "scope must be a function, and it needs a section id.");
670
+ if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
671
+ const input = definition.input;
672
+ if (!isRecordOrFunction(input) || !isRecordOrFunction(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
673
+ if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
674
+ const { maxRequestBytes } = definition;
675
+ if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
676
+ if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
677
+ const { mcp } = definition;
678
+ if (mcp !== void 0 && mcp !== false && (!isRecordOrFunction(mcp) || mcp.title !== void 0 && (String(mcp.title) !== mcp.title || !mcp.title) || mcp.format !== void 0 && !(mcp.format instanceof Function))) throw invalidDefinition(name, "mcp must be false, or an object with a title string and a format function.");
679
+ }
680
+ /** The default limit of a call, in bytes. */
681
+ const defaultRequestBytes = 65536;
682
+ /** The top-level setup commands of the CLI, such as `vitehub status`. They run before the project config loads. */
683
+ const setupCommandNames = [
684
+ "init",
685
+ "add",
686
+ "remove",
687
+ "status",
688
+ "catalog",
689
+ "link",
690
+ "unlink",
691
+ "deploy",
692
+ "deployments",
693
+ "drain",
694
+ "login",
695
+ "logout",
696
+ "whoami"
697
+ ];
698
+ /** CLI namespaces owned by built-in commands. */
699
+ const reservedOperationNamespaces = [
700
+ "inspect",
701
+ "provision",
702
+ "seed",
703
+ ...setupCommandNames
704
+ ];
705
+ function isOperation(value) {
706
+ try {
707
+ checkDefinition(value);
708
+ return true;
709
+ } catch {
710
+ return false;
711
+ }
712
+ }
713
+ function isSectionId(section) {
714
+ return typeof section === "string" && section !== "" && !section.includes(":");
715
+ }
716
+ /** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
717
+ function operationInputJsonSchema(operation) {
718
+ return standardJsonSchema(operation.input, "input") ?? { type: "object" };
719
+ }
720
+ //#endregion
721
+ //#region ../internal/dist/operation-rpc.js
722
+ /** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
723
+ const operationRpcPath = "/_vitehub/rpc";
724
+ function text(value) {
725
+ return String(value) === value && value ? value : void 0;
726
+ }
727
+ /** Read an untrusted failure body. It keeps only the diagnostic fields, so a stack never passes through. */
728
+ function readOperationRpcError(value) {
729
+ if (!isRecord(value)) return void 0;
730
+ const code = text(value.code);
731
+ const message = text(value.message);
732
+ const status = value.status;
733
+ if (!code || !message || !Number.isInteger(status)) return void 0;
734
+ const failure = {
735
+ code,
736
+ message,
737
+ status: Number(status)
738
+ };
739
+ if (text(value.fix)) failure.fix = text(value.fix);
740
+ if (text(value.docs)) failure.docs = text(value.docs);
741
+ if (isRecord(value.details)) failure.details = value.details;
742
+ return failure;
743
+ }
744
+ /** Read one response message. */
745
+ function readOperationRpcReply(value) {
746
+ if (!isRecord(value) || value.t !== "s") return void 0;
747
+ const id = text(value.i);
748
+ if (Object.hasOwn(value, "e")) {
749
+ const error = readOperationRpcError(value.e);
750
+ return error ? {
751
+ t: "s",
752
+ ...id ? { i: id } : {},
753
+ e: error
754
+ } : void 0;
755
+ }
756
+ return id ? {
757
+ t: "s",
758
+ i: id,
759
+ r: value.r
760
+ } : void 0;
761
+ }
762
+ /**
763
+ * Call one operation with birpc over a request and answer transport, such as one HTTP POST per call. `send` posts the
764
+ * JSON message and returns the parsed answer; its own failures, such as a network error or an abort, reject.
765
+ */
766
+ async function callOperationRpc(name, input, send) {
767
+ let receive;
768
+ let answer;
769
+ const notReply = /* @__PURE__ */ new Error("The answer is not a reply to the operation call.");
770
+ const rpc = createBirpc({}, {
771
+ on: (listener) => {
772
+ receive = listener;
773
+ },
774
+ post: async (message) => {
775
+ answer = await send(JSON.stringify(message));
776
+ const reply = readOperationRpcReply(answer.body);
777
+ if (!reply || reply.i !== void 0 && reply.i !== message.i) throw notReply;
778
+ await receive({
779
+ ...reply,
780
+ i: message.i
781
+ });
782
+ },
783
+ proxify: false,
784
+ timeout: -1
785
+ });
786
+ try {
787
+ return {
788
+ ok: true,
789
+ value: await rpc.$call(name, ...input === void 0 ? [] : [input]),
790
+ answer
791
+ };
792
+ } catch (error) {
793
+ if (!answer) throw error;
794
+ if (error === notReply) return {
795
+ ok: false,
796
+ error: void 0,
797
+ answer
798
+ };
799
+ return {
800
+ ok: false,
801
+ error: readOperationRpcError(error),
802
+ answer
803
+ };
804
+ }
805
+ }
806
+ //#endregion
807
+ //#region ../internal/dist/operations.js
808
+ /** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
809
+ const operationRpcHeader = "x-vitehub-console";
810
+ /** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
811
+ const operationRootHeader = "x-vitehub-root";
812
+ const operationExpectedRootsHeader = "x-vitehub-expected-roots";
813
+ /** A short stable hash of a project root. The CLI uses it to see that the dev server runs its own project. */
814
+ function projectRootHash(root) {
815
+ const normalized = root.replace(/\\/g, "/").replace(/\/+$/, "");
816
+ let first = 3735928559;
817
+ let second = 1103547991;
818
+ for (let index = 0; index < normalized.length; index++) {
819
+ const code = normalized.charCodeAt(index);
820
+ first = Math.imul(first ^ code, 2654435761);
821
+ second = Math.imul(second ^ code, 1597334677);
822
+ }
823
+ first = Math.imul(first ^ first >>> 16, 2246822507) ^ Math.imul(second ^ second >>> 13, 3266489909);
824
+ second = Math.imul(second ^ second >>> 16, 2246822507) ^ Math.imul(first ^ first >>> 13, 3266489909);
825
+ return `${(second >>> 0).toString(16).padStart(8, "0")}${(first >>> 0).toString(16).padStart(8, "0")}`;
826
+ }
827
+ /** Header that names the tool behind a call. `cli` marks `vitehub` commands. */
828
+ const operationSurfaceHeader = "x-vitehub-surface";
829
+ /** Generated CLI commands ask the server to check confirmation after it parses the input. */
830
+ const operationConfirmationHeader = "x-vitehub-confirmation";
831
+ function pluginName(plugin) {
832
+ const name = Reflect.get(plugin, "name");
833
+ return String(name) === name && name ? name : "unnamed plugin";
834
+ }
835
+ /** Reads `plugin.vitehub.operations` from resolved Vite plugins. The same module and export from two plugins counts once. */
836
+ async function collectOperationContributions(plugins) {
837
+ const collected = /* @__PURE__ */ new Map();
838
+ for (const plugin of plugins) {
839
+ if (!isRecordOrFunction(plugin) || !Object.hasOwn(plugin, "vitehub")) continue;
840
+ const declared = Reflect.get(Object(Reflect.get(plugin, "vitehub")), "operations");
841
+ if (declared === void 0) continue;
842
+ const entries = declared instanceof Function ? await declared() : declared;
843
+ const owner = pluginName(plugin);
844
+ if (!Array.isArray(entries)) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} sets vitehub.operations, which must be a list of { module, export }.` });
845
+ for (const entry of entries) {
846
+ if (!isRecordOrFunction(entry) || String(entry.module) !== entry.module || !entry.module) throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] ${owner} contributes an operation entry without a module.` });
847
+ const exportName = String(entry.export) === entry.export && entry.export ? entry.export : "default";
848
+ const key = `${entry.module}#${exportName}`;
849
+ if (collected.has(key)) continue;
850
+ collected.set(key, {
851
+ module: entry.module,
852
+ export: exportName,
853
+ plugin: owner,
854
+ ...entry.load instanceof Function ? { load: entry.load } : {},
855
+ ...entry.runtime === false ? { runtime: false } : {}
856
+ });
857
+ }
858
+ }
859
+ return [...collected.values()];
860
+ }
861
+ /** Operations of one module export, flat. A single operation or an array both work. */
862
+ function operationsOf(value) {
863
+ const list = Array.isArray(value) ? value : [value];
864
+ const operations = [];
865
+ for (const item of list) {
866
+ if (!isOperation(item)) throw invalidDefinition(isRecordOrFunction(item) ? item.name : void 0, "a contributed export must hold defineOperation() results.");
867
+ operations.push(item);
868
+ }
869
+ return operations;
870
+ }
871
+ /** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
872
+ function operationCliPath(operation) {
873
+ const dot = operation.name.indexOf(".");
874
+ return {
875
+ command: operation.cli?.command ?? operation.name.slice(dot + 1),
876
+ namespace: operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
877
+ };
878
+ }
879
+ /**
880
+ * The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
881
+ * Claude reject a dot in a tool name. `content.publish` is `content_publish`.
882
+ */
883
+ function operationToolName(name) {
884
+ return name.replace(/[^\w-]/g, "_");
885
+ }
886
+ /** Build the registry by name. A duplicate name or CLI command fails with `INTERNAL_B0048` or `INTERNAL_B0049`, two MCP tool names that match with `INTERNAL_B0050`. */
887
+ function createOperationRegistry(sources) {
888
+ const byName = /* @__PURE__ */ new Map();
889
+ for (const source of sources) for (const operation of source.operations) {
890
+ const existing = byName.get(operation.name);
891
+ if (existing && existing.operation !== operation) {
892
+ const owners = [existing.plugin, source.plugin].filter(Boolean).join(" and ");
893
+ throw internalErrorDiagnostics.INTERNAL_B0048({ message: `[vitehub] Two operations are named ${JSON.stringify(operation.name)}${owners ? ` (${owners})` : ""}.` });
894
+ }
895
+ byName.set(operation.name, {
896
+ operation,
897
+ ...source.plugin ? { plugin: source.plugin } : {}
898
+ });
899
+ }
900
+ const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
901
+ const commands = /* @__PURE__ */ new Map();
902
+ for (const operation of operations) {
903
+ const { command, namespace } = operationCliPath(operation);
904
+ if (reservedOperationNamespaces.includes(namespace)) throw invalidDefinition(operation.name, `the CLI namespace ${JSON.stringify(namespace)} is reserved for built-in commands. Set cli.namespace to another name.`);
905
+ const key = `${namespace} ${command}`;
906
+ const other = commands.get(key);
907
+ if (other) throw internalErrorDiagnostics.INTERNAL_B0049({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the CLI command \`vitehub ${key}\`.` });
908
+ commands.set(key, operation);
909
+ }
910
+ const tools = /* @__PURE__ */ new Map();
911
+ for (const operation of operations) {
912
+ if (operation.mcp === false) continue;
913
+ const tool = operationToolName(operation.name);
914
+ const other = tools.get(tool);
915
+ if (other) throw internalErrorDiagnostics.INTERNAL_B0050({ message: `[vitehub] The operations ${JSON.stringify(other.name)} and ${JSON.stringify(operation.name)} are both the MCP tool ${JSON.stringify(tool)}.` });
916
+ tools.set(tool, operation);
917
+ }
918
+ return {
919
+ get: (name) => byName.get(name)?.operation,
920
+ list: () => [...operations]
921
+ };
922
+ }
923
+ /** Issues of a failed Standard Schema check as one short line per issue. */
924
+ function describeInputIssues(issues) {
925
+ return issues.slice(0, 5).map((issue) => {
926
+ const path = (issue.path ?? []).map((segment) => String(isRecordOrFunction(segment) && "key" in segment ? segment.key : segment)).join(".");
927
+ return path ? `${path}: ${issue.message}` : issue.message;
928
+ }).join(" ");
929
+ }
930
+ /** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
931
+ async function parseOperationInput(operation, input) {
932
+ const result = await operation.input["~standard"].validate(input ?? {});
933
+ if (!result.issues) return result.value;
934
+ const error = internalErrorDiagnostics.INTERNAL_R0022({ message: `Invalid input for ${operation.name}. ${describeInputIssues(result.issues)}` });
935
+ throw Object.assign(error, { status: 400 });
936
+ }
937
+ /** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
938
+ function operationCall(operation, input) {
939
+ return {
940
+ kind: operation.kind,
941
+ readOnly: operation.readOnlyWhen?.(input) === true
942
+ };
943
+ }
944
+ const operationCredentialHint = "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.";
945
+ /** Headers of an operation call, without a signature. */
946
+ function operationHeaders() {
947
+ const headers = new Headers();
948
+ headers.set("accept", "application/json");
949
+ headers.set("content-type", "application/json");
950
+ headers.set(operationRpcHeader, "1");
951
+ headers.set(operationSurfaceHeader, "cli");
952
+ return headers;
953
+ }
954
+ /**
955
+ * The headers of one operation call to a deployed app: {@link operationHeaders}, and the signature of `body` when the
956
+ * env has a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`. The CLI signs as itself, `via: "cli"`. Throws a `TypeError` for a
957
+ * malformed private key.
958
+ */
959
+ async function signedOperationHeaders(env, url, body) {
960
+ const headers = operationHeaders();
961
+ const key = readConsoleSigningKey(env);
962
+ if (key) {
963
+ const signed = await signConsoleRequest({
964
+ body,
965
+ caller: { via: "cli" },
966
+ key,
967
+ method: "POST",
968
+ url
969
+ });
970
+ for (const [name, value] of Object.entries(signed)) headers.set(name, value);
971
+ }
972
+ return headers;
973
+ }
974
+ function unreachable(message, status = 503) {
975
+ const error = internalErrorDiagnostics.INTERNAL_R0024({ message });
976
+ return {
977
+ ok: false,
978
+ code: error.code,
979
+ fix: error.fix,
980
+ message,
981
+ status
982
+ };
983
+ }
984
+ function hasCredentials(env) {
985
+ return Object.keys(env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && Boolean(env[name]));
986
+ }
987
+ /** Call one operation over the RPC of a dev server or a deployed app. Never throws. */
988
+ async function callOperation(target, name, input) {
989
+ let origin = "the ViteHub app";
990
+ try {
991
+ const base = new URL(target.url);
992
+ if (!base.pathname.endsWith("/")) base.pathname = `${base.pathname}/`;
993
+ const url = new URL(operationRpcPath.slice(1), base);
994
+ origin = url.origin;
995
+ const env = target.roots?.length ? {} : target.env;
996
+ try {
997
+ readConsoleSigningKey(env);
998
+ } catch (error) {
999
+ return {
1000
+ ok: false,
1001
+ code: "INTERNAL_R0024",
1002
+ fix: "Run `vitehub secret console-key` for a new key pair. Set its private key here and its public key on the app.",
1003
+ message: error instanceof Error ? error.message : String(error),
1004
+ status: 401
1005
+ };
1006
+ }
1007
+ const outcome = await callOperationRpc(name, input ?? {}, async (body) => {
1008
+ const headers = await signedOperationHeaders(env, url, body);
1009
+ if (target.confirmed !== void 0) headers.set(operationConfirmationHeader, target.confirmed ? "confirmed" : "required");
1010
+ if (target.roots?.length) headers.set(operationExpectedRootsHeader, target.roots.map(projectRootHash).join(","));
1011
+ const response = await (target.fetch ?? fetch)(url.href, {
1012
+ body,
1013
+ headers,
1014
+ method: "POST",
1015
+ redirect: "manual",
1016
+ signal: AbortSignal.timeout(target.timeout ?? 3e4)
1017
+ });
1018
+ const text = await response.text();
1019
+ let json;
1020
+ try {
1021
+ json = text ? JSON.parse(text) : void 0;
1022
+ } catch {
1023
+ json = void 0;
1024
+ }
1025
+ return {
1026
+ body: json,
1027
+ response
1028
+ };
1029
+ });
1030
+ const { response } = outcome.answer;
1031
+ const served = response.headers.get(operationRootHeader);
1032
+ if (served && target.roots?.length && !target.roots.some((root) => projectRootHash(root) === served)) {
1033
+ const message = `The server at ${url.origin} runs another project than ${target.roots[0]}.`;
1034
+ const error = internalErrorDiagnostics.INTERNAL_R0025({ message });
1035
+ return {
1036
+ ok: false,
1037
+ code: error.code,
1038
+ fix: error.fix,
1039
+ message,
1040
+ status: 409
1041
+ };
1042
+ }
1043
+ if (outcome.ok) return {
1044
+ ok: true,
1045
+ value: outcome.value
1046
+ };
1047
+ const failure = outcome.error ?? readOperationRpcError(isRecordOrFunction(outcome.answer.body) ? {
1048
+ status: response.status,
1049
+ ...outcome.answer.body
1050
+ } : void 0);
1051
+ if (failure) {
1052
+ 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."}`;
1053
+ 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;
1054
+ return {
1055
+ ok: false,
1056
+ ...failure
1057
+ };
1058
+ }
1059
+ if (response.status === 401 || response.status >= 300 && response.status < 400) return unreachable(`${url.origin} asked for authentication (HTTP ${response.status}).`, 401);
1060
+ return unreachable(`${url.origin} did not answer as a ViteHub app (HTTP ${response.status}). Pass the origin of an app that runs ViteHub.`, response.status);
1061
+ } catch (error) {
1062
+ return unreachable(`The request to ${origin} failed: ${error instanceof Error ? error.message : String(error)}`);
1063
+ }
1064
+ }
1065
+ /**
1066
+ * Call one operation from a `vitehub` command: on `--url` when it is set, else on the dev server that the project
1067
+ * started. Never throws. Without a dev server the result is an `INTERNAL_R0024` failure that says to start one.
1068
+ */
1069
+ async function callOperationFromCli(call, name, input) {
1070
+ let roots;
1071
+ try {
1072
+ roots = [.../* @__PURE__ */ new Set([call.rootDir, resolveViteHubProjectRoot(call.rootDir)])];
1073
+ } catch {
1074
+ roots = [call.rootDir];
1075
+ }
1076
+ const url = call.url ?? findViteHubDevServerUrl(roots, call.env);
1077
+ if (!url) return unreachable(`No dev server is running for ${roots.at(-1)}.`);
1078
+ return await callOperation({
1079
+ ...call.confirmed !== void 0 ? { confirmed: call.confirmed } : {},
1080
+ env: call.env,
1081
+ ...call.fetch ? { fetch: call.fetch } : {},
1082
+ ...call.url ? {} : { roots },
1083
+ ...call.timeout ? { timeout: call.timeout } : {},
1084
+ url
1085
+ }, name, input);
1086
+ }
1087
+ //#endregion
1088
+ //#region ../internal/dist/vite-stage.js
1089
+ /**
1090
+ * Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
1091
+ * logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
1092
+ */
1093
+ function loadAllEnv(loadEnv, mode, envDir) {
1094
+ const write = process.stderr.write;
1095
+ process.stderr.write = () => true;
1096
+ try {
1097
+ return loadEnv(mode, envDir, "");
1098
+ } finally {
1099
+ process.stderr.write = write;
1100
+ }
1101
+ }
1102
+ const viteStageQueueKey = Symbol.for("vitehub.cli.vite-stage-queue");
1103
+ function definedEntries(env) {
1104
+ return Object.entries(env).filter((entry) => entry[1] !== void 0);
1105
+ }
1106
+ function replaceProcessEnv(entries) {
1107
+ for (const key of Object.keys(process.env)) delete process.env[key];
1108
+ for (const [key, value] of entries) process.env[key] = value;
1109
+ }
1110
+ /** Load stage config and modules under the same serialized, temporary process environment. */
1111
+ async function withViteStageEnvironment(env, callback) {
1112
+ const carrier = globalThis;
1113
+ const previous = carrier[viteStageQueueKey] ?? Promise.resolve();
1114
+ let release;
1115
+ carrier[viteStageQueueKey] = new Promise((resolve) => {
1116
+ release = resolve;
1117
+ });
1118
+ await previous;
1119
+ const previousEnvironment = definedEntries(process.env);
1120
+ const selectedEnvironment = definedEntries(env);
1121
+ try {
1122
+ replaceProcessEnv(selectedEnvironment);
1123
+ return await callback();
1124
+ } finally {
1125
+ replaceProcessEnv(previousEnvironment);
1126
+ release();
1127
+ }
1128
+ }
1129
+ //#endregion
1130
+ //#region ../internal/dist/provision-state.js
1131
+ const PROVISION_STATE_FILE = ".vitehub/provision.json";
1132
+ function getProvisionStatePath(rootDir) {
1133
+ return resolve(rootDir, PROVISION_STATE_FILE);
1134
+ }
1135
+ async function readProvisionState(rootDir) {
1136
+ const path = getProvisionStatePath(rootDir);
1137
+ try {
1138
+ return parseProvisionState(await readFile(path, "utf8"));
1139
+ } catch (cause) {
1140
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
1141
+ throw internalErrorDiagnostics.INTERNAL_R0014({
1142
+ path,
1143
+ cause
1144
+ });
1145
+ }
1146
+ }
1147
+ function readProvisionStateSync(rootDir) {
1148
+ const path = getProvisionStatePath(rootDir);
1149
+ try {
1150
+ return parseProvisionState(readFileSync(path, "utf8"));
1151
+ } catch (cause) {
1152
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
1153
+ throw internalErrorDiagnostics.INTERNAL_R0014({
1154
+ path,
1155
+ cause
1156
+ });
1157
+ }
1158
+ }
1159
+ async function writeProvisionState(rootDir, next) {
1160
+ const path = getProvisionStatePath(rootDir);
1161
+ const merged = mergeProvisionState(await readProvisionState(rootDir), next);
1162
+ await mkdir(dirname(path), { recursive: true });
1163
+ await writeFile(path, `${JSON.stringify(sortState(merged), null, 2)}\n`, "utf8");
1164
+ }
1165
+ function mergeProvisionState(base, next) {
1166
+ const merged = structuredClone(base);
1167
+ for (const provider of Object.keys(next)) {
1168
+ const categories = next[provider];
1169
+ if (!categories) continue;
1170
+ const target = merged[provider] ??= {};
1171
+ for (const [category, ids] of Object.entries(categories)) setOwn(target, category, {
1172
+ ...(Object.hasOwn(target, category) ? target[category] : void 0) ?? {},
1173
+ ...ids
1174
+ });
1175
+ }
1176
+ return merged;
1177
+ }
1178
+ function parseProvisionState(raw) {
1179
+ const parsed = JSON.parse(raw);
1180
+ if (!isRecord(parsed)) return {};
1181
+ const state = {};
1182
+ for (const provider of ["cloudflare", "vercel"]) {
1183
+ const categories = parsed[provider];
1184
+ if (!isRecord(categories)) continue;
1185
+ const validCategories = {};
1186
+ for (const [category, ids] of Object.entries(categories)) {
1187
+ if (!isRecord(ids)) continue;
1188
+ const validIds = {};
1189
+ for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
1190
+ if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
1191
+ }
1192
+ if (Object.keys(validCategories).length) state[provider] = validCategories;
1193
+ }
1194
+ return state;
1195
+ }
1196
+ function setOwn(target, key, value) {
1197
+ Object.defineProperty(target, key, {
1198
+ configurable: true,
1199
+ enumerable: true,
1200
+ value,
1201
+ writable: true
1202
+ });
1203
+ }
1204
+ function sortState(state) {
1205
+ return sortKeys(state);
1206
+ }
1207
+ function sortKeys(value) {
1208
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
1209
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]));
1210
+ }
1211
+ //#endregion
1212
+ //#region src/error-diagnostics.ts
1213
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
1214
+ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1215
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
1216
+ codes: {
1217
+ CLI_CONSOLE_LOGIN_FAILED: {
1218
+ fix: "Run `vitehub login` again, and approve the code in the browser within 15 minutes. Pass --console <url> for a self-hosted Console.",
1219
+ why: ({ console, message }) => `Sign-in to ${String(console)} did not finish. ${String(message)}`
1220
+ },
1221
+ CLI_CONSOLE_SIGNED_OUT: {
1222
+ fix: "Run `vitehub login`, or set VITEHUB_CONSOLE_TOKEN to an API key from Account settings in the Console.",
1223
+ why: ({ console }) => `There is no valid API key for ${String(console)}. The key is missing, expired, or revoked.`
1224
+ },
1225
+ CLI_ENV_FILE_EXISTS: {
1226
+ fix: ({ file }) => `Pass --yes to replace ${String(file)}, or move it first.`,
1227
+ why: ({ file }) => `${String(file)} exists. \`vitehub env pull\` does not replace a file without --yes.`
1228
+ },
1229
+ CLI_ENV_FILE_NOT_IGNORED: {
1230
+ fix: ({ file, tracked }) => tracked ? `Run \`git rm --cached ${String(file)}\` and add \`.env.*\` to .gitignore, then pull again.` : `Run \`echo '.env.*' >> .gitignore\`, then pull again.`,
1231
+ why: ({ file, tracked }) => tracked ? `git tracks ${String(file)}, so the values would be committed.` : `${String(file)} is not in .gitignore, so the values could be committed.`
1232
+ },
1233
+ CLI_ENV_PULL_FAILED: {
1234
+ fix: "Check that the Console stores env values, that the key opens the project, and that you are an owner or admin of the team.",
1235
+ why: ({ code, message }) => `The Console refused the pull (${String(code)}). ${String(message)}`
1236
+ },
1237
+ /** A host API answered with a shape that the CLI cannot read. */
1238
+ CLI_HOST_RESPONSE_INVALID: {
1239
+ fix: "Run the command again. If the error stays, check the status page of the host and update `@vite-hub/cli`.",
1240
+ why: ({ host }) => `[vitehub] The ${host} API returned an unexpected response.`
1241
+ },
1242
+ CLI_R0001: {
1243
+ ...dynamicError,
1244
+ fix: "Install `nuxt` in the project, such as with `pnpm add nuxt`, then run the command again."
1245
+ },
1246
+ CLI_R0002: {
1247
+ ...dynamicError,
1248
+ fix: "Install `@vite-hub/cli` again, such as with `pnpm add -D @vite-hub/cli`."
1249
+ },
1250
+ CLI_R0003: {
1251
+ fix: "Run the command with --help to see its input.",
1252
+ why: ({ message }) => message === void 0 ? "" : String(message)
1253
+ },
1254
+ CLI_R0005: {
1255
+ fix: "Start `vite dev` in this project, or pass `--url <origin>` of a running or deployed app. `VITEHUB_DEV_SERVER_URL` also names a server.",
1256
+ why: ({ message }) => message === void 0 ? "" : String(message)
1257
+ },
1258
+ /** A setup command failed with an error that has no code, and `--json` reports it. */
1259
+ CLI_SETUP_FAILED: {
1260
+ fix: "Fix the cause that the message names, then run the command again.",
1261
+ why: ({ message }) => message
1262
+ },
1263
+ SETUP_CONFIG_NOT_LITERAL: {
1264
+ fix: "Write the options as an object literal, such as `vitehub({ kv: true })`, or edit the config by hand.",
1265
+ why: ({ file, reason }) => `The vitehub() options in ${String(file)} cannot be read without running the config (${String(reason)}).`
1266
+ },
1267
+ SETUP_NOT_A_PROJECT: {
1268
+ fix: "Run the command in the folder of your Vite or Nuxt app, where its package.json is.",
1269
+ why: ({ root }) => `${String(root)} has no package.json, vite.config, or nuxt.config file.`
1270
+ },
1271
+ SETUP_CONFIG_MANUAL: {
1272
+ fix: ({ snippet }) => `Add these keys to the vitehub() options by hand:\n${String(snippet)}`,
1273
+ why: ({ file, reason }) => `ViteHub cannot edit the vitehub() options in ${String(file)} without running the config (${String(reason)}).`
1274
+ },
1275
+ SETUP_FEATURE_UNSUPPORTED: {
1276
+ fix: "Remove the feature from the command, or set `host` to a host that supports it. Run `vitehub catalog` to compare hosts.",
1277
+ why: ({ detail, feature, host }) => `${String(feature)} is not supported on the ${String(host)} host. ${String(detail)}`
1278
+ },
1279
+ SETUP_FILE_EXISTS: {
1280
+ fix: "Choose another --name, or edit the file by hand.",
1281
+ why: ({ definition, file, starter }) => starter === void 0 ? `${String(file)} exists and is not the starter Definition. ViteHub never overwrites a file.` : `${String(file)} already defines a ${String(definition)} Definition that conflicts with ${String(starter)}, so the build would reject both.`
1282
+ },
1283
+ SETUP_SERVER_DIR_MANUAL: {
1284
+ fix: ({ command }) => command === "remove" ? "Use literal rootDir and serverDir options without layers, or pass --force to turn the features off without checking unresolved Definition files." : "Create the Definition in your evaluated Nuxt server directory and rerun without --name, or use literal rootDir and serverDir options without layers.",
1285
+ why: "ViteHub cannot determine the Nuxt application server directory without running the config."
1286
+ },
1287
+ SETUP_INPUT_NEEDED: {
1288
+ fix: "Run the `rerun` command, or pass the missing values with --option.",
1289
+ why: ({ message }) => message === void 0 ? "" : String(message)
1290
+ },
1291
+ SETUP_INSTALL_FAILED: {
1292
+ 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."}`,
1293
+ why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
1294
+ },
1295
+ SETUP_FEATURE_IMPLIED: {
1296
+ fix: ({ by, feature }) => `Remove ${String(by)} too, or pass --force to write \`${String(feature)}: false\`.`,
1297
+ why: ({ by, feature }) => `${String(feature)} stays on because ${String(by)} turns it on.`
1298
+ },
1299
+ SETUP_FEATURE_REQUIRED: {
1300
+ fix: ({ by, feature }) => `Remove ${String(by)} too, or change its options before removing ${String(feature)}. --force cannot remove a required feature.`,
1301
+ why: ({ by, feature }) => `${String(feature)} is required by the configured options of ${String(by)}.`
1302
+ },
1303
+ SETUP_FEATURE_IN_USE: {
1304
+ fix: "Delete or move the files in `references`, then run the command again. Pass --force to turn the feature off and keep the files.",
1305
+ why: ({ features, references }) => `The app still uses ${String(features)}:\n${String(references)}`
1306
+ },
1307
+ SETUP_UNINSTALL_FAILED: {
1308
+ fix: ({ configWritten }) => `Run the uninstall command by hand to see the error. ${configWritten === false ? "ViteHub kept the config unchanged; starter files may already be deleted. Plan the removal again after fixing the uninstall." : "ViteHub already changed the config and deleted the starter files."}`,
1309
+ why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
1310
+ },
1311
+ SETUP_PLAN_UNKNOWN: {
1312
+ fix: "Plan the change again. A plan applies once, and only on the dev server that made it.",
1313
+ why: () => "The dev server has no plan with this id. It was applied already, or the server restarted."
1314
+ },
1315
+ SETUP_STALE_PLAN: {
1316
+ fix: "Run the command again to plan from the current file.",
1317
+ why: ({ file }) => `${String(file)} changed after ViteHub planned the change.`
1318
+ },
1319
+ SETUP_LINK_HOST_UNSUPPORTED: {
1320
+ fix: "Pass --host cloudflare, vercel, netlify, or deno, or set `host` in vitehub().",
1321
+ why: ({ host }) => `The ${String(host)} host has no project to link. A self-hosted Node server needs no link.`
1322
+ },
1323
+ SETUP_LINK_CREDENTIALS_MISSING: {
1324
+ fix: ({ fix }) => fix === void 0 ? "Log in with the host CLI, such as `npx wrangler login`, or set the host token, such as CLOUDFLARE_API_TOKEN, VERCEL_TOKEN, NETLIFY_AUTH_TOKEN, or DENO_DEPLOY_TOKEN, then run the command again." : String(fix),
1325
+ why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login.`
1326
+ },
1327
+ SETUP_LINK_ACCOUNT_REQUIRED: {
1328
+ fix: "Run the command again with --account <id>, using one of the account ids in `missing`.",
1329
+ why: ({ count }) => Number(count) === 0 ? "The Cloudflare token has access to no account." : `The Cloudflare token has access to ${String(count)} accounts, so the account to link is not clear.`
1330
+ },
1331
+ SETUP_LINK_HOST_REQUIRED: {
1332
+ fix: ({ command }) => `Run \`${String(command)} --host <host>\`, or make one host the default with \`vitehub link --host <host> --default\`.`,
1333
+ why: ({ hosts }) => `The project links several hosts (${String(hosts)}) and none is the default, so the host is not clear.`
1334
+ },
1335
+ SETUP_LINK_NAME_REQUIRED: {
1336
+ fix: "Pass --project <name>, or set `name` in vitehub() or in package.json.",
1337
+ why: () => "The project name is not known. vitehub() has no literal `name` and package.json has no name."
1338
+ },
1339
+ SETUP_LINK_PROJECT_NOT_FOUND: {
1340
+ fix: ({ rerun }) => `Run \`${String(rerun)}\` to create it, or pass --project with the name of a project that exists.`,
1341
+ why: ({ host, project, account }) => `The ${String(host)} project ${JSON.stringify(String(project))} does not exist${account ? ` in account ${String(account)}` : ""}.`
1342
+ },
1343
+ SETUP_INIT_DIR_NOT_EMPTY: {
1344
+ fix: "Choose a new or empty folder, or run `vitehub init` on the folder of a Vite or Nuxt app.",
1345
+ why: ({ dir }) => `${String(dir)} is not empty and holds no Vite or Nuxt app. ViteHub never overwrites a file.`
1346
+ },
1347
+ SETUP_INIT_FRAMEWORK_MISMATCH: {
1348
+ fix: ({ found }) => `Pass --framework ${String(found)}, or choose another folder.`,
1349
+ why: ({ dir, found, framework }) => `${String(dir)} holds a ${String(found)} app, not a ${String(framework)} app.`
1350
+ },
1351
+ SETUP_INIT_HOST_MIGRATION: {
1352
+ fix: "Use the app's current host, or migrate its enabled features, providers and Definitions in the config before running init again.",
1353
+ why: ({ host }) => `init cannot change an enabled ViteHub stack to the ${String(host)} host.`
1354
+ },
1355
+ SETUP_INIT_NUXT_VERSION: {
1356
+ fix: ({ dir, scaffolded }) => `${scaffolded ? `The scaffold files remain in ${String(dir)}. ` : ""}Set nuxt to a Nuxt 5 version, then run init on that folder again.`,
1357
+ why: ({ dir }) => `${String(dir)} does not declare a known Nuxt 5 version. ViteHub did not adopt it.`
1358
+ },
1359
+ SETUP_DEPLOY_HOST_UNSUPPORTED: {
1360
+ fix: "Set `host` in vitehub() to cloudflare, vercel, netlify, or deno, or start the Node server from `.output` yourself.",
1361
+ why: ({ host }) => `\`vitehub deploy\` has no upload for the ${String(host)} host.`
1362
+ },
1363
+ SETUP_DEPLOY_CREDENTIALS_MISSING: {
1364
+ fix: ({ fix }) => fix === void 0 ? "Log in with the host CLI, such as `npx wrangler login`, or set the host token, such as CLOUDFLARE_API_TOKEN, VERCEL_TOKEN, NETLIFY_AUTH_TOKEN, or DENO_DEPLOY_TOKEN, then run the command again." : String(fix),
1365
+ why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login.`
1366
+ },
1367
+ SETUP_DEPLOY_TEMPORARY_UNSUPPORTED: {
1368
+ fix: "Remove --temporary and deploy with your host login.",
1369
+ why: ({ reason }) => `--temporary cannot run here. ${String(reason)}`
1370
+ },
1371
+ SETUP_DEPLOY_PREVIEW_UNSUPPORTED: {
1372
+ fix: "Remove --preview to deploy to production.",
1373
+ why: ({ host }) => `The ${String(host)} deploy that the build writes always deploys to production.`
1374
+ },
1375
+ SETUP_DEPLOY_ORG_REQUIRED: {
1376
+ fix: "Set DENO_DEPLOY_ORG to your Deno Deploy organization, or run `vitehub link --host deno --account <org>`.",
1377
+ why: () => "The Deno Deploy organization is not known."
1378
+ },
1379
+ SETUP_DEPLOY_BUILD_FAILED: {
1380
+ fix: "Fix the build error above and run the command again, or pass --no-build to deploy the output that is there.",
1381
+ why: ({ command, exitCode }) => exitCode === void 0 ? `package.json has no \`build\` script, so \`${String(command)}\` cannot build the app.` : `\`${String(command)}\` exited with code ${String(exitCode)}.`
1382
+ },
1383
+ SETUP_DEPLOY_CHECK_FAILED: {
1384
+ fix: ({ rollback }) => `${String(rollback)} Then fix the app and deploy again. Pass --no-check only when the check itself is wrong.`,
1385
+ why: ({ failed, url }) => `The app is deployed to ${String(url)}, but a \`deploy.check\` path did not answer with a 2xx status: ${String(failed)}.`
1386
+ },
1387
+ SETUP_DEPLOY_OUTPUT_MISSING: {
1388
+ fix: "Build the app with vitehub() for this host, then run the command again without --no-build.",
1389
+ why: ({ file }) => `The build output has no ${String(file)}.`
1390
+ },
1391
+ SETUP_DEPLOY_HOST_MISMATCH: {
1392
+ fix: ({ host }) => `Build again for ${String(host)}: run \`vitehub deploy --host ${String(host)}\` without --no-build.`,
1393
+ why: ({ built, host }) => `The build output is for ${String(built)}, but this deploy goes to ${String(host)}.`
1394
+ },
1395
+ SETUP_DEPLOY_COMMAND_REJECTED: {
1396
+ fix: "Build again with vitehub(). If you set the deploy command yourself, run it yourself.",
1397
+ why: ({ command }) => `The build output names a deploy command that ViteHub did not write, so it does not run it: ${String(command)}`
1398
+ },
1399
+ SETUP_DEPLOY_ENV_MISSING: {
1400
+ 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.`,
1401
+ 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.`
1402
+ },
1403
+ SETUP_DEPLOY_ENV_NOT_LINKED: {
1404
+ fix: ({ host }) => `Run \`vitehub link --host ${String(host)} --create\` to create the project, then deploy again.`,
1405
+ why: ({ host, names }) => `The ${String(host)} project is not linked, so deploy cannot set ${String(names)} before the first deploy. Nothing was deployed.`
1406
+ },
1407
+ SETUP_DEPLOY_ENV_STAGE_UNSAFE: {
1408
+ 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.`,
1409
+ 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.`
1410
+ },
1411
+ SETUP_DEPLOY_FAILED: {
1412
+ fix: "Read the host output above, fix the cause, and run the command again.",
1413
+ why: ({ exitCode, output, step }) => `\`${String(step)}\` failed${exitCode === void 0 ? "" : ` with exit code ${String(exitCode)}`}.${output ? `\n${String(output)}` : ""}`
1414
+ },
1415
+ SETUP_DEPLOYMENTS_NOT_LINKED: {
1416
+ fix: ({ host }) => host ? `Run \`vitehub link --host ${String(host)}\`, or deploy once with \`vitehub deploy --host ${String(host)}\`.` : "Run `vitehub link` to link the project to its host, or deploy once with `vitehub deploy`.",
1417
+ why: ({ host }) => host ? `The project has no ${String(host)} target in .vitehub/link.json, so the host project to read is not known.` : "The project has no host link in .vitehub/link.json, so the host project to read is not known."
1418
+ },
1419
+ SETUP_DEPLOYMENTS_CREDENTIALS_MISSING: {
1420
+ fix: ({ fix }) => fix === void 0 ? "Log in with the host CLI, such as `npx wrangler login`, or set the host token, such as CLOUDFLARE_API_TOKEN, VERCEL_TOKEN, NETLIFY_AUTH_TOKEN, or DENO_DEPLOY_TOKEN, then run the command again." : String(fix),
1421
+ why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login, so the deployments cannot be read.`
1422
+ },
1423
+ SETUP_DEPLOYMENTS_ACCOUNT_REQUIRED: {
1424
+ fix: "Set CLOUDFLARE_ACCOUNT_ID, or run `vitehub link --host cloudflare --account <id>`.",
1425
+ why: ({ host }) => `The ${String(host)} account of the linked project is not known.`
1426
+ },
1427
+ SETUP_DEPLOYMENTS_PROJECT_ID_REQUIRED: {
1428
+ fix: ({ host }) => `Run \`vitehub link --host ${String(host)}\` to store the project id.`,
1429
+ why: ({ host }) => `The ${String(host)} link has no project id, and the ${String(host)} API lists deployments by id.`
1430
+ },
1431
+ SETUP_DEPLOY_CHECKOUT_CONFLICT: {
1432
+ fix: "Edit each file and remove the conflict markers, or run `vitehub resolve` for a binary file. Then deploy again, or pass --no-push to deploy without the push.",
1433
+ why: ({ files }) => `A checkout folder of vitehub.lock has unresolved conflicts, so the Workspace push after the deploy would fail. Nothing was built or deployed: ${String(files)}`
1434
+ },
1435
+ SETUP_DEPLOY_CHECKOUT_MODULE_FAILED: {
1436
+ fix: "Reinstall the project dependencies and check that the Workspace package is the same version as the CLI. Or pass --no-push to deploy without the push.",
1437
+ why: ({ file, message, specifier }) => `The project installs ${String(specifier)}, but ViteHub cannot load it from ${String(file)}, so it cannot push the checkout folders of vitehub.lock. Nothing was built or deployed: ${String(message)}`
1438
+ },
1439
+ SETUP_DEPLOY_PROVISION_NEEDS_BUILD: {
1440
+ fix: "Deploy again without --no-build, so the build gets the new ids.",
1441
+ why: ({ count }) => `The deploy must create or change ${String(count)} resources, but --no-build deploys an output that was built without their ids. Nothing was created or deployed.`
1442
+ },
1443
+ SETUP_DEPLOY_PROVISION_UNCHECKED: {
1444
+ fix: "Set the credential that the reason names and deploy again. Or deploy with --no-provision to skip the resources.",
1445
+ why: ({ host, missing, warnings }) => `The deploy could not check the ${String(host)} resources of the app, so it created and deployed nothing: ${String(warnings)} ${String(missing)}`
1446
+ },
1447
+ SETUP_DEPLOY_PUSH_FAILED: {
1448
+ fix: ({ fix }) => `${fix ? `${String(fix)} ` : ""}Then run \`vitehub push\`. Do not deploy again.`,
1449
+ why: ({ message, url }) => `The app is deployed to ${String(url)}, but the Workspace push failed: ${String(message)}`
1450
+ },
1451
+ CLI_R0004: {
1452
+ fix: "Run it again with --yes, or check the change first with a dry run when the command has one.",
1453
+ why: ({ message }) => message === void 0 ? "" : String(message)
1454
+ },
1455
+ SETUP_ENV_DECRYPT_FAILED: {
1456
+ fix: ({ file, key }) => `Set ${String(key)} to the private key that encrypted ${String(file)}. Check it with \`dotenvx get -f ${String(file)}\`.`,
1457
+ why: ({ file, key, name, reason }) => `${String(key)} cannot decrypt ${String(name)} in ${String(file)} (${String(reason)}).`
1458
+ },
1459
+ SETUP_ENV_FILE_NOT_IGNORED: {
1460
+ fix: ({ file }) => `Add \`.env*\` or \`${String(file)}\` to .gitignore. Or set the values in the shell for this command.`,
1461
+ why: ({ file, names }) => `The secret ${String(names)} reads ${String(file)}, which git does not ignore, so a commit can add it. \`vitehub env push\` pushes a secret only from a file that git ignores.`
1462
+ },
1463
+ SETUP_ENV_FILE_TRACKED: {
1464
+ fix: ({ file }) => `Run \`git rm --cached ${String(file)}\`, add \`.env*\` to .gitignore, and rotate the values that git has seen. Or set the values in the shell for this command.`,
1465
+ why: ({ file, names }) => `The secret ${String(names)} reads ${String(file)}, which git tracks, directly or through \`$NAME\` expansion or a symlink. \`vitehub env push\` does not push a secret that is in git.`
1466
+ },
1467
+ SETUP_ENV_GIT_FAILED: {
1468
+ fix: "Fix the git repository so that `git ls-files` and `git check-ignore` work, then run the command again. Or set the values in the shell for this command.",
1469
+ why: ({ file, reason }) => `Git could not tell whether it tracks or ignores ${String(file)}, which holds a secret: ${String(reason)}. Nothing was pushed.`
1470
+ },
1471
+ SETUP_ENV_KEYS_TRACKED: {
1472
+ fix: ({ file }) => `Run \`git rm --cached ${String(file)}\`, add it to .gitignore, and rotate the keys with \`dotenvx rotate\`. Everyone with the repository can decrypt the values until then.`,
1473
+ why: ({ file }) => `${String(file)} holds the private keys of the encrypted env files and is tracked by git. \`vitehub env push\` does not decrypt with a key that is in git.`
1474
+ },
1475
+ SETUP_ENV_NAME_UNKNOWN: {
1476
+ fix: "Pass names that `vitehub env diff` lists, or build again after you declare the name.",
1477
+ why: ({ names }) => `The build output lists no variable named ${String(names)}.`
1478
+ },
1479
+ SETUP_ENV_PRIVATE_KEY_MISSING: {
1480
+ fix: ({ key }) => `Set ${String(key)} in the shell, or add it to .env.keys, which git must ignore.`,
1481
+ why: ({ file, key, names }) => `${String(file)} holds the encrypted ${String(names)}, and ${String(key)} is not set.`
1482
+ },
1483
+ SETUP_ENV_STAGE_UNSUPPORTED: {
1484
+ fix: ({ host, stage }) => stage !== "preview" ? "Use --stage production or --stage preview, the stages of `vitehub deploy` and `vitehub deploy --preview`." : host === "cloudflare" ? "A Worker has one set of secrets for every version. Push production values with --stage production." : "`vitehub deploy` deploys this host to production only. Push with --stage production.",
1485
+ why: ({ host, stage }) => `The ${String(host)} host has no environment for the ${String(stage)} stage.`
1486
+ },
1487
+ SETUP_ENV_VALUE_UNSUPPORTED: {
1488
+ fix: ({ host }) => `Set this value in the ${String(host)} dashboard.`,
1489
+ why: ({ host, name, reason }) => `The value of ${String(name)} cannot go to ${String(host)} without a terminal prompt or argv. ${String(reason)}`
1490
+ },
1491
+ SETUP_GITHUB_REPOSITORY_REQUIRED: {
1492
+ fix: "Pass --repo owner/name, or add a GitHub remote named origin.",
1493
+ why: ({ remote }) => remote ? `The git remote origin (${String(remote)}) is not a github.com repository.` : "This folder has no git remote named origin."
1494
+ },
1495
+ SETUP_GITHUB_REQUEST_FAILED: {
1496
+ fix: "Check that the token can write the Actions secrets of the repository, and that the repository and environment exist.",
1497
+ why: ({ operation, reason }) => `GitHub refused \`${String(operation)}\`: ${String(reason)}`
1498
+ }
1499
+ }
1500
+ });
1501
+ //#endregion
1502
+ //#region ../internal/dist/host-credentials.js
1503
+ const missingFixes = {
1504
+ cloudflare: {
1505
+ missing: ["CLOUDFLARE_API_TOKEN"],
1506
+ fix: "Install Wrangler in the project and run `npx wrangler login`, or set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID."
1507
+ },
1508
+ vercel: {
1509
+ missing: ["VERCEL_TOKEN"],
1510
+ fix: "Set VERCEL_TOKEN to a token from https://vercel.com/account/tokens. Set VERCEL_TEAM_ID for a team."
1511
+ },
1512
+ netlify: {
1513
+ missing: ["NETLIFY_AUTH_TOKEN"],
1514
+ fix: "Set NETLIFY_AUTH_TOKEN to a token from https://app.netlify.com/user/applications#personal-access-tokens."
1515
+ },
1516
+ deno: {
1517
+ missing: ["DENO_DEPLOY_TOKEN"],
1518
+ fix: "Set DENO_DEPLOY_TOKEN to a token from your Deno Deploy account settings."
1519
+ }
1520
+ };
1521
+ const HOST_CLI_TIMEOUT_MS = 3e4;
1522
+ /** Reads host credentials from environment variables only. Returns undefined when the token is not set. */
1523
+ function readHostCredentialsFromEnv(host, env) {
1524
+ switch (host) {
1525
+ case "cloudflare": {
1526
+ const token = trimmed(env.CLOUDFLARE_API_TOKEN);
1527
+ const accountId = trimmed(env.CLOUDFLARE_ACCOUNT_ID);
1528
+ return token ? {
1529
+ token,
1530
+ ...accountId && { accountId }
1531
+ } : void 0;
1532
+ }
1533
+ case "vercel": {
1534
+ const token = trimmed(env.VERCEL_TOKEN);
1535
+ const teamId = trimmed(env.VERCEL_TEAM_ID) ?? trimmed(env.VERCEL_ORG_ID);
1536
+ return token ? {
1537
+ token,
1538
+ ...teamId && { teamId }
1539
+ } : void 0;
1540
+ }
1541
+ case "netlify": {
1542
+ const token = trimmed(env.NETLIFY_AUTH_TOKEN);
1543
+ return token ? { token } : void 0;
1544
+ }
1545
+ case "deno": {
1546
+ const token = trimmed(env.DENO_DEPLOY_TOKEN);
1547
+ return token ? { token } : void 0;
1548
+ }
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Finds credentials for a host: environment variables first, then the host CLI login.
1553
+ * It never writes credentials and never reads another tool's auth files.
1554
+ */
1555
+ async function resolveHostCredentials(host, context) {
1556
+ const fromEnv = readHostCredentialsFromEnv(host, context.env);
1557
+ if (fromEnv) return {
1558
+ ok: true,
1559
+ host,
1560
+ source: "env",
1561
+ ...fromEnv
1562
+ };
1563
+ if (host === "cloudflare") {
1564
+ const token = await readWranglerToken(context);
1565
+ if (token) {
1566
+ const accountId = trimmed(context.env.CLOUDFLARE_ACCOUNT_ID) ?? await readWranglerAccountId(context);
1567
+ return {
1568
+ ok: true,
1569
+ host,
1570
+ source: "host-cli",
1571
+ token,
1572
+ ...accountId && { accountId }
1573
+ };
1574
+ }
1575
+ }
1576
+ return {
1577
+ ok: false,
1578
+ host,
1579
+ ...missingFixes[host]
1580
+ };
1581
+ }
1582
+ async function readWranglerToken(context) {
1583
+ const value = await runJson(context, "wrangler", [
1584
+ "auth",
1585
+ "token",
1586
+ "--json"
1587
+ ]);
1588
+ if (!isRecord(value) || value.type !== "oauth" && value.type !== "api_token") return;
1589
+ return typeof value.token === "string" ? trimmed(value.token) : void 0;
1590
+ }
1591
+ async function readWranglerAccountId(context) {
1592
+ const value = await runJson(context, "wrangler", ["whoami", "--json"]);
1593
+ if (!isRecord(value) || value.loggedIn !== true || !Array.isArray(value.accounts) || value.accounts.length !== 1) return;
1594
+ const [account] = value.accounts;
1595
+ return isRecord(account) && typeof account.id === "string" ? trimmed(account.id) : void 0;
1596
+ }
1597
+ async function runJson(context, command, args) {
1598
+ const run = context.run ?? runHostCli;
1599
+ let result;
1600
+ let cwd;
1601
+ try {
1602
+ const local = command === "wrangler" ? localWrangler(context.cwd) : void 0;
1603
+ cwd = await mkdtemp(join$1(context.cwd ?? process.cwd(), ".vitehub-wrangler-auth-"));
1604
+ await writeFile(join$1(cwd, ".env"), "");
1605
+ await writeFile(join$1(cwd, "wrangler.json"), "{}");
1606
+ const isolatedArgs = [
1607
+ ...args,
1608
+ "--env-file",
1609
+ ".env",
1610
+ "--config",
1611
+ "wrangler.json"
1612
+ ];
1613
+ result = await run(local ? process.execPath : command, local ? [local, ...isolatedArgs] : isolatedArgs, {
1614
+ cwd,
1615
+ env: context.env
1616
+ });
1617
+ } catch {
1618
+ return;
1619
+ } finally {
1620
+ if (cwd) await rm(cwd, {
1621
+ force: true,
1622
+ recursive: true
1623
+ });
1624
+ }
1625
+ if (result.exitCode !== 0) return;
1626
+ try {
1627
+ return JSON.parse(result.stdout);
1628
+ } catch {
1629
+ return;
1630
+ }
1631
+ }
1632
+ /** Resolve a project dependency before changing cwd, as package-manager invocations do. */
1633
+ function localWrangler(cwd) {
1634
+ if (!cwd) return;
1635
+ const require = createRequire(join$1(resolve$1(cwd), "package.json"));
1636
+ let directory = resolve$1(cwd);
1637
+ while (true) {
1638
+ try {
1639
+ const manifest = require.resolve(join$1(directory, "node_modules", "wrangler", "package.json"));
1640
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
1641
+ if (!isRecord(pkg)) return;
1642
+ const bin = typeof pkg.bin === "string" ? pkg.bin : isRecord(pkg.bin) ? pkg.bin.wrangler : void 0;
1643
+ return typeof bin === "string" ? resolve$1(dirname$1(manifest), bin) : void 0;
1644
+ } catch {}
1645
+ const parent = dirname$1(directory);
1646
+ if (parent === directory) return;
1647
+ directory = parent;
1648
+ }
1649
+ }
1650
+ /** The default host CLI runner. stdin is closed so a CLI cannot wait for a prompt. */
1651
+ const runHostCli = (command, args, options) => new Promise((resolve, reject) => {
1652
+ const child = spawn(command, [...args], {
1653
+ cwd: options.cwd,
1654
+ env: options.env,
1655
+ shell: process.platform === "win32" && command !== process.execPath,
1656
+ stdio: [
1657
+ "ignore",
1658
+ "pipe",
1659
+ "ignore"
1660
+ ],
1661
+ timeout: HOST_CLI_TIMEOUT_MS,
1662
+ ...options.signal ? { signal: options.signal } : {}
1663
+ });
1664
+ const chunks = [];
1665
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
1666
+ child.on("error", reject);
1667
+ child.on("close", (exitCode) => resolve({
1668
+ exitCode,
1669
+ stdout: Buffer.concat(chunks).toString("utf8")
1670
+ }));
1671
+ });
1672
+ function trimmed(value) {
1673
+ const result = value?.trim();
1674
+ return result ? result : void 0;
1675
+ }
1676
+ //#endregion
1677
+ //#region ../internal/dist/provider-failure.js
1678
+ const cloudflareCodes = {
1679
+ d1: {},
1680
+ kv: { 10014: "conflict" },
1681
+ queues: {
1682
+ 10104: "not-found",
1683
+ 10106: "unauthorized",
1684
+ 10107: "invalid",
1685
+ 10201: "unavailable",
1686
+ 10202: "invalid",
1687
+ 10203: "invalid",
1688
+ 10204: "invalid",
1689
+ 10205: "invalid",
1690
+ 10206: "invalid",
1691
+ 10207: "invalid",
1692
+ 10208: "invalid",
1693
+ 10250: "throttled",
1694
+ 10251: "throttled",
1695
+ 10252: "throttled",
1696
+ 10253: "throttled",
1697
+ 15e3: "unavailable"
1698
+ },
1699
+ r2: {
1700
+ 10001: "unavailable",
1701
+ 10002: "unauthorized",
1702
+ 10003: "unauthorized",
1703
+ 10004: "conflict",
1704
+ 10005: "invalid",
1705
+ 10006: "not-found",
1706
+ 10007: "not-found",
1707
+ 10008: "conflict",
1708
+ 10009: "invalid",
1709
+ 10011: "invalid",
1710
+ 10012: "invalid",
1711
+ 10013: "invalid",
1712
+ 10014: "invalid",
1713
+ 10018: "unauthorized",
1714
+ 10020: "invalid",
1715
+ 10024: "not-found",
1716
+ 10025: "invalid",
1717
+ 10031: "conflict",
1718
+ 10033: "invalid",
1719
+ 10035: "unauthorized",
1720
+ 10037: "invalid",
1721
+ 10039: "invalid",
1722
+ 10042: "unauthorized",
1723
+ 10043: "unavailable",
1724
+ 10048: "invalid",
1725
+ 10054: "unavailable",
1726
+ 10058: "throttled",
1727
+ 10069: "conflict",
1728
+ 10073: "conflict",
1729
+ 100100: "invalid"
1730
+ }
1731
+ };
1732
+ const vercelCodes = {
1733
+ bad_request: "invalid",
1734
+ conflict_aliases: "conflict",
1735
+ forbidden: "unauthorized",
1736
+ internal_server_error: "unavailable",
1737
+ method_unknown: "invalid",
1738
+ not_found: "not-found",
1739
+ not_modified: "conflict",
1740
+ rate_limited: "throttled",
1741
+ service_unavailable: "unavailable"
1742
+ };
1743
+ function kindFromStatus(status) {
1744
+ if (status === 401 || status === 403) return "unauthorized";
1745
+ if (status === 404 || status === 410) return "not-found";
1746
+ if (status === 409 || status === 412) return "conflict";
1747
+ if (status === 429) return "throttled";
1748
+ if (status === 408 || status >= 500) return "unavailable";
1749
+ if (status >= 400) return "invalid";
1750
+ }
1751
+ /**
1752
+ * Classifies a failed provider call. A documented provider code wins over the HTTP status.
1753
+ * Returns `undefined` only when neither a known code nor an error status is present.
1754
+ */
1755
+ function classifyProviderFailure(source, { codes = [], status }) {
1756
+ for (const code of codes) {
1757
+ const kind = source.host === "vercel" ? typeof code === "string" && Object.hasOwn(vercelCodes, code) ? vercelCodes[code] : void 0 : source.host === "cloudflare" && source.product && typeof code === "number" && Object.hasOwn(cloudflareCodes[source.product], code) ? cloudflareCodes[source.product][code] : void 0;
1758
+ if (kind) return kind;
1759
+ }
1760
+ return status === void 0 ? void 0 : kindFromStatus(status);
1761
+ }
1762
+ /** Finds the Cloudflare product of an account API path, such as `/r2/buckets`. */
1763
+ function cloudflareProductOfPath(path) {
1764
+ if (path.startsWith("/r2/")) return "r2";
1765
+ if (path.startsWith("/storage/kv/")) return "kv";
1766
+ if (path.startsWith("/d1/")) return "d1";
1767
+ if (path === "/queues" || path.startsWith("/queues/") || path.startsWith("/queues?")) return "queues";
1768
+ }
1769
+ /**
1770
+ * Reads the error codes of a Cloudflare (`errors[].code`) or Vercel (`error.code`) error body.
1771
+ * Keeps only codes that are safe to print: numbers, and short strings without spaces or line breaks.
1772
+ */
1773
+ function readProviderErrorCodes(body) {
1774
+ if (!body || typeof body !== "object") return [];
1775
+ const error = Reflect.get(body, "error");
1776
+ const errors = Reflect.get(body, "errors");
1777
+ return [error && typeof error === "object" ? Reflect.get(error, "code") : void 0, ...Array.isArray(errors) ? errors.map((entry) => entry && typeof entry === "object" ? Reflect.get(entry, "code") : void 0) : []].filter((code) => typeof code === "number" && Number.isFinite(code) || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
1778
+ }
1779
+ //#endregion
1780
+ //#region ../internal/dist/provision.js
1781
+ /** Plans one provider in step order and collects warnings and explicit unchecked state. */
1782
+ async function planProvisionSteps(provider, steps, context) {
1783
+ const warnings = [];
1784
+ let checked = true;
1785
+ const planContext = {
1786
+ ...context,
1787
+ logger: {
1788
+ log: (message) => context.logger.log(message),
1789
+ warn(message) {
1790
+ warnings.push(message);
1791
+ context.logger.warn(message);
1792
+ }
1793
+ },
1794
+ markPlanUnchecked: () => {
1795
+ checked = false;
1796
+ }
1797
+ };
1798
+ const actions = [];
1799
+ for (const step of steps) {
1800
+ if (step.provider !== provider) continue;
1801
+ for (const action of await step.plan(planContext)) actions.push({
1802
+ action,
1803
+ step: step.id
1804
+ });
1805
+ }
1806
+ return {
1807
+ actions,
1808
+ checked,
1809
+ warnings
1810
+ };
1811
+ }
1812
+ function resolveCloudflareProvisionConfig(env) {
1813
+ const credentials = readHostCredentialsFromEnv("cloudflare", env);
1814
+ if (!credentials?.accountId) return;
1815
+ return {
1816
+ accountId: credentials.accountId,
1817
+ token: credentials.token
1818
+ };
1819
+ }
1820
+ function resolveVercelProvisionConfig(env) {
1821
+ const credentials = readHostCredentialsFromEnv("vercel", env);
1822
+ if (!credentials) return;
1823
+ return {
1824
+ token: credentials.token,
1825
+ teamId: credentials.teamId
1826
+ };
1827
+ }
1828
+ function ownParser(options) {
1829
+ if (!Object.hasOwn(options, "parse")) return;
1830
+ return options.parse;
1831
+ }
1832
+ function provisionRequestError(method, path, status, codes, kind) {
1833
+ const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
1834
+ return Object.assign(internalErrorDiagnostics.INTERNAL_R0013({ message: `Provision request failed: ${method} ${path} (${status}).${suffix}` }), {
1835
+ codes,
1836
+ kind,
1837
+ status
1838
+ });
1839
+ }
1840
+ /** Whether `error` is a failed provider API call of provisioning. */
1841
+ function isProvisionRequestError(error) {
1842
+ return error instanceof Error && Reflect.get(error, "code") === "INTERNAL_R0013";
1843
+ }
1844
+ function createJsonClient(source, baseURL, headers, fetchImpl, baseQuery) {
1845
+ return async function request(path, options = {}) {
1846
+ const url = new URL(`${baseURL}${path}`);
1847
+ const query = Object.hasOwn(options, "query") ? options.query : void 0;
1848
+ for (const [key, value] of Object.entries({
1849
+ ...baseQuery,
1850
+ ...query
1851
+ })) url.searchParams.set(key, value);
1852
+ const method = Object.hasOwn(options, "method") ? options.method : void 0;
1853
+ const body = Object.hasOwn(options, "body") ? options.body : void 0;
1854
+ const requestHeaders = Object.hasOwn(options, "headers") ? options.headers : void 0;
1855
+ const init = {
1856
+ method: method ?? "GET",
1857
+ headers: {
1858
+ ...requestHeaders,
1859
+ ...headers
1860
+ }
1861
+ };
1862
+ if (body !== void 0) {
1863
+ init.headers = {
1864
+ ...init.headers,
1865
+ "content-type": "application/json"
1866
+ };
1867
+ init.body = JSON.stringify(body);
1868
+ }
1869
+ const response = await fetchImpl(url, init);
1870
+ if (!response.ok) {
1871
+ const codes = readProviderErrorCodes(await response.json().catch(() => void 0));
1872
+ const kind = classifyProviderFailure(source(path), {
1873
+ codes,
1874
+ status: response.status
1875
+ }) ?? "unavailable";
1876
+ throw provisionRequestError(method ?? "GET", path, response.status, codes, kind);
1877
+ }
1878
+ const value = await response.json();
1879
+ const parse = ownParser(options);
1880
+ return parse ? parse(value) : value;
1881
+ };
1882
+ }
1883
+ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
1884
+ return createCloudflareClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, config.token, fetchImpl);
1885
+ }
1886
+ /** A Cloudflare REST client for requests outside one account, such as `GET /accounts`. */
1887
+ function createCloudflareApiClient(token, fetchImpl = globalThis.fetch) {
1888
+ return createCloudflareClient("https://api.cloudflare.com/client/v4", token, fetchImpl);
1889
+ }
1890
+ function createCloudflareClient(baseURL, token, fetchImpl) {
1891
+ const client = createJsonClient((path) => ({
1892
+ host: "cloudflare",
1893
+ product: cloudflareProductOfPath(path)
1894
+ }), baseURL, { authorization: `Bearer ${token}` }, fetchImpl);
1895
+ return async (path, options = {}) => {
1896
+ const parse = ownParser(options) ?? ((value) => value);
1897
+ return await client(path, {
1898
+ ...options,
1899
+ parse(value) {
1900
+ if (!value || Object(value) !== value) throw internalErrorDiagnostics.INTERNAL_R0010({ message: "Cloudflare provisioning returned an invalid response." });
1901
+ const envelope = value;
1902
+ return {
1903
+ ...envelope,
1904
+ result: envelope.result === void 0 ? void 0 : parse(envelope.result)
1905
+ };
1906
+ }
1907
+ });
1908
+ };
1909
+ }
1910
+ function createVercelProvisionClient(config, fetchImpl = globalThis.fetch) {
1911
+ return createJsonClient(() => ({ host: "vercel" }), "https://api.vercel.com", { authorization: `Bearer ${config.token}` }, fetchImpl, config.teamId ? { teamId: config.teamId } : void 0);
1912
+ }
1913
+ /** A Netlify REST client for `https://api.netlify.com/api/v1`. */
1914
+ function createNetlifyApiClient(token, fetchImpl = globalThis.fetch) {
1915
+ return createJsonClient(() => ({ host: "netlify" }), "https://api.netlify.com/api/v1", { authorization: `Bearer ${token}` }, fetchImpl);
1916
+ }
1917
+ //#endregion
1918
+ //#region src/provision.ts
1919
+ const PROVISION_HOSTS = ["cloudflare", "vercel"];
1920
+ const HOST_CREDENTIALS = {
1921
+ cloudflare: "CLOUDFLARE_ACCOUNT_ID and a Cloudflare login (`wrangler login` or CLOUDFLARE_API_TOKEN)",
1922
+ vercel: "VERCEL_TOKEN"
1923
+ };
1924
+ const USAGE = {
1925
+ run: "vitehub provision run --host <cloudflare|vercel> [--dry-run] [--json]",
1926
+ status: "vitehub provision status --host <cloudflare|vercel> [--json]"
1927
+ };
1928
+ /** Whether ViteHub can provision resources on `host`. Only Cloudflare and Vercel have Provision Steps. */
1929
+ function isProvisionHost(value) {
1930
+ return PROVISION_HOSTS.some((host) => host === value);
1931
+ }
1932
+ function setVariable(env, name, value) {
1933
+ return env[name]?.trim() || !value ? env : {
1934
+ ...env,
1935
+ [name]: value
1936
+ };
1937
+ }
1938
+ /**
1939
+ * The environment of a Provision Step: `env` with the host credentials that `resolveHostCredentials` found, such as a
1940
+ * `wrangler login` token, and the account and project ids of the host link. The selected deploy link wins over
1941
+ * environment scope; standalone provision has no link.
1942
+ */
1943
+ function provisionEnv(env, credentials, link = {}) {
1944
+ if (!credentials.ok) return env;
1945
+ if (credentials.host === "cloudflare") return {
1946
+ ...setVariable(setVariable(env, "CLOUDFLARE_API_TOKEN", credentials.token), "CLOUDFLARE_ACCOUNT_ID", credentials.accountId),
1947
+ ...link.accountId ? { CLOUDFLARE_ACCOUNT_ID: link.accountId } : {}
1948
+ };
1949
+ if (credentials.host === "vercel") {
1950
+ const teamId = credentials.teamId;
1951
+ const resolved = setVariable(setVariable(env, "VERCEL_TOKEN", credentials.token), "VERCEL_TEAM_ID", teamId);
1952
+ if (!link.accountId && !link.projectId) return resolved;
1953
+ return {
1954
+ ...resolved,
1955
+ ...link.accountId ? {
1956
+ VERCEL_TEAM_ID: link.accountId.startsWith("team_") ? link.accountId : void 0,
1957
+ VERCEL_ORG_ID: void 0
1958
+ } : {},
1959
+ ...link.projectId ? { VERCEL_PROJECT_ID: link.projectId } : {}
1960
+ };
1961
+ }
1962
+ return env;
1963
+ }
1964
+ function parseArgs(command, args) {
1965
+ const parsed = {
1966
+ dryRun: false,
1967
+ help: false,
1968
+ json: false
1969
+ };
1970
+ for (let index = 0; index < args.length; index++) {
1971
+ const arg = args[index];
1972
+ if (arg === "-h" || arg === "--help") parsed.help = true;
1973
+ else if (arg === "--json") parsed.json = true;
1974
+ else if (arg === "--dry-run" && command === "run") parsed.dryRun = true;
1975
+ else if (arg === "--host") {
1976
+ const host = args[index + 1];
1977
+ if (!host || host.startsWith("-")) parsed.error = "Option --host requires a value.";
1978
+ else {
1979
+ parsed.host = host;
1980
+ index++;
1981
+ }
1982
+ } else if (arg?.startsWith("--host=")) {
1983
+ const host = arg.slice(7);
1984
+ if (!host) parsed.error = "Option --host requires a value.";
1985
+ else parsed.host = host;
1986
+ } else if (arg === "--provider" || arg?.startsWith("--provider=")) {
1987
+ const value = arg === "--provider" ? args[index + 1] : arg.slice(11);
1988
+ const host = value && !value.startsWith("-") ? value : "<cloudflare|vercel>";
1989
+ return {
1990
+ ...parsed,
1991
+ error: `Option --provider is now --host.\nfix: run \`vitehub provision ${command} --host ${host}\`.`
1992
+ };
1993
+ } else if (arg) parsed.error = `Unknown provision argument: ${arg}`;
1994
+ }
1995
+ return parsed;
1996
+ }
1997
+ function writeUsage(command, stream) {
1998
+ const lines = command === "run" ? [
1999
+ `Usage: ${USAGE.run}`,
2000
+ "",
2001
+ "Idempotently creates missing host resources for the app's Definitions. `vitehub deploy` runs it before each deploy.",
2002
+ "Uses the credentials of `vitehub deploy`: environment variables first, then the `wrangler login` session.",
2003
+ "Never deletes resources. Changes an existing resource only for a planned update, such as D1 read replication.",
2004
+ "",
2005
+ "Options:",
2006
+ " --host <name> Target host: cloudflare or vercel (required).",
2007
+ " --dry-run Print the plan without applying it.",
2008
+ " --json Print one JSON result to stdout.",
2009
+ " -h, --help Show this help."
2010
+ ] : [
2011
+ `Usage: ${USAGE.status}`,
2012
+ "",
2013
+ "Shows the ids recorded in .vitehub/provision.json and the actions the current plan would apply.",
2014
+ "Marks recorded ids that no Definition declares, with how to delete them on the host.",
2015
+ "Never creates or deletes provider resources, and never writes Provision State.",
2016
+ "",
2017
+ "Options:",
2018
+ " --host <name> Target host: cloudflare or vercel (required).",
2019
+ " --json Print one JSON result to stdout.",
2020
+ " -h, --help Show this help."
2021
+ ];
2022
+ stream.write(`${lines.join("\n")}\n\n`);
2023
+ }
2024
+ function resolveHost(command, parsed, context) {
2025
+ if (parsed.help) {
2026
+ writeUsage(command, context.stdout);
2027
+ return { exitCode: 0 };
2028
+ }
2029
+ if (parsed.error) {
2030
+ context.stderr.write(`${parsed.error}\n`);
2031
+ writeUsage(command, context.stderr);
2032
+ return { exitCode: 1 };
2033
+ }
2034
+ if (!isProvisionHost(parsed.host)) {
2035
+ context.stderr.write("Provision requires --host cloudflare|vercel.\n");
2036
+ writeUsage(command, context.stderr);
2037
+ return { exitCode: 1 };
2038
+ }
2039
+ return { host: parsed.host };
2040
+ }
2041
+ function hasHostCredentials(host, env) {
2042
+ return Boolean(host === "cloudflare" ? resolveCloudflareProvisionConfig(env) : resolveVercelProvisionConfig(env));
2043
+ }
2044
+ /** The context with the credentials of `resolveHostCredentials` in its env, so a `wrangler login` works as in deploy. */
2045
+ async function withHostCredentials(host, context) {
2046
+ const credentials = await resolveHostCredentials(host, {
2047
+ cwd: context.rootDir,
2048
+ env: context.env,
2049
+ ...context.runHostCli ? { run: context.runHostCli } : {}
2050
+ });
2051
+ return {
2052
+ ...context,
2053
+ env: provisionEnv(context.env, credentials)
2054
+ };
2055
+ }
2056
+ async function planProvision(provider, context, options, json) {
2057
+ return await planProvisionSteps(provider, await options.collectSteps(), {
2058
+ env: context.env,
2059
+ fetch: globalThis.fetch,
2060
+ logger: {
2061
+ log: (message) => (json ? context.stderr : context.stdout).write(`${message}\n`),
2062
+ warn: (message) => {
2063
+ if (!json) context.stderr.write(`${message}\n`);
2064
+ }
2065
+ }
2066
+ });
2067
+ }
2068
+ function findUndeclaredEntries(provider, recorded, steps, env) {
2069
+ const categories = /* @__PURE__ */ new Map();
2070
+ const unverifiedDeclarations = /* @__PURE__ */ new Set();
2071
+ const activeDeclarations = /* @__PURE__ */ new Set();
2072
+ for (const step of steps) {
2073
+ if (step.provider !== provider) continue;
2074
+ const described = step.recordedState?.({ env }) ?? [];
2075
+ for (const category of described) categories.set(category.category, category);
2076
+ if (described.some((category) => category.declared.length)) for (const category of described) activeDeclarations.add(category.category);
2077
+ if (described.some((category) => category.declared.some((key) => {
2078
+ const ids = recorded[category.category] ?? {};
2079
+ const id = Object.hasOwn(ids, key) ? ids[key] : void 0;
2080
+ const expected = category.declaredResourceIdentity?.(key);
2081
+ const identity = id === void 0 ? void 0 : category.resourceIdentity ? category.resourceIdentity({
2082
+ id,
2083
+ key
2084
+ }) : id;
2085
+ return expected === void 0 || identity === void 0 || identity !== expected;
2086
+ }))) for (const category of described) unverifiedDeclarations.add(category.category);
2087
+ }
2088
+ const resourceIdentity = (category, key, id) => {
2089
+ const describe = categories.get(category)?.resourceIdentity;
2090
+ return describe ? describe({
2091
+ id,
2092
+ key
2093
+ }) : id;
2094
+ };
2095
+ const isDeclared = (category, key, id) => {
2096
+ const description = categories.get(category);
2097
+ if (!description?.declared.includes(key)) return false;
2098
+ const expected = description.declaredResourceIdentity?.(key);
2099
+ const identity = resourceIdentity(category, key, id);
2100
+ return expected === void 0 || identity === void 0 || identity === expected;
2101
+ };
2102
+ const declaredById = /* @__PURE__ */ new Map();
2103
+ for (const [category, ids] of Object.entries(recorded)) for (const [key, id] of Object.entries(ids)) {
2104
+ const identity = resourceIdentity(category, key, id);
2105
+ if (identity !== void 0 && isDeclared(category, key, id) && !declaredById.has(identity)) declaredById.set(identity, `${category} ${JSON.stringify(key)}`);
2106
+ }
2107
+ const stateEdit = `remove the entry from ${PROVISION_STATE_FILE}`;
2108
+ const entries = [];
2109
+ for (const [category, ids] of Object.entries(recorded)) for (const [key, id] of Object.entries(ids)) {
2110
+ if (isDeclared(category, key, id)) continue;
2111
+ const identity = resourceIdentity(category, key, id);
2112
+ const sharedWith = identity === void 0 ? void 0 : declaredById.get(identity);
2113
+ let fix;
2114
+ if (sharedWith) fix = `${sharedWith} uses the same id, so keep the resource and only ${stateEdit}.`;
2115
+ else if (unverifiedDeclarations.has(category) || identity === void 0 && activeDeclarations.has(category)) fix = "A current Definition may still use this recorded resource, but its identity cannot be verified from local state and config. Verify its resource id before deleting anything by comparing the provider's resource names and bindings with current Definitions.";
2116
+ else fix = `No Definition declares it. If no deployment uses ${id}, ${categories.get(category)?.deleteHint({
2117
+ id,
2118
+ key
2119
+ }) ?? `delete resource ${id} in the ${provider === "cloudflare" ? "Cloudflare" : "Vercel"} dashboard`}, then ${stateEdit}.`;
2120
+ entries.push({
2121
+ category,
2122
+ fix,
2123
+ id,
2124
+ key
2125
+ });
2126
+ }
2127
+ return entries;
2128
+ }
2129
+ function serializeAction({ action, step }) {
2130
+ return {
2131
+ ...action.pending === void 0 ? {} : { pending: action.pending },
2132
+ exists: action.exists,
2133
+ kind: action.kind,
2134
+ name: action.name,
2135
+ step,
2136
+ ...action.update === void 0 ? {} : { update: action.update }
2137
+ };
2138
+ }
2139
+ function provisionActionStatus({ action }) {
2140
+ return !action.exists ? "create" : action.update ? "update" : action.pending ? "pending" : "exists";
2141
+ }
2142
+ function writeProvisionActions(actions, stdout) {
2143
+ for (const planned of actions) {
2144
+ const { action } = planned;
2145
+ stdout.write(`${provisionActionStatus(planned)}\t${action.kind}\t${action.name}${action.update ? `\t${action.update}` : ""}\n`);
2146
+ }
2147
+ }
2148
+ async function runProvision(args, cliContext, options) {
2149
+ const parsed = parseArgs("run", args);
2150
+ const resolved = resolveHost("run", parsed, cliContext);
2151
+ if ("exitCode" in resolved) return resolved.exitCode;
2152
+ const { host: provider } = resolved;
2153
+ const context = await withHostCredentials(provider, cliContext);
2154
+ if (!parsed.dryRun && !hasHostCredentials(provider, context.env)) {
2155
+ context.stderr.write(`Provision requires ${HOST_CREDENTIALS[provider]}. Dry-run preview does not require credentials (--dry-run).\n`);
2156
+ return 1;
2157
+ }
2158
+ if (!parsed.dryRun) await readProvisionState(context.rootDir);
2159
+ const { actions, checked, warnings } = await planProvision(provider, context, options, parsed.json);
2160
+ const blocked = !checked && !parsed.dryRun;
2161
+ if (!parsed.json) {
2162
+ if (!checked) context.stdout.write("provision: plan not checked.\n");
2163
+ if (blocked) {
2164
+ context.stderr.write("provision: nothing applied. Fix the warnings above, or preview with --dry-run.\n");
2165
+ return 1;
2166
+ }
2167
+ if (!actions.length) {
2168
+ if (checked) context.stdout.write(`provision: no ${provider} resources to create.\n`);
2169
+ return 0;
2170
+ }
2171
+ writeProvisionActions(actions, context.stdout);
2172
+ }
2173
+ let state = {};
2174
+ if (!parsed.dryRun && !blocked) for (const { action } of actions) {
2175
+ const result = await action.apply();
2176
+ if (result.ids) state = mergeProvisionState(state, result.ids);
2177
+ }
2178
+ const wroteState = Object.keys(state).length > 0;
2179
+ if (wroteState) await writeProvisionState(context.rootDir, state);
2180
+ if (parsed.json) {
2181
+ if (blocked) context.stderr.write("provision: plan not checked, nothing applied. Read warnings in the JSON result.\n");
2182
+ context.stdout.write(`${JSON.stringify({
2183
+ actions: actions.map(serializeAction),
2184
+ checked,
2185
+ ids: state[provider] ?? {},
2186
+ mode: parsed.dryRun ? "dry-run" : "apply",
2187
+ provider,
2188
+ schemaVersion: 1,
2189
+ stateFile: wroteState ? PROVISION_STATE_FILE : null,
2190
+ warnings
2191
+ })}\n`);
2192
+ } else if (wroteState) context.stdout.write(`provision: wrote ids to ${PROVISION_STATE_FILE}\n`);
2193
+ return blocked ? 1 : 0;
2194
+ }
2195
+ async function runProvisionStatus(args, cliContext, options) {
2196
+ const parsed = parseArgs("status", args);
2197
+ const resolved = resolveHost("status", parsed, cliContext);
2198
+ if ("exitCode" in resolved) return resolved.exitCode;
2199
+ const { host: provider } = resolved;
2200
+ const context = await withHostCredentials(provider, cliContext);
2201
+ const recorded = (await readProvisionState(context.rootDir))[provider] ?? {};
2202
+ const undeclared = findUndeclaredEntries(provider, recorded, await options.collectSteps(), context.env);
2203
+ const hasCredentials = hasHostCredentials(provider, context.env);
2204
+ const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, options, parsed.json) : {
2205
+ actions: [],
2206
+ checked: false,
2207
+ warnings: [`provision: plan not checked, missing ${HOST_CREDENTIALS[provider]}.`]
2208
+ };
2209
+ const pending = actions.filter(({ action }) => action.pending ?? !action.exists).length;
2210
+ if (parsed.json) {
2211
+ context.stdout.write(`${JSON.stringify({
2212
+ plan: {
2213
+ actions: actions.map(serializeAction),
2214
+ checked,
2215
+ pending
2216
+ },
2217
+ provider,
2218
+ recorded,
2219
+ schemaVersion: 1,
2220
+ stateFile: PROVISION_STATE_FILE,
2221
+ undeclared,
2222
+ warnings
2223
+ })}\n`);
2224
+ return 0;
2225
+ }
2226
+ const isUndeclared = (category, key) => undeclared.some((entry) => entry.category === category && entry.key === key);
2227
+ const recordedEntries = Object.entries(recorded).flatMap(([category, ids]) => Object.entries(ids).map(([key, id]) => `${category}\t${key}\t${id}${isUndeclared(category, key) ? " not declared" : ""}\n`));
2228
+ if (recordedEntries.length) {
2229
+ context.stdout.write(`recorded ${provider} ids (${PROVISION_STATE_FILE}):\n`);
2230
+ for (const entry of recordedEntries) context.stdout.write(entry);
2231
+ for (const entry of undeclared) context.stdout.write(`fix: ${entry.category} ${JSON.stringify(entry.key)}: ${entry.fix}\n`);
2232
+ } else context.stdout.write(`recorded ${provider} ids: none in ${PROVISION_STATE_FILE}\n`);
2233
+ if (!checked) {
2234
+ if (!hasCredentials) context.stderr.write(`${warnings[0]}\n`);
2235
+ context.stdout.write("plan: not checked\n");
2236
+ return 0;
2237
+ }
2238
+ writeProvisionActions(actions, context.stdout);
2239
+ context.stdout.write(pending ? `plan: ${pending} pending ${pending === 1 ? "action" : "actions"}. Run \`vitehub provision run --host ${provider}\` to apply.\n` : "plan: no pending actions\n");
2240
+ return 0;
2241
+ }
2242
+ /** Built-in namespace that orchestrates package-contributed Provision Steps. */
2243
+ function createProvisionNamespace(steps) {
2244
+ const options = { collectSteps: async () => [...steps] };
2245
+ return {
2246
+ description: "Idempotently create missing provider resources.",
2247
+ features: [{
2248
+ description: "Create missing provider resources for the app's Definitions.",
2249
+ name: "run",
2250
+ run: (args, context) => runProvision(args, context, options),
2251
+ usage: USAGE.run
2252
+ }, {
2253
+ description: "Show recorded provider ids and pending plan actions.",
2254
+ name: "status",
2255
+ run: (args, context) => runProvisionStatus(args, context, options),
2256
+ usage: USAGE.status
2257
+ }],
2258
+ name: "provision"
2259
+ };
2260
+ }
2261
+ //#endregion
2262
+ export { operationInputJsonSchema as A, isRecord as B, callOperationFromCli as C, operationCliPath as D, operationCall as E, collectViteHubCliContribution as F, createCliDiscoveryNitroCloser as I, findViteHubDevServerUrl as L, setupCommandNames as M, resolveViteHubProjectRoot as N, operationsOf as O, internalErrorDiagnostics as P, getStableStdoutWrite as R, callOperation as S, createOperationRegistry as T, 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, reservedOperationNamespaces as j, parseOperationInput as k, createVercelProvisionClient as l, cliErrorDiagnostics as m, isProvisionHost as n, createCloudflareApiClient as o, runHostCli as p, provisionActionStatus as r, createCloudflareProvisionClient as s, createProvisionNamespace as t, isProvisionRequestError as u, readProvisionStateSync as v, collectOperationContributions as w, withViteStageEnvironment as x, writeProvisionState as y, withStdoutOnStderr as z };