@vultro/cli 0.0.0-stage → 0.0.1

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,594 @@
1
+ import { join, relative, resolve, sep } from "node:path";
2
+ // src/codegen-content.ts
3
+ /**
4
+ * 生成 `convex/_generated/` 下的文件内容。
5
+ *
6
+ * 所有渲染函数都是纯函数:不读写文件,方便在测试里直接断言字符串,
7
+ * 也方便 check 在内存中比较“磁盘上的生成文件是否过期”。
8
+ */
9
+ /** 生成文件统一使用的免责声明。 */
10
+ var GENERATED_HEADER = `/* eslint-disable */
11
+ /**
12
+ * 此文件由 \`vultro codegen\` 生成,请勿手动修改。
13
+ * 重新生成:vultro codegen
14
+ */
15
+ `;
16
+ /** 生成 server.js:把函数构建器指向 @vultro/core 的运行时实现。 */
17
+ function renderServerJs() {
18
+ return `${GENERATED_HEADER}
19
+ import {
20
+ action,
21
+ httpAction,
22
+ internalAction,
23
+ internalMutation,
24
+ internalQuery,
25
+ mutation,
26
+ query,
27
+ } from "@vultro/core";
28
+
29
+ export {
30
+ action,
31
+ httpAction,
32
+ internalAction,
33
+ internalMutation,
34
+ internalQuery,
35
+ mutation,
36
+ query,
37
+ };
38
+
39
+ /**
40
+ * 表定义与 schema 完全复用官方 convex/server 的类型和实现。
41
+ * 本项目不依赖任何 @concavejs/* 包。
42
+ */
43
+ export { defineSchema, defineTable } from "convex/server";
44
+
45
+ /**
46
+ * 用户函数可读取的环境变量。
47
+ *
48
+ * Cloudflare Worker 的 env 绑定由平台注入;这里保留 process.env 兼容层,
49
+ * 让本地 Bun 测试和 Worker 运行时都能读到同名变量。
50
+ */
51
+ export const env =
52
+ typeof process !== "undefined" && process.env ? process.env : {};
53
+ `;
54
+ }
55
+ /** 生成 server.d.ts:直接复用官方 Convex 的 builder / ctx 类型。 */
56
+ function renderServerDts() {
57
+ return `${GENERATED_HEADER}
58
+ import type {
59
+ ActionBuilder,
60
+ GenericActionCtx,
61
+ GenericDatabaseReader,
62
+ GenericDatabaseWriter,
63
+ GenericMutationCtx,
64
+ GenericQueryCtx,
65
+ HttpActionBuilder,
66
+ MutationBuilder,
67
+ QueryBuilder,
68
+ } from "convex/server";
69
+ import type { DataModel } from "./dataModel.js";
70
+
71
+ /** 公开 query。 */
72
+ export declare const query: QueryBuilder<DataModel, "public">;
73
+
74
+ /** 内部 query,只能通过 ctx.runQuery(internal.xxx, ...) 调用。 */
75
+ export declare const internalQuery: QueryBuilder<DataModel, "internal">;
76
+
77
+ /** 公开 mutation。 */
78
+ export declare const mutation: MutationBuilder<DataModel, "public">;
79
+
80
+ /** 内部 mutation。 */
81
+ export declare const internalMutation: MutationBuilder<DataModel, "internal">;
82
+
83
+ /** 公开 action。 */
84
+ export declare const action: ActionBuilder<DataModel, "public">;
85
+
86
+ /** 内部 action。 */
87
+ export declare const internalAction: ActionBuilder<DataModel, "internal">;
88
+
89
+ /** HTTP action 构建器。 */
90
+ export declare const httpAction: HttpActionBuilder;
91
+
92
+ /** 表 / schema 定义。 */
93
+ export { defineSchema, defineTable } from "convex/server";
94
+
95
+ /** 运行时环境变量。 */
96
+ export declare const env: Record<string, string | undefined>;
97
+
98
+ /** 常用 ctx 类型别名。 */
99
+ export type QueryCtx = GenericQueryCtx<DataModel>;
100
+ export type MutationCtx = GenericMutationCtx<DataModel>;
101
+ export type ActionCtx = GenericActionCtx<DataModel>;
102
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
103
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
104
+ `;
105
+ }
106
+ /** 组件引用路径。 */
107
+ function componentReferencePath(component) {
108
+ return `_reference/childComponent/${component.path}`;
109
+ }
110
+ /** 把一个函数模块的导出插入引用树。 */
111
+ function insertModuleFunctions(node, module) {
112
+ let current = node;
113
+ let path = node.path;
114
+ for (const segment of module.name.split("/")) {
115
+ path = `${path}/${segment}`;
116
+ let next = current.children.get(segment);
117
+ if (!next) {
118
+ next = {
119
+ path,
120
+ children: /* @__PURE__ */ new Map()
121
+ };
122
+ current.children.set(segment, next);
123
+ }
124
+ current = next;
125
+ }
126
+ for (const fn of module.functions) {
127
+ if (fn.kind === "httpAction") continue;
128
+ const referencePath = `${path}/${fn.name}`;
129
+ let leafNode = current.children.get(fn.name);
130
+ if (!leafNode) {
131
+ leafNode = {
132
+ path: referencePath,
133
+ children: /* @__PURE__ */ new Map()
134
+ };
135
+ current.children.set(fn.name, leafNode);
136
+ }
137
+ leafNode.leaf = {
138
+ kind: fn.kind,
139
+ referencePath
140
+ };
141
+ }
142
+ }
143
+ /** 把组件(含递归子组件)的全部函数模块插入引用树。 */
144
+ function insertComponentFunctions(component, parentNode) {
145
+ let node = parentNode.children.get(component.name);
146
+ if (!node) {
147
+ node = {
148
+ path: `${parentNode.path}.${component.name}`,
149
+ children: /* @__PURE__ */ new Map()
150
+ };
151
+ parentNode.children.set(component.name, node);
152
+ }
153
+ for (const module of component.modules) insertModuleFunctions(node, module);
154
+ for (const child of component.children) insertComponentFunctions(child, node);
155
+ }
156
+ /** 剪掉没有任何函数导出的空节点(模块可能只是 helper / 常量)。 */
157
+ function pruneRefNode(node) {
158
+ for (const [name, child] of [...node.children.entries()]) if (pruneRefNode(child)) node.children.delete(name);
159
+ return node.children.size === 0 && !node.leaf;
160
+ }
161
+ /** 构建一个顶层组件的完整引用树。 */
162
+ function buildComponentRefTree(component) {
163
+ const root = {
164
+ path: componentReferencePath(component),
165
+ children: /* @__PURE__ */ new Map()
166
+ };
167
+ for (const module of component.modules) insertModuleFunctions(root, module);
168
+ for (const child of component.children) insertComponentFunctions(child, root);
169
+ pruneRefNode(root);
170
+ return root;
171
+ }
172
+ /** 渲染引用树的 JS 对象(makeComponentReference 节点)。 */
173
+ function renderRefNodeJs(node, pad) {
174
+ const childPad = `${pad} `;
175
+ const entries = [...node.children.entries()].map(([name, child]) => `${childPad}${JSON.stringify(name)}: ${renderRefNodeJs(child, childPad)}`);
176
+ if (!node.leaf) return `makeComponentReference(${JSON.stringify(node.path)}, {\n${entries.join(",\n")}\n${pad}})`;
177
+ if (entries.length === 0) return `makeComponentReference(${JSON.stringify(node.path)})`;
178
+ return `makeComponentReference(${JSON.stringify(node.path)}, {\n${entries.join(",\n")}\n${pad}})`;
179
+ }
180
+ /**
181
+ * bootstrap 用的最小 api.js:只提供 anyApi / componentsGeneric 代理。
182
+ *
183
+ * 仅在「本地组件模块 import 了 ./_generated/api,但干净检出还没有生成
184
+ * 文件」时写入,让模块 import 能成功;真正的 api.js(静态引用树 + 类型)
185
+ * 由 codegen 生成阶段覆盖。
186
+ */
187
+ function renderApiBootstrapJs() {
188
+ return `${GENERATED_HEADER}
189
+ import { anyApi, componentsGeneric } from "convex/server";
190
+
191
+ export const api = anyApi;
192
+ export const internal = anyApi;
193
+ export const components = componentsGeneric();
194
+ `;
195
+ }
196
+ /** 生成 api.js:app 模块用 anyApi,组件用静态引用树。 */
197
+ function renderApiJs(components = []) {
198
+ return `${GENERATED_HEADER}
199
+ import { anyApi } from "convex/server";
200
+
201
+ const toReferencePath = Symbol.for("toReferencePath");
202
+
203
+ function makeComponentReference(referencePath, children) {
204
+ const node = {
205
+ ...children,
206
+ [toReferencePath]: referencePath,
207
+ [Symbol.toStringTag]: "FunctionReference",
208
+ };
209
+ // 静态树 + 动态兜底:codegen 之后的未知属性(例如刚新增的模块)也会
210
+ // 构造出正确的引用,与官方 componentsGeneric() 的行为一致。
211
+ return new Proxy(node, {
212
+ get(target, prop) {
213
+ // 只认自己的属性;继承属性(constructor 等)走动态兜底。
214
+ if (Object.hasOwn(target, prop)) return target[prop];
215
+ if (typeof prop === "string") {
216
+ return makeComponentReference(referencePath + "/" + prop);
217
+ }
218
+ return undefined;
219
+ },
220
+ });
221
+ }
222
+
223
+ /** 公开函数引用(anyApi 与 Convex 官方客户端的 getFunctionName() 兼容)。 */
224
+ export const api = anyApi;
225
+ export const internal = anyApi;
226
+
227
+ /** 组件函数引用树,形状与 Convex / @concavejs/cli codegen 一致。 */
228
+ export const components = {
229
+ ${components.map((component) => {
230
+ const tree = buildComponentRefTree(component);
231
+ return ` ${JSON.stringify(component.name)}: ${renderRefNodeJs(tree, " ")},`;
232
+ }).join("\n")}
233
+ };
234
+ `;
235
+ }
236
+ /** 渲染引用树的 TypeScript 类型。 */
237
+ function renderRefNodeDts(node, pad) {
238
+ const childPad = `${pad} `;
239
+ const entries = [...node.children.entries()].map(([name, child]) => `${childPad}${JSON.stringify(name)}: ${renderRefNodeDts(child, childPad)};`);
240
+ const objectType = entries.length === 0 ? "{}" : `{\n${entries.join("\n")}\n${pad}}`;
241
+ if (!node.leaf) return objectType;
242
+ const refType = `FunctionReference<${JSON.stringify(node.leaf.kind)}, "internal", any, any>`;
243
+ return entries.length === 0 ? refType : `${refType} & ${objectType}`;
244
+ }
245
+ /** 为模块生成合法且唯一的 TypeScript 标识符。 */
246
+ function moduleImports(modules) {
247
+ const used = /* @__PURE__ */ new Set();
248
+ return modules.map((module) => {
249
+ let base = module.name.replace(/[^A-Za-z0-9_$]/g, "_");
250
+ if (!/^[A-Za-z_$]/.test(base)) base = `_${base}`;
251
+ let variable = base;
252
+ let suffix = 2;
253
+ while (used.has(variable)) variable = `${base}_${suffix++}`;
254
+ used.add(variable);
255
+ return {
256
+ module,
257
+ variable
258
+ };
259
+ });
260
+ }
261
+ /**
262
+ * 把 `convex.config.ts` 中 mount 的组件生成成 manifest。
263
+ *
264
+ * 参考 `@concavejs/cli`:组件清单是构建期产物,放在隐藏目录
265
+ * `node_modules/.vultro/` 里,不进 `convex/_generated/`。Vite 插件 / 自定义
266
+ * 入口读取这份 manifest,在编译期生成静态 import 并把注册对象传给
267
+ * `createRuntime({ components })`。
268
+ *
269
+ * 路径都相对 `_generated/`,因此 Bun 安装目录的稳定化逻辑继续有效。
270
+ */
271
+ /**
272
+ * 组件 manifest 的存放位置: convex 项目根目录的隐藏目录
273
+ * `node_modules/.vultro/`(与 wrangler 配置等构建期产物放在一起),
274
+ * 不进 `convex/_generated/`,保持与 Convex 官方一致的生成文件清单。
275
+ */
276
+ function componentsManifestPath(convexDir) {
277
+ return resolve(convexDir, "..", "node_modules", ".vultro", "components.manifest.json");
278
+ }
279
+ function renderComponentsManifest(project) {
280
+ const generatedDir = join(project.convexDir, "_generated");
281
+ const relativePath = (filePath) => relative(generatedDir, filePath).split(sep).join("/");
282
+ const entries = [];
283
+ const visit = (component, parentPath) => {
284
+ const componentPath = parentPath ? `${parentPath}/${component.name}` : component.name;
285
+ entries.push({
286
+ componentPath,
287
+ parentPath,
288
+ name: component.name,
289
+ schemaPath: component.schemaPath ? relativePath(component.schemaPath) : void 0,
290
+ schemaExportName: component.schemaExportName ?? "default",
291
+ modules: component.modules.map((module) => ({
292
+ name: module.name,
293
+ filePath: relativePath(module.filePath)
294
+ }))
295
+ });
296
+ for (const child of component.children) visit(child, componentPath);
297
+ };
298
+ for (const component of project.components) visit(component, "");
299
+ entries.sort((left, right) => {
300
+ const depth = (path) => path.split("/").length;
301
+ return depth(left.componentPath) - depth(right.componentPath) || left.componentPath.localeCompare(right.componentPath);
302
+ });
303
+ return `${JSON.stringify({ entries }, null, 2)}\n`;
304
+ }
305
+ /**
306
+ * 生成 api.d.ts。
307
+ *
308
+ * 默认(inference)模式使用官方 `ApiFromModules`,让 TypeScript 从函数模块
309
+ * 推导参数和返回值;`--static-api` 模式生成显式的模块树,避免在大型项目里
310
+ * 让 `ApiFromModules` 对全部模块做一次深层映射。
311
+ */
312
+ /** 完整的 components 类型表达式(与 api.js 的静态引用树一致)。 */
313
+ function renderComponentsDts(components) {
314
+ if (components.length === 0) return "{}";
315
+ return `{\n${components.map((component) => ` ${JSON.stringify(component.name)}: ${renderRefNodeDts(buildComponentRefTree(component), " ")};`).join("\n")}\n}`;
316
+ }
317
+ function renderApiDts(modules, staticApi, components = []) {
318
+ const imports = moduleImports(modules);
319
+ const importLines = imports.map(({ module, variable }) => `import type * as ${variable} from "../${module.name}.js";`).join("\n");
320
+ if (!staticApi) {
321
+ const entries = imports.map(({ module, variable }) => ` ${JSON.stringify(module.name)}: ${moduleTypeExpression(module, variable)};`).join("\n");
322
+ return `${GENERATED_HEADER}
323
+ /* vultro-codegen: inference-api */
324
+
325
+ import type { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
326
+ ${importLines ? `${importLines}\n` : ""}
327
+ declare const fullApi: ApiFromModules<{
328
+ ${entries}
329
+ }>;
330
+
331
+ /** 公开函数引用。 */
332
+ export declare const api: FilterApi<typeof fullApi, FunctionReference<any, "public">>;
333
+
334
+ /** 内部函数引用。 */
335
+ export declare const internal: FilterApi<
336
+ typeof fullApi,
337
+ FunctionReference<any, "internal">
338
+ >;
339
+
340
+ export declare const components: ${renderComponentsDts(components)};
341
+ `;
342
+ }
343
+ const treeSource = renderApiTree(buildApiTree(imports), 0).join("\n");
344
+ return `${GENERATED_HEADER}
345
+ /* vultro-codegen: static-api */
346
+
347
+ import type { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
348
+ ${importLines ? `${importLines}\n` : ""}
349
+ /**
350
+ * 把单个模块转换成 FunctionReference 树。
351
+ *
352
+ * 与全局 ApiFromModules 相比,这里每个模块只做一次转换,生成的类型树是
353
+ * 静态的;模块数量很大时编辑器反馈更稳定。
354
+ */
355
+ type ModuleApi<Module extends Record<string, object>> =
356
+ ApiFromModules<{ module: Module }>["module"];
357
+
358
+ declare const fullApi: ${treeSource};
359
+
360
+ /** 公开函数引用。 */
361
+ export declare const api: FilterApi<typeof fullApi, FunctionReference<any, "public">>;
362
+
363
+ /** 内部函数引用。 */
364
+ export declare const internal: FilterApi<
365
+ typeof fullApi,
366
+ FunctionReference<any, "internal">
367
+ >;
368
+
369
+ export declare const components: ${renderComponentsDts(components)};
370
+ `;
371
+ }
372
+ /**
373
+ * 只保留函数导出,构造模块的类型表达式。
374
+ *
375
+ * 用户模块可能同时导出普通常量 / helper;直接使用 `typeof module` 会让
376
+ * `ApiFromModules` 的 `Record<string, object>` 约束失败,也会把非函数导出
377
+ * 带进 API 树。`Pick` 让生成结果只包含真正的函数。
378
+ */
379
+ function moduleTypeExpression(module, variable) {
380
+ return `Pick<typeof ${variable}, ${module.functions.map((fn) => fn.name).sort().map((name) => JSON.stringify(name)).join(" | ")}>`;
381
+ }
382
+ /** 把 `admin/users` 这样的模块路径转换成嵌套树。 */
383
+ function buildApiTree(imports) {
384
+ const root = /* @__PURE__ */ new Map();
385
+ for (const { module, variable } of imports) {
386
+ const segments = module.name.split("/");
387
+ let node = root;
388
+ for (let index = 0; index < segments.length; index++) {
389
+ const segment = segments[index];
390
+ if (index === segments.length - 1) {
391
+ if (node.get(segment) instanceof Map) throw new Error(`模块路径冲突:${module.name} 既是文件又是目录。请重命名其中一个模块。`);
392
+ node.set(segment, `ModuleApi<${moduleTypeExpression(module, variable)}>`);
393
+ break;
394
+ }
395
+ const existing = node.get(segment);
396
+ if (typeof existing === "string") throw new Error(`模块路径冲突:${module.name} 与另一个模块的文件/目录名重复。`);
397
+ if (existing === void 0) {
398
+ const child = /* @__PURE__ */ new Map();
399
+ node.set(segment, child);
400
+ node = child;
401
+ } else node = existing;
402
+ }
403
+ }
404
+ return root;
405
+ }
406
+ /** 递归渲染 api 树。 */
407
+ function renderApiTree(tree, depth) {
408
+ const indent = " ".repeat(depth);
409
+ const lines = ["{"];
410
+ for (const [key, value] of tree) if (value instanceof Map) {
411
+ const child = renderApiTree(value, depth + 1);
412
+ lines.push(`${indent} ${propertyKey(key)}: ${child[0]}`);
413
+ lines.push(...child.slice(1, -1));
414
+ lines.push(`${child[child.length - 1]};`);
415
+ } else lines.push(`${indent} ${propertyKey(key)}: ${value};`);
416
+ lines.push(`${indent}}`);
417
+ return lines;
418
+ }
419
+ /**
420
+ * 生成 dataModel.d.ts。
421
+ *
422
+ * - inference 模式从 schema 推导,类型最准确;
423
+ * - static 模式把表、字段、索引直接写进声明文件,避免深层条件类型。
424
+ */
425
+ function renderDataModelDts(schema, staticDataModel, schemaExportName = "default") {
426
+ if (!staticDataModel) return `${GENERATED_HEADER}
427
+ /* vultro-codegen: inference-data-model */
428
+
429
+ import type {
430
+ DataModelFromSchemaDefinition,
431
+ DocumentByName,
432
+ TableNamesInDataModel,
433
+ SystemTableNames,
434
+ } from "convex/server";
435
+ import type { GenericId } from "convex/values";
436
+ ${schemaExportName === "schema" ? "import type { schema } from \"../schema.js\";" : "import type schema from \"../schema.js\";"}
437
+
438
+ /** 由 schema 推导出的 DataModel。 */
439
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
440
+
441
+ /** 所有业务表名。 */
442
+ export type TableNames = TableNamesInDataModel<DataModel>;
443
+
444
+ /** 某个表的文档类型(含 _id / _creationTime)。 */
445
+ export type Doc<TableName extends TableNames> = DocumentByName<DataModel, TableName>;
446
+
447
+ /** 某个表(或系统表)的 ID 类型。 */
448
+ export type Id<TableName extends TableNames | SystemTableNames> = GenericId<TableName>;
449
+ `;
450
+ return `${GENERATED_HEADER}
451
+ /* vultro-codegen: static-data-model */
452
+
453
+ import type { SystemTableNames } from "convex/server";
454
+ import type { GenericId } from "convex/values";
455
+
456
+ /**
457
+ * 从 schema 静态生成的 DataModel。
458
+ *
459
+ * 结构与官方 DataModelFromSchemaDefinition 保持一致:
460
+ * document / fieldPaths / indexes / searchIndexes / vectorIndexes。
461
+ */
462
+ export type DataModel = {
463
+ ${schema.order.map((name) => schema.tables.get(name)).filter((table) => table !== void 0).map(renderStaticTable).join("\n")}
464
+ };
465
+
466
+ /** 所有业务表名。 */
467
+ export type TableNames = keyof DataModel & string;
468
+
469
+ /** 某个表的文档类型(含 _id / _creationTime)。 */
470
+ export type Doc<TableName extends TableNames> = DataModel[TableName]["document"];
471
+
472
+ /** 某个表(或系统表)的 ID 类型。 */
473
+ export type Id<TableName extends TableNames | SystemTableNames> = GenericId<TableName>;
474
+ `;
475
+ }
476
+ /** 渲染单张表的 DataModel 片段。 */
477
+ function renderStaticTable(table) {
478
+ const validator = table.validator;
479
+ const fields = validator?.kind === "object" ? validator.fields ?? {} : void 0;
480
+ const documentFields = [` _id: GenericId<${JSON.stringify(table.name)}>;`, " _creationTime: number;"];
481
+ if (fields) for (const [name, field] of Object.entries(fields)) {
482
+ const optional = field.isOptional === "optional" ? "?" : "";
483
+ documentFields.push(` ${propertyKey(name)}${optional}: ${validatorToTs(field)};`);
484
+ }
485
+ const fieldPaths = /* @__PURE__ */ new Set(["_id", "_creationTime"]);
486
+ if (validator) collectFieldPaths(validator, "", fieldPaths);
487
+ const orderedFieldPaths = [
488
+ "_id",
489
+ "_creationTime",
490
+ ...[...fieldPaths].filter((path) => path !== "_id" && path !== "_creationTime").sort()
491
+ ];
492
+ const indexLines = [...table.indexes.values()].sort((left, right) => left.name.localeCompare(right.name)).map((index) => ` ${propertyKey(index.name)}: [${index.fields.map((field) => JSON.stringify(field)).join(", ")}];`);
493
+ return ` ${propertyKey(table.name)}: {
494
+ document: {
495
+ ${documentFields.join("\n")}
496
+ };
497
+ fieldPaths: ${orderedFieldPaths.map((path) => JSON.stringify(path)).join(" | ")};
498
+ indexes: {
499
+ ${indexLines.join("\n")}
500
+ };
501
+ searchIndexes: {};
502
+ vectorIndexes: {};
503
+ };`;
504
+ }
505
+ /**
506
+ * 把 Convex validator 转成 TypeScript 类型表达式。
507
+ *
508
+ * 该函数只用于 `--static-data-model`;默认模式仍然让 TypeScript 从
509
+ * schema 推导,避免我们自己维护一套不完整的类型映射。
510
+ */
511
+ function validatorToTs(validator) {
512
+ switch (validator.kind) {
513
+ case "string": return "string";
514
+ case "float64": return "number";
515
+ case "int64":
516
+ case "commitTs": return "bigint";
517
+ case "boolean": return "boolean";
518
+ case "bytes": return "ArrayBuffer";
519
+ case "null": return "null";
520
+ case "any": return "any";
521
+ case "function": return "unknown";
522
+ case "id": return `GenericId<${JSON.stringify(validator.tableName ?? "string")}>`;
523
+ case "literal": return JSON.stringify(validator.value) ?? "never";
524
+ case "array": return validator.element ? `Array<${validatorToTs(validator.element)}>` : "unknown[]";
525
+ case "object": {
526
+ const fields = Object.entries(validator.fields ?? {}).map(([name, field]) => {
527
+ const optional = field.isOptional === "optional" ? "?" : "";
528
+ return `${propertyKey(name)}${optional}: ${validatorToTs(field)}`;
529
+ });
530
+ return fields.length === 0 ? "{}" : `{ ${fields.join("; ")} }`;
531
+ }
532
+ case "record": return validator.key && validator.value ? `Record<${validatorToTs(validator.key)}, ${validatorToTs(validator.value)}>` : "Record<string, unknown>";
533
+ case "union": return (validator.members ?? []).length === 0 ? "never" : (validator.members ?? []).map(validatorToTs).join(" | ");
534
+ default: return "unknown";
535
+ }
536
+ }
537
+ /**
538
+ * 收集字段路径。
539
+ *
540
+ * 与 Convex 的 `fieldPaths` 行为一致:对象字段会递归展开,但数组元素内部
541
+ * 的字段不会出现在路径里(数组只暴露数组本身作为一个路径)。
542
+ */
543
+ function collectFieldPaths(validator, prefix, output) {
544
+ if (validator.kind === "object") {
545
+ for (const [name, field] of Object.entries(validator.fields ?? {})) {
546
+ const path = prefix ? `${prefix}.${name}` : name;
547
+ output.add(path);
548
+ if (field.kind === "object") collectFieldPaths(field, path, output);
549
+ }
550
+ return;
551
+ }
552
+ if (validator.kind === "union") for (const member of validator.members ?? []) collectFieldPaths(member, prefix, output);
553
+ }
554
+ /**
555
+ * 返回文档可用的字段路径(含 `_id` / `_creationTime`)。
556
+ *
557
+ * check 用它验证索引字段是否真实存在,避免用户写出
558
+ * `.index("by_name", ["nmae"])` 这种拼写错误。
559
+ */
560
+ function documentFieldPaths(validator) {
561
+ const paths = /* @__PURE__ */ new Set(["_id", "_creationTime"]);
562
+ if (validator) collectFieldPaths(validator, "", paths);
563
+ return paths;
564
+ }
565
+ /** 生成对象字面量里的属性名;保留合法标识符,其余加引号。 */
566
+ function propertyKey(key) {
567
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
568
+ }
569
+ /** 生成全部生成文件。 */
570
+ function renderGeneratedFiles(project, options) {
571
+ return [
572
+ {
573
+ fileName: "server.js",
574
+ content: renderServerJs()
575
+ },
576
+ {
577
+ fileName: "server.d.ts",
578
+ content: renderServerDts()
579
+ },
580
+ {
581
+ fileName: "api.js",
582
+ content: renderApiJs(project.components)
583
+ },
584
+ {
585
+ fileName: "api.d.ts",
586
+ content: renderApiDts(project.modules, options.staticApi, project.components)
587
+ },
588
+ {
589
+ fileName: "dataModel.d.ts",
590
+ content: renderDataModelDts(project.schema, options.staticDataModel, project.schemaExportName ?? "default")
591
+ }
592
+ ];
593
+ }
594
+ export { componentsManifestPath, documentFieldPaths, renderApiBootstrapJs, renderApiDts, renderApiJs, renderComponentsManifest, renderDataModelDts, renderGeneratedFiles, renderServerDts, renderServerJs, validatorToTs };
@@ -0,0 +1,37 @@
1
+ import type { CliOptions } from "./args.js";
2
+ import { type GeneratedFile } from "./codegen-content.js";
3
+ import { type TypecheckResult } from "./typecheck.js";
4
+ /**
5
+ * `vultro codegen` 的实现。
6
+ *
7
+ * 流程:
8
+ * 1. 找到项目与 schema;
9
+ * 2. 加载 `convex/` 下的模块,读取函数元数据;
10
+ * 3. 生成 `_generated/` 下的五个文件;
11
+ * 4. 按 `--typecheck` 策略决定是否运行类型检查。
12
+ */
13
+ export type FileStatus = "created" | "updated" | "unchanged";
14
+ export interface GeneratedFileStatus {
15
+ fileName: string;
16
+ status: FileStatus;
17
+ }
18
+ export interface CodegenResult {
19
+ rootDir: string;
20
+ convexDir: string;
21
+ files: GeneratedFileStatus[];
22
+ typecheck?: TypecheckResult;
23
+ }
24
+ /** 执行 codegen,返回可供 check / 测试复用的结构化结果。 */
25
+ export declare function generate(options: CliOptions, runtime?: {
26
+ refreshModules?: boolean;
27
+ }): Promise<CodegenResult>;
28
+ /**
29
+ * 把生成内容写入 `convex/_generated/`。
30
+ *
31
+ * 只有内容变化时才写文件,避免每次 codegen 都触发编辑器和文件监听器。
32
+ */
33
+ export declare function writeGeneratedFiles(convexDir: string, files: GeneratedFile[]): GeneratedFileStatus[];
34
+ /** CLI 入口调用的包装:负责打印结果并返回退出码。 */
35
+ export declare function runCodegen(options: CliOptions): Promise<number>;
36
+ /** 打印类型检查结果(codegen 与 check 共用同一套格式)。 */
37
+ export declare function printTypecheck(result: TypecheckResult, mode: "enable" | "try" | "disable"): void;