@vite-hub/cli 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,15 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawn } from "node:child_process";
3
- import { readFileSync, statSync } from "node:fs";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
4
  import { dirname, resolve } from "pathe";
5
+ import { defineDiagnostics } from "nostics";
5
6
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
6
7
  import { basename as basename$1, dirname as dirname$1, join as join$1, parse, resolve as resolve$1 } from "node:path";
7
8
  import "node:readline/promises";
8
- import { defineDiagnostics } from "nostics";
9
9
  import "node:url";
10
10
  import { tmpdir } from "node:os";
11
11
  import { createBirpc } from "birpc";
12
+ import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
12
13
  //#region ../internal/dist/object.js
13
14
  /** A non-null object that is not an array. Functions do not pass. */
14
15
  function isRecord(value) {
@@ -19,149 +20,7 @@ function isRecordOrFunction(value) {
19
20
  return Object(value) === value && !Array.isArray(value);
20
21
  }
21
22
  //#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
23
+ //#region ../internal/dist/error-diagnostics-B11Jh1zF.js
165
24
  const dynamicError$1 = { why: ({ message }) => message === void 0 ? "" : String(message) };
166
25
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
167
26
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
@@ -187,7 +46,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
187
46
  why: ({ message }) => message === void 0 ? "" : String(message)
188
47
  },
189
48
  INTERNAL_R0022: {
190
- fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
49
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields, and the list_operations tool of the ViteHub MCP gives the input schema of each operation.",
191
50
  why: ({ message }) => message === void 0 ? "" : String(message)
192
51
  },
193
52
  INTERNAL_R0024: {
@@ -332,7 +191,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
332
191
  },
333
192
  INTERNAL_R0004: {
334
193
  ...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."
194
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
336
195
  },
337
196
  INTERNAL_R0005: {
338
197
  ...dynamicError$1,
@@ -378,6 +237,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
378
237
  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
238
  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
239
  },
240
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
241
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
242
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
243
+ },
381
244
  INTERNAL_FORGE_NOT_INSTALLED: {
382
245
  why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
383
246
  fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
@@ -402,6 +265,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
402
265
  why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
403
266
  fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
404
267
  },
