Files
persionalBrand/scripts/lib/template-doctor.mjs
T

560 lines
22 KiB
JavaScript

import crypto from "node:crypto";
import { execFileSync } from "node:child_process";
import path from "node:path";
import fs from "node:fs";
import ts from "typescript";
// 静态检查不推断运行时成功;未知表达式保留为 review。
export function diagnoseTemplate(manifest, source, file = "taro/index.tsx") {
const issues = [];
const regions = [];
const targets = [];
const fields = [];
const add = (code, context, message, severity = "blocker") =>
issues.push({ code, severity, file, ...context, message });
for (const section of manifest.admin?.sections ?? []) {
for (const target of section.previewTargets ?? []) {
const owned = (section.fields ?? []).filter((field) => field.previewTarget === target.key);
// 与 PresentationEditor.previewTargetSource 的优先级一致。
const source =
["offering", "trust", "brand"].find((kind) =>
owned.some((field) => field.binding?.startsWith(kind + ".")),
) ?? section.target;
targets.push({ ...target, page: section.page, source });
}
for (const field of section.fields ?? []) fields.push({ ...field, page: section.page });
}
for (const field of manifest.templateFields ?? []) fields.push(field);
for (const declaration of manifest.trustContentTypes ?? []) {
for (const page of declaration.pages ?? []) {
const key = "trust:" + declaration.type;
targets.push({ key, page, source: "trust", implicit: true });
for (const name of ["title", "summary", "content"])
if (!declaration.hideStandardFields?.includes(name))
fields.push({ binding: "trust." + name, previewTarget: key, page });
for (const field of (declaration.configFields ?? []).filter((field) => {
const target = declaration.previewTargets?.find(
(target) => target.key === field.previewTarget,
);
return !target?.page || target.page === page;
}))
fields.push({ ...field, previewTarget: field.previewTarget ?? key, page });
}
for (const target of declaration.previewTargets ?? []) {
if (!target.page)
add(
"TARGET_PAGE_UNSPECIFIED",
{ target: target.key },
"信任子区域需要明确展示页面,不能自动出现在该类型的全部页面。",
);
targets.push({ ...target, page: target.page ?? declaration.pages?.[0], source: "trust" });
}
}
const matching = (key, page) => targets.find((t) => t.key === key && t.page === page);
for (const field of fields) {
const target = matching(field.previewTarget, field.page);
const context = { page: field.page, target: field.previewTarget, binding: field.binding };
if (!target) add("FIELD_TARGET_MISSING", context, "字段必须绑定同页已声明区域。");
else if (target.composite)
add("COMPOSITE_HAS_FIELDS", context, "组合区域应导航到字段所属子区。");
else if (field.binding?.split(".")[0] !== target.source)
add(
"TARGET_SOURCE_MISMATCH",
context,
"区域来源与字段不一致,现有单记录编辑器无法完整保存。",
);
}
for (const target of targets) {
const context = { page: target.page, target: target.key };
if (targets.filter((t) => t.key === target.key && t.page === target.page).length > 1)
add("DUPLICATE_TARGET", context, "同页区域标识必须唯一。");
if (target.composite) {
if (!target.children?.length) add("COMPOSITE_EMPTY", context, "组合区域必须有子区。");
for (const child of target.children ?? [])
if (!matching(child, target.page) || matching(child, target.page)?.composite)
add("COMPOSITE_CHILD_INVALID", context, "子区必须是同页直接区域:" + child);
}
}
const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
for (const diagnostic of ast.parseDiagnostics)
add("RENDERER_PARSE_ERROR", {}, ts.flattenDiagnosticMessageText(diagnostic.messageText, " "));
const standardBrand = new Set([
"name",
"tagline",
"description",
"avatarUrl",
"contactPhone",
"contactWechat",
"address",
"hours",
"deliveryNote",
"coverUrl",
]);
const normalize = (path) => {
if (
path.startsWith("brand.") &&
!path.startsWith("brand.config.") &&
!standardBrand.has(path.split(".")[1])
)
return path.replace("brand.", "brand.config.");
return path;
};
function inspectFunction(fn) {
const aliases = new Map([["workspace", "workspace"]]);
const offeringAliases = {
image: "offering.config.detailHero",
desc: "offering.summary",
priceRange: "offering.priceText",
category: "offering.config.categoryKey",
area: "offering.config.area",
series: "offering.config.series",
keywords: "offering.config.keywords",
details: "offering.config.details",
};
const resolve = (node) => {
if (!node) return undefined;
if (ts.isIdentifier(node)) return aliases.get(node.text);
if (ts.isPropertyAccessExpression(node)) {
const base = resolve(node.expression);
if (!base) return undefined;
if (base === "offering" && offeringAliases[node.name.text])
return offeringAliases[node.name.text];
if (base === "offering.presentation") return "offering.config." + node.name.text;
const path = base + "." + node.name.text;
if (path === "workspace.brand") return "brand";
if (path === "workspace.templateData") return "brand.config.templateData";
if (path === "workspace.trustPresentation") return "trust.config";
if (path === "workspace.offerings") return "offering[]";
if (path === "workspace.trustItems") return "trust[]";
return path;
}
if (ts.isCallExpression(node) && ["object", "rows"].includes(node.expression.getText(ast)))
return resolve(node.arguments[0]);
if (ts.isCallExpression(node) && node.expression.getText(ast) === "text" && node.arguments[0])
return resolve(node.arguments[0]);
if (ts.isCallExpression(node) && node.expression.getText(ast) === "offering")
return "offering";
if (ts.isCallExpression(node) && node.expression.getText(ast) === "slot") return "trust";
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
const base = resolve(node.expression.expression);
if (["filter", "slice"].includes(node.expression.name.text)) return base;
if (node.expression.name.text === "find") return base?.replace(/\[\]$/, "");
if (node.expression.name.text === "map" && node.arguments[0]?.getText(ast) === "offering")
return "offering[]";
}
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === "presentation" &&
node.arguments[1] &&
ts.isStringLiteral(node.arguments[1])
)
return "brand.config.visualPresentation." + node.arguments[1].text;
return undefined;
};
function collect(node) {
if (node !== fn && ts.isFunctionDeclaration(node)) return;
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
const path = resolve(node.initializer);
if (path) aliases.set(node.name.text, path);
}
ts.forEachChild(node, collect);
}
collect(fn);
function visit(node, active) {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === "map"
) {
const collection = resolve(node.expression.expression);
const callback = node.arguments[0];
if (
collection &&
callback &&
ts.isArrowFunction(callback) &&
callback.parameters[0] &&
ts.isIdentifier(callback.parameters[0].name)
) {
const name = callback.parameters[0].name.text;
const previous = aliases.get(name);
aliases.set(name, collection.replace(/\[\]$/, ""));
visit(callback.body, active);
if (previous) aliases.set(name, previous);
else aliases.delete(name);
return;
}
}
if (ts.isConditionalExpression(node)) {
add(
"CONDITIONAL_RENDER_REVIEW",
{
target: active?.target,
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
},
"条件显示需验证全部分支与空数据入口。",
"review",
);
visit(node.whenTrue, active);
visit(node.whenFalse, active);
return;
}
if (
ts.isBinaryExpression(node) &&
node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken
) {
add(
"CONDITIONAL_RENDER_REVIEW",
{
target: active?.target,
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
},
"条件显示需验证全部分支与空数据入口。",
"review",
);
visit(node.right, active);
return;
}
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
const opening = ts.isJsxElement(node) ? node.openingElement : node;
const attrs = opening.attributes.properties;
const attr = attrs.find(
(a) => ts.isJsxAttribute(a) && a.name.getText(ast) === "data-editor-target",
);
if (attr) {
if (attr.initializer && ts.isStringLiteral(attr.initializer)) {
const key = attr.initializer.text;
const candidates = targets.filter((t) => t.key === key);
active = {
target: key,
page: candidates[0]?.page,
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
bindings: new Set(),
};
regions.push(active);
if (!candidates.length)
add("RENDER_TARGET_UNDECLARED", active, "renderer 区域没有声明。");
if (
candidates.some((t) => ["trust", "offering"].includes(t.source)) &&
!attrs.some(
(a) => ts.isJsxAttribute(a) && a.name.getText(ast) === "data-editor-record-id",
)
)
add(
"RECORD_ID_MISSING",
{ target: key, page: active.page, line: active.line },
"记录区域必须携带实际记录 ID。",
);
} else {
add(
"DYNAMIC_TARGET_REVIEW",
{ line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1 },
"动态目标需用真实 manifest 和实际记录验证分支。",
"review",
);
active = undefined;
}
}
// 属性中的事件和 recordId 不属于展示变量,只检查图片等展示属性。
for (const a of attrs)
if (
ts.isJsxAttribute(a) &&
["src", "title", "placeholder", "value"].includes(a.name.getText(ast)) &&
a.initializer
)
visit(a.initializer, active);
if (ts.isJsxElement(node)) for (const child of node.children) visit(child, active);
return;
}
if (ts.isPropertyAccessExpression(node) && !ts.isPropertyAccessExpression(node.parent)) {
if (ts.isElementAccessExpression(node.parent) && node.parent.expression === node) return;
const path = resolve(node);
if (path && /^(brand|trust|offering)\./.test(path)) {
const binding = normalize(path);
if (active) active.bindings.add(binding);
else
add(
"UNSCOPED_RENDER_VALUE",
{ binding, line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1 },
"展示变量没有可证明的编辑区域。",
"review",
);
} else if (active)
add(
"UNRESOLVED_RENDER_VALUE",
{
target: active.target,
page: active.page,
expression: node.getText(ast),
line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1,
},
"需要核对循环项或间接映射,不能视为已覆盖。",
"review",
);
}
if (ts.isElementAccessExpression(node) && active)
add(
"DYNAMIC_VALUE_REVIEW",
{ target: active.target, page: active.page, expression: node.getText(ast) },
"动态索引必须验证实际分支。",
"review",
);
ts.forEachChild(node, (child) => visit(child, active));
}
// 只从 JSX 开始,避免把数据准备和事件中的读取当成展示值。
function roots(node) {
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) return visit(node, undefined);
ts.forEachChild(node, roots);
}
roots(fn);
}
for (const statement of ast.statements) {
if (ts.isFunctionDeclaration(statement)) inspectFunction(statement);
else {
const check = (node) => {
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
add(
"UNSUPPORTED_COMPONENT_REVIEW",
{ line: ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1 },
"非函数声明组件需扩展解析器或补真实交互验证,不能静态认定覆盖。",
"review",
);
return;
}
ts.forEachChild(node, check);
};
check(statement);
}
}
for (const region of regions) {
const context = { page: region.page, target: region.target, line: region.line };
const declared = fields.filter(
(f) => f.previewTarget === region.target && f.page === region.page,
);
for (const binding of region.bindings)
if (
!(
region.page === "detail" && binding.startsWith("offering.")
? fields.filter((f) => f.binding?.startsWith("offering."))
: declared
).some((f) => f.binding === binding || binding.startsWith(f.binding + "."))
)
add(
"REGION_FIELD_MISSING",
{ ...context, binding },
"选区实际展示该变量但当前面板没有对应字段;补真实绑定或明确只读模式。",
);
for (const binding of region.bindings) {
const field = declared.find((f) => f.input === "list" && binding.startsWith(f.binding + "."));
if (!field || field.itemValueKey) continue;
const child = binding.slice(field.binding.length + 1).split(".")[0];
if (["map", "slice", "length", "filter", "join"].includes(child)) continue;
if (!field.itemFields?.some((item) => item.key === child))
add(
"LIST_FIELD_MISSING",
{ ...context, binding },
"列表展示的子字段必须在 itemFields 中提供编辑入口。",
);
}
}
for (const target of targets)
if (!target.implicit && !regions.some((r) => r.target === target.key))
add(
"TARGET_RENDER_UNVERIFIED",
{ page: target.page, target: target.key },
"未找到字面量区域,需验证动态目标或组件路径。",
"review",
);
return {
template: manifest.packageKey,
staticStatus: issues.length ? "fail" : "pass",
completionStatus: "unverified",
requiredEvidence: [
"real-manifest-interaction",
"save-reload-publish-isolation",
"visual-reference",
"empty-error-branches",
],
regions: regions.map((r) => ({ ...r, bindings: [...r.bindings] })),
issues,
};
}
const REVIEW_KEY_FIELDS = ["file", "page", "target", "binding", "line", "message"];
function reviewKey(item) {
return JSON.stringify(
Object.fromEntries(REVIEW_KEY_FIELDS.map((key) => [key, item[key] ?? null])),
);
}
export function applyManualReview(reports, reviews, reviewScope) {
if (reviewScope !== "人工映射审查,保留原诊断,不是自动豁免或全条件组合证明")
throw new Error("Manual review registry has an unsupported scope");
const byKey = new Map();
for (const item of reviews) {
if (item.severity !== "review" || item.reviewStatus !== "source-reviewed" || !item.decision)
throw new Error("Manual review registry contains an invalid entry");
byKey.set(reviewKey(item), item);
}
for (const report of reports) {
let unresolved = 0;
report.issues.forEach((issue) => {
const reviewed = issue.severity === "review" && byKey.get(reviewKey(issue));
if (reviewed) issue.reviewStatus = "source-reviewed";
else unresolved++;
});
report.reviewedIssues = report.issues.length - unresolved;
report.unresolvedIssues = unresolved;
report.staticStatus = report.issues.some(
(issue) => issue.severity === "blocker" || issue.reviewStatus !== "source-reviewed",
)
? "fail"
: "pass";
}
return reports;
}
function walkRepositoryFiles(root, directory = root) {
const files = [];
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
if (
entry.name === ".git" ||
entry.name === "node_modules" ||
entry.name === "dist" ||
entry.name === ".turbo"
)
continue;
const full = path.join(directory, entry.name);
if (entry.isDirectory()) files.push(...walkRepositoryFiles(root, full));
else if (entry.isFile()) files.push(full);
}
return files;
}
const EVIDENCE_SCOPE_IGNORED_PREFIXES = [".codex-tasks/", ".gitea/", "deploy/", "scripts/deploy/"];
const EVIDENCE_SCOPE_IGNORED_EXTENSIONS = [".md", ".mdx"];
const EVIDENCE_SCOPE_ALWAYS_INCLUDED = ["docs/template-completion-rules.md"];
// 证据哈希只覆盖会影响模板交付的源码:文档、CI 配置和部署脚本的改动不使证据失效。
export function isEvidenceSourcePath(relativePath) {
const normalized = relativePath.split(path.sep).join("/");
if (EVIDENCE_SCOPE_ALWAYS_INCLUDED.includes(normalized)) return true;
if (EVIDENCE_SCOPE_IGNORED_PREFIXES.some((prefix) => normalized.startsWith(prefix))) return false;
return !EVIDENCE_SCOPE_IGNORED_EXTENSIONS.some((extension) => normalized.endsWith(extension));
}
export function sourceTreeHash(root, options = {}) {
const rootPath = path.resolve(root);
const { staged = false } = options;
let files;
let readContent;
if (fs.existsSync(path.join(rootPath, ".git"))) {
// 只统计已跟踪文件:未纳入版本控制的文件不属于任何一次可复现的交付。
// staged 模式从 Git index 读取内容,供 pre-commit 使用,避免部分暂存时把
// 工作区里的未提交改动算进提交对应的证据哈希。
const output = execFileSync("git", ["ls-files", "-z", "--cached"], {
cwd: rootPath,
maxBuffer: 64 * 1024 * 1024,
});
files = output
.toString("utf8")
.split("\0")
.filter((file) => file && isEvidenceSourcePath(file))
.map((file) => path.join(rootPath, file));
readContent = staged
? (file) =>
execFileSync("git", ["show", ":" + path.relative(rootPath, file)], {
cwd: rootPath,
maxBuffer: 64 * 1024 * 1024,
})
: (file) => fs.readFileSync(file);
} else {
files = walkRepositoryFiles(rootPath).filter((file) =>
isEvidenceSourcePath(path.relative(rootPath, file)),
);
readContent = (file) => fs.readFileSync(file);
}
files.sort();
const hash = crypto.createHash("sha256");
for (const file of files) {
hash.update(path.relative(rootPath, file));
hash.update("\0");
hash.update(readContent(file));
hash.update("\0");
}
return hash.digest("hex");
}
export function applyCompletionEvidence(reports, registry, root) {
if (registry === undefined) {
for (const report of reports) report.completionStatus = "unverified";
return { completionStatus: "unverified", reports };
}
if (
!registry ||
registry.schemaVersion !== 1 ||
registry.scope !== "模板完成证据登记,保留命令、日志与产物哈希" ||
!registry.templates ||
typeof registry.templates !== "object" ||
Array.isArray(registry.templates) ||
!/^[a-f0-9]{64}$/.test(registry.sourceTreeHash ?? "")
) {
throw new Error("Completion evidence registry has an unsupported schema");
}
const expectedTemplates = new Set(reports.map((report) => report.template));
const registeredTemplates = new Set(Object.keys(registry.templates));
const rootPath = path.resolve(root);
const insideRoot = (value) => {
const resolved = path.resolve(rootPath, value);
if (resolved !== rootPath && !resolved.startsWith(rootPath + path.sep)) return null;
return resolved;
};
const validEvidence = (evidence) => {
if (!evidence || evidence.status !== "passed" || !Array.isArray(evidence.commands)) return null;
if (
!evidence.commands.length ||
evidence.commands.some((command) => !command.trim() || /<[^>]+>/.test(command))
)
return null;
if (evidence.exitCode !== 0) return null;
if (!Array.isArray(evidence.artifacts) || !evidence.artifacts.length) return null;
return evidence;
};
const currentSourceTreeHash = sourceTreeHash(root);
let complete = true;
for (const report of reports) {
const evidence = registry.templates[report.template] ?? {};
const completionIssues = [];
if (registry.sourceTreeHash !== currentSourceTreeHash)
completionIssues.push("source tree hash mismatch");
for (const key of report.requiredEvidence) {
const item = validEvidence(evidence[key]);
if (!item) {
completionIssues.push(`${key}: missing or invalid passed evidence`);
continue;
}
for (const artifact of item.artifacts) {
if (!artifact?.path || !/^[a-f0-9]{64}$/.test(artifact.sha256 ?? "")) {
completionIssues.push(`${key}: artifact path or sha256 is invalid`);
continue;
}
const filePath = insideRoot(artifact.path);
if (!filePath || !fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
completionIssues.push(`${key}: artifact does not exist: ${artifact.path}`);
continue;
}
const hash = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
if (hash !== artifact.sha256)
completionIssues.push(`${key}: artifact checksum mismatch: ${artifact.path}`);
}
}
report.evidence = evidence;
report.completionIssues = completionIssues;
report.completionStatus = completionIssues.length ? "incomplete" : "complete";
if (completionIssues.length) complete = false;
}
return { completionStatus: complete ? "complete" : "incomplete", reports };
}