@vultro/cli 0.0.0-stage → 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.
@@ -0,0 +1,115 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, relative } from "node:path";
3
+ import { componentsManifestPath, renderComponentsManifest, renderGeneratedFiles } from "./codegen-content.js";
4
+ import { ProjectError, findModulePathConflicts, findProjectDir, loadProject } from "./project.js";
5
+ import { runTypecheck } from "./typecheck.js";
6
+ // src/codegen.ts
7
+ /** 执行 codegen,返回可供 check / 测试复用的结构化结果。 */
8
+ async function generate(options, runtime = {}) {
9
+ const rootDir = findProjectDir(options.dir);
10
+ const serverExisted = existsSync(join(rootDir, "convex", "_generated", "server.js"));
11
+ const project = await loadProject({
12
+ dir: rootDir,
13
+ bootstrapGeneratedServer: true,
14
+ refreshModules: runtime.refreshModules
15
+ });
16
+ if (project.moduleErrors.length > 0) throw new ProjectError(["以下模块加载失败,无法生成完整的 api:", ...project.moduleErrors.map((error) => ` - ${error.relativePath}: ${error.message}`)].join("\n"));
17
+ if (!project.schemaPath) throw new ProjectError("没有找到 convex/schema.ts。Vultro 运行时需要 schema 才能分配表号和索引。");
18
+ if (project.schema.tables.size === 0) throw new ProjectError("convex/schema.ts 没有定义任何表。请先使用 defineSchema({ ... }) 声明表。");
19
+ const conflicts = findModulePathConflicts(project.modules);
20
+ if (conflicts.length > 0) throw new ProjectError(["模块路径冲突,无法生成 api:", ...conflicts.map((line) => ` - ${line}`)].join("\n"));
21
+ const generated = renderGeneratedFiles(project, {
22
+ staticApi: options.staticApi,
23
+ staticDataModel: options.staticDataModel
24
+ });
25
+ const files = writeGeneratedFiles(project.convexDir, generated);
26
+ const manifestPath = componentsManifestPath(project.convexDir);
27
+ mkdirSync(dirname(manifestPath), { recursive: true });
28
+ writeFileSync(manifestPath, renderComponentsManifest(project));
29
+ if (!serverExisted) {
30
+ const server = files.find((file) => file.fileName === "server.js");
31
+ if (server) server.status = "created";
32
+ }
33
+ let typecheck;
34
+ if (options.typecheck !== "disable") typecheck = runTypecheck(project.rootDir);
35
+ return {
36
+ rootDir: project.rootDir,
37
+ convexDir: project.convexDir,
38
+ files,
39
+ typecheck
40
+ };
41
+ }
42
+ /**
43
+ * 把生成内容写入 `convex/_generated/`。
44
+ *
45
+ * 只有内容变化时才写文件,避免每次 codegen 都触发编辑器和文件监听器。
46
+ */
47
+ function writeGeneratedFiles(convexDir, files) {
48
+ const generatedDir = join(convexDir, "_generated");
49
+ mkdirSync(generatedDir, { recursive: true });
50
+ return files.map((file) => {
51
+ const target = join(generatedDir, file.fileName);
52
+ const existed = existsSync(target);
53
+ if (existed && readFileSync(target, "utf8") === file.content) return {
54
+ fileName: file.fileName,
55
+ status: "unchanged"
56
+ };
57
+ writeFileSync(target, file.content, "utf8");
58
+ return {
59
+ fileName: file.fileName,
60
+ status: existed ? "updated" : "created"
61
+ };
62
+ });
63
+ }
64
+ /** CLI 入口调用的包装:负责打印结果并返回退出码。 */
65
+ async function runCodegen(options) {
66
+ let result;
67
+ try {
68
+ result = await generate(options);
69
+ } catch (error) {
70
+ if (options.json) console.log(JSON.stringify({
71
+ ok: false,
72
+ error: error instanceof Error ? error.message : String(error)
73
+ }, null, 2));
74
+ else console.error(`✗ codegen 失败:${error instanceof Error ? error.message : String(error)}`);
75
+ return 1;
76
+ }
77
+ const changed = result.files.filter((file) => file.status !== "unchanged");
78
+ const created = result.files.filter((file) => file.status === "created").length;
79
+ const updated = result.files.filter((file) => file.status === "updated").length;
80
+ const typecheckFailed = options.typecheck === "enable" && result.typecheck !== void 0 && !result.typecheck.ok;
81
+ if (options.json) console.log(JSON.stringify({
82
+ ok: !typecheckFailed,
83
+ rootDir: result.rootDir,
84
+ files: result.files,
85
+ typecheck: result.typecheck ?? null
86
+ }, null, 2));
87
+ else {
88
+ const projectPath = relative(process.cwd(), result.rootDir) || ".";
89
+ console.log(`vultro codegen ${projectPath}`);
90
+ for (const file of result.files) {
91
+ if (!options.verbose && file.status === "unchanged") continue;
92
+ const label = file.status === "created" ? "created" : file.status === "updated" ? "updated" : "unchanged";
93
+ console.log(` ${label.padEnd(9)} convex/_generated/${file.fileName}`);
94
+ }
95
+ if (changed.length === 0) console.log("✓ 生成文件已是最新");
96
+ else console.log(`✓ 生成完成:${result.files.length} 个文件(${created} 新建,${updated} 更新,${result.files.length - created - updated} 未变)`);
97
+ if (result.typecheck) printTypecheck(result.typecheck, options.typecheck);
98
+ }
99
+ return typecheckFailed ? 1 : 0;
100
+ }
101
+ /** 打印类型检查结果(codegen 与 check 共用同一套格式)。 */
102
+ function printTypecheck(result, mode) {
103
+ if (result.skipped) {
104
+ console.log(`- 类型检查:${result.detail}`);
105
+ return;
106
+ }
107
+ if (result.ok) {
108
+ console.log(`✓ 类型检查:${result.detail}`);
109
+ return;
110
+ }
111
+ console.log(`${mode === "enable" ? "✗" : "!"} 类型检查失败${mode === "enable" ? "" : "(try 模式不阻断)"}`);
112
+ for (const line of result.diagnostics.slice(0, 12)) console.log(` ${line}`);
113
+ if (result.diagnostics.length > 12) console.log(` ... 还有 ${result.diagnostics.length - 12} 行,请直接运行项目类型检查(tsc / bun check)`);
114
+ }
115
+ export { generate, printTypecheck, runCodegen, writeGeneratedFiles };
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,169 @@
1
+ #!/usr/bin/env bun
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { UsageError, parseArgs } from "./args.js";
6
+ import { runCheck } from "./check.js";
7
+ import { runVite } from "./run.js";
8
+ import { mcpOptionsFromCli, runMcp } from "./mcp.js";
9
+ import { runCodegen } from "./codegen.js";
10
+ // src/index.ts
11
+ /**
12
+ * Vultro CLI 入口。
13
+ *
14
+ * 只做三件事:
15
+ * 1. 解析参数;
16
+ * 2. 分发到 codegen / check;
17
+ * 3. 把 UsageError 转成退出码 2,其它错误转成退出码 1。
18
+ *
19
+ * 具体逻辑都在 `codegen.ts` / `check.ts`,方便单元测试直接调用。
20
+ */
21
+ async function main(argv) {
22
+ let options;
23
+ try {
24
+ options = parseArgs(argv);
25
+ } catch (error) {
26
+ if (error instanceof UsageError) {
27
+ console.error(`✗ ${error.message}`);
28
+ console.error("运行 vultro --help 查看用法。");
29
+ return 2;
30
+ }
31
+ throw error;
32
+ }
33
+ if (options.command === "version") {
34
+ console.log(`@vultro/cli ${readVersion()}`);
35
+ return 0;
36
+ }
37
+ if (options.command === "help") {
38
+ printHelp(options.helpFor);
39
+ return 0;
40
+ }
41
+ if (options.command === "codegen") return runCodegen(options);
42
+ if (options.command === "check") return runCheck(options);
43
+ if (options.command === "mcp") return runMcp(mcpOptionsFromCli(options), readVersion());
44
+ if (options.command === "dev") return runVite("dev", options);
45
+ return runVite("build", options);
46
+ }
47
+ /** 从 package.json 读取版本号,避免硬编码后忘记同步。 */
48
+ function readVersion() {
49
+ try {
50
+ const packageJsonPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
51
+ return JSON.parse(readFileSync(packageJsonPath, "utf8")).version ?? "0.0.0";
52
+ } catch {
53
+ return "0.0.0";
54
+ }
55
+ }
56
+ /** 打印帮助。 */
57
+ function printHelp(command) {
58
+ if (command === "codegen") {
59
+ console.log(`用法:vultro codegen [目录] [选项]
60
+
61
+ 生成 convex/_generated/ 下的 TypeScript 类型。
62
+
63
+ 选项:
64
+ --static-api 生成显式的 API 模块树(默认使用 ApiFromModules 推导)
65
+ --static-data-model 从 schema 生成静态 DataModel(默认从 schema 推导)
66
+ --typecheck <mode> enable | try | disable(默认 try)
67
+ --dir <path> 指定项目目录(默认当前目录,自动向上查找 convex/)
68
+ --verbose 显示未变化的文件
69
+ --json 输出机器可读结果
70
+ -h, --help 显示帮助`);
71
+ return;
72
+ }
73
+ if (command === "dev") {
74
+ console.log(`用法:vultro dev [选项] [-- <vite 参数>]
75
+
76
+ 在项目根目录启动 Vite dev server。运行时由 vultro.config.ts 的 runtime 决定。
77
+
78
+ 选项:
79
+ --cf 强制使用 Cloudflare 运行时
80
+ --bun 强制使用 Bun 运行时
81
+ --node 强制使用 Node 运行时(默认)
82
+ --cloud 强制使用 Cloud(workerd)运行时
83
+ --dir <path> 指定项目目录(默认当前目录,自动向上查找 convex/)
84
+ <其它参数> 原样透传给 vite,例如 --port 8787、--host
85
+ -h, --help 显示帮助`);
86
+ return;
87
+ }
88
+ if (command === "build") {
89
+ console.log(`用法:vultro build [选项] [-- <vite 参数>]
90
+
91
+ 在项目根目录执行 vite build。runtime 为 bun / node 时同时产出
92
+ dist/client 与 dist/server;cloudflare 时产出 Worker 与静态资源。
93
+
94
+ 选项:
95
+ --cf 强制使用 Cloudflare 运行时
96
+ --bun 强制使用 Bun 运行时
97
+ --node 强制使用 Node 运行时(默认)
98
+ --cloud 强制使用 Cloud(workerd)运行时
99
+ --dir <path> 指定项目目录(默认当前目录,自动向上查找 convex/)
100
+ <其它参数> 原样透传给 vite build
101
+ -h, --help 显示帮助`);
102
+ return;
103
+ }
104
+ if (command === "check") {
105
+ console.log(`用法:vultro check [目录] [选项]
106
+
107
+ 校验项目结构、schema、生成文件、兼容性告警与 TypeScript 类型。
108
+
109
+ 选项:
110
+ --json 输出机器可读报告
111
+ --fix 安全修复:重新生成过期的 convex/_generated 文件
112
+ --no-typecheck 跳过 TypeScript 类型检查
113
+ --strict 把警告视为错误
114
+ --dir <path> 指定项目目录(默认当前目录,自动向上查找 convex/)
115
+ --static-api 按静态 API 模式比较生成文件
116
+ --static-data-model 按静态 DataModel 模式比较生成文件
117
+ -h, --help 显示帮助`);
118
+ return;
119
+ }
120
+ if (command === "mcp") {
121
+ console.log(`用法:vultro mcp [选项]
122
+
123
+ 把后端作为 MCP server 暴露在 stdio 上(供 Claude Code / Cursor 等 agent 接入)。
124
+ 目标是一个运行中的 dev server;后端地址按 --url → --port →
125
+ .vultro/agent/status.json(自动向上查找,需 ready:true)→ VULTRO_URL 顺序解析。
126
+
127
+ 工具(默认只读):
128
+ status / run_query / list_tables / table_data / function_spec /
129
+ schema / logs / scheduled_functions
130
+
131
+ 选项:
132
+ --writes 额外暴露 run_mutation / run_action 写工具
133
+ (也可用环境变量 VULTRO_MCP_ALLOW_WRITES=1)
134
+ --allow-internal 允许调用 internal 函数
135
+ --allow <patterns> 函数路径白名单(逗号分隔,支持 glob / 前缀,
136
+ 例如 "messages:*")
137
+ --port <n> dev server 端口
138
+ --url <url> 后端地址(含路由前缀,如 http://localhost:8788/v1)
139
+ --dir <path> 状态文件发现的起始目录
140
+ -h, --help 显示帮助
141
+
142
+ .mcp.json 示例:
143
+ { "mcpServers": { "vultro": { "command": "vultro", "args": ["mcp"] } } }`);
144
+ return;
145
+ }
146
+ console.log(`Vultro CLI ${readVersion()}
147
+
148
+ 用法:vultro <command> [目录] [选项]
149
+
150
+ 命令:
151
+ codegen 生成 convex/_generated 下的 API / DataModel / 函数构建器类型
152
+ check 校验项目结构、schema、生成文件、兼容性告警与 TypeScript 类型
153
+ dev 在项目根目录启动 Vite dev server
154
+ build 执行 vite build(按 runtime 生成客户端 / 服务端产物)
155
+
156
+ 常用示例:
157
+ vultro codegen
158
+ vultro codegen --static-api --static-data-model
159
+ vultro check
160
+ vultro check --json --strict
161
+ vultro check --fix
162
+ vultro dev --port 8787
163
+ vultro dev --bun
164
+ vultro build --cf
165
+
166
+ 运行 vultro codegen --help 或 vultro check --help 查看命令选项。`);
167
+ }
168
+ var exitCode = await main(process.argv.slice(2));
169
+ process.exit(exitCode);
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,91 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { CliOptions } from "./args.js";
3
+ /** MCP server 的运行期选项。 */
4
+ export interface McpOptions {
5
+ /** `--port <n>`:dev server 端口。 */
6
+ port?: number;
7
+ /** `--url <url>`:后端地址(含前缀),覆盖 `--port`。 */
8
+ url?: string;
9
+ /** 是否暴露写工具。 */
10
+ writes: boolean;
11
+ /** 是否允许调用 internal 函数。 */
12
+ allowInternal: boolean;
13
+ /** 函数路径白名单(glob / 前缀);空数组表示不限制。 */
14
+ allow: string[];
15
+ /** 状态文件发现的起始目录。 */
16
+ cwd: string;
17
+ }
18
+ /** 从 CliOptions 提取 MCP 选项。 */
19
+ export declare function mcpOptionsFromCli(options: CliOptions): McpOptions;
20
+ /** 运行期可变状态(函数清单缓存等)。 */
21
+ export interface McpState {
22
+ options: McpOptions;
23
+ specCache: Map<string, {
24
+ fetchedAt: number;
25
+ functions: McpFunction[];
26
+ }>;
27
+ }
28
+ export declare function createMcpState(options: McpOptions): McpState;
29
+ /** `status.json` 中与我们相关的字段(解析校验后的形状)。 */
30
+ interface AgentStatusRecord {
31
+ backendUrl?: string;
32
+ ready?: unknown;
33
+ stopped?: unknown;
34
+ pid?: unknown;
35
+ }
36
+ /**
37
+ * 解析后端地址;解析不到时返回 undefined 并给出已尝试的来源,
38
+ * 让 `status` 工具能把原因告诉 agent,而不是静默打错端口。
39
+ */
40
+ export declare function resolveBackendUrl(options: McpOptions): {
41
+ url: string;
42
+ source: string;
43
+ } | undefined;
44
+ /** 从起始目录向上查找「活跃」的状态文件(ready 且未 stopped 且 pid 存活)。 */
45
+ export declare function findActiveAgentStatus(cwd: string): AgentStatusRecord | undefined;
46
+ /** 一个后端函数(来自 `_system/frontend/modules:listForAllComponents`)。 */
47
+ export interface McpFunction {
48
+ /** 展示路径:根组件 `module:export`,组件函数 `component:module:export`。 */
49
+ path: string;
50
+ /** 实际调用用的函数路径(`module:export`)。 */
51
+ callPath: string;
52
+ /** 组件路径;根组件为 undefined。 */
53
+ componentPath?: string;
54
+ /** `query` / `mutation` / `action` / `httpAction`。 */
55
+ type: string;
56
+ visibility: "public" | "internal";
57
+ }
58
+ /**
59
+ * 拉取(带缓存)后端函数清单。
60
+ *
61
+ * `listForAllComponents` 返回 `[[component | null, [file, {functions}]], ...]`:
62
+ * 根组件的 key 是 null,子组件的 key 是组件路径。
63
+ */
64
+ export declare function loadFunctions(state: McpState, backendUrl: string): Promise<McpFunction[]>;
65
+ /** MCP 策略错误;映射为 `isError: true` 的工具结果。 */
66
+ export declare class McpPolicyError extends Error {
67
+ }
68
+ /** 校验目标函数满足 MCP 策略(存在 / 类型 / internal / 白名单)。 */
69
+ export declare function resolveFunction(state: McpState, backendUrl: string, name: string, kind: "query" | "mutation" | "action"): Promise<McpFunction>;
70
+ /** 白名单匹配:`*` 通配(`messages:*` 匹配 `messages:list`),其余为前缀匹配。 */
71
+ export declare function matchesAllowlist(path: string, patterns: string[]): boolean;
72
+ /** 执行一个后端函数(`/api/query` / `/api/mutation` / `/api/action`)。 */
73
+ export declare function executeFunction(backendUrl: string, kind: "query" | "mutation" | "action", path: string, args: Record<string, unknown> | undefined, componentPath?: string): Promise<unknown>;
74
+ /** 调用系统 UDF(`_system/frontend/*`)。 */
75
+ export declare function postQuery(backendUrl: string, path: string, args: Record<string, unknown>): Promise<unknown>;
76
+ /**
77
+ * 创建 MCP server 并注册全部工具。
78
+ *
79
+ * 协议细节(握手 / 版本协商 / tools/list / ping)由 SDK 处理;这里只提供
80
+ * 工具回调。策略错误(McpPolicyError)与后端错误都转成 `isError: true` 的
81
+ * 工具结果——MCP 约定工具级失败不抛协议错误,让 agent 能读到错误文本。
82
+ */
83
+ export declare function createMcpServer(state: McpState, version: string): McpServer;
84
+ /**
85
+ * `vultro mcp` 入口:把 MCP server 挂在 stdin/stdout 上常驻,直到对端关闭。
86
+ *
87
+ * 横幅信息走 **stderr**:stdio 是 MCP 协议通道,任何多余的 stdout 输出都会
88
+ * 破坏 agent harness 的 JSON 解析。
89
+ */
90
+ export declare function runMcp(options: McpOptions, version: string): Promise<number>;
91
+ export {};