268
+ INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT: {
269
+ why: ({ first, name, second }) => `[vitehub] One server function needs ${name} from two installations: ${first} and ${second}.`,
270
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`, then build again."
271
+ },
405
272
  INTERNAL_SECRET_PURPOSE_MISSING: {
406
273
  why: "[vitehub] A derived secret requires a purpose.",
407
274
  fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
@@ -425,6 +292,844 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
425
292
  }
426
293
  });
427
294
  //#endregion
295
+ //#region ../internal/dist/cli.js
296
+ /** Validate an explicit `--url` before sending a Console request. The caller adds the RPC path. */
297
+ function appUrlError(url) {
298
+ let base;
299
+ try {
300
+ base = new URL(url);
301
+ } catch {
302
+ return "--url must be a URL.";
303
+ }
304
+ const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "[::1]";
305
+ if (base.protocol !== "https:" && !(local && base.protocol === "http:")) return "--url must use HTTPS, except for localhost.";
306
+ if (base.username || base.password || base.search || base.hash) return "--url must not contain credentials, a query, or a fragment.";
307
+ const consolePath = /(?:^|\/)_vitehub(?:\/|$)/.exec(base.pathname);
308
+ if (consolePath) return `--url is the app URL, not the Console URL. Pass --url ${`${base.origin}${base.pathname.slice(0, consolePath.index).replace(/\/$/, "")}`}.`;
309
+ }
310
+ const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
311
+ const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
312
+ const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
313
+ const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
314
+ const stdoutRedirectGlobal = globalThis;
315
+ /**
316
+ * Sends `process.stdout` writes to stderr while `run` loads project config.
317
+ * Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
318
+ */
319
+ async function withStdoutOnStderr(run, stderr = process.stderr) {
320
+ getStableStdoutWrite();
321
+ const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
322
+ let release;
323
+ stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
324
+ release = resolve;
325
+ });
326
+ await previous;
327
+ const write = process.stdout.write;
328
+ if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
329
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
330
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
331
+ }
332
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
333
+ process.stdout.write = ((chunk, encoding, callback) => {
334
+ const done = typeof encoding === "function" ? encoding : callback;
335
+ let called = false;
336
+ const onComplete = (error) => {
337
+ if (called) return;
338
+ called = true;
339
+ done?.(error);
340
+ };
341
+ const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
342
+ if (done && !called) {
343
+ if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
344
+ else if (stderr.write.length < 2) onComplete();
345
+ }
346
+ return result;
347
+ });
348
+ try {
349
+ return await run();
350
+ } finally {
351
+ process.stdout.write = write;
352
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
353
+ release();
354
+ }
355
+ }
356
+ /**
357
+ * A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
358
+ * Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
359
+ * config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
360
+ * then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
361
+ */
362
+ function createCliDiscoveryNitroCloser() {
363
+ const instances = [];
364
+ return {
365
+ close: async () => {
366
+ await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
367
+ },
368
+ plugin: {
369
+ name: "vite-hub/cli-discovery-nitro",
370
+ nitro: { setup: (nitro) => {
371
+ instances.push(nitro);
372
+ } }
373
+ }
374
+ };
375
+ }
376
+ /** Let Vite load its config normally, without overriding the root declared by the project. */
377
+ function viteCliProjectConfig(rootDir) {
378
+ const configFile = [
379
+ "js",
380
+ "mjs",
381
+ "ts",
382
+ "cjs",
383
+ "mts",
384
+ "cts"
385
+ ].map((extension) => resolve$1(rootDir, `vite.config.${extension}`)).find((file) => existsSync(file));
386
+ if (!configFile) return {
387
+ root: rootDir,
388
+ plugins: []
389
+ };
390
+ return {
391
+ configFile,
392
+ plugins: [{
393
+ name: "vite-hub/cli-discovery-root",
394
+ enforce: "pre",
395
+ config: {
396
+ order: "pre",
397
+ handler: ({ root }) => ({ root: resolve$1(rootDir, root || ".") })
398
+ }
399
+ }]
400
+ };
401
+ }
402
+ /** Returns the unredirected process stdout writer for payload output. */
403
+ function getStableStdoutWrite() {
404
+ const current = process.stdout.write;
405
+ if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
406
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
407
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
408
+ }
409
+ return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
410
+ }
411
+ async function resolveContributor(value) {
412
+ return typeof value === "function" ? await value() : value;
413
+ }
414
+ /** Resolves command namespaces and Provision Steps from one contribution per plugin. */
415
+ async function collectViteHubCliContribution(plugins) {
416
+ const namespaces = /* @__PURE__ */ new Map();
417
+ const steps = /* @__PURE__ */ new Map();
418
+ const seeds = /* @__PURE__ */ new Map();
419
+ let publicUrl;
420
+ for (const plugin of plugins) {
421
+ if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
422
+ const metadata = plugin.vitehub;
423
+ const contributor = await resolveContributor(metadata?.cli);
424
+ if (!contributor) continue;
425
+ publicUrl ??= contributor.publicUrl;
426
+ for (const namespace of contributor.namespaces) {
427
+ const existing = namespaces.get(namespace.name);
428
+ if (!existing) {
429
+ namespaces.set(namespace.name, {
430
+ ...namespace,
431
+ features: [...namespace.features]
432
+ });
433
+ continue;
434
+ }
435
+ const features = new Map(existing.features.map((feature) => [feature.name, feature]));
436
+ for (const feature of namespace.features) features.set(feature.name, feature);
437
+ existing.features = [...features.values()];
438
+ }
439
+ for (const step of contributor.provision ?? []) steps.set(step.id, step);
440
+ for (const seed of contributor.seeds ?? []) seeds.set(seed.name, seed);
441
+ }
442
+ return {
443
+ namespaces: [...namespaces.values()],
444
+ provision: [...steps.values()],
445
+ seeds: [...seeds.values()],
446
+ ...publicUrl ? { publicUrl } : {}
447
+ };
448
+ }
449
+ /** File in the project root where the running dev server tells commands where it listens. */
450
+ const viteHubDevServerFile = ".vitehub/dev-server.json";
451
+ /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
452
+ function readViteHubDevServerFile(root) {
453
+ try {
454
+ const value = JSON.parse(readFileSync(join$1(root, viteHubDevServerFile), "utf8"));
455
+ const url = isRecord(value) ? value.url : void 0;
456
+ const served = isRecord(value) ? value.root : void 0;
457
+ return typeof url === "string" && url && typeof served === "string" && served ? {
458
+ root: served,
459
+ url
460
+ } : void 0;
461
+ } catch {
462
+ return;
463
+ }
464
+ }
465
+ /**
466
+ * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
467
+ * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
468
+ */
469
+ function findViteHubDevServerUrl(roots, env) {
470
+ for (const root of roots) {
471
+ const file = readViteHubDevServerFile(root);
472
+ if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
473
+ }
474
+ return env["VITEHUB_DEV_SERVER_URL"] || void 0;
475
+ }
476
+ //#endregion
477
+ //#region ../internal/dist/invariant.js
478
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
479
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
480
+ codes: { INTERNAL_INVARIANT_FAILED: {
481
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
482
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
483
+ } }
484
+ });
485
+ /**
486
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
487
+ * Use a code from the package catalog when a developer can cause the error or fix it.
488
+ */
489
+ function invariantError(what) {
490
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
491
+ }
492
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
493
+ function invariant(condition, what) {
494
+ if (!condition) throw invariantError(what);
495
+ }
496
+ //#endregion
497
+ //#region ../internal/dist/features.js
498
+ /**
499
+ * The feature keys of `vitehub({...})`. `vitehub add <feature>` and `vitehub status` read this list before the owner
500
+ * package of a feature is installed, so the catalog is plain data with no owner imports.
501
+ */
502
+ const featureIds = [
503
+ "agent",
504
+ "auth",
505
+ "blob",
506
+ "browser",
507
+ "cache",
508
+ "channels",
509
+ "comments",
510
+ "connections",
511
+ "console",
512
+ "database",
513
+ "email",
514
+ "env",
515
+ "i18n",
516
+ "kv",
517
+ "mcp",
518
+ "observability",
519
+ "queue",
520
+ "rateLimit",
521
+ "realtime",
522
+ "sandboxTask",
523
+ "schedule",
524
+ "workflow",
525
+ "workspace"
526
+ ];
527
+ /** `dev` stores default Node development support. Use `featureSupport()` with the configured host for development lookups. */
528
+ const featureHosts = [
529
+ "dev",
530
+ "cloudflare",
531
+ "vercel",
532
+ "netlify",
533
+ "deno",
534
+ "node"
535
+ ];
536
+ const noHostLimit = "No host limit in ViteHub.";
537
+ function native(driver, display, detail, guarantee = "native") {
538
+ return {
539
+ detail,
540
+ display,
541
+ driver,
542
+ guarantee,
543
+ level: "native"
544
+ };
545
+ }
546
+ function explicit(option, display, detail) {
547
+ return {
548
+ detail,
549
+ display,
550
+ level: "explicit",
551
+ option
552
+ };
553
+ }
554
+ function unsupported(detail) {
555
+ return {
556
+ detail,
557
+ level: "unsupported"
558
+ };
559
+ }
560
+ function everywhere(driver, display, detail = noHostLimit) {
561
+ const support = native(driver, display, detail);
562
+ return {
563
+ cloudflare: support,
564
+ deno: support,
565
+ dev: support,
566
+ netlify: support,
567
+ node: support,
568
+ vercel: support
569
+ };
570
+ }
571
+ function feature(definition) {
572
+ return {
573
+ devPackages: [],
574
+ enabledByDefault: false,
575
+ implies: [],
576
+ packages: [],
577
+ ...definition
578
+ };
579
+ }
580
+ const sourceExtensions = [
581
+ "ts",
582
+ "mts",
583
+ "js",
584
+ "mjs",
585
+ "cts",
586
+ "cjs"
587
+ ];
588
+ /** `<base>.<ext>` for each source extension. */
589
+ function sourceFiles(base) {
590
+ return sourceExtensions.map((extension) => `${base}.${extension}`);
591
+ }
592
+ /**
593
+ * A starter for Definitions in `dir`, one `<name>.ts` file each. With `suffix`, the owner also discovers the Vite
594
+ * form `src/<name>.<suffix>.ts`, and a Definition folder `<dir>/<name>/` when `folder` names its entry file.
595
+ */
596
+ function starter(dir, template, options = {}) {
597
+ return {
598
+ conflicts: (name) => [
599
+ ...sourceFiles(`${dir}/${name}`).slice(1),
600
+ ...options.folder ? sourceFiles(`${dir}/${name}/${options.folder}`) : [],
601
+ ...options.suffix ? [...sourceFiles(`src/${name}.${options.suffix}`), ...sourceFiles(`${name}.${options.suffix}`)] : []
602
+ ],
603
+ dir,
604
+ file: (name) => `${dir}/${name}.ts`,
605
+ template
606
+ };
607
+ }
608
+ const features = {
609
+ agent: feature({
610
+ definition: starter("server/agents", (name) => `import { defineAgent } from "vite-hub/agent"
611
+
612
+ export default defineAgent({
613
+ driver: { run: () => ({ text: "Hello from ${name}." }) },
614
+ })
615
+ `, {
616
+ folder: "agent",
617
+ suffix: "agent"
618
+ }),
619
+ docs: "/docs/agents",
620
+ enabledByDiscovery: ["agents"],
621
+ hosts: {
622
+ ...everywhere("nitro", "Nitro"),
623
+ deno: native("nitro", "Nitro", "Agent routes run in the Nitro output. The Agent Deno runtime is not supported on this host."),
624
+ netlify: native("nitro", "Nitro", "Agent HTTP routes run in generated functions. `agent.invocations` is not supported, so `agent: true` fails the build. Set `agent: { invocations: false }` and configure invocations on each Agent Definition.")
625
+ },
626
+ id: "agent",
627
+ packages: ["@vite-hub/agent"],
628
+ summary: "Agents in `server/agents/` with tools, Capabilities, channels, and invocations.",
629
+ title: "Agent"
630
+ }),
631
+ auth: feature({
632
+ docs: "/docs/auth",
633
+ enabledByDiscovery: sourceFiles("auth"),
634
+ hosts: everywhere("better-auth", "Better Auth"),
635
+ id: "auth",
636
+ packages: [
637
+ "@vite-hub/auth",
638
+ "better-auth",
639
+ "drizzle-orm"
640
+ ],
641
+ summary: "Better Auth sign-in, sessions, and organizations, with tables that ViteHub owns.",
642
+ title: "Auth"
643
+ }),
644
+ blob: feature({
645
+ docs: "/docs/blob",
646
+ hosts: {
647
+ cloudflare: native("cloudflare", "R2", "Cloudflare R2 binding or S3-compatible HTTP access."),
648
+ deno: explicit("blob.driver", "S3", "Use a remote S3-compatible store. No Deno-native Blob driver is provided."),
649
+ dev: native("fs", "fs", "Local filesystem storage for development.", "single-host"),
650
+ netlify: native("netlify-blobs", "Netlify Blobs", "Netlify Blobs selected from the detected host."),
651
+ node: native("fs", "fs / S3", "Filesystem, S3-compatible, MinIO, or files-sdk drivers.", "single-host"),
652
+ vercel: native("vercel", "Vercel Blob", "Vercel Blob through the vercel driver.")
653
+ },
654
+ id: "blob",
655
+ packages: ["@vite-hub/blob"],
656
+ providerPackages: { driver: { s3: [
657
+ "@aws-sdk/client-s3",
658
+ "@aws-sdk/lib-storage",
659
+ "@aws-sdk/s3-presigned-post",
660
+ "@aws-sdk/s3-request-presigner"
661
+ ] } },
662
+ service: "blob",
663
+ summary: "Object storage for files and uploads, with one API on every host.",
664
+ title: "Blob"
665
+ }),
666
+ browser: feature({
667
+ docs: "/docs/browser",
668
+ enabledByDiscovery: ["browsers"],
669
+ hosts: {
670
+ cloudflare: native("cloudflare", "Browser Run", "Cloudflare Browser Run binding and provider output."),
671
+ deno: unsupported("Browser Definitions do not have a Deno provider."),
672
+ dev: unsupported("Browser Definitions need the Cloudflare host. Use createBrowser({ driver: localBrowser({ executablePath }) }) from code for a trusted local process."),
673
+ netlify: unsupported("Browser Definitions do not have a Netlify provider."),
674
+ node: unsupported("The Node host has no built-in Browser Provider. Use localBrowser() from code for a trusted process."),
675
+ vercel: unsupported("Browser Definitions do not have a Vercel provider.")
676
+ },
677
+ id: "browser",
678
+ packages: ["@vite-hub/browser"],
679
+ service: "browser",
680
+ summary: "Headless browser sessions for Agents and server code.",
681
+ title: "Browser"
682
+ }),
683
+ cache: feature({
684
+ developmentOverrides: [
685
+ "cloudflare",
686
+ "deno",
687
+ "vercel"
688
+ ],
689
+ docs: "/docs/reference/config-options",
690
+ hosts: {
691
+ cloudflare: native("cloudflare", "Workers KV", "Workers KV binding `CACHE`."),
692
+ deno: native("deno-kv", "Deno KV", "Native Deno KV."),
693
+ dev: native("fs-lite", "fs-lite", "`.vitehub/data/cache` during development.", "single-host"),
694
+ netlify: explicit("cache.driver", "KV", "`cache: true` has no default store on Netlify. Set `cache: { driver: \"kv\" }` and enable `kv`."),
695
+ node: native("fs-lite", "fs-lite", "`.vitehub/data/cache` on the server disk.", "single-host"),
696
+ vercel: native("vercel", "Runtime Cache", "Vercel Runtime Cache.")
697
+ },
698
+ id: "cache",
699
+ summary: "Storage for Nitro's cache mount, used by defineCachedFunction() and defineCachedEventHandler().",
700
+ title: "Cache"
701
+ }),
702
+ channels: feature({
703
+ docs: "/docs/channels",
704
+ enabledByDiscovery: ["channels"],
705
+ hosts: everywhere("nitro", "Nitro"),
706
+ id: "channels",
707
+ packages: ["@vite-hub/channels"],
708
+ summary: "Chat channels such as Slack, Discord, and GitHub that deliver messages to Agents.",
709
+ title: "Channels"
710
+ }),
711
+ comments: feature({
712
+ docs: "/docs/comments",
713
+ enabledByDiscovery: [
714
+ "comments.ts",
715
+ "comments.mts",
716
+ "comments.js",
717
+ "comments.mjs"
718
+ ],
719
+ hosts: everywhere("database", "Database"),
720
+ id: "comments",
721
+ implies: [{ feature: "database" }],
722
+ packages: ["@vite-hub/comments"],
723
+ summary: "Comments on the app's pages, stored in a ViteHub Database.",
724
+ title: "Comments"
725
+ }),
726
+ connections: feature({
727
+ docs: "/docs/connections",
728
+ enabledByDiscovery: ["connections"],
729
+ hosts: everywhere("database", "Database"),
730
+ id: "connections",
731
+ implies: [{ feature: "database" }],
732
+ packages: [
733
+ "@vite-hub/connections",
734
+ "@vite-hub/database",
735
+ "drizzle-orm"
736
+ ],
737
+ summary: "OAuth and API key Connections in `server/connections/`, with grants stored in a Database.",
738
+ title: "Connections"
739
+ }),
740
+ console: feature({
741
+ docs: "/docs/console",
742
+ hosts: everywhere("nitro", "Nitro"),
743
+ id: "console",
744
+ packages: [],
745
+ summary: "The Operations endpoint and MCP at `/_vitehub`, which the hosted Console at console.vitehub.dev and the CLI call.",
746
+ title: "Console"
747
+ }),
748
+ database: feature({
749
+ definition: {
750
+ conflicts: (name) => [
751
+ ...sourceFiles(`server/databases/${name}`).slice(1),
752
+ ...sourceFiles(`server/databases/${name}/index`),
753
+ ...name === "default" ? ["src/database.ts"] : [...sourceFiles(`src/${name}.database`), "src/database.ts"]
754
+ ],
755
+ dir: "server/databases",
756
+ file: (name) => `server/databases/${name}.ts`,
757
+ template: (name) => `import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
758
+ import { defineDatabase } from "vite-hub/database"
759
+
760
+ export default defineDatabase({
761
+ ${name === "default" ? "" : ` name: ${JSON.stringify(name)},\n`} schema: {
762
+ notes: sqliteTable("notes", {
763
+ id: integer("id").primaryKey(),
764
+ title: text("title").notNull(),
765
+ }),
766
+ },
767
+ })
768
+ `
769
+ },
770
+ developmentOverrides: [
771
+ "deno",
772
+ "netlify",
773
+ "vercel"
774
+ ],
775
+ devPackages: ["drizzle-kit"],
776
+ docs: "/docs/database",
777
+ hosts: {
778
+ cloudflare: native("cloudflare", "D1", "Cloudflare D1 binding, with authenticated HTTP available for development. A PostgreSQL Database Definition connects through Hyperdrive or `connection.url`."),
779
+ deno: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. No Deno-native database driver is provided."),
780
+ dev: native("sqlite", "SQLite", "Local SQLite through libSQL and Drizzle.", "single-host"),
781
+ netlify: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. No Netlify-native database driver is provided."),
782
+ node: native("sqlite", "SQLite / libSQL / Postgres", "SQLite or hosted libSQL through the selected Database connection, or a PostgreSQL Database Definition. Several servers can share Postgres and migrate on start under one advisory lock.", "single-host"),
783
+ vercel: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. The default local SQLite file is not supported in Vercel functions.")
784
+ },
785
+ id: "database",
786
+ packages: ["@vite-hub/database", "drizzle-orm"],
787
+ summary: "Drizzle Databases in `server/databases/` with migrations and a local SQLite in development.",
788
+ title: "Database"
789
+ }),
790
+ email: feature({
791
+ docs: "/docs/email",
792
+ hosts: {
793
+ cloudflare: native("cloudflare", "Cloudflare Email", "The Cloudflare Email driver is the default. Resend is also supported."),
794
+ deno: explicit("email.driver", "Resend", "Configure the built-in fetch-based Resend driver."),
795
+ dev: native("log", "Log", "`email: true` keeps each message in the development outbox and sends nothing. Set `email.driver` for a production build.", "process-local"),
796
+ netlify: explicit("email.driver", "Resend", "Configure the built-in Resend driver."),
797
+ node: explicit("email.driver", "Resend / SMTP / custom", "Configure Resend, `smtp` with the `nodemailer` package, or a driver module for another provider."),
798
+ vercel: explicit("email.driver", "Resend", "Configure the built-in Resend driver.")
799
+ },
800
+ developmentOverrides: [
801
+ "deno",
802
+ "netlify",
803
+ "vercel"
804
+ ],
805
+ id: "email",
806
+ packages: ["@vite-hub/email"],
807
+ summary: "Send email from server code and Agents, with a development outbox.",
808
+ title: "Email"
809
+ }),
810
+ env: feature({
811
+ docs: "/docs/env",
812
+ enabledByDefault: true,
813
+ hosts: everywhere("nitro", "Nitro"),
814
+ id: "env",
815
+ summary: "Typed environment variables and secrets, validated at build and at runtime.",
816
+ title: "Env"
817
+ }),
818
+ i18n: feature({
819
+ docs: "/docs/i18n",
820
+ hosts: everywhere("nitro", "Nitro 3", "Requires Nitro 3 with request async context, or Nuxt 5. Nuxt 4 and Nitro 2 are unsupported."),
821
+ id: "i18n",
822
+ packages: ["@vite-hub/i18n"],
823
+ requiredOptions: [{
824
+ option: "i18n.locales",
825
+ detail: "Pass a nonempty JSON array of locale names or set locales in your I18n config."
826
+ }],
827
+ summary: "Messages with translation records for each locale and a locale for each request.",
828
+ title: "I18n"
829
+ }),
830
+ kv: feature({
831
+ developmentOverrides: ["netlify"],
832
+ docs: "/docs/kv",
833
+ hosts: {
834
+ cloudflare: native("cloudflare", "Workers KV", "Cloudflare Workers KV binding."),
835
+ deno: native("deno-kv", "Deno KV", "Native Deno KV through Deno.openKv()."),
836
+ dev: native("fs-lite", "fs-lite", "Local filesystem-backed KV for development.", "single-host"),
837
+ netlify: explicit("kv.driver", "Upstash / Redis", "Set `kv.driver` (or `kv.stores.default.driver` when using multiple stores) to `upstash`, `redis`, or `database`, or set Upstash REST credentials at build time. No Netlify-native KV output is provided. Without them, KV uses a Postgres Default Database, else `fs-lite` files that other function instances cannot read."),
838
+ node: native("fs-lite", "Redis / Postgres / fs-lite", "A table in a Postgres Default Database, else local files. Redis requires kv: { driver: 'redis' }; REDIS_URL supplies its URL on every server. Upstash with REST credentials at build time.", "single-host"),
839
+ vercel: native("upstash", "Upstash", "Upstash Redis with KV REST credentials.")
840
+ },
841
+ id: "kv",
842
+ packages: ["@vite-hub/kv"],
843
+ providerPackages: { driver: { upstash: ["@upstash/redis"] } },
844
+ summary: "Key-value storage with one API on every host.",
845
+ title: "KV"
846
+ }),
847
+ mcp: feature({
848
+ docs: "/docs/mcp",
849
+ hosts: everywhere("nitro", "Nitro"),
850
+ id: "mcp",
851
+ packages: ["@vite-hub/mcp"],
852
+ requiredOptions: [{
853
+ option: "mcp.auth",
854
+ detail: "Choose an access mode when Auth is disabled. With Auth enabled, MCP requires sign-in by default. The optional mode requires Auth and lets anyone call public tools. Set false only when anyone may call every tool."
855
+ }],
856
+ summary: "The app's own MCP server, with one tool per file in `server/mcp/tools/`.",
857
+ title: "MCP server"
858
+ }),
859
+ observability: feature({
860
+ docs: "/docs/agents/observability",
861
+ hosts: everywhere("evlog", "Evlog"),
862
+ id: "observability",
863
+ packages: ["evlog"],
864
+ summary: "Request logs through Evlog, the logs that the Console reads, and Agent telemetry with a service name.",
865
+ title: "Observability"
866
+ }),
867
+ queue: feature({
868
+ definition: starter("server/queues", (name) => `import { defineQueue } from "vite-hub/queue"
869
+
870
+ export default defineQueue<{ id: string }>({
871
+ handler: async ({ payload }) => {
872
+ console.log("${name}", payload.id)
873
+ },
874
+ })
875
+ `, { suffix: "queue" }),
876
+ docs: "/docs/queue",
877
+ enabledByDiscovery: ["queues"],
878
+ hosts: {
879
+ cloudflare: native("cloudflare", "Queues", "Cloudflare Queues bindings and consumers."),
880
+ deno: unsupported("No Deno Queue driver is provided."),
881
+ dev: native("local", "Local driver", "The local driver stores jobs in .vitehub/data/queue and runs them in the dev server process.", "single-host"),
882
+ netlify: unsupported("Netlify has no Queue driver, so `vitehub({ queue })` fails on Netlify."),
883
+ node: native("local", "Postgres / local driver", "With a Postgres Default Database, the postgres driver keeps jobs in Postgres and every instance runs them. Else the local driver keeps jobs on the disk of one host.", "single-host"),
884
+ vercel: native("vercel", "Vercel Queues", "Vercel Queues callbacks and runtime client.")
885
+ },
886
+ id: "queue",
887
+ packages: ["@vite-hub/queue"],
888
+ providerPackages: { driver: { postgres: ["postgres"] } },
889
+ service: "queue",
890
+ summary: "Background jobs in `server/queues/` with retries and delivery on every supported host.",
891
+ title: "Queue"
892
+ }),
893
+ rateLimit: feature({
894
+ developmentOverrides: ["cloudflare"],
895
+ docs: "/docs/rate-limit",
896
+ hosts: {
897
+ cloudflare: native("cloudflare", "Cloudflare", "Native Cloudflare Rate Limiting binding."),
898
+ deno: unsupported("ViteHub has no native Deno Rate Limit driver."),
899
+ dev: native("memory", "memory", "Process-local memory driver for development and tests.", "process-local"),
900
+ netlify: unsupported("ViteHub has no native Netlify Rate Limit driver."),
901
+ node: native("memory", "memory, or KV", "Without KV, each process counts alone. With KV on, ViteHub selects the kv provider, which shares the counts when KV uses Redis or a Postgres Database.", "process-local"),
902
+ vercel: unsupported("ViteHub has no native Vercel Rate Limit driver.")
903
+ },
904
+ id: "rateLimit",
905
+ packages: ["@vite-hub/rate-limit"],
906
+ service: "rateLimit",
907
+ summary: "Rate limits in `server/rate-limits/` that protect routes and Agent tools.",
908
+ title: "Rate Limit"
909
+ }),
910
+ realtime: feature({
911
+ definition: starter("server/realtime", (name) => `import { defineRealtime } from "vite-hub/realtime"
912
+
913
+ export default defineRealtime({
914
+ authorize: true,
915
+ document: { workspace: "${name}" },
916
+ })
917
+ `),
918
+ developmentOverrides: [
919
+ "cloudflare",
920
+ "deno",
921
+ "netlify",
922
+ "vercel"
923
+ ],
924
+ docs: "/docs/realtime",
925
+ enabledByDiscovery: ["realtime"],
926
+ hosts: {
927
+ cloudflare: native("cloudflare", "Durable Objects", "Cloudflare Durable Objects run the production rooms."),
928
+ deno: unsupported("Realtime has no distributed Deno driver, and process memory is rejected for the Deno host."),
929
+ dev: native("memory", "memory", "Process-memory driver for local development.", "process-local"),
930
+ netlify: unsupported("Realtime has no distributed Netlify driver, and process memory is rejected for the Netlify host."),
931
+ node: native("node", "Postgres or Redis", "Each instance keeps its rooms in memory and shares them through Redis with REDIS_URL, else Postgres on a Postgres Default Database. Without either, rooms stay in one process."),
932
+ vercel: unsupported("Realtime has no distributed Vercel driver, and process memory is rejected for the Vercel host.")
933
+ },
934
+ id: "realtime",
935
+ packages: ["@vite-hub/realtime"],
936
+ service: "realtime",
937
+ summary: "Shared rooms with presence and Yjs documents.",
938
+ title: "Realtime"
939
+ }),
940
+ sandboxTask: feature({
941
+ docs: "/docs/sandbox",
942
+ hosts: {
943
+ cloudflare: native("cloudflare", "CF Sandbox", "Cloudflare Sandbox execution provider."),
944
+ deno: unsupported("No Deno Sandbox driver is provided."),
945
+ dev: unsupported("The default Node host has no Sandbox Provider. With the Cloudflare or Vercel host, `vite dev` runs each Sandbox Task as a process on this machine, with no isolation and no provider account. `sandboxTask: { remote: true }` uses the host's Sandbox instead."),
946
+ netlify: explicit("sandboxTask.driver", "Vercel Sandbox", "The Netlify host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
947
+ node: explicit("sandboxTask.driver", "Vercel Sandbox", "The Node host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
948
+ vercel: native("vercel", "Vercel Sandbox", "Vercel Sandbox execution provider.")
949
+ },
950
+ id: "sandboxTask",
951
+ packages: ["@vite-hub/sandbox"],
952
+ service: "sandbox",
953
+ summary: "Sandbox Tasks in `server/sandbox-tasks/`. Each run starts an isolated Cloudflare or Vercel Sandbox.",
954
+ title: "Sandbox"
955
+ }),
956
+ schedule: feature({
957
+ definition: starter("server/schedules", (name) => `import { defineSchedule } from "vite-hub/schedule"
958
+
959
+ export default defineSchedule({
960
+ cron: "0 * * * *",
961
+ handler: () => {
962
+ console.log("${name}")
963
+ },
964
+ })
965
+ `, { suffix: "schedule" }),
966
+ developmentOverrides: [
967
+ "cloudflare",
968
+ "netlify",
969
+ "vercel"
970
+ ],
971
+ docs: "/docs/schedule",
972
+ enabledByDiscovery: ["schedules"],
973
+ hosts: {
974
+ cloudflare: native("cloudflare", "Cron triggers", "Cloudflare scheduled events and Nitro Provider Wake."),
975
+ deno: native("deno", "Deno.cron", "`Deno.cron` output that the generated `.output/main.ts` loads before the Nitro server."),
976
+ dev: native("local", "Local / process", "Local development runner and the explicit process runtime.", "single-host"),
977
+ netlify: native("netlify", "Scheduled fn", "One generated Netlify scheduled function per static Schedule."),
978
+ node: native("process", "process", "Process runtime in the server process. `schedule: true` uses it. Set `providerOutput: false` to wake Schedules yourself. With a Postgres or remote libSQL Default Database, servers claim occurrences in `vitehub_leases`. A run can repeat if its lease expires. Without a shared lease store, run one server.", "single-host"),
979
+ vercel: native("vercel", "Vercel Cron", "Vercel Cron Jobs provider output.")
980
+ },
981
+ id: "schedule",
982
+ packages: ["@vite-hub/schedule"],
983
+ summary: "Cron Schedules in `server/schedules/` that run on the host's scheduler.",
984
+ title: "Schedule"
985
+ }),
986
+ workflow: feature({
987
+ definition: starter("server/workflows", () => `import { defineWorkflow } from "vite-hub/workflow"
988
+
989
+ export default defineWorkflow<{ id: string }>({
990
+ handler: async ({ payload }) => {
991
+ return { id: payload.id }
992
+ },
993
+ })
994
+ `, {
995
+ folder: "index",
996
+ suffix: "workflow"
997
+ }),
998
+ docs: "/docs/workflows",
999
+ enabledByDiscovery: ["workflows"],
1000
+ hosts: {
1001
+ cloudflare: native("cloudflare", "CF Workflows", "Cloudflare Workflows provider."),
1002
+ deno: explicit("workflow.driver", "OpenWorkflow", "Set `workflow.driver` to \"openworkflow\" with `workflow.postgres.url`, and start its worker. A build without a driver fails."),
1003
+ dev: native("openworkflow", "OpenWorkflow", "The Node host runs OpenWorkflow and its worker in the dev server, on .vitehub/data/openworkflow.sqlite.db. workflow.remote lets it use the Postgres Default Database or OPENWORKFLOW_POSTGRES_URL."),
1004
+ netlify: explicit("workflow.driver", "OpenWorkflow", "Use OpenWorkflow explicitly. No Netlify-native Workflow driver is provided."),
1005
+ node: {
1006
+ ...native("openworkflow", "OpenWorkflow", "OpenWorkflow is the default, and each server runs its worker. It uses OPENWORKFLOW_POSTGRES_URL or the Postgres Default Database. Without them, runs use a SQLite file on one host.", "single-host"),
1007
+ envOverrides: ["OPENWORKFLOW_POSTGRES_URL"].map((env) => ({
1008
+ env,
1009
+ support: native("openworkflow", "OpenWorkflow (Postgres)", `${env} selects Postgres. Several servers can run the worker on the same database, and each run executes once.`)
1010
+ }))
1011
+ },
1012
+ vercel: native("vercel", "Vercel Workflow", "Vercel Workflow provider and Workflow DevKit output.")
1013
+ },
1014
+ id: "workflow",
1015
+ packages: ["@vite-hub/workflow"],
1016
+ summary: "Durable Workflows in `server/workflows/` with steps and driver retries.",
1017
+ title: "Workflow"
1018
+ }),
1019
+ workspace: feature({
1020
+ developmentOverrides: [
1021
+ "cloudflare",
1022
+ "deno",
1023
+ "netlify",
1024
+ "vercel"
1025
+ ],
1026
+ docs: "/docs/workspace",
1027
+ enabledByDiscovery: ["workspaces"],
1028
+ hosts: {
1029
+ cloudflare: native("memory", "Artifacts / GitHub", "Memory by default, or Cloudflare Artifacts beta and GitHub for durable state.", "process-local"),
1030
+ deno: explicit("workspace.store", "GitHub", "Select the GitHub Workspace Store explicitly for durable state."),
1031
+ dev: native("local", "local / memory", "Local filesystem or in-memory Workspace Store.", "single-host"),
1032
+ netlify: explicit("workspace.store", "GitHub", "Select the GitHub Workspace Store explicitly for durable state."),
1033
+ node: native("local", "local / GitHub", "Local filesystem, memory, or GitHub Workspace Store.", "single-host"),
1034
+ vercel: {
1035
+ ...native("memory", "memory / Blob / GitHub", "Process-local memory by default. BLOB_READ_WRITE_TOKEN selects Vercel Blob; GitHub can be selected explicitly for durable state.", "process-local"),
1036
+ envOverrides: [{
1037
+ env: "BLOB_READ_WRITE_TOKEN",
1038
+ support: native("vercel", "Blob / GitHub", "BLOB_READ_WRITE_TOKEN selects durable Vercel Blob storage by default.")
1039
+ }]
1040
+ }
1041
+ },
1042
+ id: "workspace",
1043
+ packages: ["@vite-hub/workspace"],
1044
+ summary: "File workspaces that Agents read and edit, backed by local, Blob, or GitHub stores.",
1045
+ title: "Workspace"
1046
+ })
1047
+ };
1048
+ /** Packages needed by a feature, its provider, and its enabled feature integrations. */
1049
+ function featurePackages(id, value, host, enabled = []) {
1050
+ const definition = features[id];
1051
+ const options = value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1052
+ const stores = options?.stores;
1053
+ const selected = ((id === "blob" || id === "kv") && stores && typeof stores === "object" && !Array.isArray(stores) ? [value, ...Object.values(stores)] : [value]).flatMap((value) => Object.entries(definition.providerPackages ?? {}).flatMap(([key, choices]) => {
1054
+ const choice = value && typeof value === "object" && !Array.isArray(value) ? Reflect.get(value, key) : void 0;
1055
+ return typeof choice === "string" ? choices[choice] ?? [] : [];
1056
+ }));
1057
+ if (id === "observability" && typeof options?.service === "string") selected.push("@vite-hub/agent");
1058
+ if (id === "observability" && options?.posthog) selected.push("posthog-node");
1059
+ const sandboxDriver = typeof options?.driver === "string" ? options.driver : host;
1060
+ if (id === "sandboxTask" && (sandboxDriver === "vercel" || sandboxDriver === "cloudflare")) selected.push(sandboxDriverPackages[sandboxDriver]);
1061
+ if ((id === "queue" || id === "workflow") && host === "vercel" && (options?.driver ?? "vercel") === "vercel") selected.push(...vercelProviderPackages[id]);
1062
+ if (id === "email" && options?.driver === "smtp" && host !== "cloudflare") selected.push(...ownerCheckedPackages.email ?? []);
1063
+ if (id === "console" && enabled.includes("agent")) selected.push(...consoleFeaturePackages.agents);
1064
+ return [.../* @__PURE__ */ new Set([...definition.packages, ...selected])];
1065
+ }
1066
+ const ownerCheckedPackages = { email: ["nodemailer"] };
1067
+ const sandboxDriverPackages = {
1068
+ cloudflare: "@cloudflare/sandbox",
1069
+ vercel: "@vercel/sandbox"
1070
+ };
1071
+ /**
1072
+ * The SDKs of the Vercel provider. Native Vercel Workflows also need `workflow` and `@workflow/builders`, but only
1073
+ * `@vite-hub/workflow` knows when a Workflow is native, so it checks those two itself.
1074
+ */
1075
+ const vercelProviderPackages = {
1076
+ queue: ["@vercel/queue", "@vercel/functions"],
1077
+ workflow: ["@vercel/functions"]
1078
+ };
1079
+ const drizzleRange = "1.0.0-rc.5 || ^1.0.0";
1080
+ const installRanges = {
1081
+ "drizzle-kit": drizzleRange,
1082
+ "drizzle-orm": drizzleRange
1083
+ };
1084
+ /**
1085
+ * The package manager argument that installs `name`, such as `drizzle-orm@1.0.0-rc.5 || ^1.0.0`. Drizzle tags 0.x as
1086
+ * `latest` and the next 1.0 candidate as `rc`, so a plain name installs a version that ViteHub cannot import. npm saves
1087
+ * the range as written, and an exact version would be saved as `^1.0.0-rc.5`, which also matches later candidates.
1088
+ * Other packages keep their name. Feature catalogs, status, and removal use the plain name.
1089
+ */
1090
+ function installSpecifier(name) {
1091
+ const range = installRanges[name];
1092
+ return range ? `${name}@${range}` : name;
1093
+ }
1094
+ function quoteSupportedInstallSpecifier(value) {
1095
+ const separator = value.indexOf("@", 1);
1096
+ if (separator < 0) return void 0;
1097
+ const name = value.slice(0, separator);
1098
+ return Object.hasOwn(installRanges, name) && value === installSpecifier(name) ? `"${value}"` : void 0;
1099
+ }
1100
+ function formatInstallArgument(value) {
1101
+ return quoteSupportedInstallSpecifier(value) ?? (/^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`);
1102
+ }
1103
+ /** Additional Console owners selected by its enabled Agent integration. */
1104
+ const consoleFeaturePackages = { agents: ["@libsql/client", "drizzle-orm"] };
1105
+ function featureSupport(id, host, appHost) {
1106
+ const definition = features[id];
1107
+ if (host !== "dev") return definition.hosts[host];
1108
+ invariant(appHost, "every caller of featureSupport() for the dev host passes the configured ViteHub host");
1109
+ if (id === "workflow" && appHost === "deno") return native("vercel", "Inline", "Development runs each Workflow inline unless OpenWorkflow storage or a provider is configured.", "process-local");
1110
+ return definition.hosts[appHost === "node" || definition.developmentOverrides?.includes(appHost) ? "dev" : appHost];
1111
+ }
1112
+ /**
1113
+ * The features that `enabled` turn on through implications, without the ones already in `enabled`.
1114
+ * This follows implications transitively.
1115
+ * `disabled` lists features that the app sets to `false`; an implication never turns them on.
1116
+ */
1117
+ function impliedFeatures(enabled, disabled = []) {
1118
+ const on = new Set(enabled);
1119
+ const implied = [];
1120
+ const pending = [...enabled];
1121
+ while (pending.length) {
1122
+ const id = pending.shift();
1123
+ for (const implication of features[id].implies) {
1124
+ if (on.has(implication.feature) || disabled.includes(implication.feature)) continue;
1125
+ on.add(implication.feature);
1126
+ implied.push(implication.feature);
1127
+ pending.push(implication.feature);
1128
+ }
1129
+ }
1130
+ return implied;
1131
+ }
1132
+ //#endregion
428
1133
  //#region ../internal/dist/console-signature.js
429
1134
  /**
430
1135
  * Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
@@ -555,7 +1260,7 @@ function readConsoleSigningKey(env) {
555
1260
  };
556
1261
  }
557
1262
  //#endregion
558
- //#region ../internal/dist/build/vite.js
1263
+ //#region ../internal/dist/vite-DGZFNpcx.js
559
1264
  const projectRootDirectoryMarkers = [
560
1265
  ["server", "agents"],
561
1266
  ["server", "channels"],
@@ -599,7 +1304,7 @@ function hasProjectRootDirectoryMarker(root) {
599
1304
  for (const marker of projectRootDirectoryMarkers) try {
600
1305
  if (statSync(resolve$1(root, ...marker)).isDirectory()) return true;
601
1306
  } catch (error) {
602
- if (error.code !== "ENOENT") throw error;
1307
+ if (!isMissingProjectMarker(error)) throw error;
603
1308
  }
604
1309
  return false;
605
1310
  }
@@ -613,11 +1318,15 @@ function hasProjectRootFileMarker(root, markers) {
613
1318
  try {
614
1319
  if (statSync(resolve$1(root, ...path)).isFile()) return true;
615
1320
  } catch (error) {
616
- if (error.code !== "ENOENT") throw error;
1321
+ if (!isMissingProjectMarker(error)) throw error;
617
1322
  }
618
1323
  }
619
1324
  return false;
620
1325
  }
1326
+ function isMissingProjectMarker(error) {
1327
+ const code = error.code;
1328
+ return code === "ENOENT" || code === "ENOTDIR";
1329
+ }
621
1330
  //#endregion
622
1331
  //#region ../internal/dist/standard-schema.js
623
1332
  function readOwn(value, key) {
@@ -693,6 +1402,7 @@ const setupCommandNames = [
693
1402
  "drain",
694
1403
  "login",
695
1404
  "logout",
1405
+ "update",
696
1406
  "whoami"
697
1407
  ];
698
1408
  /** CLI namespaces owned by built-in commands. */
@@ -871,11 +1581,16 @@ function operationsOf(value) {
871
1581
  /** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
872
1582
  function operationCliPath(operation) {
873
1583
  const dot = operation.name.indexOf(".");
1584
+ const cli = operationCliOptions(operation);
874
1585
  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))
1586
+ command: cli?.command ?? operation.name.slice(dot + 1),
1587
+ namespace: cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
877
1588
  };
878
1589
  }
1590
+ /** The CLI options of an operation, or undefined for an operation without options or with `cli: false`. */
1591
+ function operationCliOptions(operation) {
1592
+ return operation.cli || void 0;
1593
+ }
879
1594
  /**
880
1595
  * The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
881
1596
  * Claude reject a dot in a tool name. `content.publish` is `content_publish`.
@@ -900,6 +1615,7 @@ function createOperationRegistry(sources) {
900
1615
  const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
901
1616
  const commands = /* @__PURE__ */ new Map();
902
1617
  for (const operation of operations) {
1618
+ if (operation.cli === false) continue;
903
1619
  const { command, namespace } = operationCliPath(operation);
904
1620
  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
1621
  const key = `${namespace} ${command}`;
@@ -927,12 +1643,23 @@ function describeInputIssues(issues) {
927
1643
  return path ? `${path}: ${issue.message}` : issue.message;
928
1644
  }).join(" ");
929
1645
  }
1646
+ function describeInputFields(schema) {
1647
+ const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).map((shape) => {
1648
+ if (!isRecordOrFunction(shape) || !isRecordOrFunction(shape.properties)) return void 0;
1649
+ const required = Array.isArray(shape.required) ? shape.required : [];
1650
+ const fields = Object.keys(shape.properties).map((field) => required.includes(field) ? field : `${field}?`);
1651
+ return fields.length ? `{ ${fields.join(", ")} }` : "{}";
1652
+ });
1653
+ return shapes.every((shape) => shape !== void 0) ? shapes.join(" or ") : void 0;
1654
+ }
930
1655
  /** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
931
1656
  async function parseOperationInput(operation, input) {
932
1657
  const result = await operation.input["~standard"].validate(input ?? {});
933
1658
  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 });
1659
+ const fields = describeInputFields(operationInputJsonSchema(operation));
1660
+ const issues = describeInputIssues(result.issues);
1661
+ const message = `Invalid input for ${operation.name}. ${issues}${fields ? `${/[.!?]$/.test(issues) ? "" : "."} ${operation.name} takes ${fields}.` : ""}`;
1662
+ throw Object.assign(internalErrorDiagnostics.INTERNAL_R0022({ message }), { status: 400 });
936
1663
  }
937
1664
  /** The kind of one call of an operation: a `readOnlyWhen` match makes a write operation a read. */
938
1665
  function operationCall(operation, input) {
@@ -1212,7 +1939,7 @@ function sortKeys(value) {
1212
1939
  //#region src/error-diagnostics.ts
1213
1940
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
1214
1941
  const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1215
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
1942
+ docsBase: "https://vitehub.dev/docs/cli/diagnostics",
1216
1943
  codes: {
1217
1944
  CLI_CONSOLE_LOGIN_FAILED: {
1218
1945
  fix: "Run `vitehub login` again, and approve the code in the browser within 15 minutes. Pass --console <url> for a self-hosted Console.",
@@ -1234,7 +1961,6 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1234
1961
  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
1962
  why: ({ code, message }) => `The Console refused the pull (${String(code)}). ${String(message)}`
1236
1963
  },
1237
- /** A host API answered with a shape that the CLI cannot read. */
1238
1964
  CLI_HOST_RESPONSE_INVALID: {
1239
1965
  fix: "Run the command again. If the error stays, check the status page of the host and update `@vite-hub/cli`.",
1240
1966
  why: ({ host }) => `[vitehub] The ${host} API returned an unexpected response.`
@@ -1255,21 +1981,40 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1255
1981
  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
1982
  why: ({ message }) => message === void 0 ? "" : String(message)
1257
1983
  },
1258
- /** A setup command failed with an error that has no code, and `--json` reports it. */
1259
1984
  CLI_SETUP_FAILED: {
1260
1985
  fix: "Fix the cause that the message names, then run the command again.",
1261
1986
  why: ({ message }) => message
1262
1987
  },
1988
+ CLI_UPDATE_INSTALL_FAILED: {
1989
+ fix: ({ command }) => `The package files already name the new versions. Fix the cause that the package manager printed, then run \`${String(command)}\`. To undo the update, restore the changed files with git.`,
1990
+ why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
1991
+ },
1992
+ CLI_UPDATE_NO_PACKAGES: {
1993
+ fix: "Run `vitehub update` in the folder of the app or of the workspace that installs `vite-hub`. To start, run `pnpm add vite-hub`.",
1994
+ why: ({ root }) => `No package.json in ${String(root)} or its workspace packages names \`vite-hub\` or an \`@vite-hub/*\` package with a version or a pkg.pr.new URL.`
1995
+ },
1996
+ CLI_UPDATE_PACKAGE_MISSING: {
1997
+ fix: ({ target }) => String(target) === "npm" ? "Pass --preview <commit> to use a pkg.pr.new build that has these packages, or remove them from package.json." : "Pass the commit of a build that has these packages, such as a newer commit of main, or remove them from package.json.",
1998
+ why: ({ packages, target }) => `The project depends on ${String(packages)}, which ${String(target)} does not have. Nothing was changed.`
1999
+ },
2000
+ CLI_UPDATE_REQUEST_FAILED: {
2001
+ fix: "Check the network and the npm registry in `npm_config_registry`, then run `vitehub update` again.",
2002
+ why: ({ status, url }) => `The request to ${String(url)} failed (${String(status)}). Nothing was changed.`
2003
+ },
1263
2004
  SETUP_CONFIG_NOT_LITERAL: {
1264
2005
  fix: "Write the options as an object literal, such as `vitehub({ kv: true })`, or edit the config by hand.",
1265
2006
  why: ({ file, reason }) => `The vitehub() options in ${String(file)} cannot be read without running the config (${String(reason)}).`
1266
2007
  },
2008
+ SETUP_LOGS_OPTION_MOVED: {
2009
+ why: "`observability.logs` is no longer a ViteHub option.",
2010
+ fix: "Remove the option from the command. Configure the top-level `logs` key by hand, for example `logs: { source: './server/logs.ts' }` to set `logs.source`."
2011
+ },
1267
2012
  SETUP_NOT_A_PROJECT: {
1268
2013
  fix: "Run the command in the folder of your Vite or Nuxt app, where its package.json is.",
1269
2014
  why: ({ root }) => `${String(root)} has no package.json, vite.config, or nuxt.config file.`
1270
2015
  },
1271
2016
  SETUP_CONFIG_MANUAL: {
1272
- fix: ({ snippet }) => `Add these keys to the vitehub() options by hand:\n${String(snippet)}`,
2017
+ fix: ({ fix, snippet }) => fix ?? `Add these keys to the vitehub() options by hand:\n${String(snippet)}`,
1273
2018
  why: ({ file, reason }) => `ViteHub cannot edit the vitehub() options in ${String(file)} without running the config (${String(reason)}).`
1274
2019
  },
1275
2020
  SETUP_FEATURE_UNSUPPORTED: {
@@ -1281,11 +2026,11 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1281
2026
  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
2027
  },
1283
2028
  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.",
2029
+ fix: ({ command }) => command === "remove" ? "Pass --force to turn the features off without checking unresolved Definition files, or use literal directory options without layers or directory overrides." : "Create the Definition in your evaluated Nuxt server directory and rerun without --name, or use literal directory options without layers or directory overrides.",
1285
2030
  why: "ViteHub cannot determine the Nuxt application server directory without running the config."
1286
2031
  },
1287
2032
  SETUP_INPUT_NEEDED: {
1288
- fix: "Run the `rerun` command, or pass the missing values with --option.",
2033
+ fix: ({ fix }) => fix ?? "Run the `rerun` command, or pass the missing values with --option.",
1289
2034
  why: ({ message }) => message === void 0 ? "" : String(message)
1290
2035
  },
1291
2036
  SETUP_INSTALL_FAILED: {
@@ -1337,7 +2082,7 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1337
2082
  why: () => "The project name is not known. vitehub() has no literal `name` and package.json has no name."
1338
2083
  },
1339
2084
  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.`,
2085
+ fix: ({ host, rerun }) => host === "deno" ? "Create the app in Deno Deploy first, then run `vitehub link --host deno`, or pass --project with the name of an existing app." : `Run \`${String(rerun)}\` to create it, or pass --project with the name of a project that exists.`,
1341
2086
  why: ({ host, project, account }) => `The ${String(host)} project ${JSON.stringify(String(project))} does not exist${account ? ` in account ${String(account)}` : ""}.`
1342
2087
  },
