@tbox.cn/app-build 0.0.0-stage → 1.0.0-alpha.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/LICENSE +9 -0
- package/README.md +22 -2
- package/agents/app-agent.md +5 -0
- package/agents/app-base.md +8 -0
- package/agents/app-web.md +4 -0
- package/agents/base.md +12 -0
- package/agents/kind-agent.md +5 -0
- package/agents/kind-web.md +3 -0
- package/agents/modules.md +9 -0
- package/dist/index.d.ts +200 -0
- package/dist/index.js +1038 -0
- package/package.json +45 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1038 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var AppBuildError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
file;
|
|
5
|
+
fix;
|
|
6
|
+
constructor(code, message, options = {}) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "AppBuildError";
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.file = options.file;
|
|
11
|
+
this.fix = options.fix;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// src/app-meta.ts
|
|
16
|
+
import path2 from "path";
|
|
17
|
+
|
|
18
|
+
// src/fs.ts
|
|
19
|
+
import { existsSync } from "fs";
|
|
20
|
+
import { mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
|
|
21
|
+
import path from "path";
|
|
22
|
+
async function readText(file) {
|
|
23
|
+
return readFile(file, "utf8");
|
|
24
|
+
}
|
|
25
|
+
async function readJson(file) {
|
|
26
|
+
return JSON.parse(await readText(file));
|
|
27
|
+
}
|
|
28
|
+
async function writeText(file, text) {
|
|
29
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
30
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
31
|
+
await writeFile(tmp, text, "utf8");
|
|
32
|
+
await rename(tmp, file);
|
|
33
|
+
}
|
|
34
|
+
async function removeFile(file) {
|
|
35
|
+
await rm(file, { force: true });
|
|
36
|
+
}
|
|
37
|
+
async function writeTextIfChanged(file, text) {
|
|
38
|
+
try {
|
|
39
|
+
if (await readFile(file, "utf8") === text) return false;
|
|
40
|
+
} catch {
|
|
41
|
+
}
|
|
42
|
+
await writeText(file, text);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
async function listFiles(dir) {
|
|
46
|
+
if (!existsSync(dir)) return [];
|
|
47
|
+
const out = [];
|
|
48
|
+
async function walk(current) {
|
|
49
|
+
const entries = await readdir(current, { withFileTypes: true });
|
|
50
|
+
for (const entry of entries) {
|
|
51
|
+
const full = path.join(current, entry.name);
|
|
52
|
+
if (entry.isDirectory()) await walk(full);
|
|
53
|
+
else if (entry.isFile()) out.push(full);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
await walk(dir);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
function relativePosix(fromFile, toFile) {
|
|
60
|
+
let rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join("/");
|
|
61
|
+
if (!rel.startsWith(".")) rel = `./${rel}`;
|
|
62
|
+
return rel;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/app-meta.ts
|
|
66
|
+
async function readAppMeta(root) {
|
|
67
|
+
const file = path2.join(root, ".tbox", "app.json");
|
|
68
|
+
let raw;
|
|
69
|
+
try {
|
|
70
|
+
raw = await readJson(file);
|
|
71
|
+
} catch {
|
|
72
|
+
throw new AppBuildError("APP_ROOT_MISSING", `缺少 ${path2.relative(root, file)}(不是 tbox-app 1.0 应用)`, { file });
|
|
73
|
+
}
|
|
74
|
+
if (!raw || typeof raw !== "object") {
|
|
75
|
+
throw new AppBuildError("APP_META_INVALID", ".tbox/app.json 必须是对象", { file });
|
|
76
|
+
}
|
|
77
|
+
const value = raw;
|
|
78
|
+
if (value.schemaVersion !== 1) {
|
|
79
|
+
throw new AppBuildError("APP_META_INVALID", ".tbox/app.json schemaVersion 必须为 1", { file });
|
|
80
|
+
}
|
|
81
|
+
if (value.appKind !== "agent" && value.appKind !== "web") {
|
|
82
|
+
throw new AppBuildError("APP_KIND_INVALID", 'appKind 必须是 "agent" 或 "web"', { file });
|
|
83
|
+
}
|
|
84
|
+
return { ...value, schemaVersion: 1, appKind: value.appKind };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/scan.ts
|
|
88
|
+
import path7 from "path";
|
|
89
|
+
|
|
90
|
+
// src/pages.ts
|
|
91
|
+
import path3 from "path";
|
|
92
|
+
|
|
93
|
+
// src/ast.ts
|
|
94
|
+
import ts from "typescript";
|
|
95
|
+
function parseSource(file, text) {
|
|
96
|
+
return ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
97
|
+
}
|
|
98
|
+
function hasDefaultExport(sf) {
|
|
99
|
+
for (const stmt of sf.statements) {
|
|
100
|
+
if (ts.isExportAssignment(stmt) && !stmt.isExportEquals) return true;
|
|
101
|
+
if (ts.isFunctionDeclaration(stmt) && stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) return true;
|
|
102
|
+
if (ts.isClassDeclaration(stmt) && stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) return true;
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
function findExportedVariable(sf, name) {
|
|
107
|
+
for (const stmt of sf.statements) {
|
|
108
|
+
if (!ts.isVariableStatement(stmt)) continue;
|
|
109
|
+
const exported = stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;
|
|
110
|
+
if (!exported) continue;
|
|
111
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
112
|
+
if (ts.isIdentifier(decl.name) && decl.name.text === name && decl.initializer) return decl.initializer;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
function unwrapExpression(expr) {
|
|
118
|
+
let current = expr;
|
|
119
|
+
while (ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isParenthesizedExpression(current)) {
|
|
120
|
+
current = current.expression;
|
|
121
|
+
}
|
|
122
|
+
return current;
|
|
123
|
+
}
|
|
124
|
+
function propertyName(node) {
|
|
125
|
+
if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return node.text;
|
|
126
|
+
return void 0;
|
|
127
|
+
}
|
|
128
|
+
function getProperty(obj, name) {
|
|
129
|
+
for (const prop of obj.properties) {
|
|
130
|
+
if (!ts.isPropertyAssignment(prop)) continue;
|
|
131
|
+
if (propertyName(prop.name) === name) return prop.initializer;
|
|
132
|
+
}
|
|
133
|
+
return void 0;
|
|
134
|
+
}
|
|
135
|
+
function objectFromExpression(expr, label) {
|
|
136
|
+
const unwrapped = unwrapExpression(expr);
|
|
137
|
+
if (ts.isObjectLiteralExpression(unwrapped)) return unwrapped;
|
|
138
|
+
if (ts.isCallExpression(unwrapped)) {
|
|
139
|
+
const first = unwrapped.arguments[0];
|
|
140
|
+
if (first) {
|
|
141
|
+
const arg = unwrapExpression(first);
|
|
142
|
+
if (ts.isObjectLiteralExpression(arg)) return arg;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
throw new AppBuildError("META_NOT_STATIC", `${label} 必须是静态对象字面量或 create* 的首个对象参数`);
|
|
146
|
+
}
|
|
147
|
+
function stringProperty(expr, name, label) {
|
|
148
|
+
const obj = objectFromExpression(expr, label);
|
|
149
|
+
const value = getProperty(obj, name);
|
|
150
|
+
if (!value) throw new AppBuildError("META_PROPERTY_MISSING", `${label} 缺少静态属性 "${name}"`);
|
|
151
|
+
const unwrapped = unwrapExpression(value);
|
|
152
|
+
if (ts.isStringLiteral(unwrapped) || ts.isNoSubstitutionTemplateLiteral(unwrapped)) return unwrapped.text;
|
|
153
|
+
throw new AppBuildError("META_NOT_STATIC", `${label} 的 "${name}" 必须是字符串字面量`);
|
|
154
|
+
}
|
|
155
|
+
function literalToJson(expr, label) {
|
|
156
|
+
const node = unwrapExpression(expr);
|
|
157
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
|
158
|
+
if (ts.isNumericLiteral(node)) return Number(node.text);
|
|
159
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
|
|
160
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
|
|
161
|
+
if (node.kind === ts.SyntaxKind.NullKeyword) return null;
|
|
162
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
|
|
163
|
+
const value = literalToJson(node.operand, label);
|
|
164
|
+
if (typeof value === "number") return -value;
|
|
165
|
+
}
|
|
166
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
167
|
+
return node.elements.map((item) => literalToJson(item, label));
|
|
168
|
+
}
|
|
169
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
170
|
+
const out = {};
|
|
171
|
+
for (const prop of node.properties) {
|
|
172
|
+
if (!ts.isPropertyAssignment(prop)) {
|
|
173
|
+
throw new AppBuildError("PAGE_META_NOT_STATIC", `${label} 的 meta 只支持普通键值对象`);
|
|
174
|
+
}
|
|
175
|
+
const key = propertyName(prop.name);
|
|
176
|
+
if (!key) throw new AppBuildError("PAGE_META_NOT_STATIC", `${label} 的 meta 键必须是静态字符串`);
|
|
177
|
+
out[key] = literalToJson(prop.initializer, label);
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
throw new AppBuildError("PAGE_META_NOT_STATIC", `${label} 必须是静态 JSON 字面量`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/pages.ts
|
|
185
|
+
var RESERVED = "_tbox";
|
|
186
|
+
function routeFromRelative(relativeFile) {
|
|
187
|
+
const dir = path3.posix.dirname(relativeFile.split(path3.sep).join("/"));
|
|
188
|
+
if (dir === "." || dir === "") return "/";
|
|
189
|
+
return `/${dir}`;
|
|
190
|
+
}
|
|
191
|
+
function validateRoute(route) {
|
|
192
|
+
if (route !== "/" && route.endsWith("/")) throw new AppBuildError("PAGE_ROUTE_INVALID", `页面路由不得带尾斜杠: ${route}`);
|
|
193
|
+
if (route !== "/" && route.slice(1).split("/").some((part) => part === "" || part === "." || part === "..")) {
|
|
194
|
+
throw new AppBuildError("PAGE_ROUTE_INVALID", `页面路由不合法: ${route}`);
|
|
195
|
+
}
|
|
196
|
+
if (route === `/${RESERVED}` || route.startsWith(`/${RESERVED}/`)) {
|
|
197
|
+
throw new AppBuildError("PAGE_ROUTE_RESERVED", `页面路由不得使用保留前缀 /${RESERVED}: ${route}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async function parsePageMeta(file) {
|
|
201
|
+
const text = await readText(file);
|
|
202
|
+
const sf = parseSource(file, text);
|
|
203
|
+
const expr = findExportedVariable(sf, "page");
|
|
204
|
+
if (!expr) throw new AppBuildError("PAGE_META_MISSING", "页面必须导出静态 const page = { title: ... }", { file });
|
|
205
|
+
const obj = objectFromExpression(expr, "page");
|
|
206
|
+
const titleExpr = obj.properties.find((prop) => {
|
|
207
|
+
if (!("name" in prop) || !prop.name) return false;
|
|
208
|
+
return prop.name.text === "title";
|
|
209
|
+
});
|
|
210
|
+
if (!titleExpr) throw new AppBuildError("PAGE_META_INVALID", "page.title 必须存在", { file });
|
|
211
|
+
const meta = literalToJson(expr, "page");
|
|
212
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
|
|
213
|
+
throw new AppBuildError("PAGE_META_INVALID", "page 必须是对象", { file });
|
|
214
|
+
}
|
|
215
|
+
const value = meta;
|
|
216
|
+
if (typeof value.title !== "string" || !value.title.trim()) {
|
|
217
|
+
throw new AppBuildError("PAGE_META_INVALID", "page.title 必须是非空字符串", { file });
|
|
218
|
+
}
|
|
219
|
+
if (value.meta !== void 0 && (typeof value.meta !== "object" || value.meta === null || Array.isArray(value.meta))) {
|
|
220
|
+
throw new AppBuildError("PAGE_META_INVALID", "page.meta 必须是对象", { file });
|
|
221
|
+
}
|
|
222
|
+
return { title: value.title, ...value.meta ? { meta: value.meta } : {} };
|
|
223
|
+
}
|
|
224
|
+
async function scanPages(root) {
|
|
225
|
+
const pagesDir = path3.join(root, "apps", "client", "src", "pages");
|
|
226
|
+
const files = (await listFiles(pagesDir)).filter((file) => path3.basename(file) === "page.tsx");
|
|
227
|
+
const pages = [];
|
|
228
|
+
const seen = /* @__PURE__ */ new Set();
|
|
229
|
+
for (const file of files.sort()) {
|
|
230
|
+
const relativeFile = path3.relative(pagesDir, file).split(path3.sep).join("/");
|
|
231
|
+
const route = routeFromRelative(relativeFile);
|
|
232
|
+
validateRoute(route);
|
|
233
|
+
if (seen.has(route)) throw new AppBuildError("PAGE_ROUTE_DUPLICATE", `页面路由重复: ${route}`, { file });
|
|
234
|
+
seen.add(route);
|
|
235
|
+
const id = route === "/" ? "index" : route.slice(1).replace(/[^a-zA-Z0-9_-]/g, "-");
|
|
236
|
+
if (pages.some((page) => page.id === id)) {
|
|
237
|
+
throw new AppBuildError("PAGE_ID_COLLISION", `页面 entry id 冲突: ${route} -> ${id}`, { file });
|
|
238
|
+
}
|
|
239
|
+
pages.push({ id, route, file, relativeFile, meta: await parsePageMeta(file) });
|
|
240
|
+
}
|
|
241
|
+
if (!pages.some((page) => page.route === "/")) {
|
|
242
|
+
throw new AppBuildError("PAGE_ROOT_MISSING", "缺少根页面 apps/client/src/pages/page.tsx", {
|
|
243
|
+
file: path3.join(pagesDir, "page.tsx")
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
pages.sort((a, b) => a.route === "/" ? -1 : b.route === "/" ? 1 : a.route.localeCompare(b.route));
|
|
247
|
+
return pages;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// src/functions.ts
|
|
251
|
+
import path4 from "path";
|
|
252
|
+
import { readdir as readdir2 } from "fs/promises";
|
|
253
|
+
import { existsSync as existsSync2 } from "fs";
|
|
254
|
+
var FUNCTION_ID_RE = /^[a-z][a-z0-9]*(?:[.-][a-z][a-z0-9]*)*$/;
|
|
255
|
+
async function scanFunctions(root) {
|
|
256
|
+
const dir = path4.join(root, "apps", "server", "src", "functions");
|
|
257
|
+
if (!existsSync2(dir)) return [];
|
|
258
|
+
for (const entry of await readdir2(dir, { withFileTypes: true })) {
|
|
259
|
+
if (entry.isDirectory()) {
|
|
260
|
+
throw new AppBuildError("FUNCTION_NESTED_DIR", `函数目录不支持子目录: ${path4.join(dir, entry.name)}`, {
|
|
261
|
+
file: path4.join(dir, entry.name)
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const files = (await listFiles(dir)).filter((file) => file.endsWith(".server.ts"));
|
|
266
|
+
const out = [];
|
|
267
|
+
const seen = /* @__PURE__ */ new Set();
|
|
268
|
+
for (const file of files.sort()) {
|
|
269
|
+
const base = path4.basename(file, ".server.ts");
|
|
270
|
+
if (!FUNCTION_ID_RE.test(base)) {
|
|
271
|
+
throw new AppBuildError("FUNCTION_ID_INVALID", `函数 ID 不合法: ${base}`, { file });
|
|
272
|
+
}
|
|
273
|
+
if (seen.has(base)) throw new AppBuildError("FUNCTION_DUPLICATE", `函数 ID 重复: ${base}`, { file });
|
|
274
|
+
seen.add(base);
|
|
275
|
+
const sf = parseSource(file, await readText(file));
|
|
276
|
+
if (!hasDefaultExport(sf)) {
|
|
277
|
+
throw new AppBuildError("FUNCTION_DEFAULT_MISSING", `函数必须 default export: ${base}`, { file });
|
|
278
|
+
}
|
|
279
|
+
out.push({ id: base, file, relativeFile: path4.relative(root, file).split(path4.sep).join("/") });
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/primitives.ts
|
|
285
|
+
import path5 from "path";
|
|
286
|
+
import { existsSync as existsSync3 } from "fs";
|
|
287
|
+
async function readExported(file, name) {
|
|
288
|
+
const source = parseSource(file, await readText(file));
|
|
289
|
+
const expr = findExportedVariable(source, name);
|
|
290
|
+
if (!expr) {
|
|
291
|
+
const code = name === "card" ? "CARD_EXPORT_MISSING" : `${name.toUpperCase()}_EXPORT_MISSING`;
|
|
292
|
+
throw new AppBuildError(code, `${path5.basename(file)} 必须 export const ${name}`, { file });
|
|
293
|
+
}
|
|
294
|
+
return { file, source, expr };
|
|
295
|
+
}
|
|
296
|
+
async function scanToolDir(dir) {
|
|
297
|
+
if (!existsSync3(dir)) return [];
|
|
298
|
+
const files = (await listFiles(dir)).filter((file) => file.endsWith(".tool.ts"));
|
|
299
|
+
const out = [];
|
|
300
|
+
for (const file of files.sort()) {
|
|
301
|
+
const { expr } = await readExported(file, "tool");
|
|
302
|
+
const id = stringProperty(expr, "id", `tool (${path5.basename(file)})`);
|
|
303
|
+
out.push({ id, file, relativeFile: path5.relative(dir, file).split(path5.sep).join("/") });
|
|
304
|
+
}
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
async function scanSkillDir(dir) {
|
|
308
|
+
if (!existsSync3(dir)) return [];
|
|
309
|
+
const files = (await listFiles(dir)).filter((file) => file.endsWith(".skill.ts"));
|
|
310
|
+
const out = [];
|
|
311
|
+
for (const file of files.sort()) {
|
|
312
|
+
const { expr } = await readExported(file, "skill");
|
|
313
|
+
const id = stringProperty(expr, "id", `skill (${path5.basename(file)})`);
|
|
314
|
+
out.push({ id, file, relativeFile: path5.relative(dir, file).split(path5.sep).join("/") });
|
|
315
|
+
}
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
async function scanCardDirs(serverDir, clientDir) {
|
|
319
|
+
if (!existsSync3(serverDir) && !existsSync3(clientDir)) return [];
|
|
320
|
+
const server = /* @__PURE__ */ new Map();
|
|
321
|
+
const client = /* @__PURE__ */ new Map();
|
|
322
|
+
for (const file of (await listFiles(serverDir)).filter((f) => f.endsWith(".card.ts"))) {
|
|
323
|
+
server.set(path5.basename(file, ".card.ts"), file);
|
|
324
|
+
}
|
|
325
|
+
for (const file of (await listFiles(clientDir)).filter((f) => f.endsWith(".card.tsx"))) {
|
|
326
|
+
client.set(path5.basename(file, ".card.tsx"), file);
|
|
327
|
+
}
|
|
328
|
+
const bases = /* @__PURE__ */ new Set([...server.keys(), ...client.keys()]);
|
|
329
|
+
const out = [];
|
|
330
|
+
for (const base of [...bases].sort()) {
|
|
331
|
+
const serverFile = server.get(base);
|
|
332
|
+
const clientFile = client.get(base);
|
|
333
|
+
if (!serverFile || !clientFile) {
|
|
334
|
+
throw new AppBuildError("CARD_PAIR_MISSING", `卡片 ${base} 必须在 server/client 双端成对存在`, {
|
|
335
|
+
file: serverFile ?? clientFile
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
const { expr: serverExpr } = await readExported(serverFile, "card");
|
|
339
|
+
const { expr: clientExpr } = await readExported(clientFile, "card");
|
|
340
|
+
const cardType = stringProperty(serverExpr, "cardType", `card (${base})`);
|
|
341
|
+
const clientType = stringProperty(clientExpr, "type", `card (${base})`);
|
|
342
|
+
if (cardType !== clientType) {
|
|
343
|
+
throw new AppBuildError("CARD_TYPE_MISMATCH", `卡片 ${base} 双端类型不一致: ${cardType} !== ${clientType}`, {
|
|
344
|
+
file: clientFile
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
out.push({
|
|
348
|
+
cardType,
|
|
349
|
+
serverFile,
|
|
350
|
+
clientFile,
|
|
351
|
+
serverRelativeFile: path5.relative(serverDir, serverFile).split(path5.sep).join("/"),
|
|
352
|
+
clientRelativeFile: path5.relative(clientDir, clientFile).split(path5.sep).join("/")
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
return out;
|
|
356
|
+
}
|
|
357
|
+
async function scanAppPrimitives(root) {
|
|
358
|
+
const appDir = path5.join(root, "apps");
|
|
359
|
+
return {
|
|
360
|
+
tools: await scanToolDir(path5.join(appDir, "server", "src", "tools")),
|
|
361
|
+
skills: await scanSkillDir(path5.join(appDir, "server", "src", "skills")),
|
|
362
|
+
cards: await scanCardDirs(path5.join(appDir, "server", "src", "cards"), path5.join(appDir, "client", "src", "cards"))
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
async function scanModulePrimitives(moduleDir) {
|
|
366
|
+
return {
|
|
367
|
+
tools: await scanToolDir(path5.join(moduleDir, "src", "server", "tools")),
|
|
368
|
+
skills: await scanSkillDir(path5.join(moduleDir, "src", "server", "skills")),
|
|
369
|
+
cards: await scanCardDirs(path5.join(moduleDir, "src", "server", "cards"), path5.join(moduleDir, "src", "client", "cards"))
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function assertUnique(items, code, label) {
|
|
373
|
+
const seen = /* @__PURE__ */ new Set();
|
|
374
|
+
for (const item of items) {
|
|
375
|
+
const key = item.id ?? item.cardType;
|
|
376
|
+
if (!key) continue;
|
|
377
|
+
if (seen.has(key)) throw new AppBuildError(code, `${label} 重复: ${key}`);
|
|
378
|
+
seen.add(key);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// src/modules.ts
|
|
383
|
+
import path6 from "path";
|
|
384
|
+
import { existsSync as existsSync4 } from "fs";
|
|
385
|
+
import { readdir as readdir3, stat } from "fs/promises";
|
|
386
|
+
function asStringArray(value, label) {
|
|
387
|
+
if (value === void 0) return [];
|
|
388
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
|
|
389
|
+
throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `${label} 必须是字符串数组`);
|
|
390
|
+
}
|
|
391
|
+
return value;
|
|
392
|
+
}
|
|
393
|
+
function asCardIdArray(value, label) {
|
|
394
|
+
if (value === void 0) return [];
|
|
395
|
+
if (!Array.isArray(value)) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `${label} 必须是数组`);
|
|
396
|
+
return value.map((item) => {
|
|
397
|
+
if (typeof item === "string") return item;
|
|
398
|
+
if (item && typeof item === "object" && typeof item.cardType === "string") {
|
|
399
|
+
return item.cardType;
|
|
400
|
+
}
|
|
401
|
+
throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `${label} 项必须是字符串或 { cardType }`);
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
function asDependencyIdArray(value, label) {
|
|
405
|
+
if (value === void 0) return [];
|
|
406
|
+
if (!Array.isArray(value)) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `${label} 必须是数组`);
|
|
407
|
+
return value.map((item) => {
|
|
408
|
+
if (typeof item === "string") return item;
|
|
409
|
+
if (item && typeof item === "object" && typeof item.id === "string") {
|
|
410
|
+
return item.id;
|
|
411
|
+
}
|
|
412
|
+
throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `${label} 项必须是字符串或 { id }`);
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
function moduleDependencyIds(descriptor) {
|
|
416
|
+
return asDependencyIdArray(descriptor.dependencies?.modules, "dependencies.modules");
|
|
417
|
+
}
|
|
418
|
+
function validateDescriptor(raw, dir) {
|
|
419
|
+
if (!raw || typeof raw !== "object") throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 必须是对象: ${dir}`);
|
|
420
|
+
const value = raw;
|
|
421
|
+
if (value.schemaVersion !== 1) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json schemaVersion 必须为 1: ${dir}`);
|
|
422
|
+
if (typeof value.id !== "string" || !value.id) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 id: ${dir}`);
|
|
423
|
+
if (typeof value.version !== "string" || !value.version) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 version: ${dir}`);
|
|
424
|
+
const dirName = path6.basename(dir);
|
|
425
|
+
if (value.id !== dirName) throw new AppBuildError("MODULE_ID_MISMATCH", `模块 id "${value.id}" 必须等于目录名 "${dirName}"`, { file: path6.join(dir, "tbox.module.json") });
|
|
426
|
+
if (!value.declare || typeof value.declare !== "object") throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 declare: ${dir}`);
|
|
427
|
+
const declare = value.declare;
|
|
428
|
+
asStringArray(declare.tools, "declare.tools");
|
|
429
|
+
asCardIdArray(declare.cards, "declare.cards");
|
|
430
|
+
asStringArray(declare.skills, "declare.skills");
|
|
431
|
+
if (declare.providers !== void 0 && (typeof declare.providers !== "object" || declare.providers === null)) {
|
|
432
|
+
throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `declare.providers 必须是对象: ${dir}`);
|
|
433
|
+
}
|
|
434
|
+
const dependencies = value.dependencies;
|
|
435
|
+
if (dependencies !== void 0) {
|
|
436
|
+
if (typeof dependencies !== "object" || dependencies === null) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `dependencies 必须是对象: ${dir}`);
|
|
437
|
+
asDependencyIdArray(dependencies.modules, "dependencies.modules");
|
|
438
|
+
asStringArray(dependencies.packages, "dependencies.packages");
|
|
439
|
+
}
|
|
440
|
+
asStringArray(value.env, "env");
|
|
441
|
+
return value;
|
|
442
|
+
}
|
|
443
|
+
function appKindsFromPackage(pkg) {
|
|
444
|
+
const tbox = pkg?.tbox;
|
|
445
|
+
if (!tbox || typeof tbox !== "object") return ["agent", "web"];
|
|
446
|
+
const appKinds = tbox.appKinds;
|
|
447
|
+
if (appKinds === void 0) return ["agent", "web"];
|
|
448
|
+
if (!Array.isArray(appKinds) || appKinds.some((item) => item !== "agent" && item !== "web")) {
|
|
449
|
+
throw new AppBuildError("MODULE_APPKIND_INVALID", 'package.json tbox.appKinds 必须只包含 "agent" / "web"');
|
|
450
|
+
}
|
|
451
|
+
return appKinds;
|
|
452
|
+
}
|
|
453
|
+
function isPackageDependency(root, descriptor, dep) {
|
|
454
|
+
if (descriptor.dependencies?.packages?.includes(dep)) return true;
|
|
455
|
+
return [path6.join(root, "apps", dep), path6.join(root, "packages", dep)].some((dir) => existsSync4(path6.join(dir, "package.json")));
|
|
456
|
+
}
|
|
457
|
+
async function scanModules(root) {
|
|
458
|
+
const modulesDir = path6.join(root, "modules");
|
|
459
|
+
if (!existsSync4(modulesDir)) return [];
|
|
460
|
+
const entries = await readdir3(modulesDir, { withFileTypes: true });
|
|
461
|
+
const modules = [];
|
|
462
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
463
|
+
const dir = path6.join(modulesDir, entry.name);
|
|
464
|
+
if (!(await stat(dir)).isDirectory()) continue;
|
|
465
|
+
const descriptorFile = path6.join(dir, "tbox.module.json");
|
|
466
|
+
if (!existsSync4(descriptorFile)) continue;
|
|
467
|
+
const descriptor = validateDescriptor(await readJson(descriptorFile), dir);
|
|
468
|
+
const packageFile = path6.join(dir, "package.json");
|
|
469
|
+
const vendored = existsSync4(packageFile);
|
|
470
|
+
const pkg = vendored ? await readJson(packageFile) : void 0;
|
|
471
|
+
const hasServer = existsSync4(path6.join(dir, "src/server/index.ts"));
|
|
472
|
+
const hasClient = existsSync4(path6.join(dir, "src/client/index.ts"));
|
|
473
|
+
if (!hasServer && !hasClient) {
|
|
474
|
+
throw new AppBuildError("MODULE_ENTRY_MISSING", `模块 "${descriptor.id}" 缺 src/server/index.ts 与 src/client/index.ts`, { file: descriptorFile });
|
|
475
|
+
}
|
|
476
|
+
modules.push({
|
|
477
|
+
id: descriptor.id,
|
|
478
|
+
dir,
|
|
479
|
+
relativeDir: path6.relative(root, dir).split(path6.sep).join("/"),
|
|
480
|
+
descriptor,
|
|
481
|
+
packageName: typeof pkg?.name === "string" ? pkg.name : void 0,
|
|
482
|
+
vendored,
|
|
483
|
+
appKinds: appKindsFromPackage(pkg),
|
|
484
|
+
hasServer,
|
|
485
|
+
hasClient
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
return sortModules(root, modules);
|
|
489
|
+
}
|
|
490
|
+
function sortModules(root, modules) {
|
|
491
|
+
const byId = new Map(modules.map((module) => [module.id, module]));
|
|
492
|
+
for (const module of modules) {
|
|
493
|
+
for (const dep of moduleDependencyIds(module.descriptor)) {
|
|
494
|
+
if (byId.has(dep)) continue;
|
|
495
|
+
if (isPackageDependency(root, module.descriptor, dep)) continue;
|
|
496
|
+
throw new AppBuildError("MODULE_DEPENDENCY_MISSING", `模块 "${module.id}" 依赖不存在模块 "${dep}"`, {
|
|
497
|
+
file: path6.join(module.dir, "tbox.module.json")
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
502
|
+
const visited = /* @__PURE__ */ new Set();
|
|
503
|
+
const out = [];
|
|
504
|
+
function visit(module) {
|
|
505
|
+
if (visited.has(module.id)) return;
|
|
506
|
+
if (visiting.has(module.id)) {
|
|
507
|
+
throw new AppBuildError("MODULE_DEPENDENCY_CYCLE", `模块依赖成环: ${module.id}`, { file: path6.join(module.dir, "tbox.module.json") });
|
|
508
|
+
}
|
|
509
|
+
visiting.add(module.id);
|
|
510
|
+
for (const dep of moduleDependencyIds(module.descriptor)) {
|
|
511
|
+
const target = byId.get(dep);
|
|
512
|
+
if (target) visit(target);
|
|
513
|
+
}
|
|
514
|
+
visiting.delete(module.id);
|
|
515
|
+
visited.add(module.id);
|
|
516
|
+
out.push(module);
|
|
517
|
+
}
|
|
518
|
+
for (const module of [...modules].sort((a, b) => a.id.localeCompare(b.id))) visit(module);
|
|
519
|
+
return out;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// src/layout.ts
|
|
523
|
+
var APPS_DIR = "apps";
|
|
524
|
+
var CLIENT_DIR = "apps/client";
|
|
525
|
+
var SERVER_DIR = "apps/server";
|
|
526
|
+
var SHELL_FILE = "apps/client/index.html";
|
|
527
|
+
var CARD_PREVIEW_PAGE_FILE = "apps/client/src/platform/card-preview-page.tsx";
|
|
528
|
+
|
|
529
|
+
// src/scan.ts
|
|
530
|
+
async function scanApp(root) {
|
|
531
|
+
const absoluteRoot = path7.resolve(root);
|
|
532
|
+
const appDir = path7.join(absoluteRoot, APPS_DIR);
|
|
533
|
+
const meta = await readAppMeta(absoluteRoot);
|
|
534
|
+
const pages = await scanPages(absoluteRoot);
|
|
535
|
+
const functions = await scanFunctions(absoluteRoot);
|
|
536
|
+
const primitives = await scanAppPrimitives(absoluteRoot);
|
|
537
|
+
const modules = await scanModules(absoluteRoot);
|
|
538
|
+
assertUnique(primitives.tools, "TOOL_ID_DUPLICATE", "工具 ID");
|
|
539
|
+
assertUnique(primitives.skills, "SKILL_ID_DUPLICATE", "技能 ID");
|
|
540
|
+
assertUnique(primitives.cards, "CARD_TYPE_DUPLICATE", "卡片类型");
|
|
541
|
+
if (meta.appKind === "web") {
|
|
542
|
+
const hasAgentSurface = primitives.tools.length > 0 || primitives.skills.length > 0 || primitives.cards.length > 0;
|
|
543
|
+
if (hasAgentSurface) {
|
|
544
|
+
throw new AppBuildError("WEB_AGENT_SURFACE", "web 应用不得包含 tools / skills / cards", { file: appDir });
|
|
545
|
+
}
|
|
546
|
+
for (const module of modules) {
|
|
547
|
+
const declare = module.descriptor.declare;
|
|
548
|
+
const hasAgentSurface2 = (declare.tools?.length ?? 0) > 0 || (declare.skills?.length ?? 0) > 0 || (declare.cards?.length ?? 0) > 0;
|
|
549
|
+
if (hasAgentSurface2) {
|
|
550
|
+
throw new AppBuildError("WEB_AGENT_SURFACE", `web 应用不得装配 agent 模块 "${module.id}"`, { file: module.dir });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
for (const module of modules) {
|
|
555
|
+
if (!module.appKinds.includes(meta.appKind)) {
|
|
556
|
+
throw new AppBuildError("MODULE_APPKIND_VIOLATION", `模块 "${module.id}" 不支持 appKind "${meta.appKind}"`, { file: path7.join(module.dir, "package.json") });
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
const npmModules = Array.isArray(meta.npmModules) ? meta.npmModules : [];
|
|
560
|
+
for (const item of npmModules) {
|
|
561
|
+
const id = typeof item === "string" ? item : item?.id ?? item?.package;
|
|
562
|
+
if (id === "agent-ui-kit" || id === "@tbox.cn/app-agent-ui-kit" || id === "@app/agent-ui-kit") {
|
|
563
|
+
throw new AppBuildError("AGENT_UI_KIT_AS_MODULE", "agent-ui-kit 必须是普通 workspace 包,不得出现在 .tbox/app.json npmModules", {
|
|
564
|
+
file: path7.join(absoluteRoot, ".tbox", "app.json")
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
root: absoluteRoot,
|
|
570
|
+
appDir,
|
|
571
|
+
appKind: meta.appKind,
|
|
572
|
+
pages,
|
|
573
|
+
functions,
|
|
574
|
+
tools: primitives.tools,
|
|
575
|
+
skills: primitives.skills,
|
|
576
|
+
cards: primitives.cards,
|
|
577
|
+
modules
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// src/generate.ts
|
|
582
|
+
import path8 from "path";
|
|
583
|
+
import { existsSync as existsSync5 } from "fs";
|
|
584
|
+
import { watch as fsWatch } from "fs";
|
|
585
|
+
function pageDocument(route) {
|
|
586
|
+
if (route === "/") return "index.html";
|
|
587
|
+
if (route === "/_tbox/card-preview") return "_tbox/card-preview.html";
|
|
588
|
+
return `${route.slice(1)}/index.html`;
|
|
589
|
+
}
|
|
590
|
+
function pageRank(route) {
|
|
591
|
+
if (route === "/") return 0;
|
|
592
|
+
if (route === "/_tbox/card-preview") return 2;
|
|
593
|
+
return 1;
|
|
594
|
+
}
|
|
595
|
+
function buildManifest(scan) {
|
|
596
|
+
const pages = scan.pages.map((page) => ({
|
|
597
|
+
path: page.route,
|
|
598
|
+
entry: `/.tbox-gen/entries/${page.id}.tsx`,
|
|
599
|
+
document: pageDocument(page.route),
|
|
600
|
+
title: page.meta.title
|
|
601
|
+
}));
|
|
602
|
+
if (scan.appKind === "agent") {
|
|
603
|
+
pages.push({
|
|
604
|
+
path: "/_tbox/card-preview",
|
|
605
|
+
entry: "/.tbox-gen/entries/card-preview.tsx",
|
|
606
|
+
document: "_tbox/card-preview.html",
|
|
607
|
+
title: "卡片预览"
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
pages.sort((a, b) => pageRank(a.path) - pageRank(b.path) || a.path.localeCompare(b.path));
|
|
611
|
+
return { schemaVersion: 1, pages };
|
|
612
|
+
}
|
|
613
|
+
function escapeHtml(value) {
|
|
614
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
615
|
+
}
|
|
616
|
+
function renderDocument(shell, title, meta, entrySrc) {
|
|
617
|
+
let html = shell;
|
|
618
|
+
if (!/<head[^>]*>/i.test(html)) throw new AppBuildError("APP_INDEX_INVALID", "apps/client/index.html 缺少 <head>");
|
|
619
|
+
if (!/<body[^>]*>/i.test(html)) throw new AppBuildError("APP_INDEX_INVALID", "apps/client/index.html 缺少 <body>");
|
|
620
|
+
const titleTag = `<title>${escapeHtml(title)}</title>`;
|
|
621
|
+
html = /<title[^>]*>[\s\S]*?<\/title>/i.test(html) ? html.replace(/<title[^>]*>[\s\S]*?<\/title>/i, titleTag) : html.replace(/<\/head>/i, ` ${titleTag}
|
|
622
|
+
</head>`);
|
|
623
|
+
if (meta) {
|
|
624
|
+
const tags = Object.entries(meta).filter(([, value]) => typeof value === "string" || typeof value === "number" || typeof value === "boolean").map(([key, value]) => ` <meta name="${escapeHtml(key)}" content="${escapeHtml(String(value))}" />`).join("\n");
|
|
625
|
+
if (tags) html = html.replace(/<\/head>/i, `${tags}
|
|
626
|
+
</head>`);
|
|
627
|
+
}
|
|
628
|
+
if (!html.includes("</body>")) throw new AppBuildError("APP_INDEX_INVALID", "apps/client/index.html 缺少 </body>");
|
|
629
|
+
const scripts = html.match(/<script\b[^>]*\bsrc=["'][^"']*["'][^>]*><\/script>/gi) ?? [];
|
|
630
|
+
for (const tag of scripts) {
|
|
631
|
+
if (!tag.includes("__vs_inspector__.js")) {
|
|
632
|
+
throw new AppBuildError("APP_INDEX_INVALID", "apps/client/index.html 不得包含页面入口脚本——由 app-build 注入");
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
html = html.replace(/\s*<script\b[^>]*\bsrc=["'][^"']*__vs_inspector__\.js["'][^>]*><\/script>/gi, "");
|
|
636
|
+
html = html.replace(/<\/body>/i, ` <script type="module" src="${escapeHtml(entrySrc)}"></script>
|
|
637
|
+
</body>`);
|
|
638
|
+
return html;
|
|
639
|
+
}
|
|
640
|
+
function buildServerRegistry(genDir, scan) {
|
|
641
|
+
const file = path8.join(genDir, "registry.server.ts");
|
|
642
|
+
const lines = ["// @generated by @tbox.cn/app-build; do not edit."];
|
|
643
|
+
const serverModules = scan.modules.filter((mod) => mod.hasServer);
|
|
644
|
+
scan.functions.forEach((fn, i) => lines.push(`import fn${i} from '${relativePosix(file, fn.file)}';`));
|
|
645
|
+
scan.tools.forEach((tool, i) => lines.push(`import { tool as tool${i} } from '${relativePosix(file, tool.file)}';`));
|
|
646
|
+
scan.skills.forEach((skill, i) => lines.push(`import { skill as skill${i} } from '${relativePosix(file, skill.file)}';`));
|
|
647
|
+
scan.cards.forEach((card, i) => lines.push(`import { card as card${i} } from '${relativePosix(file, card.serverFile)}';`));
|
|
648
|
+
serverModules.forEach((mod, i) => lines.push(`import { serverModule as module${i} } from '${relativePosix(file, path8.join(mod.dir, "src/server/index.ts"))}';`));
|
|
649
|
+
lines.push("");
|
|
650
|
+
lines.push("export const functions = {");
|
|
651
|
+
scan.functions.forEach((fn, i) => lines.push(` '${fn.id}': fn${i},`));
|
|
652
|
+
lines.push("};");
|
|
653
|
+
lines.push("");
|
|
654
|
+
lines.push(`export const tools = [${scan.tools.map((_, i) => `tool${i}`).join(", ")}];`);
|
|
655
|
+
lines.push(`export const skills = [${scan.skills.map((_, i) => `skill${i}`).join(", ")}];`);
|
|
656
|
+
lines.push("export const cards = {");
|
|
657
|
+
scan.cards.forEach((card, i) => lines.push(` '${card.cardType}': card${i},`));
|
|
658
|
+
lines.push("};");
|
|
659
|
+
lines.push(`export const modules = [${serverModules.map((_, i) => `module${i}`).join(", ")}];`);
|
|
660
|
+
lines.push("");
|
|
661
|
+
lines.push("export const registry = { functions, tools, skills, cards, modules };");
|
|
662
|
+
lines.push("");
|
|
663
|
+
return lines.join("\n");
|
|
664
|
+
}
|
|
665
|
+
function buildClientRegistry(genDir, scan) {
|
|
666
|
+
const file = path8.join(genDir, "registry.client.ts");
|
|
667
|
+
const lines = ["// @generated by @tbox.cn/app-build; do not edit."];
|
|
668
|
+
const clientModules = scan.modules.filter((mod) => mod.hasClient);
|
|
669
|
+
scan.cards.forEach((card, i) => lines.push(`import { card as card${i} } from '${relativePosix(file, card.clientFile)}';`));
|
|
670
|
+
clientModules.forEach((mod, i) => lines.push(`import { clientModule as module${i} } from '${relativePosix(file, path8.join(mod.dir, "src/client/index.ts"))}';`));
|
|
671
|
+
lines.push("");
|
|
672
|
+
lines.push("export const cards = {");
|
|
673
|
+
scan.cards.forEach((card, i) => lines.push(` '${card.cardType}': card${i},`));
|
|
674
|
+
lines.push("};");
|
|
675
|
+
lines.push("");
|
|
676
|
+
lines.push(`export const modules = [${clientModules.map((_, i) => `module${i}`).join(", ")}];`);
|
|
677
|
+
lines.push("");
|
|
678
|
+
return lines.join("\n");
|
|
679
|
+
}
|
|
680
|
+
function buildEntry(genDir, scan, pageId2, pageFile, cardPreview = false) {
|
|
681
|
+
const file = path8.join(genDir, "entries", `${pageId2}.tsx`);
|
|
682
|
+
const pageImport = relativePosix(file, pageFile);
|
|
683
|
+
const mountImport = relativePosix(file, path8.join(scan.root, "apps", "client", "src", "platform", "mount-page.tsx"));
|
|
684
|
+
const registryImport = relativePosix(file, path8.join(genDir, "registry.client.ts"));
|
|
685
|
+
const mountCall = cardPreview ? "mountPage(Page, { shell: false });" : "mountPage(Page);";
|
|
686
|
+
return [
|
|
687
|
+
"// @generated by @tbox.cn/app-build; do not edit.",
|
|
688
|
+
"import { registerClientModules, registerClientCards } from '@tbox.cn/app-sdk-client';",
|
|
689
|
+
`import { modules, cards } from '${registryImport}';`,
|
|
690
|
+
`import { mountPage } from '${mountImport}';`,
|
|
691
|
+
"",
|
|
692
|
+
"registerClientCards(cards);",
|
|
693
|
+
"",
|
|
694
|
+
"async function start() {",
|
|
695
|
+
" try {",
|
|
696
|
+
" await registerClientModules(modules);",
|
|
697
|
+
` const { default: Page } = await import('${pageImport}');`,
|
|
698
|
+
` ${mountCall}`,
|
|
699
|
+
" } catch (error) {",
|
|
700
|
+
" console.error('[app-build] page bootstrap failed', error);",
|
|
701
|
+
" }",
|
|
702
|
+
"}",
|
|
703
|
+
"",
|
|
704
|
+
"void start();",
|
|
705
|
+
""
|
|
706
|
+
].join("\n");
|
|
707
|
+
}
|
|
708
|
+
async function generateCore(root, shell, scan) {
|
|
709
|
+
const genDir = path8.join(root, "apps", "client", ".tbox-gen");
|
|
710
|
+
const files = [];
|
|
711
|
+
const write = async (file, text) => {
|
|
712
|
+
await writeTextIfChanged(file, text);
|
|
713
|
+
files.push(file);
|
|
714
|
+
};
|
|
715
|
+
const manifest = buildManifest(scan);
|
|
716
|
+
await write(path8.join(genDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
|
|
717
|
+
`);
|
|
718
|
+
await write(path8.join(genDir, "app-kind.ts"), `export const appKind = '${scan.appKind}' as const;
|
|
719
|
+
`);
|
|
720
|
+
await write(path8.join(genDir, "registry.server.ts"), buildServerRegistry(genDir, scan));
|
|
721
|
+
await write(path8.join(genDir, "registry.client.ts"), buildClientRegistry(genDir, scan));
|
|
722
|
+
for (const page of scan.pages) {
|
|
723
|
+
await write(path8.join(genDir, "entries", `${page.id}.tsx`), buildEntry(genDir, scan, page.id, page.file));
|
|
724
|
+
const doc = renderDocument(shell, page.meta.title, page.meta.meta, `/.tbox-gen/entries/${page.id}.tsx`);
|
|
725
|
+
await write(path8.join(genDir, "documents", pageDocument(page.route)), doc);
|
|
726
|
+
}
|
|
727
|
+
if (scan.appKind === "agent") {
|
|
728
|
+
const pageFile = path8.join(root, "apps", "client", "src", "platform", "card-preview-page.tsx");
|
|
729
|
+
if (!existsSync5(pageFile)) {
|
|
730
|
+
throw new AppBuildError("CARD_PREVIEW_PAGE_MISSING", "agent 应用缺少 apps/client/src/platform/card-preview-page.tsx", { file: pageFile });
|
|
731
|
+
}
|
|
732
|
+
await write(path8.join(genDir, "entries", "card-preview.tsx"), buildEntry(genDir, scan, "card-preview", pageFile, true));
|
|
733
|
+
const doc = renderDocument(shell, "卡片预览", void 0, "/.tbox-gen/entries/card-preview.tsx");
|
|
734
|
+
await write(path8.join(genDir, "documents", "_tbox/card-preview.html"), doc);
|
|
735
|
+
}
|
|
736
|
+
const generated = new Set(files.map((file) => path8.resolve(file)));
|
|
737
|
+
for (const file of await listFiles(genDir)) {
|
|
738
|
+
if (!generated.has(path8.resolve(file))) await removeFile(file);
|
|
739
|
+
}
|
|
740
|
+
return { files, manifest };
|
|
741
|
+
}
|
|
742
|
+
async function generateApp(options) {
|
|
743
|
+
const root = path8.resolve(options.root);
|
|
744
|
+
const shellFile = path8.join(root, "apps", "client", "index.html");
|
|
745
|
+
if (!existsSync5(shellFile)) throw new AppBuildError("APP_INDEX_MISSING", "缺少 apps/client/index.html", { file: shellFile });
|
|
746
|
+
let shell = await readText(shellFile);
|
|
747
|
+
let scan = await scanApp(root);
|
|
748
|
+
let core = await generateCore(root, shell, scan);
|
|
749
|
+
options.onManifest?.(core.manifest);
|
|
750
|
+
let watcher;
|
|
751
|
+
let timer;
|
|
752
|
+
let closed = false;
|
|
753
|
+
let running = false;
|
|
754
|
+
const regenerate = async () => {
|
|
755
|
+
if (running || closed) return;
|
|
756
|
+
running = true;
|
|
757
|
+
try {
|
|
758
|
+
shell = await readText(shellFile);
|
|
759
|
+
scan = await scanApp(root);
|
|
760
|
+
core = await generateCore(root, shell, scan);
|
|
761
|
+
options.onManifest?.(core.manifest);
|
|
762
|
+
} catch (error) {
|
|
763
|
+
options.onError?.(error);
|
|
764
|
+
} finally {
|
|
765
|
+
running = false;
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
if (options.watch) {
|
|
769
|
+
watcher = fsWatch(root, { recursive: true }, (_event, filename) => {
|
|
770
|
+
const name = filename?.toString().split(path8.sep).join("/") ?? "";
|
|
771
|
+
if (!name) return;
|
|
772
|
+
if (name.startsWith("apps/client/.tbox-gen/") || name.startsWith("node_modules/") || name.startsWith(".git/")) return;
|
|
773
|
+
const relevant = name === ".tbox/app.json" || name === "apps/client/index.html" || name.startsWith("apps/client/src/pages/") || name.startsWith("apps/server/src/") || name.startsWith("modules/");
|
|
774
|
+
if (!relevant) return;
|
|
775
|
+
if (timer) clearTimeout(timer);
|
|
776
|
+
timer = setTimeout(() => void regenerate(), 50);
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
return {
|
|
780
|
+
get manifest() {
|
|
781
|
+
return core.manifest;
|
|
782
|
+
},
|
|
783
|
+
get files() {
|
|
784
|
+
return core.files;
|
|
785
|
+
},
|
|
786
|
+
get scan() {
|
|
787
|
+
return scan;
|
|
788
|
+
},
|
|
789
|
+
appKind: scan.appKind,
|
|
790
|
+
close: async () => {
|
|
791
|
+
closed = true;
|
|
792
|
+
if (timer) clearTimeout(timer);
|
|
793
|
+
watcher?.close();
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
async function listGeneratedFiles(root) {
|
|
798
|
+
return listFiles(path8.join(path8.resolve(root), "apps", "client", ".tbox-gen"));
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// src/check.ts
|
|
802
|
+
import path9 from "path";
|
|
803
|
+
import { existsSync as existsSync6 } from "fs";
|
|
804
|
+
async function checkApp(options) {
|
|
805
|
+
const root = path9.resolve(options.root);
|
|
806
|
+
const issues = [];
|
|
807
|
+
const forbidden = [
|
|
808
|
+
["app", "APP_ROOT_FORBIDDEN"],
|
|
809
|
+
["apps/shared", "APP_SHARED_FORBIDDEN"],
|
|
810
|
+
["apps/client/src/business/routes.json", "ROUTES_JSON_FORBIDDEN"],
|
|
811
|
+
["apps/server/src/business/routes.json", "ROUTES_JSON_FORBIDDEN"],
|
|
812
|
+
["routes.json", "ROUTES_JSON_FORBIDDEN"],
|
|
813
|
+
["tbox.config", "TBOX_CONFIG_FORBIDDEN"],
|
|
814
|
+
["tbox.config.ts", "TBOX_CONFIG_FORBIDDEN"],
|
|
815
|
+
["apps/client/src/modules.ts", "MODULES_TS_FORBIDDEN"],
|
|
816
|
+
["apps/server/src/modules.ts", "MODULES_TS_FORBIDDEN"]
|
|
817
|
+
];
|
|
818
|
+
for (const [relative, code] of forbidden) {
|
|
819
|
+
if (existsSync6(path9.join(root, relative))) {
|
|
820
|
+
issues.push({ code, severity: "error", file: path9.join(root, relative), message: `1.0 不允许 ${relative}` });
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
const sharedPackage = path9.join(root, "packages", "shared", "package.json");
|
|
824
|
+
if (!existsSync6(sharedPackage)) {
|
|
825
|
+
issues.push({
|
|
826
|
+
code: "SHARED_PACKAGE_MISSING",
|
|
827
|
+
severity: "warning",
|
|
828
|
+
file: sharedPackage,
|
|
829
|
+
message: "缺少 packages/shared(1.0 模板应预创建跨端 DTO 包)",
|
|
830
|
+
fix: "创建 packages/shared,包名 @app/shared,并让 client/server 通过 file: 或 workspace: 依赖"
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
if (!existsSync6(path9.join(root, SHELL_FILE))) {
|
|
834
|
+
issues.push({ code: "APP_INDEX_MISSING", severity: "error", file: path9.join(root, SHELL_FILE), message: `缺少 ${SHELL_FILE}` });
|
|
835
|
+
}
|
|
836
|
+
try {
|
|
837
|
+
const meta = await readAppMeta(root);
|
|
838
|
+
if (meta.appKind === "agent") {
|
|
839
|
+
const preview = path9.join(root, CARD_PREVIEW_PAGE_FILE);
|
|
840
|
+
if (!existsSync6(preview)) {
|
|
841
|
+
issues.push({ code: "CARD_PREVIEW_PAGE_MISSING", severity: "error", file: preview, message: `agent 应用缺少 ${CARD_PREVIEW_PAGE_FILE}` });
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
} catch {
|
|
845
|
+
}
|
|
846
|
+
const pagesDir = path9.join(root, CLIENT_DIR, "src", "pages");
|
|
847
|
+
for (const file of await listFiles(pagesDir)) {
|
|
848
|
+
const name = path9.basename(file);
|
|
849
|
+
if (name.startsWith("page.config") || name === "routes.json") {
|
|
850
|
+
issues.push({ code: "PAGE_CONFIG_FORBIDDEN", severity: "error", file, message: "页面元数据必须 inline export const page;不允许 page.config / routes.json" });
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
if (!existsSync6(path9.join(root, SERVER_DIR, "package.json"))) {
|
|
854
|
+
issues.push({ code: "APP_SERVER_MISSING", severity: "error", file: path9.join(root, SERVER_DIR), message: `缺少 ${SERVER_DIR}/package.json` });
|
|
855
|
+
}
|
|
856
|
+
try {
|
|
857
|
+
await scanApp(root);
|
|
858
|
+
} catch (error) {
|
|
859
|
+
if (error instanceof AppBuildError) {
|
|
860
|
+
issues.push({ code: error.code, severity: "error", file: error.file, message: error.message, fix: error.fix });
|
|
861
|
+
} else {
|
|
862
|
+
issues.push({ code: "CHECK_FAILED", severity: "error", message: error.message });
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
return { ok: issues.every((issue) => issue.severity !== "error"), issues };
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// src/agents.ts
|
|
869
|
+
import path10 from "path";
|
|
870
|
+
import { existsSync as existsSync7 } from "fs";
|
|
871
|
+
import { fileURLToPath } from "url";
|
|
872
|
+
var BLOCK_BEGIN = "<!-- tbox:agents:begin -->";
|
|
873
|
+
var BLOCK_END = "<!-- tbox:agents:end -->";
|
|
874
|
+
function fragmentDir() {
|
|
875
|
+
return fileURLToPath(new URL("../agents/", import.meta.url));
|
|
876
|
+
}
|
|
877
|
+
async function readFragment(name) {
|
|
878
|
+
const file = path10.join(fragmentDir(), name);
|
|
879
|
+
if (!existsSync7(file)) throw new Error(`app-build AGENTS fragment missing: ${file}`);
|
|
880
|
+
return (await readText(file)).trim();
|
|
881
|
+
}
|
|
882
|
+
async function composeAgents(options) {
|
|
883
|
+
const kind = options.appKind;
|
|
884
|
+
const root = [
|
|
885
|
+
await readFragment("base.md"),
|
|
886
|
+
await readFragment(`kind-${kind}.md`)
|
|
887
|
+
].join("\n\n");
|
|
888
|
+
const app = [
|
|
889
|
+
await readFragment("app-base.md"),
|
|
890
|
+
await readFragment(`app-${kind}.md`)
|
|
891
|
+
].join("\n\n");
|
|
892
|
+
const modules = options.hasModules ? (await readText(path10.join(fragmentDir(), "modules.md"))).trim() : void 0;
|
|
893
|
+
return {
|
|
894
|
+
root: wrapBlock(root),
|
|
895
|
+
app: wrapBlock(app),
|
|
896
|
+
...modules ? { modules: wrapBlock(modules) } : {}
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
function wrapBlock(content) {
|
|
900
|
+
return `${BLOCK_BEGIN}
|
|
901
|
+
${content.trim()}
|
|
902
|
+
${BLOCK_END}`;
|
|
903
|
+
}
|
|
904
|
+
function extractOverlay(existing) {
|
|
905
|
+
const start = existing.indexOf(BLOCK_BEGIN);
|
|
906
|
+
const end = existing.indexOf(BLOCK_END);
|
|
907
|
+
if (start === -1 || end === -1 || end < start) return existing.trim();
|
|
908
|
+
return `${existing.slice(0, start)}${existing.slice(end + BLOCK_END.length)}`.trim();
|
|
909
|
+
}
|
|
910
|
+
function replaceBlock(existing, content) {
|
|
911
|
+
const start = existing.indexOf(BLOCK_BEGIN);
|
|
912
|
+
const end = existing.indexOf(BLOCK_END);
|
|
913
|
+
if (start === -1 || end === -1 || end < start) {
|
|
914
|
+
const overlay = existing.trim();
|
|
915
|
+
return overlay ? `${overlay}
|
|
916
|
+
|
|
917
|
+
${content}
|
|
918
|
+
` : `${content}
|
|
919
|
+
`;
|
|
920
|
+
}
|
|
921
|
+
const before = existing.slice(0, start).trimEnd();
|
|
922
|
+
const after = existing.slice(end + BLOCK_END.length).trimStart();
|
|
923
|
+
return [before, content, after].filter(Boolean).join("\n\n") + "\n";
|
|
924
|
+
}
|
|
925
|
+
async function syncAgents(options) {
|
|
926
|
+
const composed = await composeAgents(options);
|
|
927
|
+
const targets = [
|
|
928
|
+
[path10.join(options.root, "AGENTS.md"), composed.root],
|
|
929
|
+
[path10.join(options.root, "apps", "AGENTS.md"), composed.app]
|
|
930
|
+
];
|
|
931
|
+
if (composed.modules) targets.push([path10.join(options.root, "modules", "AGENTS.md"), composed.modules]);
|
|
932
|
+
const written = [];
|
|
933
|
+
for (const [file, block] of targets) {
|
|
934
|
+
const exists = existsSync7(file);
|
|
935
|
+
const existing = exists ? await readText(file) : "";
|
|
936
|
+
if (existing && !existing.includes(BLOCK_BEGIN) && !options.allowAppend) {
|
|
937
|
+
throw new Error(`${file} 缺少 ${BLOCK_BEGIN}(拒绝覆盖用户内容;加 --append 或手动加 block)`);
|
|
938
|
+
}
|
|
939
|
+
await writeText(file, replaceBlock(existing, block));
|
|
940
|
+
written.push(file);
|
|
941
|
+
}
|
|
942
|
+
return written;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// src/vite-plugin.ts
|
|
946
|
+
import path11 from "path";
|
|
947
|
+
import { existsSync as existsSync8, readFileSync } from "fs";
|
|
948
|
+
function readManifest(root) {
|
|
949
|
+
const file = path11.join(root, "apps", "client", ".tbox-gen", "manifest.json");
|
|
950
|
+
if (!existsSync8(file)) throw new Error(`[tbox-app] 缺少 ${file};先运行 generate`);
|
|
951
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
952
|
+
}
|
|
953
|
+
function pageId(pagePath) {
|
|
954
|
+
if (pagePath === "/") return "index";
|
|
955
|
+
return pagePath.slice(1).replace(/[^a-zA-Z0-9_-]/g, "-");
|
|
956
|
+
}
|
|
957
|
+
function inject(html, title, entry) {
|
|
958
|
+
let out = html;
|
|
959
|
+
if (/<title[^>]*>[\s\S]*?<\/title>/i.test(out)) out = out.replace(/<title[^>]*>[\s\S]*?<\/title>/i, `<title>${title.replace(/</g, "<")}</title>`);
|
|
960
|
+
else out = out.replace(/<\/head>/i, ` <title>${title.replace(/</g, "<")}</title>
|
|
961
|
+
</head>`);
|
|
962
|
+
out = out.replace(/<\/body>/i, ` <script type="module" src="${entry}"></script>
|
|
963
|
+
</body>`);
|
|
964
|
+
return out;
|
|
965
|
+
}
|
|
966
|
+
function tboxAppPlugin(options = {}) {
|
|
967
|
+
let root = options.root ? path11.resolve(options.root) : "";
|
|
968
|
+
const getManifest = () => {
|
|
969
|
+
if (options.getManifest) return options.getManifest();
|
|
970
|
+
return readManifest(root);
|
|
971
|
+
};
|
|
972
|
+
return {
|
|
973
|
+
name: "tbox-app",
|
|
974
|
+
enforce: "post",
|
|
975
|
+
config(config) {
|
|
976
|
+
const viteRoot = config.root ? path11.resolve(config.root) : process.cwd();
|
|
977
|
+
root = options.root ? path11.resolve(options.root) : path11.dirname(viteRoot);
|
|
978
|
+
const current = getManifest();
|
|
979
|
+
const input = {};
|
|
980
|
+
for (const page of current.pages) {
|
|
981
|
+
input[pageId(page.path)] = path11.join(root, "apps", "client", ".tbox-gen", "documents", page.document);
|
|
982
|
+
}
|
|
983
|
+
return {
|
|
984
|
+
build: {
|
|
985
|
+
rollupOptions: {
|
|
986
|
+
input
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
},
|
|
991
|
+
transformIndexHtml: {
|
|
992
|
+
order: "post",
|
|
993
|
+
handler(html, ctx) {
|
|
994
|
+
if (!ctx.server) return html;
|
|
995
|
+
const url = (ctx.originalUrl || ctx.path || "/").split("?")[0];
|
|
996
|
+
const normalized = url !== "/" && url.endsWith("/") ? url.slice(0, -1) : url;
|
|
997
|
+
const page = getManifest().pages.find((item) => item.path === normalized);
|
|
998
|
+
if (!page) return html;
|
|
999
|
+
const entry = page.entry ?? `/.tbox-gen/entries/${pageId(page.path)}.tsx`;
|
|
1000
|
+
return inject(html, page.title, entry);
|
|
1001
|
+
}
|
|
1002
|
+
},
|
|
1003
|
+
generateBundle(_outputOptions, bundle) {
|
|
1004
|
+
const current = getManifest();
|
|
1005
|
+
const byDocument = new Map(current.pages.map((page) => [`.tbox-gen/documents/${page.document}`.split(path11.sep).join("/"), page.document]));
|
|
1006
|
+
for (const [fileName, asset] of Object.entries(bundle)) {
|
|
1007
|
+
const normalized = fileName.split(path11.sep).join("/");
|
|
1008
|
+
const target = byDocument.get(normalized);
|
|
1009
|
+
if (!target) continue;
|
|
1010
|
+
delete bundle[fileName];
|
|
1011
|
+
asset.fileName = target;
|
|
1012
|
+
bundle[target] = asset;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
export {
|
|
1018
|
+
AppBuildError,
|
|
1019
|
+
FUNCTION_ID_RE,
|
|
1020
|
+
buildManifest,
|
|
1021
|
+
checkApp,
|
|
1022
|
+
composeAgents,
|
|
1023
|
+
extractOverlay,
|
|
1024
|
+
generateApp,
|
|
1025
|
+
listGeneratedFiles,
|
|
1026
|
+
parsePageMeta,
|
|
1027
|
+
readAppMeta,
|
|
1028
|
+
replaceBlock,
|
|
1029
|
+
scanApp,
|
|
1030
|
+
scanAppPrimitives,
|
|
1031
|
+
scanFunctions,
|
|
1032
|
+
scanModulePrimitives,
|
|
1033
|
+
scanModules,
|
|
1034
|
+
scanPages,
|
|
1035
|
+
syncAgents,
|
|
1036
|
+
tboxAppPlugin,
|
|
1037
|
+
wrapBlock
|
|
1038
|
+
};
|