fix: 保留系统字段语义并固化架构示例检查

修正 DataLink 公共 SDK 示例,直接提取 README 中的示例与实际 SDK 一起编译。架构依赖扫描改为 AST,覆盖项目别名、再导出、动态与类型导入,新增单据 Session 传输收口卡点。
收尾回归保留未声明系统键的读取/透传语义,防止 active 被模糊匹配到 inactive 业务标签。同步模块导航、单工具 MCP 与认证说明,记录七项问题的实际修复、兼容选择和验证范围。

验证:bun test 926 通过、0 失败(119 文件、4379 断言);bun run check、bun run check:version、git diff --check 与文档链接检查通过。版本维持 0.8.21,未操作真实企业。
This commit is contained in:
gitea committed 2026-10-29 18:31:02 +08:00
1 parent 55d31e27e6
commit 6249feee23
11 files changed
+195 -71

No files matched your search

+47 -12
View File
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import { readdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
import ts from "typescript";
const SRC_ROOT = join(import.meta.dir, "..");
@@ -20,25 +21,59 @@ function collectTsFiles(dir: string, includeTests = false): string[] {
function extractImportSpecifiers(source: string): string[] {
const specifiers: string[] = [];
const staticImportRe = /(?:import|export)\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g;
const dynamicImportRe = /import\(\s*["']([^"']+)["']\s*\)/g;
for (const match of source.matchAll(staticImportRe)) {
if (match[1]) specifiers.push(match[1]);
}
for (const match of source.matchAll(dynamicImportRe)) {
if (match[1]) specifiers.push(match[1]);
}
const ast = ts.createSourceFile("boundary.ts", source, ts.ScriptTarget.Latest, true);
const visit = (node: ts.Node) => {
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text);
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) specifiers.push(node.arguments[0].text);
if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) specifiers.push(node.argument.literal.text);
ts.forEachChild(node, visit);
};
visit(ast);
return specifiers;
}
function resolveImportRelativeToSrc(fromFile: string, specifier: string): string | null {
if (!specifier.startsWith(".")) return null;
const abs = resolve(dirname(fromFile), specifier).replace(/\.[jt]s$/, "");
return relative(SRC_ROOT, abs);
const path = specifier.startsWith(".") ? resolve(dirname(fromFile), specifier)
: specifier.startsWith("@core/") ? join(SRC_ROOT, "core", specifier.slice(6))
: specifier.startsWith("@domains/") ? join(SRC_ROOT, "domains", specifier.slice(9)) : undefined;
return path ? relative(SRC_ROOT, path.replace(/\.[jt]s$/, "")).replaceAll("\\", "/") : null;
}
describe("Architecture Layering Boundaries", () => {
test("dependency extraction covers aliases, re-exports and literal dynamic/type imports", () => {
const imports = extractImportSpecifiers(`
import { x } from "@core/errors.js";
export { y } from "@domains/bill/api.js";
const z = import("../domains/bill/api.js");
type T = import("@domains/bill/types.js").FormSpecification;
const text = 'import("not-a-real-import")';
`);
expect(imports).toEqual(["@core/errors.js", "@domains/bill/api.js", "../domains/bill/api.js", "@domains/bill/types.js"]);
expect(resolveImportRelativeToSrc(join(SRC_ROOT, "cli", "example.ts"), imports[1])).toBe("domains/bill/api");
});
test("bill Session HTTP calls stay in the transport module", () => {
const violations: string[] = [];
for (const file of collectTsFiles(join(SRC_ROOT, "domains", "bill"))) {
if (file.endsWith("api.ts")) continue;
const source = readFileSync(file, "utf8");
const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
const visit = (node: ts.Node) => {
if (ts.isCallExpression(node)) {
const expr = node.expression;
const receiver = ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr) ? expr.expression.getText(ast) : "";
const method = ts.isPropertyAccessExpression(expr) ? expr.name.text
: ts.isElementAccessExpression(expr) && ts.isStringLiteral(expr.argumentExpression) ? expr.argumentExpression.text : "";
if (/client|^ky$/i.test(receiver) && ["get", "post", "put", "patch", "delete"].includes(method)) {
violations.push(`${relative(SRC_ROOT, file)}:${ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1}`);
}
}
ts.forEachChild(node, visit);
};
visit(ast);
}
expect(violations).toEqual([]);
});
test("workflow imports use the module directories after the platform migration", () => {
const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/;
const violations: string[] = [];
+3 -3
View File
@@ -6,9 +6,9 @@
| 域 | 内部形态 | 说明 | 详细文档 |
|---|---|---|---|
| `platform/` | `api / tools / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
| `platform/` | `api / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
| `datalink/` | `api / services / fields / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
| `bill/` | `api / tools / create / copy / submit / templates / write / draft-validation / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
| `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) |
| `assist-platform/` | `api / services / types` | 合思协助平台(Unity 运营中心)多租户检索、工单匹配、指定代客员工免密直通与落盘提权 | [README.assist-platform.md](./assist-platform/README.assist-platform.md) |
| `store/` | `api / tools / types` | 企业应用中心/应用商店与 OpenAPI 密钥凭证探查 | [README.store.md](./store/README.store.md) |
+13 -7
View File
@@ -8,8 +8,8 @@ DataLink 域负责跨企业查询当前账号可见的自建应用、业务对
src/domains/datalink/
├── types.ts # 应用详情、对象字段、记录分页与权限模型
├── api.ts # DataLink HTTP 传输层
├── services.ts # 应用/对象名称解析与查询表达式辅助
└── tools.ts # MCP tool 注册
├── services.ts # 应用/对象名称解析与查询表达式辅助、SDK 门面
└── fields.ts # 读取与写入共用的唯一字段解析
```
## 查询链路
@@ -74,19 +74,25 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
```typescript
import {
initCorpRuntime,
requireSelectedCorp,
createClientsForCorp,
resolvePlatform,
resolveEntity,
iterateAllEntityRecords,
normalizeDatalinkRecord,
calculateEntityRecordStats,
} from "hose-use/sdk";
const runtime = await initCorpRuntime();
const platform = await resolvePlatform(runtime.clients.ekbClient, "新转转集团");
const entity = await resolveEntity(runtime.clients.ekbClient, platform.id, "合同");
const runtime = initCorpRuntime({ corpId: "企业配置ID", stateless: true });
const corp = requireSelectedCorp(runtime);
const clients = await createClientsForCorp(corp);
const corpId = corp.corpId || corp.credentials.corpId;
const platform = await resolvePlatform(clients.ekbClient, corpId, "应用名称");
if (!platform) throw new Error("未找到自建应用");
const entity = await resolveEntity(clients.ekbClient, corpId, platform, "合同");
if (!entity) throw new Error("未找到业务对象");
// 1. 万级海量数据 $O(1)$ 内存流式遍历
for await (const rawRecord of iterateAllEntityRecords(runtime.clients.ekbClient, runtime.corpId, entity.id, { pageSize: 200 })) {
for await (const rawRecord of iterateAllEntityRecords(clients.ekbClient, corpId, entity.id, { pageSize: 200 })) {
const record = normalizeDatalinkRecord(rawRecord, entity);
// 执行业务逻辑...
}
@@ -44,3 +44,9 @@ test("安全编辑遇到歧义字段在发出写请求前终止", async () => {
await expect(safeEditRecord(client, "corp", { entityId: entity.id, recordId: "r", detail: { id: "r" }, fields: entity.fields, patchForm: { 金额: 10 } })).rejects.toThrow("歧义");
expect(requests).toEqual([]);
});
test("未声明的系统字段保留原语义,不会模糊匹配 inactive 等业务标签", () => {
const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [{ name: "E_entity_old", label: "inactive", type: "text" }] });
expect(compileRecordPredicate("active == true", fields)({ active: true, E_entity_old: false })).toBe(true);
expect(parseSetClause("active=true", fields)).toEqual({ active: true });
});
+6 -3
View File
@@ -17,8 +17,11 @@ export function resolveDatalinkField(
}
return byName.values().next().value;
};
return unique(fields.filter((field) => field.name.toLowerCase() === key))
const exact = unique(fields.filter((field) => field.name.toLowerCase() === key))
?? unique(fields.filter((field) => field.name.toLowerCase() === prefix + key))
?? unique(fields.filter((field) => field.label?.toLowerCase() === key))
?? unique(fields.filter((field) => field.label?.toLowerCase().includes(key)));
?? unique(fields.filter((field) => field.label?.toLowerCase() === key));
if (exact) return exact;
// 未在元数据声明的系统键由调用方读取/透传,不能误匹配到 inactive 等业务标签。
if (["id", "recordid", "active", "name", "code", "createtime", "updatetime", "entityid"].includes(key)) return undefined;
return unique(fields.filter((field) => field.label?.toLowerCase().includes(key)));
}
+2 -2
View File
@@ -19,7 +19,7 @@ src/domains/platform/
│ ├── analysis/ # 工作流静态吞错、审批状态死锁过滤与联动覆盖巡检 (analyzer, types)
│ ├── state/ # 草稿版本状态机与发布乐观锁保护
│ └── alert/ # 错误指纹告警与 SQLite 本地持久化
└── tools.ts # MCP tool 注册
└── execution-context.ts # 执行树与节点输出上下文辅助
```
## 工作流使用与诊断
@@ -34,6 +34,6 @@ CLI 命令、触发器分类、生产调试风险、节点与脚本校验、实
## 详细文档
完整接口说明、认证链路、MCP tool 列表见:
接口职责、认证链路与 CLI 能力导航见(MCP 统一使用 `hose_cli`):
[docs/modules/platform.md](../../../docs/modules/platform.md)