1343
2088
  SETUP_INIT_DIR_NOT_EMPTY: {
@@ -1364,6 +2109,10 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1364
2109
  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
2110
  why: ({ host }) => `No ${String(host)} credentials were found in the environment or in the host CLI login.`
1366
2111
  },
2112
+ SETUP_DEPLOY_D1_MIGRATIONS_PENDING: {
2113
+ fix: ({ apply }) => `Set \`database.migrateOnDeploy: true\` so that \`vitehub deploy\` applies them before the Worker deploys. Or run \`${String(apply)}\` in the build output folder, then deploy again.`,
2114
+ why: ({ binding, migrations }) => `The build has D1 migrations that the remote database of the binding ${String(binding)} has not applied: ${String(migrations)}. The new code would query tables or columns that do not exist yet. Nothing was deployed.`
2115
+ },
1367
2116
  SETUP_DEPLOY_TEMPORARY_UNSUPPORTED: {
1368
2117
  fix: "Remove --temporary and deploy with your host login.",
1369
2118
  why: ({ reason }) => `--temporary cannot run here. ${String(reason)}`
@@ -1401,7 +2150,7 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1401
2150
  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
2151
  },
1403
2152
  SETUP_DEPLOY_ENV_NOT_LINKED: {
1404
- fix: ({ host }) => `Run \`vitehub link --host ${String(host)} --create\` to create the project, then deploy again.`,
2153
+ fix: ({ host }) => host === "deno" ? "Create the app in Deno Deploy if needed, run `vitehub link --host deno`, then deploy again." : `Run \`vitehub link --host ${String(host)} --create\` to create the project, then deploy again.`,
1405
2154
  why: ({ host, names }) => `The ${String(host)} project is not linked, so deploy cannot set ${String(names)} before the first deploy. Nothing was deployed.`
1406
2155
  },
