@vite-hub/cli 0.0.0 → 0.0.2

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.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
1
  # @vite-hub/cli
2
2
 
3
- Reserved package name for ViteHub.
3
+ <p>
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
+ <img alt="CLI" src="https://img.shields.io/badge/CLI-package%20workflows-18181b?style=flat-square">
7
+ </p>
8
+
9
+ `@vite-hub/cli` loads the local Vite config, collects package-contributed commands, and runs them from `vitehub`.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ pnpm add -D @vite-hub/cli
15
+ ```
16
+
17
+ ## Minimal API
18
+
19
+ ```sh
20
+ pnpm vitehub --help
21
+ pnpm vitehub agent info
22
+ pnpm vitehub agent dev
23
+ pnpm vitehub agent eval
24
+ pnpm vitehub db generate
25
+ pnpm vitehub db migrate
26
+ pnpm vitehub workspace dev docs
27
+ pnpm vitehub provision run --provider cloudflare --dry-run
28
+ ```
29
+
30
+ ```ts
31
+ // scripts/vitehub.ts
32
+ import { runViteHubCli } from "@vite-hub/cli"
33
+
34
+ const exitCode = await runViteHubCli({
35
+ args: ["agent", "eval"],
36
+ cwd: process.cwd(),
37
+ })
38
+ ```
39
+
40
+ ## Vite
41
+
42
+ Commands come from the active Vite plugins, so package CLIs stay package-owned. The Agent integration contributes `agent info`, `agent dev`, and Evalite-backed `agent eval`; Database contributes `db generate` and `db migrate`; Workspace contributes `workspace dev`. The CLI also owns `provision run` for executing package-contributed provider provisioning steps.
43
+
44
+ Learn more at [vitehub.dev](https://vitehub.dev).
@@ -0,0 +1,34 @@
1
+ import { ResolvedConfig } from "vite";
2
+
3
+ //#region src/index.d.ts
4
+ interface ViteHubCliSpawnResult {
5
+ exitCode: number | null;
6
+ signal?: NodeJS.Signals | null;
7
+ }
8
+ interface ViteHubCliSpawnOptions {
9
+ cwd?: string;
10
+ env?: NodeJS.ProcessEnv;
11
+ stderr?: "inherit" | "pipe";
12
+ stdout?: "inherit" | "pipe";
13
+ }
14
+ type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
15
+ interface ViteHubCliStreams {
16
+ stderr: {
17
+ write: (chunk: string | Uint8Array) => unknown;
18
+ };
19
+ stdout: {
20
+ write: (chunk: string | Uint8Array) => unknown;
21
+ };
22
+ }
23
+ interface RunViteHubCliOptions {
24
+ args?: string[];
25
+ cwd?: string;
26
+ env?: NodeJS.ProcessEnv;
27
+ loadConfig?: (rootDir: string) => Promise<Pick<ResolvedConfig, "plugins" | "root">>;
28
+ spawn?: ViteHubCliSpawn;
29
+ stderr?: ViteHubCliStreams["stderr"];
30
+ stdout?: ViteHubCliStreams["stdout"];
31
+ }
32
+ declare function runViteHubCli(options?: RunViteHubCliOptions): Promise<number>;
33
+ //#endregion
34
+ export { RunViteHubCliOptions, runViteHubCli };
package/dist/index.js ADDED
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { realpathSync } from "node:fs";
4
+ import process from "node:process";
5
+ import { fileURLToPath } from "node:url";
6
+ import { dirname, resolve } from "pathe";
7
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
8
+ //#region ../internal/dist/cli.js
9
+ async function resolveContributor(value) {
10
+ return typeof value === "function" ? await value() : value;
11
+ }
12
+ async function collectViteHubCliNamespaces(plugins) {
13
+ const namespaces = /* @__PURE__ */ new Map();
14
+ for (const plugin of plugins) {
15
+ if (!plugin || typeof plugin !== "object") continue;
16
+ const metadata = plugin.vitehub;
17
+ const contributor = await resolveContributor(metadata?.cli);
18
+ if (!contributor) continue;
19
+ for (const namespace of contributor.namespaces) {
20
+ const existing = namespaces.get(namespace.name);
21
+ if (!existing) {
22
+ namespaces.set(namespace.name, {
23
+ ...namespace,
24
+ features: [...namespace.features]
25
+ });
26
+ continue;
27
+ }
28
+ const features = new Map(existing.features.map((feature) => [feature.name, feature]));
29
+ for (const feature of namespace.features) features.set(feature.name, feature);
30
+ existing.features = [...features.values()];
31
+ }
32
+ }
33
+ return [...namespaces.values()];
34
+ }
35
+ async function collectViteHubProvisionSteps(plugins) {
36
+ const steps = /* @__PURE__ */ new Map();
37
+ for (const plugin of plugins) {
38
+ if (!plugin || typeof plugin !== "object") continue;
39
+ const contributor = await resolveContributor(plugin.vitehub?.cli);
40
+ for (const step of contributor?.provision ?? []) steps.set(step.id, step);
41
+ }
42
+ return [...steps.values()];
43
+ }
44
+ //#endregion
45
+ //#region ../internal/dist/provision-state.js
46
+ const PROVISION_STATE_FILE = ".vitehub/provision.json";
47
+ function getProvisionStatePath(rootDir) {
48
+ return resolve(rootDir, PROVISION_STATE_FILE);
49
+ }
50
+ async function readProvisionState(rootDir) {
51
+ try {
52
+ return parseProvisionState(await readFile(getProvisionStatePath(rootDir), "utf8"));
53
+ } catch {
54
+ return {};
55
+ }
56
+ }
57
+ async function writeProvisionState(rootDir, next) {
58
+ const path = getProvisionStatePath(rootDir);
59
+ const merged = mergeProvisionState(await readProvisionState(rootDir), next);
60
+ await mkdir(dirname(path), { recursive: true });
61
+ await writeFile(path, `${JSON.stringify(sortState(merged), null, 2)}\n`, "utf8");
62
+ }
63
+ function mergeProvisionState(base, next) {
64
+ const merged = structuredClone(base);
65
+ for (const provider of Object.keys(next)) {
66
+ const categories = next[provider];
67
+ if (!categories) continue;
68
+ const target = merged[provider] ??= {};
69
+ for (const [category, ids] of Object.entries(categories)) target[category] = {
70
+ ...target[category],
71
+ ...ids
72
+ };
73
+ }
74
+ return merged;
75
+ }
76
+ function parseProvisionState(raw) {
77
+ const parsed = JSON.parse(raw);
78
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
79
+ }
80
+ function sortState(state) {
81
+ return sortKeys(state);
82
+ }
83
+ function sortKeys(value) {
84
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
85
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]));
86
+ }
87
+ //#endregion
88
+ //#region ../internal/dist/provision.js
89
+ function resolveCloudflareProvisionConfig(env) {
90
+ const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
91
+ const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
92
+ if (!accountId || !token) return;
93
+ return {
94
+ accountId,
95
+ token
96
+ };
97
+ }
98
+ function resolveVercelProvisionConfig(env) {
99
+ const token = trimmedEnv(env.VERCEL_TOKEN);
100
+ if (!token) return;
101
+ return {
102
+ token,
103
+ teamId: trimmedEnv(env.VERCEL_TEAM_ID) ?? trimmedEnv(env.VERCEL_ORG_ID)
104
+ };
105
+ }
106
+ function trimmedEnv(value) {
107
+ const trimmed = value?.trim();
108
+ return trimmed ? trimmed : void 0;
109
+ }
110
+ //#endregion
111
+ //#region src/provision.ts
112
+ function parseArgs(args) {
113
+ const parsed = {
114
+ dryRun: false,
115
+ help: false
116
+ };
117
+ for (let index = 0; index < args.length; index++) {
118
+ const arg = args[index];
119
+ if (arg === "-h" || arg === "--help") parsed.help = true;
120
+ else if (arg === "--dry-run") parsed.dryRun = true;
121
+ else if (arg === "--provider") parsed.provider = args[++index];
122
+ else if (arg?.startsWith("--provider=")) parsed.provider = arg.slice(11);
123
+ }
124
+ return parsed;
125
+ }
126
+ function writeUsage(context) {
127
+ context.stdout.write([
128
+ "Usage: vitehub provision run --provider <cloudflare|vercel> [--dry-run]",
129
+ "",
130
+ "Idempotently creates missing provider resources for the app's Definitions.",
131
+ "Never deletes or mutates existing resources.",
132
+ "",
133
+ "Options:",
134
+ " --provider <name> Target provider: cloudflare or vercel (required).",
135
+ " --dry-run Print the plan without applying it.",
136
+ " -h, --help Show this help.",
137
+ ""
138
+ ].join("\n"));
139
+ }
140
+ async function runProvision(args, context, options) {
141
+ const parsed = parseArgs(args);
142
+ if (parsed.help) {
143
+ writeUsage(context);
144
+ return 0;
145
+ }
146
+ if (parsed.provider !== "cloudflare" && parsed.provider !== "vercel") {
147
+ context.stderr.write("Provision requires --provider cloudflare|vercel.\n");
148
+ writeUsage(context);
149
+ return 1;
150
+ }
151
+ const provider = parsed.provider;
152
+ if (!parsed.dryRun) {
153
+ if (!(provider === "cloudflare" ? resolveCloudflareProvisionConfig(context.env) : resolveVercelProvisionConfig(context.env))) {
154
+ const required = provider === "cloudflare" ? "CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN" : "VERCEL_TOKEN";
155
+ context.stderr.write(`Provision requires ${required} to be set. Dry-run preview does not require credentials (--dry-run).\n`);
156
+ return 1;
157
+ }
158
+ }
159
+ const steps = (await options.collectSteps()).filter((step) => step.provider === provider);
160
+ const provisionContext = {
161
+ env: context.env,
162
+ fetch: globalThis.fetch,
163
+ logger: {
164
+ log: (message) => context.stdout.write(`${message}\n`),
165
+ warn: (message) => context.stderr.write(`${message}\n`)
166
+ }
167
+ };
168
+ const actions = [];
169
+ for (const step of steps) for (const action of await step.plan(provisionContext)) actions.push({
170
+ stepId: step.id,
171
+ action
172
+ });
173
+ if (!actions.length) {
174
+ context.stdout.write(`provision: no ${provider} resources to create.\n`);
175
+ return 0;
176
+ }
177
+ for (const { action } of actions) context.stdout.write(`${action.exists ? "exists" : "create"}\t${action.kind}\t${action.name}\n`);
178
+ if (parsed.dryRun) return 0;
179
+ let state = {};
180
+ for (const { action } of actions) {
181
+ const result = await action.apply();
182
+ if (result.ids) state = mergeProvisionState(state, result.ids);
183
+ }
184
+ if (Object.keys(state).length) {
185
+ await writeProvisionState(context.rootDir, state);
186
+ context.stdout.write(`provision: wrote ids to .vitehub/provision.json\n`);
187
+ }
188
+ return 0;
189
+ }
190
+ //#endregion
191
+ //#region src/index.ts
192
+ function defaultSpawn(command, args, options = {}) {
193
+ return new Promise((resolveResult, reject) => {
194
+ const child = spawn(command, args, {
195
+ cwd: options.cwd,
196
+ env: options.env,
197
+ shell: process.platform === "win32",
198
+ stdio: [
199
+ "inherit",
200
+ options.stdout || "inherit",
201
+ options.stderr || "inherit"
202
+ ]
203
+ });
204
+ child.on("error", reject);
205
+ child.on("close", (exitCode, signal) => resolveResult({
206
+ exitCode,
207
+ signal
208
+ }));
209
+ });
210
+ }
211
+ async function loadViteConfig(rootDir) {
212
+ const { resolveConfig } = await import("vite");
213
+ return await resolveConfig({ root: rootDir }, "serve", "development");
214
+ }
215
+ function createProvisionNamespace(plugins) {
216
+ const collectSteps = () => collectViteHubProvisionSteps(plugins);
217
+ const run = (args, context) => runProvision(args, context, { collectSteps });
218
+ return {
219
+ description: "Idempotently create missing provider resources.",
220
+ features: [{
221
+ description: "Create missing provider resources for the app's Definitions.",
222
+ name: "run",
223
+ run,
224
+ usage: "vitehub provision run --provider <cloudflare|vercel> [--dry-run]"
225
+ }],
226
+ name: "provision"
227
+ };
228
+ }
229
+ function writeRootHelp(namespaces, stdout) {
230
+ stdout.write([
231
+ "Usage: vitehub <namespace> <feature> [args...]",
232
+ "",
233
+ "Available namespaces:",
234
+ ...namespaces.map((namespace) => ` ${namespace.name.padEnd(12)} ${namespace.description || ""}`.trimEnd()),
235
+ ""
236
+ ].join("\n"));
237
+ }
238
+ function writeNamespaceHelp(namespace, stdout) {
239
+ stdout.write([
240
+ `Usage: vitehub ${namespace.name} <feature> [args...]`,
241
+ "",
242
+ namespace.description || "",
243
+ "",
244
+ "Available features:",
245
+ ...namespace.features.map((feature) => ` ${feature.name.padEnd(12)} ${feature.description || ""}`.trimEnd()),
246
+ ""
247
+ ].filter(Boolean).join("\n"));
248
+ }
249
+ function isRootHelp(args) {
250
+ return args[0] === "-h" || args[0] === "--help";
251
+ }
252
+ async function runViteHubCli(options = {}) {
253
+ const args = options.args || process.argv.slice(2);
254
+ const cwd = options.cwd || process.cwd();
255
+ const env = options.env || process.env;
256
+ const stdout = options.stdout || process.stdout;
257
+ const stderr = options.stderr || process.stderr;
258
+ const config = await (options.loadConfig || loadViteConfig)(cwd);
259
+ const rootDir = resolve(config.root || cwd);
260
+ const namespaces = [...await collectViteHubCliNamespaces(config.plugins), createProvisionNamespace(config.plugins)];
261
+ const context = {
262
+ cwd,
263
+ env,
264
+ rootDir,
265
+ spawn: options.spawn || defaultSpawn,
266
+ stderr,
267
+ stdout
268
+ };
269
+ if (!args.length || isRootHelp(args)) {
270
+ writeRootHelp(namespaces, stdout);
271
+ return 0;
272
+ }
273
+ const namespaceName = args[0];
274
+ const namespace = namespaces.find((item) => item.name === namespaceName);
275
+ if (!namespace) {
276
+ stderr.write(`Unknown ViteHub CLI namespace: ${namespaceName}\n`);
277
+ writeRootHelp(namespaces, stderr);
278
+ return 1;
279
+ }
280
+ const featureName = args[1];
281
+ if (!featureName || args[1] === "-h" || args[1] === "--help") {
282
+ writeNamespaceHelp(namespace, stdout);
283
+ return 0;
284
+ }
285
+ const feature = namespace.features.find((item) => item.name === featureName);
286
+ if (!feature) {
287
+ stderr.write(`Unknown ViteHub CLI feature: ${namespace.name} ${featureName}\n`);
288
+ writeNamespaceHelp(namespace, stderr);
289
+ return 1;
290
+ }
291
+ const result = await feature.run(args.slice(2), context);
292
+ return typeof result === "number" ? result : 0;
293
+ }
294
+ function isCliEntrypoint() {
295
+ if (!process.argv[1]) return false;
296
+ try {
297
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
298
+ } catch {
299
+ return false;
300
+ }
301
+ }
302
+ if (isCliEntrypoint()) runViteHubCli().then((exitCode) => {
303
+ process.exit(exitCode);
304
+ }).catch((error) => {
305
+ console.error(error instanceof Error ? error.message : error);
306
+ process.exit(1);
307
+ });
308
+ //#endregion
309
+ export { runViteHubCli };
package/package.json CHANGED
@@ -1,9 +1,57 @@
1
1
  {
2
2
  "name": "@vite-hub/cli",
3
- "version": "0.0.0",
4
- "description": "Reserved package name for ViteHub.",
3
+ "version": "0.0.2",
4
+ "description": "Command-line workflows for ViteHub projects.",
5
+ "keywords": [
6
+ "agent",
7
+ "cli",
8
+ "eval",
9
+ "vitehub"
10
+ ],
11
+ "homepage": "https://github.com/vite-hub/vitehub#readme",
12
+ "bugs": "https://github.com/vite-hub/vitehub/issues",
5
13
  "license": "Apache-2.0",
6
- "publishConfig": {
7
- "access": "public"
14
+ "author": "onmax <maximogarciamtnez@gmail.com>",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/vite-hub/vitehub.git",
18
+ "directory": "packages/cli"
19
+ },
20
+ "bin": {
21
+ "vitehub": "./dist/index.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "package.json"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": "./dist/index.js",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "dependencies": {
35
+ "pathe": "^2.0.3"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^24.13.3",
39
+ "typescript": "^6.0.3",
40
+ "vite": "^8.0.8",
41
+ "vite-plus": "^0.1.24",
42
+ "vitest": "^4.1.4",
43
+ "@vite-hub/internal": "0.0.1"
44
+ },
45
+ "peerDependencies": {
46
+ "vite": ">=8.0.0"
47
+ },
48
+ "engines": {
49
+ "node": ">=24.0.0"
50
+ },
51
+ "scripts": {
52
+ "build": "vp pack",
53
+ "dev": "vp pack --watch",
54
+ "typecheck": "tsc --noEmit -p ./tsconfig.json",
55
+ "test": "vp run -t @vite-hub/cli#build && vp test"
8
56
  }
9
- }
57
+ }