@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.
package/dist/check.js ADDED
@@ -0,0 +1,295 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { documentFieldPaths, renderGeneratedFiles } from "./codegen-content.js";
4
+ import { writeGeneratedFiles } from "./codegen.js";
5
+ import { findModulePathConflicts, loadProject, readSource } from "./project.js";
6
+ import { runTypecheck } from "./typecheck.js";
7
+ // src/check.ts
8
+ /** 根据现有生成文件判断上次 codegen 使用的模式。 */
9
+ function detectCodegenMode(convexDir) {
10
+ const api = readIfExists(join(convexDir, "_generated", "api.d.ts"));
11
+ const dataModel = readIfExists(join(convexDir, "_generated", "dataModel.d.ts"));
12
+ return {
13
+ staticApi: api.includes("vultro-codegen: static-api"),
14
+ staticDataModel: dataModel.includes("vultro-codegen: static-data-model")
15
+ };
16
+ }
17
+ /** 执行 check,返回结构化报告。 */
18
+ async function collectCheckReport(options) {
19
+ const checks = [];
20
+ let project;
21
+ try {
22
+ project = await loadProject({
23
+ dir: options.dir,
24
+ bootstrapGeneratedServer: options.fix
25
+ });
26
+ } catch (error) {
27
+ checks.push({
28
+ id: "project",
29
+ status: "fail",
30
+ detail: error instanceof Error ? error.message : String(error)
31
+ });
32
+ return finishReport(options, process.cwd(), checks);
33
+ }
34
+ const projectPath = relative(process.cwd(), project.rootDir) || ".";
35
+ checks.push({
36
+ id: "project",
37
+ status: "ok",
38
+ detail: `找到 ${projectPath},${project.modules.length} 个函数模块`
39
+ });
40
+ if (project.moduleErrors.length > 0) checks.push({
41
+ id: "modules",
42
+ status: "fail",
43
+ detail: `${project.moduleErrors.length} 个模块加载失败`,
44
+ diagnostics: project.moduleErrors.map((error) => `${error.relativePath}: ${error.message}`)
45
+ });
46
+ else {
47
+ const functionCount = project.modules.reduce((total, module) => total + module.functions.length, 0);
48
+ const conflicts = findModulePathConflicts(project.modules);
49
+ checks.push({
50
+ id: "modules",
51
+ status: conflicts.length > 0 ? "fail" : project.modules.length === 0 ? "warn" : "ok",
52
+ detail: conflicts.length > 0 ? `${conflicts.length} 个模块路径冲突` : project.modules.length === 0 ? "没有发现任何函数模块" : `${project.modules.length} 个模块,${functionCount} 个函数`,
53
+ diagnostics: conflicts.length > 0 ? conflicts : void 0
54
+ });
55
+ }
56
+ checks.push(validateSchema(project));
57
+ checks.push(project.moduleErrors.length > 0 ? {
58
+ id: "codegen",
59
+ status: "skip",
60
+ detail: "模块加载失败,无法比较生成文件是否最新"
61
+ } : validateCodegen(project, options));
62
+ checks.push(collectAdvisories(project));
63
+ if (options.typecheck === "disable") checks.push({
64
+ id: "typecheck",
65
+ status: "skip",
66
+ detail: "已通过 --no-typecheck 跳过"
67
+ });
68
+ else {
69
+ const typecheck = runTypecheck(project.rootDir);
70
+ checks.push({
71
+ id: "typecheck",
72
+ status: typecheck.ok ? typecheck.skipped ? "skip" : "ok" : "fail",
73
+ detail: typecheck.detail,
74
+ diagnostics: typecheck.diagnostics.length > 0 ? typecheck.diagnostics : void 0
75
+ });
76
+ }
77
+ return finishReport(options, project.rootDir, checks);
78
+ }
79
+ /** 校验 schema 的表、索引与保留字段。 */
80
+ function validateSchema(project) {
81
+ if (!project.schemaPath) return {
82
+ id: "schema",
83
+ status: "fail",
84
+ detail: "缺少 convex/schema.ts"
85
+ };
86
+ if (project.schema.tables.size === 0) return {
87
+ id: "schema",
88
+ status: "fail",
89
+ detail: "schema 没有定义任何表"
90
+ };
91
+ const errors = [];
92
+ const warnings = [];
93
+ let indexCount = 0;
94
+ for (const [tableName, table] of project.schema.tables) {
95
+ if (tableName.startsWith("_")) errors.push(`表名 "${tableName}" 不能以 _ 开头(系统表保留前缀)`);
96
+ const fields = documentFieldPaths(table.validator);
97
+ for (const index of table.indexes.values()) {
98
+ indexCount++;
99
+ if (index.name.startsWith("_") && !index.virtual) warnings.push(`表 "${tableName}" 的索引 "${index.name}" 使用了保留前缀 _`);
100
+ for (const field of index.fields) if (!fields.has(field)) errors.push(`表 "${tableName}" 的索引 "${index.name}" 引用了不存在的字段 "${field}"`);
101
+ }
102
+ const exported = (project.rawSchema?.tables?.[tableName])?.export?.();
103
+ const searchIndexes = [...exported?.searchIndexes ?? [], ...exported?.stagedSearchIndexes ?? []];
104
+ for (const index of searchIndexes) {
105
+ indexCount++;
106
+ if (!fields.has(index.searchField)) errors.push(`表 "${tableName}" 的搜索索引 "${index.indexDescriptor}" 引用了不存在的字段 "${index.searchField}"`);
107
+ for (const field of index.filterFields ?? []) if (!fields.has(field)) errors.push(`表 "${tableName}" 的搜索索引 "${index.indexDescriptor}" 过滤字段 "${field}" 不存在`);
108
+ }
109
+ const vectorIndexes = [...exported?.vectorIndexes ?? [], ...exported?.stagedVectorIndexes ?? []];
110
+ for (const index of vectorIndexes) {
111
+ indexCount++;
112
+ if (!fields.has(index.vectorField)) errors.push(`表 "${tableName}" 的向量索引 "${index.indexDescriptor}" 引用了不存在的字段 "${index.vectorField}"`);
113
+ if (!Number.isInteger(index.dimensions) || Number(index.dimensions) <= 0) errors.push(`表 "${tableName}" 的向量索引 "${index.indexDescriptor}" 必须声明正整数 dimensions`);
114
+ for (const field of index.filterFields ?? []) if (!fields.has(field)) errors.push(`表 "${tableName}" 的向量索引 "${index.indexDescriptor}" 过滤字段 "${field}" 不存在`);
115
+ }
116
+ }
117
+ if (errors.length > 0) return {
118
+ id: "schema",
119
+ status: "fail",
120
+ detail: `${project.schema.tables.size} 张表,但存在 ${errors.length} 个问题`,
121
+ diagnostics: [...errors, ...warnings]
122
+ };
123
+ return {
124
+ id: "schema",
125
+ status: warnings.length > 0 ? "warn" : "ok",
126
+ detail: `${project.schema.tables.size} 张表,${indexCount} 个索引`,
127
+ diagnostics: warnings.length > 0 ? warnings : void 0
128
+ };
129
+ }
130
+ /** 比较磁盘上的生成文件与当前 schema / 模块是否一致。 */
131
+ function validateCodegen(project, options) {
132
+ if (!project.schemaPath) return {
133
+ id: "codegen",
134
+ status: "skip",
135
+ detail: "缺少 schema,无法生成 dataModel.d.ts"
136
+ };
137
+ const detected = detectCodegenMode(project.convexDir);
138
+ const staticApi = options.staticApi || detected.staticApi;
139
+ const staticDataModel = options.staticDataModel || detected.staticDataModel;
140
+ let expected;
141
+ try {
142
+ expected = renderGeneratedFiles(project, {
143
+ staticApi,
144
+ staticDataModel
145
+ });
146
+ } catch (error) {
147
+ return {
148
+ id: "codegen",
149
+ status: "fail",
150
+ detail: error instanceof Error ? error.message : String(error)
151
+ };
152
+ }
153
+ const generatedDir = join(project.convexDir, "_generated");
154
+ const stale = [];
155
+ for (const file of expected) {
156
+ const target = join(generatedDir, file.fileName);
157
+ if (!existsSync(target)) {
158
+ stale.push(`${file.fileName}: 缺失`);
159
+ continue;
160
+ }
161
+ if (readFileSync(target, "utf8") !== file.content) stale.push(`${file.fileName}: 内容与当前 schema / 模块不一致`);
162
+ }
163
+ if (stale.length === 0) return {
164
+ id: "codegen",
165
+ status: "ok",
166
+ detail: `${expected.length} 个生成文件均为最新`
167
+ };
168
+ if (options.fix) {
169
+ writeGeneratedFiles(project.convexDir, expected);
170
+ return {
171
+ id: "codegen",
172
+ status: "ok",
173
+ detail: `已重新生成 ${stale.length} 个文件`,
174
+ fixable: true
175
+ };
176
+ }
177
+ return {
178
+ id: "codegen",
179
+ status: "fail",
180
+ detail: `${stale.length} 个生成文件已过期`,
181
+ diagnostics: [...stale, "运行 vultro codegen 或 vultro check --fix"],
182
+ fixable: true
183
+ };
184
+ }
185
+ /** 收集兼容性 / 安全方面的告警。 */
186
+ function collectAdvisories(project) {
187
+ const errors = [];
188
+ const warnings = [];
189
+ for (const filePath of project.sourceFiles) {
190
+ const source = readSource(filePath);
191
+ const displayPath = relative(project.rootDir, filePath).split("\\").join("/");
192
+ if (/(?:from\s*|import\s*\(\s*|require\s*\(\s*)["']@concavejs\//.test(source)) errors.push(`${displayPath} 导入了 @concavejs/*(本项目禁止该依赖)`);
193
+ if (/\bhttpAction\s*\(/.test(source)) warnings.push(`${displayPath} 使用了 httpAction;Vultro 已支持 convex/http.ts 路由(单 Worker 下通过 /_http<path> 访问)`);
194
+ if (/\bctx\.scheduler\b/.test(source)) warnings.push(`${displayPath} 使用了 ctx.scheduler;Vultro 已实现 runAfter / runAt / cancel,crons.ts 的周期任务由 DO alarm 执行`);
195
+ if (/\bctx\.storage\b/.test(source)) warnings.push(`${displayPath} 使用了 ctx.storage;Vultro 已实现文件存储,单文件上限 25MB,内容保存在 Durable Object SQLite`);
196
+ }
197
+ const packageJsonPath = join(project.rootDir, "package.json");
198
+ if (existsSync(packageJsonPath)) try {
199
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
200
+ const dependencies = {
201
+ ...packageJson.dependencies,
202
+ ...packageJson.devDependencies
203
+ };
204
+ if (!dependencies.convex) warnings.push("package.json 没有声明 convex 依赖;用户函数通常需要 convex/values");
205
+ const forbiddenDependencies = Object.keys(dependencies).filter((name) => name.startsWith("@concavejs/"));
206
+ if (forbiddenDependencies.length > 0) errors.push(`package.json 声明了禁止的依赖:${forbiddenDependencies.join(", ")}`);
207
+ } catch {
208
+ warnings.push("package.json 不是合法的 JSON");
209
+ }
210
+ if (errors.length > 0) return {
211
+ id: "advisories",
212
+ status: "fail",
213
+ detail: `${errors.length} 个错误,${warnings.length} 个警告`,
214
+ diagnostics: [...errors, ...warnings]
215
+ };
216
+ if (warnings.length > 0) return {
217
+ id: "advisories",
218
+ status: "warn",
219
+ detail: `${warnings.length} 个兼容性警告`,
220
+ diagnostics: warnings
221
+ };
222
+ return {
223
+ id: "advisories",
224
+ status: "ok",
225
+ detail: "未发现兼容性警告"
226
+ };
227
+ }
228
+ /** 汇总报告;`--strict` 会把警告也视为失败。 */
229
+ function finishReport(options, rootDir, checks) {
230
+ const errors = checks.filter((check) => check.status === "fail").length;
231
+ const warnings = checks.filter((check) => check.status === "warn").length;
232
+ return {
233
+ contractVersion: 1,
234
+ ok: errors === 0 && (!options.strict || warnings === 0),
235
+ rootDir,
236
+ checks,
237
+ summary: {
238
+ checks: checks.length,
239
+ errors,
240
+ warnings
241
+ }
242
+ };
243
+ }
244
+ /** CLI 入口:打印人类可读报告或 `--json`,返回退出码。 */
245
+ async function runCheck(options) {
246
+ let report;
247
+ try {
248
+ report = await collectCheckReport(options);
249
+ } catch (error) {
250
+ if (options.json) console.log(JSON.stringify({
251
+ contractVersion: 1,
252
+ ok: false,
253
+ error: error instanceof Error ? error.message : String(error)
254
+ }, null, 2));
255
+ else console.error(`✗ check 失败:${error instanceof Error ? error.message : String(error)}`);
256
+ return 1;
257
+ }
258
+ if (options.json) console.log(JSON.stringify(report, null, 2));
259
+ else printReport(report, options);
260
+ return report.ok ? 0 : 1;
261
+ }
262
+ /** 人类可读输出。 */
263
+ function printReport(report, options) {
264
+ const projectPath = relative(process.cwd(), report.rootDir) || ".";
265
+ console.log(`vultro check ${projectPath}`);
266
+ console.log("");
267
+ const symbols = {
268
+ ok: "✓",
269
+ warn: "!",
270
+ fail: "✗",
271
+ skip: "-"
272
+ };
273
+ for (const check of report.checks) {
274
+ console.log(`${symbols[check.status]} ${check.id.padEnd(11)} ${check.detail}`);
275
+ for (const line of check.diagnostics ?? []) console.log(` ${line}`);
276
+ }
277
+ console.log("");
278
+ if (report.ok) {
279
+ console.log(report.summary.warnings > 0 ? `✓ 检查通过(${report.summary.warnings} 个警告)` : "✓ 检查通过");
280
+ return;
281
+ }
282
+ const fixable = report.checks.some((check) => check.fixable);
283
+ console.log(`✗ 检查失败:${report.summary.errors} 个错误,${report.summary.warnings} 个警告`);
284
+ if (options.strict && report.summary.errors === 0) console.log(" --strict 模式把警告视为错误");
285
+ if (fixable) console.log(" 运行 vultro check --fix 可修复生成文件");
286
+ }
287
+ /** 读取文件;不存在时返回空字符串。 */
288
+ function readIfExists(path) {
289
+ try {
290
+ return readFileSync(path, "utf8");
291
+ } catch {
292
+ return "";
293
+ }
294
+ }
295
+ export { collectCheckReport, detectCodegenMode, printReport, runCheck };
@@ -0,0 +1,77 @@
1
+ import type { SchemaInfo } from "@vultro/core";
2
+ import type { ConvexModule, ConvexProject, ProjectComponent } from "./project.js";
3
+ export interface GeneratedFile {
4
+ /** 相对 `convex/_generated/` 的文件名。 */
5
+ fileName: string;
6
+ content: string;
7
+ }
8
+ /** 生成 server.js:把函数构建器指向 @vultro/core 的运行时实现。 */
9
+ export declare function renderServerJs(): string;
10
+ /** 生成 server.d.ts:直接复用官方 Convex 的 builder / ctx 类型。 */
11
+ export declare function renderServerDts(): string;
12
+ /**
13
+ * bootstrap 用的最小 api.js:只提供 anyApi / componentsGeneric 代理。
14
+ *
15
+ * 仅在「本地组件模块 import 了 ./_generated/api,但干净检出还没有生成
16
+ * 文件」时写入,让模块 import 能成功;真正的 api.js(静态引用树 + 类型)
17
+ * 由 codegen 生成阶段覆盖。
18
+ */
19
+ export declare function renderApiBootstrapJs(): string;
20
+ /** 生成 api.js:app 模块用 anyApi,组件用静态引用树。 */
21
+ export declare function renderApiJs(components?: ProjectComponent[]): string;
22
+ /**
23
+ * 把 `convex.config.ts` 中 mount 的组件生成成 manifest。
24
+ *
25
+ * 参考 `@concavejs/cli`:组件清单是构建期产物,放在隐藏目录
26
+ * `node_modules/.vultro/` 里,不进 `convex/_generated/`。Vite 插件 / 自定义
27
+ * 入口读取这份 manifest,在编译期生成静态 import 并把注册对象传给
28
+ * `createRuntime({ components })`。
29
+ *
30
+ * 路径都相对 `_generated/`,因此 Bun 安装目录的稳定化逻辑继续有效。
31
+ */
32
+ /**
33
+ * 组件 manifest 的存放位置: convex 项目根目录的隐藏目录
34
+ * `node_modules/.vultro/`(与 wrangler 配置等构建期产物放在一起),
35
+ * 不进 `convex/_generated/`,保持与 Convex 官方一致的生成文件清单。
36
+ */
37
+ export declare function componentsManifestPath(convexDir: string): string;
38
+ export declare function renderComponentsManifest(project: Pick<ConvexProject, "components" | "convexDir">): string;
39
+ export declare function renderApiDts(modules: ConvexModule[], staticApi: boolean, components?: ProjectComponent[]): string;
40
+ /**
41
+ * 生成 dataModel.d.ts。
42
+ *
43
+ * - inference 模式从 schema 推导,类型最准确;
44
+ * - static 模式把表、字段、索引直接写进声明文件,避免深层条件类型。
45
+ */
46
+ export declare function renderDataModelDts(schema: SchemaInfo, staticDataModel: boolean, schemaExportName?: "default" | "schema"): string;
47
+ /** 原始 validator 的运行时形状(只声明 codegen 用到的字段)。 */
48
+ interface RawValidator {
49
+ kind?: string;
50
+ isOptional?: "optional" | "required";
51
+ fields?: Record<string, RawValidator>;
52
+ element?: RawValidator;
53
+ members?: RawValidator[];
54
+ key?: RawValidator;
55
+ value?: unknown;
56
+ tableName?: string;
57
+ }
58
+ /**
59
+ * 把 Convex validator 转成 TypeScript 类型表达式。
60
+ *
61
+ * 该函数只用于 `--static-data-model`;默认模式仍然让 TypeScript 从
62
+ * schema 推导,避免我们自己维护一套不完整的类型映射。
63
+ */
64
+ export declare function validatorToTs(validator: RawValidator): string;
65
+ /**
66
+ * 返回文档可用的字段路径(含 `_id` / `_creationTime`)。
67
+ *
68
+ * check 用它验证索引字段是否真实存在,避免用户写出
69
+ * `.index("by_name", ["nmae"])` 这种拼写错误。
70
+ */
71
+ export declare function documentFieldPaths(validator: unknown): Set<string>;
72
+ /** 生成全部生成文件。 */
73
+ export declare function renderGeneratedFiles(project: Pick<ConvexProject, "schema" | "modules" | "schemaExportName" | "components" | "convexDir">, options: {
74
+ staticApi: boolean;
75
+ staticDataModel: boolean;
76
+ }): GeneratedFile[];
77
+ export {};