1407
2156
  SETUP_DEPLOY_ENV_STAGE_UNSAFE: {
@@ -1922,8 +2671,8 @@ const HOST_CREDENTIALS = {
1922
2671
  vercel: "VERCEL_TOKEN"
1923
2672
  };
1924
2673
  const USAGE = {
1925
- run: "vitehub provision run --host <cloudflare|vercel> [--dry-run] [--json]",
1926
- status: "vitehub provision status --host <cloudflare|vercel> [--json]"
2674
+ run: "vitehub provision run [--host <cloudflare|vercel>] [--dry-run] [--json]",
2675
+ status: "vitehub provision status [--host <cloudflare|vercel>] [--json]"
1927
2676
  };
1928
2677
  /** Whether ViteHub can provision resources on `host`. Only Cloudflare and Vercel have Provision Steps. */
1929
2678
  function isProvisionHost(value) {
@@ -1937,8 +2686,7 @@ function setVariable(env, name, value) {
1937
2686
  }
1938
2687
  /**
1939
2688
  * 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.
2689
+ * `wrangler login` token, and the account and project ids of the host link. The selected link wins over environment scope.
1942
2690
  */
1943
2691
  function provisionEnv(env, credentials, link = {}) {
1944
2692
  if (!credentials.ok) return env;
@@ -2003,7 +2751,8 @@ function writeUsage(command, stream) {
2003
2751
  "Never deletes resources. Changes an existing resource only for a planned update, such as D1 read replication.",
2004
2752
  "",
2005
2753
  "Options:",
2006
- " --host <name> Target host: cloudflare or vercel (required).",
2754
+ " --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`:",
2755
+ " the default target of .vitehub/link.json, else the only one, else `host` in vitehub().",
2007
2756
  " --dry-run Print the plan without applying it.",
2008
2757
  " --json Print one JSON result to stdout.",
2009
2758
  " -h, --help Show this help."
@@ -2015,13 +2764,13 @@ function writeUsage(command, stream) {
2015
2764
  "Never creates or deletes provider resources, and never writes Provision State.",
2016
2765
  "",
2017
2766
  "Options:",
2018
- " --host <name> Target host: cloudflare or vercel (required).",
2767
+ " --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`.",
2019
2768
  " --json Print one JSON result to stdout.",
2020
2769
  " -h, --help Show this help."
2021
2770
  ];
2022
2771
  stream.write(`${lines.join("\n")}\n\n`);
2023
2772
  }
2024
- function resolveHost(command, parsed, context) {
2773
+ async function resolveHost(command, parsed, context) {
2025
2774
  if (parsed.help) {
2026
2775
  writeUsage(command, context.stdout);
2027
2776
  return { exitCode: 0 };
@@ -2031,18 +2780,37 @@ function resolveHost(command, parsed, context) {
2031
2780
  writeUsage(command, context.stderr);
2032
2781
  return { exitCode: 1 };
2033
2782
  }
2034
- if (!isProvisionHost(parsed.host)) {
2783
+ let host = parsed.host;
2784
+ let link;
2785
+ if (host === void 0) {
2786
+ const { resolveDefaultDeployTarget } = await import("./deploy-CHW75le_.js").then((n) => n.n);
2787
+ try {
2788
+ const target = await resolveDefaultDeployTarget(resolveViteHubProjectRoot(context.rootDir), context.env, `vitehub provision ${command}`);
2789
+ host = target.host;
2790
+ link = target.link;
2791
+ } catch (error) {
2792
+ context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
2793
+ return { exitCode: 1 };
2794
+ }
2795
+ if (!isProvisionHost(host)) {
2796
+ context.stderr.write(`The host of this project is ${host}, and provision supports cloudflare and vercel. Pass --host cloudflare|vercel to provision another host.\n`);
2797
+ return { exitCode: 1 };
2798
+ }
2799
+ }
2800
+ if (!isProvisionHost(host)) {
2035
2801
  context.stderr.write("Provision requires --host cloudflare|vercel.\n");
2036
2802
  writeUsage(command, context.stderr);
2037
2803
  return { exitCode: 1 };
2038
2804
  }
2039
- return { host: parsed.host };
2805
+ return {
2806
+ host,
2807
+ ...link ? { link } : {}
2808
+ };
2040
2809
  }
2041
2810
  function hasHostCredentials(host, env) {
2042
2811
  return Boolean(host === "cloudflare" ? resolveCloudflareProvisionConfig(env) : resolveVercelProvisionConfig(env));
2043
2812
  }
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) {
2813
+ async function withHostCredentials(host, context, link) {
2046
2814
  const credentials = await resolveHostCredentials(host, {
2047
2815
  cwd: context.rootDir,
2048
2816
  env: context.env,
@@ -2050,11 +2818,14 @@ async function withHostCredentials(host, context) {
2050
2818
  });
2051
2819
  return {
2052
2820
  ...context,
2053
- env: provisionEnv(context.env, credentials)
2821
+ env: provisionEnv(context.env, credentials, {
2822
+ ...link?.account?.id ? { accountId: link.account.id } : {},
2823
+ ...link?.project.id ? { projectId: link.project.id } : {}
2824
+ })
2054
2825
  };
2055
2826
  }
2056
- async function planProvision(provider, context, options, json) {
2057
- return await planProvisionSteps(provider, await options.collectSteps(), {
2827
+ async function planProvision(provider, context, steps, json) {
2828
+ return await planProvisionSteps(provider, [...steps], {
2058
2829
  env: context.env,
2059
2830
  fetch: globalThis.fetch,
2060
2831
  logger: {
@@ -2145,18 +2916,23 @@ function writeProvisionActions(actions, stdout) {
2145
2916
  stdout.write(`${provisionActionStatus(planned)}\t${action.kind}\t${action.name}${action.update ? `\t${action.update}` : ""}\n`);
2146
2917
  }
2147
2918
  }
2148
- async function runProvision(args, cliContext, options) {
2919
+ async function runProvision(args, cliContext, load) {
2149
2920
  const parsed = parseArgs("run", args);
2150
- const resolved = resolveHost("run", parsed, cliContext);
2921
+ const resolved = await resolveHost("run", parsed, cliContext);
2151
2922
  if ("exitCode" in resolved) return resolved.exitCode;
2152
2923
  const { host: provider } = resolved;
2153
- const context = await withHostCredentials(provider, cliContext);
2924
+ const { env = cliContext.env, rootDir, steps } = await load(provider);
2925
+ const context = await withHostCredentials(provider, {
2926
+ ...cliContext,
2927
+ env,
2928
+ rootDir
2929
+ }, resolved.link);
2154
2930
  if (!parsed.dryRun && !hasHostCredentials(provider, context.env)) {
2155
2931
  context.stderr.write(`Provision requires ${HOST_CREDENTIALS[provider]}. Dry-run preview does not require credentials (--dry-run).\n`);
2156
2932
  return 1;
2157
2933
  }
2158
2934
  if (!parsed.dryRun) await readProvisionState(context.rootDir);
2159
- const { actions, checked, warnings } = await planProvision(provider, context, options, parsed.json);
2935
+ const { actions, checked, warnings } = await planProvision(provider, context, steps, parsed.json);
2160
2936
  const blocked = !checked && !parsed.dryRun;
2161
2937
  if (!parsed.json) {
2162
2938
  if (!checked) context.stdout.write("provision: plan not checked.\n");
@@ -2192,16 +2968,21 @@ async function runProvision(args, cliContext, options) {
2192
2968
  } else if (wroteState) context.stdout.write(`provision: wrote ids to ${PROVISION_STATE_FILE}\n`);
2193
2969
  return blocked ? 1 : 0;
2194
2970
  }
2195
- async function runProvisionStatus(args, cliContext, options) {
2971
+ async function runProvisionStatus(args, cliContext, load) {
2196
2972
  const parsed = parseArgs("status", args);
2197
- const resolved = resolveHost("status", parsed, cliContext);
2973
+ const resolved = await resolveHost("status", parsed, cliContext);
2198
2974
  if ("exitCode" in resolved) return resolved.exitCode;
2199
2975
  const { host: provider } = resolved;
2200
- const context = await withHostCredentials(provider, cliContext);
2976
+ const { env = cliContext.env, rootDir, steps } = await load(provider);
2977
+ const context = await withHostCredentials(provider, {
2978
+ ...cliContext,
2979
+ env,
2980
+ rootDir
2981
+ }, resolved.link);
2201
2982
  const recorded = (await readProvisionState(context.rootDir))[provider] ?? {};
2202
- const undeclared = findUndeclaredEntries(provider, recorded, await options.collectSteps(), context.env);
2983
+ const undeclared = findUndeclaredEntries(provider, recorded, steps, context.env);
2203
2984
  const hasCredentials = hasHostCredentials(provider, context.env);
2204
- const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, options, parsed.json) : {
2985
+ const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, steps, parsed.json) : {
2205
2986
  actions: [],
2206
2987
  checked: false,
2207
2988
  warnings: [`provision: plan not checked, missing ${HOST_CREDENTIALS[provider]}.`]
@@ -2239,24 +3020,26 @@ async function runProvisionStatus(args, cliContext, options) {
2239
3020
  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
3021
  return 0;
2241
3022
  }
2242
- /** Built-in namespace that orchestrates package-contributed Provision Steps. */
2243
- function createProvisionNamespace(steps) {
2244
- const options = { collectSteps: async () => [...steps] };
3023
+ /**
3024
+ * Built-in namespace that orchestrates package-contributed Provision Steps. `load` reads the steps of a build for the
3025
+ * `--host` of the command, so `provision run --host cloudflare` plans what `vitehub deploy --host cloudflare` creates.
3026
+ */
3027
+ function createProvisionNamespace(load) {
2245
3028
  return {
2246
3029
  description: "Idempotently create missing provider resources.",
2247
3030
  features: [{
2248
3031
  description: "Create missing provider resources for the app's Definitions.",
2249
3032
  name: "run",
2250
- run: (args, context) => runProvision(args, context, options),
3033
+ run: (args, context) => runProvision(args, context, load),
2251
3034
  usage: USAGE.run
2252
3035
  }, {
2253
3036
  description: "Show recorded provider ids and pending plan actions.",
2254
3037
  name: "status",
2255
- run: (args, context) => runProvisionStatus(args, context, options),
3038
+ run: (args, context) => runProvisionStatus(args, context, load),
2256
3039
  usage: USAGE.status
2257
3040
  }],
2258
3041
  name: "provision"
2259
3042
  };
2260
3043
  }
2261
3044
  //#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 };
3045
+ export { isRecord as $, parseOperationInput as A, formatInstallArgument as B, callOperationFromCli as C, operationCliOptions as D, operationCall as E, featureHosts as F, appUrlError as G, installSpecifier as H, featureIds as I, findViteHubDevServerUrl as J, collectViteHubCliContribution as K, featurePackages as L, reservedOperationNamespaces as M, setupCommandNames as N, operationCliPath as O, resolveViteHubProjectRoot as P, internalErrorDiagnostics as Q, featureSupport as R, callOperation as S, createOperationRegistry as T, quoteSupportedInstallSpecifier as U, impliedFeatures as V, invariant as W, viteCliProjectConfig as X, getStableStdoutWrite as Y, withStdoutOnStderr as Z, readProvisionState as _, writeProvisionActions as a, loadAllEnv as b, createNetlifyApiClient as c, planProvisionSteps as d, resolveHostCredentials as f, mergeProvisionState as g, PROVISION_STATE_FILE as h, provisionEnv as i, operationInputJsonSchema as j, operationsOf as k, createVercelProvisionClient as l, cliErrorDiagnostics as m, isProvisionHost as n, createCloudflareApiClient as o, runHostCli as p, createCliDiscoveryNitroCloser as q, provisionActionStatus as r, createCloudflareProvisionClient as s, createProvisionNamespace as t, isProvisionRequestError as u, readProvisionStateSync as v, collectOperationContributions as w, withViteStageEnvironment as x, writeProvisionState as y, features as z };