@tbox.cn/app-build 1.0.0-alpha.1 → 1.0.0-alpha.7
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 +2 -3
- package/dist/index.d.ts +21 -19
- package/dist/index.js +252 -147
- package/package.json +2 -3
- package/agents/app-agent.md +0 -5
- package/agents/app-base.md +0 -8
- package/agents/app-web.md +0 -4
- package/agents/base.md +0 -12
- package/agents/kind-agent.md +0 -5
- package/agents/kind-web.md +0 -3
- package/agents/modules.md +0 -9
package/README.md
CHANGED
|
@@ -5,15 +5,14 @@ tbox-app 1.0 构建期叶子包。负责:
|
|
|
5
5
|
- 扫描 `apps/client`、`apps/server` 与 `modules/<id>/`;
|
|
6
6
|
- 生成 `apps/client/.tbox-gen/{manifest.json,registry.*,entries,documents}`;
|
|
7
7
|
- 提供 Vite 插件;
|
|
8
|
-
- `checkApp`
|
|
9
|
-
- `composeAgents` / `syncAgents`。
|
|
8
|
+
- `checkApp` 结构检查。
|
|
10
9
|
|
|
11
10
|
不依赖 `@tbox.cn/app-toolkit`。
|
|
12
11
|
|
|
13
12
|
## API
|
|
14
13
|
|
|
15
14
|
```ts
|
|
16
|
-
import { generateApp, checkApp, tboxAppPlugin
|
|
15
|
+
import { generateApp, checkApp, tboxAppPlugin } from '@tbox.cn/app-build';
|
|
17
16
|
```
|
|
18
17
|
|
|
19
18
|
```ts
|
package/dist/index.d.ts
CHANGED
|
@@ -54,6 +54,11 @@ interface SkillModule {
|
|
|
54
54
|
file: string;
|
|
55
55
|
relativeFile: string;
|
|
56
56
|
}
|
|
57
|
+
interface ActionModule {
|
|
58
|
+
id: string;
|
|
59
|
+
file: string;
|
|
60
|
+
relativeFile: string;
|
|
61
|
+
}
|
|
57
62
|
interface CardModule {
|
|
58
63
|
cardType: string;
|
|
59
64
|
serverFile: string;
|
|
@@ -109,6 +114,7 @@ interface ScanResult {
|
|
|
109
114
|
tools: ToolModule[];
|
|
110
115
|
skills: SkillModule[];
|
|
111
116
|
cards: CardModule[];
|
|
117
|
+
actions: ActionModule[];
|
|
112
118
|
modules: LoadedModule[];
|
|
113
119
|
}
|
|
114
120
|
interface GeneratedApp {
|
|
@@ -146,6 +152,7 @@ interface PrimitiveSet {
|
|
|
146
152
|
tools: ToolModule[];
|
|
147
153
|
skills: SkillModule[];
|
|
148
154
|
cards: CardModule[];
|
|
155
|
+
actions: ActionModule[];
|
|
149
156
|
}
|
|
150
157
|
declare function scanAppPrimitives(root: string): Promise<PrimitiveSet>;
|
|
151
158
|
declare function scanModulePrimitives(moduleDir: string): Promise<PrimitiveSet>;
|
|
@@ -165,7 +172,7 @@ interface GenerateResult {
|
|
|
165
172
|
scan: ScanResult;
|
|
166
173
|
close: () => Promise<void>;
|
|
167
174
|
}
|
|
168
|
-
declare function buildManifest(scan: ScanResult): AppManifest;
|
|
175
|
+
declare function buildManifest(scan: ScanResult, entryFor?: (pageId: string) => string): AppManifest;
|
|
169
176
|
declare function generateApp(options: GenerateOptions): Promise<GenerateResult>;
|
|
170
177
|
declare function listGeneratedFiles(root: string): Promise<string[]>;
|
|
171
178
|
|
|
@@ -173,23 +180,18 @@ declare function checkApp(options: {
|
|
|
173
180
|
root: string;
|
|
174
181
|
}): Promise<CheckResult>;
|
|
175
182
|
|
|
176
|
-
interface
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
declare function
|
|
188
|
-
interface SyncAgentsOptions extends ComposeAgentsOptions {
|
|
189
|
-
root: string;
|
|
190
|
-
allowAppend?: boolean;
|
|
191
|
-
}
|
|
192
|
-
declare function syncAgents(options: SyncAgentsOptions): Promise<string[]>;
|
|
183
|
+
interface CardSampleEntry {
|
|
184
|
+
label?: string;
|
|
185
|
+
note?: string;
|
|
186
|
+
data: unknown;
|
|
187
|
+
}
|
|
188
|
+
interface CardSampleSet {
|
|
189
|
+
cardType?: string;
|
|
190
|
+
samples: CardSampleEntry[];
|
|
191
|
+
/** 样例缺失或不可静态求值时的说明 */
|
|
192
|
+
issues: string[];
|
|
193
|
+
}
|
|
194
|
+
declare function readCardSamples(file: string): CardSampleSet;
|
|
193
195
|
|
|
194
196
|
interface TboxAppPluginOptions {
|
|
195
197
|
root?: string;
|
|
@@ -197,4 +199,4 @@ interface TboxAppPluginOptions {
|
|
|
197
199
|
}
|
|
198
200
|
declare function tboxAppPlugin(options?: TboxAppPluginOptions): Plugin;
|
|
199
201
|
|
|
200
|
-
export { AppBuildError, type AppKind, type AppManifest, type AppMeta, type CardModule, type CheckIssue, type CheckResult, FUNCTION_ID_RE, type FunctionModule, type GenerateOptions, type GenerateResult, type GeneratedApp, type LoadedModule, type ModuleDescriptor, type PageEntry, type PageMeta, type PageModule, type ScanResult, type SkillModule, type TboxAppPluginOptions, type ToolModule, buildManifest, checkApp,
|
|
202
|
+
export { type ActionModule, AppBuildError, type AppKind, type AppManifest, type AppMeta, type CardModule, type CardSampleEntry, type CardSampleSet, type CheckIssue, type CheckResult, FUNCTION_ID_RE, type FunctionModule, type GenerateOptions, type GenerateResult, type GeneratedApp, type LoadedModule, type ModuleDescriptor, type PageEntry, type PageMeta, type PageModule, type ScanResult, type SkillModule, type TboxAppPluginOptions, type ToolModule, buildManifest, checkApp, generateApp, listGeneratedFiles, parsePageMeta, readAppMeta, readCardSamples, scanApp, scanAppPrimitives, scanFunctions, scanModulePrimitives, scanModules, scanPages, tboxAppPlugin };
|
package/dist/index.js
CHANGED
|
@@ -16,7 +16,7 @@ var AppBuildError = class extends Error {
|
|
|
16
16
|
import path2 from "path";
|
|
17
17
|
|
|
18
18
|
// src/fs.ts
|
|
19
|
-
import { existsSync } from "fs";
|
|
19
|
+
import { existsSync, readFileSync } from "fs";
|
|
20
20
|
import { mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
|
|
21
21
|
import path from "path";
|
|
22
22
|
async function readText(file) {
|
|
@@ -25,6 +25,9 @@ async function readText(file) {
|
|
|
25
25
|
async function readJson(file) {
|
|
26
26
|
return JSON.parse(await readText(file));
|
|
27
27
|
}
|
|
28
|
+
function readJsonSync(file) {
|
|
29
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
30
|
+
}
|
|
28
31
|
async function writeText(file, text) {
|
|
29
32
|
await mkdir(path.dirname(file), { recursive: true });
|
|
30
33
|
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
@@ -315,6 +318,17 @@ async function scanSkillDir(dir) {
|
|
|
315
318
|
}
|
|
316
319
|
return out;
|
|
317
320
|
}
|
|
321
|
+
async function scanActionDir(dir) {
|
|
322
|
+
if (!existsSync3(dir)) return [];
|
|
323
|
+
const files = (await listFiles(dir)).filter((file) => file.endsWith(".action.ts"));
|
|
324
|
+
const out = [];
|
|
325
|
+
for (const file of files.sort()) {
|
|
326
|
+
const { expr } = await readExported(file, "action");
|
|
327
|
+
const id = stringProperty(expr, "id", `action (${path5.basename(file)})`);
|
|
328
|
+
out.push({ id, file, relativeFile: path5.relative(dir, file).split(path5.sep).join("/") });
|
|
329
|
+
}
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
318
332
|
async function scanCardDirs(serverDir, clientDir) {
|
|
319
333
|
if (!existsSync3(serverDir) && !existsSync3(clientDir)) return [];
|
|
320
334
|
const server = /* @__PURE__ */ new Map();
|
|
@@ -359,14 +373,17 @@ async function scanAppPrimitives(root) {
|
|
|
359
373
|
return {
|
|
360
374
|
tools: await scanToolDir(path5.join(appDir, "server", "src", "tools")),
|
|
361
375
|
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"))
|
|
376
|
+
cards: await scanCardDirs(path5.join(appDir, "server", "src", "cards"), path5.join(appDir, "client", "src", "cards")),
|
|
377
|
+
actions: await scanActionDir(path5.join(appDir, "server", "src", "actions"))
|
|
363
378
|
};
|
|
364
379
|
}
|
|
365
380
|
async function scanModulePrimitives(moduleDir) {
|
|
366
381
|
return {
|
|
367
382
|
tools: await scanToolDir(path5.join(moduleDir, "src", "server", "tools")),
|
|
368
383
|
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"))
|
|
384
|
+
cards: await scanCardDirs(path5.join(moduleDir, "src", "server", "cards"), path5.join(moduleDir, "src", "client", "cards")),
|
|
385
|
+
// 模块动作走 serverModule.register 里的 ctx.cardActions,不经文件约定
|
|
386
|
+
actions: []
|
|
370
387
|
};
|
|
371
388
|
}
|
|
372
389
|
function assertUnique(items, code, label) {
|
|
@@ -420,7 +437,12 @@ function validateDescriptor(raw, dir) {
|
|
|
420
437
|
const value = raw;
|
|
421
438
|
if (value.schemaVersion !== 1) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json schemaVersion 必须为 1: ${dir}`);
|
|
422
439
|
if (typeof value.id !== "string" || !value.id) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 id: ${dir}`);
|
|
423
|
-
|
|
440
|
+
const manifestFile = path6.join(dir, "package.json");
|
|
441
|
+
const manifestVersion = existsSync4(manifestFile) ? readJsonSync(manifestFile).version : void 0;
|
|
442
|
+
const descriptorVersion = typeof value.version === "string" && value.version ? value.version : void 0;
|
|
443
|
+
const version = typeof manifestVersion === "string" && manifestVersion ? manifestVersion : descriptorVersion;
|
|
444
|
+
if (!version) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `模块版本未知(package.json 与 tbox.module.json 都没有 version): ${dir}`);
|
|
445
|
+
value.version = version;
|
|
424
446
|
const dirName = path6.basename(dir);
|
|
425
447
|
if (value.id !== dirName) throw new AppBuildError("MODULE_ID_MISMATCH", `模块 id "${value.id}" 必须等于目录名 "${dirName}"`, { file: path6.join(dir, "tbox.module.json") });
|
|
426
448
|
if (!value.declare || typeof value.declare !== "object") throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 declare: ${dir}`);
|
|
@@ -524,7 +546,8 @@ var APPS_DIR = "apps";
|
|
|
524
546
|
var CLIENT_DIR = "apps/client";
|
|
525
547
|
var SERVER_DIR = "apps/server";
|
|
526
548
|
var SHELL_FILE = "apps/client/index.html";
|
|
527
|
-
var
|
|
549
|
+
var APP_CONFIG_FILE = "apps/client/src/app.config.ts";
|
|
550
|
+
var ENTRY_OVERRIDE_FILE = "apps/client/src/entry.tsx";
|
|
528
551
|
|
|
529
552
|
// src/scan.ts
|
|
530
553
|
async function scanApp(root) {
|
|
@@ -538,6 +561,7 @@ async function scanApp(root) {
|
|
|
538
561
|
assertUnique(primitives.tools, "TOOL_ID_DUPLICATE", "工具 ID");
|
|
539
562
|
assertUnique(primitives.skills, "SKILL_ID_DUPLICATE", "技能 ID");
|
|
540
563
|
assertUnique(primitives.cards, "CARD_TYPE_DUPLICATE", "卡片类型");
|
|
564
|
+
assertUnique(primitives.actions, "ACTION_ID_DUPLICATE", "动作 ID");
|
|
541
565
|
if (meta.appKind === "web") {
|
|
542
566
|
const hasAgentSurface = primitives.tools.length > 0 || primitives.skills.length > 0 || primitives.cards.length > 0;
|
|
543
567
|
if (hasAgentSurface) {
|
|
@@ -574,14 +598,16 @@ async function scanApp(root) {
|
|
|
574
598
|
tools: primitives.tools,
|
|
575
599
|
skills: primitives.skills,
|
|
576
600
|
cards: primitives.cards,
|
|
601
|
+
actions: primitives.actions,
|
|
577
602
|
modules
|
|
578
603
|
};
|
|
579
604
|
}
|
|
580
605
|
|
|
581
606
|
// src/generate.ts
|
|
582
607
|
import path8 from "path";
|
|
583
|
-
import { existsSync as existsSync5 } from "fs";
|
|
608
|
+
import { existsSync as existsSync5, readdirSync } from "fs";
|
|
584
609
|
import { watch as fsWatch } from "fs";
|
|
610
|
+
import ts2 from "typescript";
|
|
585
611
|
function pageDocument(route) {
|
|
586
612
|
if (route === "/") return "index.html";
|
|
587
613
|
if (route === "/_tbox/card-preview") return "_tbox/card-preview.html";
|
|
@@ -592,17 +618,18 @@ function pageRank(route) {
|
|
|
592
618
|
if (route === "/_tbox/card-preview") return 2;
|
|
593
619
|
return 1;
|
|
594
620
|
}
|
|
595
|
-
|
|
621
|
+
var defaultEntryFor = (pageId2) => `/.tbox-gen/entries/${pageId2}.tsx`;
|
|
622
|
+
function buildManifest(scan, entryFor = defaultEntryFor) {
|
|
596
623
|
const pages = scan.pages.map((page) => ({
|
|
597
624
|
path: page.route,
|
|
598
|
-
entry:
|
|
625
|
+
entry: entryFor(page.id),
|
|
599
626
|
document: pageDocument(page.route),
|
|
600
627
|
title: page.meta.title
|
|
601
628
|
}));
|
|
602
629
|
if (scan.appKind === "agent") {
|
|
603
630
|
pages.push({
|
|
604
631
|
path: "/_tbox/card-preview",
|
|
605
|
-
entry: "
|
|
632
|
+
entry: entryFor("card-preview"),
|
|
606
633
|
document: "_tbox/card-preview.html",
|
|
607
634
|
title: "卡片预览"
|
|
608
635
|
});
|
|
@@ -645,6 +672,7 @@ function buildServerRegistry(genDir, scan) {
|
|
|
645
672
|
scan.tools.forEach((tool, i) => lines.push(`import { tool as tool${i} } from '${relativePosix(file, tool.file)}';`));
|
|
646
673
|
scan.skills.forEach((skill, i) => lines.push(`import { skill as skill${i} } from '${relativePosix(file, skill.file)}';`));
|
|
647
674
|
scan.cards.forEach((card, i) => lines.push(`import { card as card${i} } from '${relativePosix(file, card.serverFile)}';`));
|
|
675
|
+
scan.actions.forEach((action, i) => lines.push(`import { action as action${i} } from '${relativePosix(file, action.file)}';`));
|
|
648
676
|
serverModules.forEach((mod, i) => lines.push(`import { serverModule as module${i} } from '${relativePosix(file, path8.join(mod.dir, "src/server/index.ts"))}';`));
|
|
649
677
|
lines.push("");
|
|
650
678
|
lines.push("export const functions = {");
|
|
@@ -656,12 +684,64 @@ function buildServerRegistry(genDir, scan) {
|
|
|
656
684
|
lines.push("export const cards = {");
|
|
657
685
|
scan.cards.forEach((card, i) => lines.push(` '${card.cardType}': card${i},`));
|
|
658
686
|
lines.push("};");
|
|
687
|
+
lines.push("export const actions = {");
|
|
688
|
+
scan.actions.forEach((action, i) => lines.push(` '${action.id}': action${i},`));
|
|
689
|
+
lines.push("};");
|
|
659
690
|
lines.push(`export const modules = [${serverModules.map((_, i) => `module${i}`).join(", ")}];`);
|
|
660
691
|
lines.push("");
|
|
661
|
-
lines.push("export const registry = { functions, tools, skills, cards, modules };");
|
|
692
|
+
lines.push("export const registry = { functions, tools, skills, cards, actions, modules };");
|
|
662
693
|
lines.push("");
|
|
663
694
|
return lines.join("\n");
|
|
664
695
|
}
|
|
696
|
+
async function collectObservedCardTypes(scan) {
|
|
697
|
+
const files = [...scan.tools.map((tool) => tool.file), ...scan.actions.map((action) => action.file)];
|
|
698
|
+
for (const mod of scan.modules) {
|
|
699
|
+
for (const sub of ["src/server", "src/client"]) {
|
|
700
|
+
const dir = path8.join(mod.dir, sub);
|
|
701
|
+
if (!existsSync5(dir)) continue;
|
|
702
|
+
for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {
|
|
703
|
+
if (!entry.isFile() || !/\.(ts|tsx)$/.test(entry.name)) continue;
|
|
704
|
+
files.push(path8.join(entry.parentPath ?? dir, entry.name));
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const observed = /* @__PURE__ */ new Set();
|
|
709
|
+
for (const file of files) {
|
|
710
|
+
let text;
|
|
711
|
+
try {
|
|
712
|
+
text = await readText(file);
|
|
713
|
+
} catch {
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
const source = parseSource(file, text);
|
|
717
|
+
const visit = (node) => {
|
|
718
|
+
if (ts2.isPropertyAssignment(node) && propertyName(node.name) === "cardType") {
|
|
719
|
+
const init = node.initializer;
|
|
720
|
+
if (ts2.isStringLiteral(init) || ts2.isNoSubstitutionTemplateLiteral(init)) observed.add(init.text);
|
|
721
|
+
}
|
|
722
|
+
ts2.forEachChild(node, visit);
|
|
723
|
+
};
|
|
724
|
+
visit(source);
|
|
725
|
+
}
|
|
726
|
+
return [...observed].sort();
|
|
727
|
+
}
|
|
728
|
+
function buildAppRegistry(scan, observed) {
|
|
729
|
+
const declared = [...new Set(scan.cards.map((card) => card.cardType))].sort();
|
|
730
|
+
const union = declared.length > 0 ? declared.map((type) => `'${type}'`).join(" | ") : "string";
|
|
731
|
+
const lines = [
|
|
732
|
+
"// @generated by @tbox.cn/app-build; do not edit.",
|
|
733
|
+
"",
|
|
734
|
+
`export type AppCardType = ${union};`,
|
|
735
|
+
""
|
|
736
|
+
];
|
|
737
|
+
if (observed.length > 0) {
|
|
738
|
+
lines.push("// C1:源码里出现的 cardType 字面量。任何一项不在 AppCardType 里,类型检查会报错并列出合法取值。");
|
|
739
|
+
lines.push(`const observedCardTypes: AppCardType[] = [${observed.map((type) => `'${type}'`).join(", ")}];`);
|
|
740
|
+
lines.push("void observedCardTypes;");
|
|
741
|
+
lines.push("");
|
|
742
|
+
}
|
|
743
|
+
return lines.join("\n");
|
|
744
|
+
}
|
|
665
745
|
function buildClientRegistry(genDir, scan) {
|
|
666
746
|
const file = path8.join(genDir, "registry.client.ts");
|
|
667
747
|
const lines = ["// @generated by @tbox.cn/app-build; do not edit."];
|
|
@@ -677,66 +757,102 @@ function buildClientRegistry(genDir, scan) {
|
|
|
677
757
|
lines.push("");
|
|
678
758
|
return lines.join("\n");
|
|
679
759
|
}
|
|
680
|
-
function buildEntry(genDir, scan, pageId2, pageFile, cardPreview = false) {
|
|
760
|
+
function buildEntry(root, genDir, scan, pageId2, pageFile, cardPreview = false) {
|
|
681
761
|
const file = path8.join(genDir, "entries", `${pageId2}.tsx`);
|
|
682
|
-
const
|
|
683
|
-
const mountImport = relativePosix(file, path8.join(scan.root, "apps", "client", "src", "platform", "mount-page.tsx"));
|
|
762
|
+
const configImport = relativePosix(file, path8.join(root, "apps", "client", "src", "app.config.ts"));
|
|
684
763
|
const registryImport = relativePosix(file, path8.join(genDir, "registry.client.ts"));
|
|
685
|
-
|
|
764
|
+
if (cardPreview) {
|
|
765
|
+
return [
|
|
766
|
+
"// @generated by @tbox.cn/app-build; do not edit.",
|
|
767
|
+
`import config from '${configImport}';`,
|
|
768
|
+
`import { modules, cards } from '${registryImport}';`,
|
|
769
|
+
"import { startCardPreview } from '@tbox.cn/app-agent-sdk-client/app/card-preview';",
|
|
770
|
+
"",
|
|
771
|
+
"void startCardPreview({ config, modules, cards });",
|
|
772
|
+
""
|
|
773
|
+
].join("\n");
|
|
774
|
+
}
|
|
775
|
+
const pageImport = relativePosix(file, pageFile);
|
|
776
|
+
const isAgent = scan.appKind === "agent";
|
|
777
|
+
const startName = isAgent ? "startAgentApp" : "startApp";
|
|
778
|
+
const startImport = isAgent ? "@tbox.cn/app-agent-sdk-client/app" : "@tbox.cn/app-sdk-client/app";
|
|
686
779
|
return [
|
|
687
780
|
"// @generated by @tbox.cn/app-build; do not edit.",
|
|
688
|
-
|
|
781
|
+
// app.config 必须第一个 import:模块顶层 auth 单例先于 registry 的 module 顶层执行。
|
|
782
|
+
`import config from '${configImport}';`,
|
|
689
783
|
`import { modules, cards } from '${registryImport}';`,
|
|
690
|
-
`import {
|
|
691
|
-
"",
|
|
692
|
-
"registerClientCards(cards);",
|
|
784
|
+
`import { ${startName} } from '${startImport}';`,
|
|
693
785
|
"",
|
|
694
|
-
|
|
695
|
-
"
|
|
696
|
-
"
|
|
697
|
-
|
|
698
|
-
`
|
|
699
|
-
"
|
|
700
|
-
" console.error('[app-build] page bootstrap failed', error);",
|
|
701
|
-
" }",
|
|
702
|
-
"}",
|
|
703
|
-
"",
|
|
704
|
-
"void start();",
|
|
786
|
+
`void ${startName}({`,
|
|
787
|
+
" config,",
|
|
788
|
+
" modules,",
|
|
789
|
+
" cards,",
|
|
790
|
+
` page: () => import('${pageImport}'),`,
|
|
791
|
+
"});",
|
|
705
792
|
""
|
|
706
793
|
].join("\n");
|
|
707
794
|
}
|
|
708
795
|
async function generateCore(root, shell, scan) {
|
|
709
796
|
const genDir = path8.join(root, "apps", "client", ".tbox-gen");
|
|
797
|
+
const manifestFile = path8.join(genDir, "manifest.json");
|
|
798
|
+
const appConfigFile = path8.join(root, "apps", "client", "src", "app.config.ts");
|
|
799
|
+
const overrideFile = path8.join(root, "apps", "client", "src", "entry.tsx");
|
|
800
|
+
const useOverride = existsSync5(overrideFile);
|
|
801
|
+
if (!useOverride && !existsSync5(appConfigFile)) {
|
|
802
|
+
throw new AppBuildError(
|
|
803
|
+
"APP_CONFIG_MISSING",
|
|
804
|
+
"缺少 apps/client/src/app.config.ts(客户端装配真源)",
|
|
805
|
+
{ file: appConfigFile }
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
const entryFor = (pageId2) => useOverride ? "/src/entry.tsx" : `/.tbox-gen/entries/${pageId2}.tsx`;
|
|
809
|
+
const manifest = buildManifest(scan, entryFor);
|
|
810
|
+
await removeFile(manifestFile);
|
|
710
811
|
const files = [];
|
|
711
812
|
const write = async (file, text) => {
|
|
712
813
|
await writeTextIfChanged(file, text);
|
|
713
814
|
files.push(file);
|
|
714
815
|
};
|
|
715
|
-
const
|
|
716
|
-
await write(path8.join(genDir, "
|
|
717
|
-
`);
|
|
718
|
-
await write(path8.join(genDir, "app-kind.ts"), `export const appKind = '${scan.appKind}' as const;
|
|
719
|
-
`);
|
|
816
|
+
const observedCardTypes = await collectObservedCardTypes(scan);
|
|
817
|
+
await write(path8.join(genDir, "app-registry.ts"), buildAppRegistry(scan, observedCardTypes));
|
|
720
818
|
await write(path8.join(genDir, "registry.server.ts"), buildServerRegistry(genDir, scan));
|
|
721
819
|
await write(path8.join(genDir, "registry.client.ts"), buildClientRegistry(genDir, scan));
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
if (
|
|
730
|
-
|
|
820
|
+
const writeDocuments = async () => {
|
|
821
|
+
for (const page of scan.pages) {
|
|
822
|
+
await write(
|
|
823
|
+
path8.join(genDir, "documents", pageDocument(page.route)),
|
|
824
|
+
renderDocument(shell, page.meta.title, page.meta.meta, entryFor(page.id))
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
if (scan.appKind === "agent") {
|
|
828
|
+
await write(
|
|
829
|
+
path8.join(genDir, "documents", "_tbox/card-preview.html"),
|
|
830
|
+
renderDocument(shell, "卡片预览", void 0, entryFor("card-preview"))
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
if (!useOverride) {
|
|
835
|
+
for (const page of scan.pages) {
|
|
836
|
+
await write(
|
|
837
|
+
path8.join(genDir, "entries", `${page.id}.tsx`),
|
|
838
|
+
buildEntry(root, genDir, scan, page.id, page.file)
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
if (scan.appKind === "agent") {
|
|
842
|
+
await write(
|
|
843
|
+
path8.join(genDir, "entries", "card-preview.tsx"),
|
|
844
|
+
buildEntry(root, genDir, scan, "card-preview", "", true)
|
|
845
|
+
);
|
|
731
846
|
}
|
|
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
847
|
}
|
|
848
|
+
await writeDocuments();
|
|
736
849
|
const generated = new Set(files.map((file) => path8.resolve(file)));
|
|
850
|
+
generated.add(path8.resolve(manifestFile));
|
|
737
851
|
for (const file of await listFiles(genDir)) {
|
|
738
852
|
if (!generated.has(path8.resolve(file))) await removeFile(file);
|
|
739
853
|
}
|
|
854
|
+
await write(manifestFile, `${JSON.stringify(manifest, null, 2)}
|
|
855
|
+
`);
|
|
740
856
|
return { files, manifest };
|
|
741
857
|
}
|
|
742
858
|
async function generateApp(options) {
|
|
@@ -770,7 +886,7 @@ async function generateApp(options) {
|
|
|
770
886
|
const name = filename?.toString().split(path8.sep).join("/") ?? "";
|
|
771
887
|
if (!name) return;
|
|
772
888
|
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/");
|
|
889
|
+
const relevant = name === ".tbox/app.json" || name === "apps/client/index.html" || name === "apps/client/src/app.config.ts" || name === "apps/client/src/entry.tsx" || name.startsWith("apps/client/src/pages/") || name.startsWith("apps/server/src/") || name.startsWith("modules/");
|
|
774
890
|
if (!relevant) return;
|
|
775
891
|
if (timer) clearTimeout(timer);
|
|
776
892
|
timer = setTimeout(() => void regenerate(), 50);
|
|
@@ -833,15 +949,16 @@ async function checkApp(options) {
|
|
|
833
949
|
if (!existsSync6(path9.join(root, SHELL_FILE))) {
|
|
834
950
|
issues.push({ code: "APP_INDEX_MISSING", severity: "error", file: path9.join(root, SHELL_FILE), message: `缺少 ${SHELL_FILE}` });
|
|
835
951
|
}
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
952
|
+
const appConfig = path9.join(root, APP_CONFIG_FILE);
|
|
953
|
+
const entryOverride = path9.join(root, ENTRY_OVERRIDE_FILE);
|
|
954
|
+
if (!existsSync6(appConfig) && !existsSync6(entryOverride)) {
|
|
955
|
+
issues.push({
|
|
956
|
+
code: "APP_CONFIG_MISSING",
|
|
957
|
+
severity: "error",
|
|
958
|
+
file: appConfig,
|
|
959
|
+
message: `缺少 ${APP_CONFIG_FILE}(或 ${ENTRY_OVERRIDE_FILE} 全量接管入口)`,
|
|
960
|
+
fix: "从模板复制 app.config.ts;需要完全自定义入口时创建 src/entry.tsx"
|
|
961
|
+
});
|
|
845
962
|
}
|
|
846
963
|
const pagesDir = path9.join(root, CLIENT_DIR, "src", "pages");
|
|
847
964
|
for (const file of await listFiles(pagesDir)) {
|
|
@@ -865,90 +982,71 @@ async function checkApp(options) {
|
|
|
865
982
|
return { ok: issues.every((issue) => issue.severity !== "error"), issues };
|
|
866
983
|
}
|
|
867
984
|
|
|
868
|
-
// src/
|
|
869
|
-
import
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
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
|
-
`;
|
|
985
|
+
// src/card-samples.ts
|
|
986
|
+
import { existsSync as existsSync7, readFileSync as readFileSync2 } from "fs";
|
|
987
|
+
function readCardSamples(file) {
|
|
988
|
+
const issues = [];
|
|
989
|
+
if (!existsSync7(file)) return { samples: [], issues: [`文件不存在: ${file}`] };
|
|
990
|
+
const text = readFileSync2(file, "utf8");
|
|
991
|
+
const sf = parseSource(file, text);
|
|
992
|
+
const exported = findExportedVariable(sf, "card");
|
|
993
|
+
if (!exported) return { samples: [], issues: ["没有找到 export const card"] };
|
|
994
|
+
let object;
|
|
995
|
+
try {
|
|
996
|
+
object = objectFromExpression(exported, file);
|
|
997
|
+
} catch (error) {
|
|
998
|
+
return { samples: [], issues: [`卡片声明不是静态对象字面量: ${error.message}`] };
|
|
920
999
|
}
|
|
921
|
-
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
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)`);
|
|
1000
|
+
let cardType;
|
|
1001
|
+
const typeNode = getProperty(object, "cardType");
|
|
1002
|
+
if (typeNode) {
|
|
1003
|
+
try {
|
|
1004
|
+
const value = literalToJson(typeNode, file);
|
|
1005
|
+
if (typeof value === "string") cardType = value;
|
|
1006
|
+
} catch {
|
|
1007
|
+
issues.push("cardType 不是静态字面量");
|
|
938
1008
|
}
|
|
939
|
-
await writeText(file, replaceBlock(existing, block));
|
|
940
|
-
written.push(file);
|
|
941
1009
|
}
|
|
942
|
-
|
|
1010
|
+
const samples = [];
|
|
1011
|
+
const sampleData = getProperty(object, "sampleData");
|
|
1012
|
+
if (sampleData) {
|
|
1013
|
+
try {
|
|
1014
|
+
samples.push({ label: "sampleData", data: literalToJson(sampleData, file) });
|
|
1015
|
+
} catch (error) {
|
|
1016
|
+
issues.push(`sampleData 不是静态字面量: ${error.message}`);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
const extra = getProperty(object, "samples");
|
|
1020
|
+
if (extra) {
|
|
1021
|
+
try {
|
|
1022
|
+
const list = literalToJson(extra, file);
|
|
1023
|
+
if (Array.isArray(list)) {
|
|
1024
|
+
list.forEach((entry, index) => {
|
|
1025
|
+
const row = entry ?? {};
|
|
1026
|
+
samples.push({
|
|
1027
|
+
...typeof row.label === "string" ? { label: row.label } : { label: `samples[${index}]` },
|
|
1028
|
+
...typeof row.note === "string" ? { note: row.note } : {},
|
|
1029
|
+
data: row.data
|
|
1030
|
+
});
|
|
1031
|
+
});
|
|
1032
|
+
} else {
|
|
1033
|
+
issues.push("samples 不是数组");
|
|
1034
|
+
}
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
issues.push(`samples 不是静态字面量: ${error.message}`);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
if (samples.length === 0) issues.push("没有可用样例(补 sampleData)");
|
|
1040
|
+
return { cardType, samples, issues };
|
|
943
1041
|
}
|
|
944
1042
|
|
|
945
1043
|
// src/vite-plugin.ts
|
|
946
|
-
import
|
|
947
|
-
import { existsSync as existsSync8, readFileSync } from "fs";
|
|
1044
|
+
import path10 from "path";
|
|
1045
|
+
import { existsSync as existsSync8, readFileSync as readFileSync3 } from "fs";
|
|
948
1046
|
function readManifest(root) {
|
|
949
|
-
const file =
|
|
1047
|
+
const file = path10.join(root, "apps", "client", ".tbox-gen", "manifest.json");
|
|
950
1048
|
if (!existsSync8(file)) throw new Error(`[tbox-app] 缺少 ${file};先运行 generate`);
|
|
951
|
-
return JSON.parse(
|
|
1049
|
+
return JSON.parse(readFileSync3(file, "utf8"));
|
|
952
1050
|
}
|
|
953
1051
|
function pageId(pagePath) {
|
|
954
1052
|
if (pagePath === "/") return "index";
|
|
@@ -964,21 +1062,29 @@ function inject(html, title, entry) {
|
|
|
964
1062
|
return out;
|
|
965
1063
|
}
|
|
966
1064
|
function tboxAppPlugin(options = {}) {
|
|
967
|
-
let root = options.root ?
|
|
1065
|
+
let root = options.root ? path10.resolve(options.root) : "";
|
|
968
1066
|
const getManifest = () => {
|
|
969
1067
|
if (options.getManifest) return options.getManifest();
|
|
970
1068
|
return readManifest(root);
|
|
971
1069
|
};
|
|
1070
|
+
const getManifestSafe = () => {
|
|
1071
|
+
try {
|
|
1072
|
+
return getManifest();
|
|
1073
|
+
} catch {
|
|
1074
|
+
return null;
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
972
1077
|
return {
|
|
973
1078
|
name: "tbox-app",
|
|
974
1079
|
enforce: "post",
|
|
975
1080
|
config(config) {
|
|
976
|
-
const viteRoot = config.root ?
|
|
977
|
-
root = options.root ?
|
|
978
|
-
const current =
|
|
1081
|
+
const viteRoot = config.root ? path10.resolve(config.root) : process.cwd();
|
|
1082
|
+
root = options.root ? path10.resolve(options.root) : path10.dirname(viteRoot);
|
|
1083
|
+
const current = getManifestSafe();
|
|
1084
|
+
if (!current) throw new Error("[tbox-app] 缺少 .tbox-gen/manifest.json;先运行 generate");
|
|
979
1085
|
const input = {};
|
|
980
1086
|
for (const page of current.pages) {
|
|
981
|
-
input[pageId(page.path)] =
|
|
1087
|
+
input[pageId(page.path)] = path10.join(root, "apps", "client", ".tbox-gen", "documents", page.document);
|
|
982
1088
|
}
|
|
983
1089
|
return {
|
|
984
1090
|
build: {
|
|
@@ -994,17 +1100,20 @@ function tboxAppPlugin(options = {}) {
|
|
|
994
1100
|
if (!ctx.server) return html;
|
|
995
1101
|
const url = (ctx.originalUrl || ctx.path || "/").split("?")[0];
|
|
996
1102
|
const normalized = url !== "/" && url.endsWith("/") ? url.slice(0, -1) : url;
|
|
997
|
-
const
|
|
1103
|
+
const current = getManifestSafe();
|
|
1104
|
+
if (!current) return html;
|
|
1105
|
+
const page = current.pages.find((item) => item.path === normalized);
|
|
998
1106
|
if (!page) return html;
|
|
999
1107
|
const entry = page.entry ?? `/.tbox-gen/entries/${pageId(page.path)}.tsx`;
|
|
1000
1108
|
return inject(html, page.title, entry);
|
|
1001
1109
|
}
|
|
1002
1110
|
},
|
|
1003
1111
|
generateBundle(_outputOptions, bundle) {
|
|
1004
|
-
const current =
|
|
1005
|
-
|
|
1112
|
+
const current = getManifestSafe();
|
|
1113
|
+
if (!current) return;
|
|
1114
|
+
const byDocument = new Map(current.pages.map((page) => [`.tbox-gen/documents/${page.document}`.split(path10.sep).join("/"), page.document]));
|
|
1006
1115
|
for (const [fileName, asset] of Object.entries(bundle)) {
|
|
1007
|
-
const normalized = fileName.split(
|
|
1116
|
+
const normalized = fileName.split(path10.sep).join("/");
|
|
1008
1117
|
const target = byDocument.get(normalized);
|
|
1009
1118
|
if (!target) continue;
|
|
1010
1119
|
delete bundle[fileName];
|
|
@@ -1019,20 +1128,16 @@ export {
|
|
|
1019
1128
|
FUNCTION_ID_RE,
|
|
1020
1129
|
buildManifest,
|
|
1021
1130
|
checkApp,
|
|
1022
|
-
composeAgents,
|
|
1023
|
-
extractOverlay,
|
|
1024
1131
|
generateApp,
|
|
1025
1132
|
listGeneratedFiles,
|
|
1026
1133
|
parsePageMeta,
|
|
1027
1134
|
readAppMeta,
|
|
1028
|
-
|
|
1135
|
+
readCardSamples,
|
|
1029
1136
|
scanApp,
|
|
1030
1137
|
scanAppPrimitives,
|
|
1031
1138
|
scanFunctions,
|
|
1032
1139
|
scanModulePrimitives,
|
|
1033
1140
|
scanModules,
|
|
1034
1141
|
scanPages,
|
|
1035
|
-
|
|
1036
|
-
tboxAppPlugin,
|
|
1037
|
-
wrapBlock
|
|
1142
|
+
tboxAppPlugin
|
|
1038
1143
|
};
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-build",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.7",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "tbox-app 1.0 build-time leaf: scan apps/ modules/ and generate manifest, registries, documents; Vite plugin
|
|
5
|
+
"description": "tbox-app 1.0 build-time leaf: scan apps/ modules/ and generate manifest, registries, documents; Vite plugin and checks.",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
@@ -35,7 +35,6 @@
|
|
|
35
35
|
},
|
|
36
36
|
"files": [
|
|
37
37
|
"dist",
|
|
38
|
-
"agents",
|
|
39
38
|
"README.md",
|
|
40
39
|
"LICENSE"
|
|
41
40
|
],
|
package/agents/app-agent.md
DELETED
package/agents/app-base.md
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
# 应用代码
|
|
2
|
-
|
|
3
|
-
- 页面:`apps/client/src/pages/**/page.tsx`。
|
|
4
|
-
- 函数:`apps/server/src/functions/*.server.ts`,直接 import 使用。
|
|
5
|
-
- HTTP:`request`;不要新增第二套 HTTP 客户端。
|
|
6
|
-
- 共享 DTO:`packages/shared/`,导入 `@app/shared`。
|
|
7
|
-
- 构建产物:`apps/client/dist`(部署静态根)、`apps/server/dist`。
|
|
8
|
-
- 不要手写路由表;页面目录就是路由。
|
package/agents/app-web.md
DELETED
package/agents/base.md
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
# tbox-app
|
|
2
|
-
|
|
3
|
-
这是一个 tbox-app 1.0 应用。应用代码根是 `apps/`(`apps/client` + `apps/server`)。
|
|
4
|
-
|
|
5
|
-
- `apps/client/src/pages/**/page.tsx`:页面;目录即 URL;页面元数据用 inline `export const page`。
|
|
6
|
-
- `apps/server/src/functions/*.server.ts`:函数;文件名即 `/api/fn/<id>`。
|
|
7
|
-
- `apps/server/src/tools/*.tool.ts`、`skills/*.skill.ts`、`cards/*.card.ts`:应用级原语(仅 agent)。
|
|
8
|
-
- `packages/shared/`:跨端 DTO(`@app/shared`),只放纯类型与常量。
|
|
9
|
-
- `modules/<id>/`:可复用/可分发模块;必须有 `tbox.module.json`。
|
|
10
|
-
- 不要创建 `app/`、`apps/client/src/modules.ts`、`routes.json`、`page.config.jsonc`。
|
|
11
|
-
|
|
12
|
-
修改后先运行 `pnpm check`,再按需运行 `pnpm typecheck`。
|
package/agents/kind-agent.md
DELETED
package/agents/kind-web.md
DELETED
package/agents/modules.md
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
# 模块
|
|
2
|
-
|
|
3
|
-
模块只在需要复用、分发或自定义安装后源码时创建。
|
|
4
|
-
|
|
5
|
-
- 本地模块:`modules/<id>/`,无 `package.json`。
|
|
6
|
-
- Vendored 模块:`modules/<id>/`,有 `package.json` 与 `tbox.upstream`。
|
|
7
|
-
- 两种模块都必须有 `tbox.module.json`。
|
|
8
|
-
- 模块入口:`src/server/index.ts` 导出 `serverModule`;`src/client/index.ts` 导出 `clientModule`。
|
|
9
|
-
- 模块只注册,不解析;跨模块经 `ctx`。
|