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