@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.
- package/README.md +142 -2
- package/dist/_virtual/_vite/preload-helper.js +102 -0
- package/dist/args.d.ts +75 -0
- package/dist/args.js +169 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +295 -0
- package/dist/codegen-content.d.ts +77 -0
- package/dist/codegen-content.js +594 -0
- package/dist/codegen.d.ts +37 -0
- package/dist/codegen.js +115 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +166 -0
- package/dist/mcp.d.ts +91 -0
- package/dist/mcp.js +440 -0
- package/dist/project.d.ts +172 -0
- package/dist/project.js +597 -0
- package/dist/run.d.ts +37 -0
- package/dist/run.js +103 -0
- package/dist/typecheck.d.ts +36 -0
- package/dist/typecheck.js +85 -0
- package/package.json +29 -4
package/dist/project.js
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { readSchema } from "@vultro/core";
|
|
6
|
+
import { __vitePreload } from "./_virtual/_vite/preload-helper.js";
|
|
7
|
+
// src/project.ts
|
|
8
|
+
/**
|
|
9
|
+
* 项目发现与模块加载。
|
|
10
|
+
*
|
|
11
|
+
* CLI 需要复用真实的用户代码(而不是解析 AST):
|
|
12
|
+
* - schema 通过 `defineSchema()` 运行后可以直接读取表 / 索引 / 校验器;
|
|
13
|
+
* - 函数通过 `query()` / `mutation()` 运行后带有 `_type` / `_visibility`
|
|
14
|
+
* 元数据,codegen 不需要猜测导出类型。
|
|
15
|
+
*
|
|
16
|
+
* 代价是模块加载会执行用户顶层代码。Convex 的官方 codegen 也是运行
|
|
17
|
+
* 模块来读取函数元数据的,因此这里保持一致;如果模块顶层有副作用,
|
|
18
|
+
* 应该放到 handler 内部。
|
|
19
|
+
*/
|
|
20
|
+
/** 支持的源码扩展名。 */
|
|
21
|
+
var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
22
|
+
".ts",
|
|
23
|
+
".tsx",
|
|
24
|
+
".mts",
|
|
25
|
+
".cts",
|
|
26
|
+
".js",
|
|
27
|
+
".jsx",
|
|
28
|
+
".mjs",
|
|
29
|
+
".cjs"
|
|
30
|
+
]);
|
|
31
|
+
var ProjectError = class extends Error {};
|
|
32
|
+
/**
|
|
33
|
+
* 清空 `roots` 目录下(不含 `node_modules`)已加载模块的缓存。
|
|
34
|
+
*
|
|
35
|
+
* Bun 会把 ESM `import()` 的结果同样登记在 `require.cache` 里,删除条目后
|
|
36
|
+
* 下一次 `import()` 会重新读取磁盘;Node 的 ESM 缓存不暴露且无法失效,
|
|
37
|
+
* 因此这个函数只对 Bun 生效(其它运行时返回 0,由调用方回退到子进程)。
|
|
38
|
+
*
|
|
39
|
+
* 只清理项目自己的源码,避免把 `@vultro/core`、`convex` 等依赖也重新求值,
|
|
40
|
+
* 那会破坏模块单例(例如 `instanceof` 判断、运行时全局状态)。
|
|
41
|
+
*/
|
|
42
|
+
function clearModuleCache(roots) {
|
|
43
|
+
const cache = createRequire(import.meta.url).cache;
|
|
44
|
+
if (!cache) return 0;
|
|
45
|
+
const prefixes = roots.map((root) => resolve(root) + sep);
|
|
46
|
+
const nodeModules = `${sep}node_modules${sep}`;
|
|
47
|
+
let removed = 0;
|
|
48
|
+
for (const key of Object.keys(cache)) {
|
|
49
|
+
if (key.includes(nodeModules)) continue;
|
|
50
|
+
const file = resolve(key);
|
|
51
|
+
if (!prefixes.some((prefix) => file.startsWith(prefix))) continue;
|
|
52
|
+
delete cache[key];
|
|
53
|
+
removed++;
|
|
54
|
+
}
|
|
55
|
+
return removed;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 从任意目录向上寻找包含 `convex/` 的项目根目录。
|
|
59
|
+
*
|
|
60
|
+
* 允许在项目子目录里执行 `vultro codegen`,行为与 `convex`
|
|
61
|
+
* 的“从当前目录开始向上找”一致。
|
|
62
|
+
*/
|
|
63
|
+
function findProjectDir(start = process.cwd()) {
|
|
64
|
+
let current = resolve(start);
|
|
65
|
+
if (current.split(sep).pop() === "convex" && isDirectory(current)) return dirname(current);
|
|
66
|
+
while (true) {
|
|
67
|
+
if (isDirectory(join(current, "convex"))) return current;
|
|
68
|
+
const parent = dirname(current);
|
|
69
|
+
if (parent === current) break;
|
|
70
|
+
current = parent;
|
|
71
|
+
}
|
|
72
|
+
throw new ProjectError(`没有找到 convex/ 目录(从 ${resolve(start)} 开始向上查找)。请先创建 Convex 项目结构。`);
|
|
73
|
+
}
|
|
74
|
+
/** 递归列出 `convex/` 下的源码文件。 */
|
|
75
|
+
function discoverSourceFiles(convexDir) {
|
|
76
|
+
const files = [];
|
|
77
|
+
const walk = (directory) => {
|
|
78
|
+
const entries = readdirSync(directory, { withFileTypes: true });
|
|
79
|
+
for (const entry of entries) {
|
|
80
|
+
if (entry.name === "_generated" || entry.name === "node_modules") continue;
|
|
81
|
+
if (entry.name.startsWith(".")) continue;
|
|
82
|
+
const fullPath = join(directory, entry.name);
|
|
83
|
+
if (entry.isDirectory()) {
|
|
84
|
+
walk(fullPath);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (!entry.isFile()) continue;
|
|
88
|
+
const extension = extname(entry.name);
|
|
89
|
+
if (!SOURCE_EXTENSIONS.has(extension)) continue;
|
|
90
|
+
if (entry.name.endsWith(".d.ts")) continue;
|
|
91
|
+
if (/^convex\.config\.[^.]+$/.test(entry.name)) continue;
|
|
92
|
+
if (/^auth\.config\.[^.]+$/.test(entry.name)) continue;
|
|
93
|
+
if (/\.(test|spec)\.[^.]+$/.test(entry.name)) continue;
|
|
94
|
+
files.push(fullPath);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
walk(convexDir);
|
|
98
|
+
return files.sort((left, right) => left.localeCompare(right));
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* 加载项目 schema 与函数模块。
|
|
102
|
+
*
|
|
103
|
+
* 任一模块加载失败都会抛出 `ProjectError`,并在消息中带上相对路径,
|
|
104
|
+
* 避免用户只看到一个裸的 `Cannot find module`。
|
|
105
|
+
*/
|
|
106
|
+
async function loadProject(options = {}) {
|
|
107
|
+
const rootDir = findProjectDir(options.dir);
|
|
108
|
+
const convexDir = join(rootDir, "convex");
|
|
109
|
+
const sourceFiles = discoverSourceFiles(convexDir);
|
|
110
|
+
if (options.bootstrapGeneratedServer) await ensureGeneratedServer(convexDir);
|
|
111
|
+
if (options.refreshModules !== false) clearModuleCache([rootDir]);
|
|
112
|
+
const schemaPath = findSchemaFile(sourceFiles);
|
|
113
|
+
let schemaExportName;
|
|
114
|
+
let rawSchema;
|
|
115
|
+
let schema = readSchema(void 0);
|
|
116
|
+
if (schemaPath) {
|
|
117
|
+
const loaded = await importModule(schemaPath, rootDir);
|
|
118
|
+
const candidate = pickSchemaExport(loaded, schemaPath, rootDir);
|
|
119
|
+
schemaExportName = loaded.default !== void 0 ? "default" : "schema";
|
|
120
|
+
if (candidate !== void 0) {
|
|
121
|
+
rawSchema = candidate;
|
|
122
|
+
schema = readSchema(candidate);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const modules = [];
|
|
126
|
+
const moduleErrors = [];
|
|
127
|
+
for (const filePath of sourceFiles) {
|
|
128
|
+
if (filePath === schemaPath) continue;
|
|
129
|
+
let loaded;
|
|
130
|
+
try {
|
|
131
|
+
loaded = await importModule(filePath, rootDir);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
moduleErrors.push({
|
|
134
|
+
relativePath: relative(rootDir, filePath).split(sep).join("/"),
|
|
135
|
+
message: error instanceof Error ? error.message : String(error)
|
|
136
|
+
});
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const functions = collectFunctions(loaded);
|
|
140
|
+
if (functions.length === 0) continue;
|
|
141
|
+
modules.push({
|
|
142
|
+
name: moduleName(convexDir, filePath),
|
|
143
|
+
relativePath: relative(rootDir, filePath).split(sep).join("/"),
|
|
144
|
+
filePath,
|
|
145
|
+
functions
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
modules.sort((left, right) => left.name.localeCompare(right.name));
|
|
149
|
+
const components = await loadComponentRegistrations(convexDir, rootDir);
|
|
150
|
+
return {
|
|
151
|
+
rootDir,
|
|
152
|
+
convexDir,
|
|
153
|
+
schemaPath,
|
|
154
|
+
schemaExportName,
|
|
155
|
+
rawSchema,
|
|
156
|
+
schema,
|
|
157
|
+
modules,
|
|
158
|
+
sourceFiles,
|
|
159
|
+
moduleErrors,
|
|
160
|
+
components
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* 静态解析 `convex/convex.config.ts` 的 `defineApp()` / `app.use(...)`。
|
|
165
|
+
*
|
|
166
|
+
* 不执行配置模块(`defineApp().use()` 依赖 Convex 构建期注入的
|
|
167
|
+
* `componentDefinitionPath`),只解析 import 与 use 声明,然后回到组件
|
|
168
|
+
* 包目录读取它自己的 schema / 函数模块。
|
|
169
|
+
*
|
|
170
|
+
* 解析是递归的:组件配置里的 `.use(...)` 会生成 `parent.child` 子组件。
|
|
171
|
+
* 循环 mount(A 使用 B、B 又使用 A)会被检测并报错,避免生成无限嵌套。
|
|
172
|
+
*/
|
|
173
|
+
async function loadComponentRegistrations(convexDir, rootDir) {
|
|
174
|
+
const configPath = findConfigPath(convexDir);
|
|
175
|
+
if (!configPath) return [];
|
|
176
|
+
return loadConfigRegistrations(configPath, rootDir, "", []);
|
|
177
|
+
}
|
|
178
|
+
/** 在目录中寻找 convex.config.*。 */
|
|
179
|
+
function findConfigPath(directory) {
|
|
180
|
+
return [
|
|
181
|
+
"convex.config.ts",
|
|
182
|
+
"convex.config.mts",
|
|
183
|
+
"convex.config.js",
|
|
184
|
+
"convex.config.mjs"
|
|
185
|
+
].map((name) => join(directory, name)).find((candidate) => existsSync(candidate));
|
|
186
|
+
}
|
|
187
|
+
/** 递归解析一个 config 文件中的 `.use(...)`。 */
|
|
188
|
+
async function loadConfigRegistrations(configPath, rootDir, prefix, stack) {
|
|
189
|
+
const absoluteConfig = resolve(configPath);
|
|
190
|
+
if (stack.includes(absoluteConfig)) throw new ProjectError(`组件循环 mount:${[...stack, absoluteConfig].map((path) => relative(rootDir, path).split(sep).join("/")).join(" -> ")}`);
|
|
191
|
+
const source = readFileSync(configPath, "utf8");
|
|
192
|
+
const imports = /* @__PURE__ */ new Map();
|
|
193
|
+
for (const match of source.matchAll(/import\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']+)["']/g)) imports.set(match[1], match[2]);
|
|
194
|
+
const registrations = [];
|
|
195
|
+
const seen = /* @__PURE__ */ new Set();
|
|
196
|
+
for (const use of findComponentUses(source)) {
|
|
197
|
+
const identifier = use.identifier;
|
|
198
|
+
const spec = imports.get(identifier);
|
|
199
|
+
if (!spec) throw new ProjectError(`${relative(rootDir, configPath)} 使用了 ${identifier},但没有找到对应的 import`);
|
|
200
|
+
const componentConfigPath = resolveComponentSpec(spec, dirname(configPath));
|
|
201
|
+
if (!componentConfigPath) throw new ProjectError(`无法解析组件 "${spec}";请检查包名或相对路径是否正确`);
|
|
202
|
+
const componentRoot = dirname(componentConfigPath);
|
|
203
|
+
const localConvexDir = join(componentRoot, "convex");
|
|
204
|
+
const componentConvexDir = existsSync(localConvexDir) ? localConvexDir : spec.startsWith(".") ? localConvexDir : componentRoot;
|
|
205
|
+
if (!existsSync(componentConvexDir)) throw new ProjectError(`组件 ${spec} 缺少 convex/ 目录:${relative(rootDir, componentConvexDir)}`);
|
|
206
|
+
const componentSource = readFileSync(componentConfigPath, "utf8");
|
|
207
|
+
const definedName = /defineComponent(?:<[^>]*>)?\(\s*["'`]([^"'`]+)["'`]/.exec(componentSource)?.[1] ?? basename(componentRoot);
|
|
208
|
+
const name = topLevelComponentName(use.options) ?? definedName;
|
|
209
|
+
if (name.includes(".") || name.includes("/")) throw new ProjectError(`组件挂载名 "${name}" 不能包含 "." 或 "/";嵌套组件请使用组件自己的 convex.config.ts`);
|
|
210
|
+
if (seen.has(name)) throw new ProjectError(`组件挂载名重复:${name}`);
|
|
211
|
+
seen.add(name);
|
|
212
|
+
const path = prefix ? `${prefix}.${name}` : name;
|
|
213
|
+
const componentFiles = discoverSourceFiles(componentConvexDir);
|
|
214
|
+
const schemaPath = componentFiles.find((file) => /(^|\/)schema\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(file));
|
|
215
|
+
let schemaExportName;
|
|
216
|
+
if (schemaPath) schemaExportName = (await importModule(schemaPath, rootDir)).default !== void 0 ? "default" : "schema";
|
|
217
|
+
if (componentFiles.some((file) => {
|
|
218
|
+
try {
|
|
219
|
+
return /["'](\.\.?\/)*_generated\/(server|api)/.test(readFileSync(file, "utf8"));
|
|
220
|
+
} catch {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
})) await ensureGeneratedServer(componentConvexDir, { api: true });
|
|
224
|
+
const modules = (await Promise.all(componentFiles.filter((file) => file !== schemaPath).map(async (file) => {
|
|
225
|
+
const loaded = await importModule(file, rootDir);
|
|
226
|
+
return {
|
|
227
|
+
name: moduleName(componentConvexDir, file),
|
|
228
|
+
filePath: file,
|
|
229
|
+
functions: collectFunctions(loaded)
|
|
230
|
+
};
|
|
231
|
+
}))).filter((module) => module.name.length > 0).sort((left, right) => left.name.localeCompare(right.name));
|
|
232
|
+
const children = await loadConfigRegistrations(componentConfigPath, rootDir, path, [...stack, absoluteConfig]);
|
|
233
|
+
const moduleRoots = new Set(modules.map((module) => module.name.split("/")[0]));
|
|
234
|
+
for (const child of children) if (moduleRoots.has(child.name)) throw new ProjectError(`组件挂载名 "${child.name}" 与组件模块 "${child.name}" 冲突,请重命名其中一个`);
|
|
235
|
+
registrations.push({
|
|
236
|
+
name,
|
|
237
|
+
path,
|
|
238
|
+
defaultName: definedName,
|
|
239
|
+
configPath: stabilizePackagePath(componentConfigPath, [rootDir]),
|
|
240
|
+
rootDir: componentRoot,
|
|
241
|
+
convexDir: componentConvexDir,
|
|
242
|
+
schemaPath: schemaPath ? stabilizePackagePath(schemaPath, [rootDir]) : void 0,
|
|
243
|
+
schemaExportName,
|
|
244
|
+
modules: modules.map((module) => ({
|
|
245
|
+
...module,
|
|
246
|
+
filePath: stabilizePackagePath(module.filePath, [rootDir])
|
|
247
|
+
})),
|
|
248
|
+
children
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
return registrations;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* 去掉 JS / TS 注释,但完整保留字符串和模板字符串。
|
|
255
|
+
*
|
|
256
|
+
* 不能用简单正则直接删 `//`:`{ env: { PREFIX: "a//b" } }` 里的协议
|
|
257
|
+
* 片段也会被删掉,进而破坏后面的括号匹配。这里逐字符扫描,只有真正
|
|
258
|
+
* 位于字符串之外时才跳过注释。
|
|
259
|
+
*/
|
|
260
|
+
function stripComments(source) {
|
|
261
|
+
let result = "";
|
|
262
|
+
let quote;
|
|
263
|
+
let escaped = false;
|
|
264
|
+
for (let index = 0; index < source.length; index++) {
|
|
265
|
+
const char = source[index];
|
|
266
|
+
if (quote) {
|
|
267
|
+
result += char;
|
|
268
|
+
if (escaped) escaped = false;
|
|
269
|
+
else if (char === "\\") escaped = true;
|
|
270
|
+
else if (char === quote) quote = void 0;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (char === "\"" || char === "'" || char === "`") {
|
|
274
|
+
quote = char;
|
|
275
|
+
result += char;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (char === "/" && source[index + 1] === "/") {
|
|
279
|
+
while (index < source.length && source[index] !== "\n") index += 1;
|
|
280
|
+
result += "\n";
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (char === "/" && source[index + 1] === "*") {
|
|
284
|
+
index += 2;
|
|
285
|
+
while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) index += 1;
|
|
286
|
+
index += 1;
|
|
287
|
+
result += " ";
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
result += char;
|
|
291
|
+
}
|
|
292
|
+
return result;
|
|
293
|
+
}
|
|
294
|
+
/** 从字符串字面量起始位置读取内容;不是字符串时返回 undefined。 */
|
|
295
|
+
function readStringLiteral(source, start) {
|
|
296
|
+
const quote = source[start];
|
|
297
|
+
if (quote !== "\"" && quote !== "'" && quote !== "`") return void 0;
|
|
298
|
+
let value = "";
|
|
299
|
+
let escaped = false;
|
|
300
|
+
for (let index = start + 1; index < source.length; index++) {
|
|
301
|
+
const char = source[index];
|
|
302
|
+
if (escaped) {
|
|
303
|
+
value += char;
|
|
304
|
+
escaped = false;
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
if (char === "\\") {
|
|
308
|
+
escaped = true;
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (char === quote) return {
|
|
312
|
+
value,
|
|
313
|
+
end: index + 1
|
|
314
|
+
};
|
|
315
|
+
value += char;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* 读取 `.use(component, options)` 里 **顶层** 的 `name` 选项。
|
|
320
|
+
*
|
|
321
|
+
* 不能直接正则第一个 `name:`:options 可能包含
|
|
322
|
+
* `{ args: { name: "inner" }, name: "outer" }`,嵌套值不该被当成
|
|
323
|
+
* 组件挂载名。
|
|
324
|
+
*/
|
|
325
|
+
function topLevelComponentName(options) {
|
|
326
|
+
const objectStart = options.indexOf("{");
|
|
327
|
+
if (objectStart === -1) return void 0;
|
|
328
|
+
let depth = 0;
|
|
329
|
+
let quote;
|
|
330
|
+
let escaped = false;
|
|
331
|
+
for (let index = objectStart; index < options.length; index++) {
|
|
332
|
+
const char = options[index];
|
|
333
|
+
if (quote) {
|
|
334
|
+
if (escaped) escaped = false;
|
|
335
|
+
else if (char === "\\") escaped = true;
|
|
336
|
+
else if (char === quote) quote = void 0;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (char === "\"" || char === "'" || char === "`") {
|
|
340
|
+
quote = char;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (char === "{") {
|
|
344
|
+
depth += 1;
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (char === "}") {
|
|
348
|
+
depth -= 1;
|
|
349
|
+
if (depth === 0) break;
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (depth !== 1 || char !== "n") continue;
|
|
353
|
+
if (!options.startsWith("name", index)) continue;
|
|
354
|
+
const before = options[index - 1];
|
|
355
|
+
if (before && before !== "{" && before !== "," && !/\s/.test(before)) continue;
|
|
356
|
+
let cursor = index + 4;
|
|
357
|
+
while (cursor < options.length && /\s/.test(options[cursor])) cursor += 1;
|
|
358
|
+
if (options[cursor] !== ":") continue;
|
|
359
|
+
cursor += 1;
|
|
360
|
+
while (cursor < options.length && /\s/.test(options[cursor])) cursor += 1;
|
|
361
|
+
const literal = readStringLiteral(options, cursor);
|
|
362
|
+
if (literal) return literal.value;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* 扫描 `component.use(...)` 调用。
|
|
367
|
+
*
|
|
368
|
+
* 不能简单用正则匹配到第一个 `)`:npm 组件经常把 env / args 对象作为
|
|
369
|
+
* 第二个参数(例如 `use(workpool, { env: { LOG_LEVEL: ... } })`)。这里
|
|
370
|
+
* 按括号配对找到完整的参数文本,再从中提取 `name: "..."` 别名。
|
|
371
|
+
*/
|
|
372
|
+
function findComponentUses(source) {
|
|
373
|
+
const result = [];
|
|
374
|
+
const code = stripComments(source);
|
|
375
|
+
for (const match of code.matchAll(/\.use\(\s*([A-Za-z_$][\w$]*)/g)) {
|
|
376
|
+
const openIndex = code.indexOf("(", match.index ?? 0);
|
|
377
|
+
if (openIndex === -1) continue;
|
|
378
|
+
let depth = 1;
|
|
379
|
+
let quote;
|
|
380
|
+
let escaped = false;
|
|
381
|
+
let closeIndex = -1;
|
|
382
|
+
for (let index = openIndex + 1; index < code.length; index++) {
|
|
383
|
+
const char = code[index];
|
|
384
|
+
if (quote) {
|
|
385
|
+
if (escaped) escaped = false;
|
|
386
|
+
else if (char === "\\") escaped = true;
|
|
387
|
+
else if (char === quote) quote = void 0;
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
if (char === "\"" || char === "'" || char === "`") {
|
|
391
|
+
quote = char;
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
if (char === "(") depth += 1;
|
|
395
|
+
else if (char === ")") {
|
|
396
|
+
depth -= 1;
|
|
397
|
+
if (depth === 0) {
|
|
398
|
+
closeIndex = index;
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (closeIndex === -1) continue;
|
|
404
|
+
result.push({
|
|
405
|
+
identifier: match[1],
|
|
406
|
+
options: code.slice(openIndex + 1, closeIndex)
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
return result;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* 把 Bun 安装器返回的真实路径还原成包管理器提供的稳定符号链接路径。
|
|
413
|
+
*
|
|
414
|
+
* Bun 把依赖放在 `node_modules/.bun/<包名>@<版本>+<内容哈希>/node_modules/`
|
|
415
|
+
* 下,`require.resolve` 默认返回这个真实路径。codegen 会把组件的
|
|
416
|
+
* schema / 函数模块路径写进已提交的 `_generated/components.ts`,一旦
|
|
417
|
+
* 路径里带上版本或内容哈希,重新安装依赖(例如 CI 上)就会让同样的源码
|
|
418
|
+
* 生成出不同的 import 路径,`git diff --exit-code` 随之失败。
|
|
419
|
+
*
|
|
420
|
+
* 因此这里按「包内相对路径」反查项目里的符号链接目录
|
|
421
|
+
* (`node_modules/<包名>/...`),输出只和包名、文件位置有关。
|
|
422
|
+
* 找不到对应符号链接时退回真实路径,保证 codegen 仍然可用。
|
|
423
|
+
*
|
|
424
|
+
* @param resolvedPath `require.resolve` 得到的绝对路径
|
|
425
|
+
* @param searchDirs 依次尝试的起始目录(项目根目录优先,其次组件所在目录)
|
|
426
|
+
*/
|
|
427
|
+
function stabilizePackagePath(resolvedPath, searchDirs) {
|
|
428
|
+
const bunMarker = `${sep}node_modules${sep}.bun${sep}`;
|
|
429
|
+
const markerIndex = resolvedPath.indexOf(bunMarker);
|
|
430
|
+
if (markerIndex === -1) return resolvedPath;
|
|
431
|
+
const storeRelative = resolvedPath.slice(markerIndex + bunMarker.length);
|
|
432
|
+
const innerMarker = `${sep}node_modules${sep}`;
|
|
433
|
+
const innerIndex = storeRelative.indexOf(innerMarker);
|
|
434
|
+
if (innerIndex === -1) return resolvedPath;
|
|
435
|
+
const packageRelative = storeRelative.slice(innerIndex + innerMarker.length);
|
|
436
|
+
for (const startDir of searchDirs) {
|
|
437
|
+
let current = resolve(startDir);
|
|
438
|
+
for (;;) {
|
|
439
|
+
const candidate = join(current, "node_modules", packageRelative);
|
|
440
|
+
if (existsSync(candidate)) return candidate;
|
|
441
|
+
const parent = dirname(current);
|
|
442
|
+
if (parent === current) break;
|
|
443
|
+
current = parent;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return resolvedPath;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* 解析组件 import spec。
|
|
450
|
+
*
|
|
451
|
+
* - 相对路径:支持省略扩展名 / index(本地 `components/` 目录);
|
|
452
|
+
* - npm 包:通过 Node/Bun 的 `require.resolve` 解析 package exports,
|
|
453
|
+
* 例如 `@convex-dev/workflow/convex.config`。
|
|
454
|
+
*
|
|
455
|
+
* npm 包解析结果保持真实路径(见 {@link stabilizePackagePath}),
|
|
456
|
+
* 因为嵌套组件需要在真实安装目录里继续解析自己的依赖;生成文件里的
|
|
457
|
+
* 路径会在注册组件时单独归一化。
|
|
458
|
+
*/
|
|
459
|
+
function resolveComponentSpec(spec, baseDir) {
|
|
460
|
+
if (!spec.startsWith(".")) try {
|
|
461
|
+
return createRequire(join(baseDir, "package.json")).resolve(spec);
|
|
462
|
+
} catch {
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
const absolute = resolve(baseDir, spec);
|
|
466
|
+
return [
|
|
467
|
+
absolute,
|
|
468
|
+
`${absolute}.ts`,
|
|
469
|
+
`${absolute}.tsx`,
|
|
470
|
+
`${absolute}.mts`,
|
|
471
|
+
`${absolute}.cts`,
|
|
472
|
+
`${absolute}.js`,
|
|
473
|
+
`${absolute}.mjs`,
|
|
474
|
+
`${absolute}.cjs`,
|
|
475
|
+
join(absolute, "convex.config.ts"),
|
|
476
|
+
join(absolute, "convex.config.js"),
|
|
477
|
+
join(absolute, "index.ts"),
|
|
478
|
+
join(absolute, "index.js")
|
|
479
|
+
].find((candidate) => existsSync(candidate) && statSync(candidate).isFile());
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* 检查 `foo.ts` 与 `foo/bar.ts` 这种文件 / 目录同名冲突。
|
|
483
|
+
*
|
|
484
|
+
* Convex 的 API 树用模块路径作为命名空间;一个路径不能同时是函数模块
|
|
485
|
+
* 和目录。提前报告比让 codegen 生成出错误类型更友好。
|
|
486
|
+
*/
|
|
487
|
+
function findModulePathConflicts(modules) {
|
|
488
|
+
const names = new Set(modules.map((module) => module.name));
|
|
489
|
+
const conflicts = [];
|
|
490
|
+
for (const module of modules) {
|
|
491
|
+
const segments = module.name.split("/");
|
|
492
|
+
for (let index = 1; index < segments.length; index++) {
|
|
493
|
+
const prefix = segments.slice(0, index).join("/");
|
|
494
|
+
if (names.has(prefix)) conflicts.push(`${module.relativePath} 与 ${prefix} 冲突:同一路径不能既是模块又是目录`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return conflicts;
|
|
498
|
+
}
|
|
499
|
+
/** 判断路径是否是目录。 */
|
|
500
|
+
function isDirectory(path) {
|
|
501
|
+
try {
|
|
502
|
+
return statSync(path).isDirectory();
|
|
503
|
+
} catch {
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/** 在源码列表中寻找 schema 文件。 */
|
|
508
|
+
function findSchemaFile(sourceFiles) {
|
|
509
|
+
return sourceFiles.find((file) => /(^|\/)schema\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(file));
|
|
510
|
+
}
|
|
511
|
+
/** 动态 import 一个源码文件,并把加载错误包装成可读信息。 */
|
|
512
|
+
async function importModule(filePath, rootDir) {
|
|
513
|
+
const displayPath = relative(rootDir, filePath).split(sep).join("/");
|
|
514
|
+
try {
|
|
515
|
+
return await import(pathToFileURL(filePath).href);
|
|
516
|
+
} catch (error) {
|
|
517
|
+
throw new ProjectError(`加载模块 ${displayPath} 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
/** 从 schema 模块中取默认导出(也兼容具名 `schema`)。 */
|
|
521
|
+
function pickSchemaExport(loaded, schemaPath, rootDir) {
|
|
522
|
+
if (loaded.default !== void 0) return loaded.default;
|
|
523
|
+
if (loaded.schema !== void 0) return loaded.schema;
|
|
524
|
+
throw new ProjectError(`${relative(rootDir, schemaPath).split(sep).join("/")} 必须默认导出 defineSchema(...) 的结果。`);
|
|
525
|
+
}
|
|
526
|
+
/** 收集模块中所有 Vultro 函数导出。 */
|
|
527
|
+
function collectFunctions(loaded) {
|
|
528
|
+
const functions = [];
|
|
529
|
+
for (const [name, value] of Object.entries(loaded)) {
|
|
530
|
+
const meta = readFunctionMeta(value);
|
|
531
|
+
if (meta) functions.push({
|
|
532
|
+
name,
|
|
533
|
+
...meta
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
return functions;
|
|
537
|
+
}
|
|
538
|
+
/** 读取函数对象上的运行时元数据。 */
|
|
539
|
+
function readFunctionMeta(value) {
|
|
540
|
+
if (typeof value !== "function" && (typeof value !== "object" || value === null)) return;
|
|
541
|
+
const record = value;
|
|
542
|
+
const kind = record._type ?? (record.isQuery ? "query" : record.isMutation ? "mutation" : record.isAction ? "action" : record.isHttpAction ? "httpAction" : void 0);
|
|
543
|
+
if (kind !== "query" && kind !== "mutation" && kind !== "action" && kind !== "httpAction") return;
|
|
544
|
+
const visibility = record._visibility ?? (record.isInternal ? "internal" : record.isPublic ? "public" : void 0);
|
|
545
|
+
if (visibility !== "public" && visibility !== "internal") return void 0;
|
|
546
|
+
if (typeof record.handler !== "function" && typeof record._handler !== "function") return;
|
|
547
|
+
return {
|
|
548
|
+
kind,
|
|
549
|
+
visibility,
|
|
550
|
+
argsValidator: record.argsValidator,
|
|
551
|
+
returnsValidator: record.returnsValidator
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
/** 把绝对路径转换成 `admin/users` 这样的模块名。 */
|
|
555
|
+
function moduleName(convexDir, filePath) {
|
|
556
|
+
const relativePath = relative(convexDir, filePath);
|
|
557
|
+
return relativePath.slice(0, -extname(relativePath).length).split(sep).join("/");
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* 首次 codegen 时,用户模块可能还不存在 `_generated/server.js`。
|
|
561
|
+
*
|
|
562
|
+
* 这里先写一个最小的 server.js(与最终生成内容一致),让 `import` 能成功;
|
|
563
|
+
* `server.d.ts` / `api.d.ts` / `dataModel.d.ts` 仍由 codegen 后续正常生成,
|
|
564
|
+
* 避免在类型层面提前写出一份不完整的声明。
|
|
565
|
+
*/
|
|
566
|
+
async function ensureGeneratedServer(convexDir, options = {}) {
|
|
567
|
+
const generatedDir = join(convexDir, "_generated");
|
|
568
|
+
const serverJs = join(generatedDir, "server.js");
|
|
569
|
+
const apiJs = join(generatedDir, "api.js");
|
|
570
|
+
if (existsSync(serverJs) && (!options.api || existsSync(apiJs))) return;
|
|
571
|
+
const { renderServerJs, renderApiBootstrapJs } = await __vitePreload(async () => {
|
|
572
|
+
const { renderServerJs, renderApiBootstrapJs } = await import("./codegen-content.js");
|
|
573
|
+
return {
|
|
574
|
+
renderServerJs,
|
|
575
|
+
renderApiBootstrapJs
|
|
576
|
+
};
|
|
577
|
+
}, []);
|
|
578
|
+
const { mkdirSync, writeFileSync } = await __vitePreload(async () => {
|
|
579
|
+
const { mkdirSync, writeFileSync } = await import("node:fs");
|
|
580
|
+
return {
|
|
581
|
+
mkdirSync,
|
|
582
|
+
writeFileSync
|
|
583
|
+
};
|
|
584
|
+
}, []);
|
|
585
|
+
mkdirSync(generatedDir, { recursive: true });
|
|
586
|
+
if (!existsSync(serverJs)) writeFileSync(serverJs, renderServerJs(), "utf8");
|
|
587
|
+
if (options.api && !existsSync(apiJs)) writeFileSync(apiJs, renderApiBootstrapJs(), "utf8");
|
|
588
|
+
}
|
|
589
|
+
/** 读取文本文件;check 的静态扫描使用。 */
|
|
590
|
+
function readSource(filePath) {
|
|
591
|
+
try {
|
|
592
|
+
return readFileSync(filePath, "utf8");
|
|
593
|
+
} catch {
|
|
594
|
+
return "";
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
export { ProjectError, clearModuleCache, collectFunctions, discoverSourceFiles, findModulePathConflicts, findProjectDir, loadProject, readSource, stabilizePackagePath };
|
package/dist/run.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { CliOptions } from "./args.js";
|
|
2
|
+
/**
|
|
3
|
+
* `vultro dev` / `vultro build` 的实现。
|
|
4
|
+
*
|
|
5
|
+
* 运行时差异(Cloudflare / Bun / Node)由 `vultro.config.ts` 和
|
|
6
|
+
* `@vultro/vite-plugin` 决定,所以 CLI 只负责在应用根目录启动 Vite:
|
|
7
|
+
*
|
|
8
|
+
* - `dev` → `vite`
|
|
9
|
+
* - `build` → `vite build`
|
|
10
|
+
*
|
|
11
|
+
* 默认使用项目本地安装的 `node_modules/.bin/vite`,其次 `npx --no-install
|
|
12
|
+
* vite`;只有显式设置 `VULTRO_BUN` 时才退回 `bun x vite`。这样 CLI 不需要
|
|
13
|
+
* 依赖 Bun,也避免 `bun x` 临时下载不同版本的 Vite。
|
|
14
|
+
*/
|
|
15
|
+
/** 构造 Vite 参数;`viaBun` 时保留 `bun x vite` 的写法。 */
|
|
16
|
+
export declare function viteArgs(mode: "dev" | "build", passthrough?: string[], viaBun?: boolean): string[];
|
|
17
|
+
/**
|
|
18
|
+
* 找到包含 Vite / Vultro 配置的应用根目录。
|
|
19
|
+
*
|
|
20
|
+
* 不能用 `findProjectDir`(它要求当前目录链上有 `convex/`):拆分后的
|
|
21
|
+
* play 应用把 `convex/` 放在共享包里,app 自己只有 `vite.config.ts` /
|
|
22
|
+
* `vultro.config.ts`。这里从当前目录向上找这两个文件;找不到时退回
|
|
23
|
+
* 起始目录,让 Vite 自己报错。
|
|
24
|
+
*/
|
|
25
|
+
export declare function findAppDir(start?: string): string;
|
|
26
|
+
/** 从应用目录向上找本地安装的 Vite 可执行文件。 */
|
|
27
|
+
export declare function findLocalVite(startDir: string): string | undefined;
|
|
28
|
+
/** 解析出的 Vite 启动命令。 */
|
|
29
|
+
export interface ViteCommand {
|
|
30
|
+
command: string;
|
|
31
|
+
args: string[];
|
|
32
|
+
label: string;
|
|
33
|
+
}
|
|
34
|
+
/** 选择 Vite 启动方式:本地 bin → npx → 显式 Bun。 */
|
|
35
|
+
export declare function viteCommand(rootDir: string, mode: "dev" | "build", passthrough: string[], runtime?: "cloudflare" | "bun" | "node" | "cloud"): ViteCommand;
|
|
36
|
+
/** 在应用根目录启动 Vite,并返回退出码。 */
|
|
37
|
+
export declare function runVite(mode: "dev" | "build", options: CliOptions): Promise<number>;
|