index.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import { promises as fs } from "node:fs";
  2. import path from "node:path";
  3. import {
  4. countPublicMethods,
  5. discoverFiles,
  6. importDeclarationsOf,
  7. isException,
  8. layerForFile,
  9. loadPolicy,
  10. manifestRequires,
  11. moduleForFile,
  12. posix,
  13. publicEntrypointMatches,
  14. resolveImport,
  15. } from "./policy.mjs";
  16. import { loadWorkspace } from "./resolver.mjs";
  17. import { cycleViolations, unmanagedNewFileViolations, violation } from "./violations.mjs";
  18. async function readBaseline(cwd) {
  19. try {
  20. return JSON.parse(await fs.readFile(path.join(cwd, ".architecture-baseline.json"), "utf8"));
  21. } catch {
  22. return { version: 1, violations: [] };
  23. }
  24. }
  25. export async function checkArchitecture({
  26. cwd = process.cwd(),
  27. changedFiles = null,
  28. addedFiles = null,
  29. } = {}) {
  30. const policy = await loadPolicy(cwd);
  31. const workspace = await loadWorkspace(cwd);
  32. const files = await discoverFiles(policy);
  33. const knownFiles = new Set(files);
  34. const modulesByFile = new Map(files.map((file) => [file, moduleForFile(file, policy)]));
  35. const edges = new Map(files.map((file) => [file, []]));
  36. const violations = [];
  37. const manifestRequiresByModule = new Map();
  38. const moduleIds = new Set(policy.modules.map((module) => module.id));
  39. const today = new Date().toISOString().slice(0, 10);
  40. for (const exception of policy.exceptions) {
  41. if (exception.expires && exception.expires < today) {
  42. violations.push(
  43. violation({
  44. cwd,
  45. rule: "expired-exception",
  46. file: path.join(cwd, "architecture-policy.yaml"),
  47. detail: exception.id ?? exception.rule,
  48. message: `例外 ${exception.id ?? exception.rule} 已于 ${exception.expires} 过期`,
  49. global: true,
  50. }),
  51. );
  52. }
  53. }
  54. for (const module of policy.modules.filter((item) => item.managed)) {
  55. const moduleFiles = files.filter((file) => modulesByFile.get(file)?.id === module.id);
  56. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  57. if (manifest) {
  58. const declared = manifestRequires(await fs.readFile(manifest, "utf8"));
  59. if (declared) {
  60. manifestRequiresByModule.set(module.id, declared);
  61. // manifest-policy-mismatch:文档写"策略与模块声明必须互相校验",首版只是优先读 module.ts。
  62. const unknown = declared.filter((id) => !moduleIds.has(id));
  63. const onlyInManifest = declared.filter((id) => !module.requires.includes(id));
  64. const onlyInPolicy = module.requires.filter((id) => !declared.includes(id));
  65. if (unknown.length || onlyInManifest.length || onlyInPolicy.length) {
  66. const parts = [];
  67. if (unknown.length) parts.push(`未知模块 ${unknown.join(", ")}`);
  68. if (onlyInManifest.length) parts.push(`仅 module.ts 声明 ${onlyInManifest.join(", ")}`);
  69. if (onlyInPolicy.length) parts.push(`仅 policy 声明 ${onlyInPolicy.join(", ")}`);
  70. violations.push(
  71. violation({
  72. cwd,
  73. rule: "manifest-policy-mismatch",
  74. file: manifest,
  75. detail: parts.join("; "),
  76. module,
  77. message: `module.ts 与 architecture-policy.yaml 的 requires 不一致:${parts.join(";")}`,
  78. }),
  79. );
  80. }
  81. }
  82. }
  83. const required = [
  84. "module.ts",
  85. "contract.ts",
  86. "contract.example.ts",
  87. "contract.test.ts",
  88. "CONTRACT.md",
  89. ];
  90. for (const artifact of required) {
  91. // 修复原因:discoverFiles 只收集源码扩展名,CONTRACT.md 永远不在 moduleFiles 里,
  92. // 首版对每个 managed 模块都会误报缺少 CONTRACT.md(--changed 下被 scope 过滤掉才没暴露)。
  93. const present = (
  94. await Promise.all(
  95. module.roots.map((root) =>
  96. fs.stat(path.join(root, artifact)).then(
  97. () => true,
  98. () => false,
  99. ),
  100. ),
  101. )
  102. ).some(Boolean);
  103. if (!present) {
  104. violations.push(
  105. violation({
  106. cwd,
  107. rule: "missing-module-artifact",
  108. file: module.roots[0],
  109. detail: artifact,
  110. module,
  111. message: `模块 ${module.id} 缺少 ${artifact}`,
  112. }),
  113. );
  114. }
  115. }
  116. }
  117. for (const file of files) {
  118. // CONTRACT.md 只参与产物存在性检查,文档里的示例不能当成源码依赖或源码行数。
  119. if (path.extname(file) === ".md") continue;
  120. const module = modulesByFile.get(file);
  121. if (!module) continue;
  122. const source = await fs.readFile(file, "utf8");
  123. const declarations = importDeclarationsOf(file, source);
  124. // 边对所有文件建立(含 unmanaged),否则 --changed 的反向闭包与环检测都会缺边;规则只对 managed 生效。
  125. for (const { specifier } of declarations) {
  126. const target = resolveImport(file, specifier, knownFiles, workspace);
  127. if (target) edges.get(file).push(target);
  128. }
  129. if (policy.global.managedOnly && !module.managed) continue;
  130. const lines = source.split(/\r?\n/).length;
  131. if (lines > policy.global.maxFileLines && !isException(policy, "max-file-lines", file, cwd)) {
  132. violations.push(
  133. violation({
  134. cwd,
  135. rule: "max-file-lines",
  136. file,
  137. detail: String(lines),
  138. module,
  139. message: `文件 ${lines} 行,超过上限 ${policy.global.maxFileLines} 行`,
  140. }),
  141. );
  142. }
  143. if (path.basename(file).startsWith("contract.") && lines > policy.global.maxContractLines) {
  144. violations.push(
  145. violation({
  146. cwd,
  147. rule: "max-contract-lines",
  148. file,
  149. detail: String(lines),
  150. module,
  151. message: `契约 ${lines} 行,超过上限 ${policy.global.maxContractLines} 行`,
  152. }),
  153. );
  154. }
  155. const disableCount = source
  156. .split(/\r?\n/)
  157. .filter((line) => /(?:oxlint|eslint)-disable/.test(line)).length;
  158. if (disableCount > 0 && !isException(policy, "disable-count", file, cwd)) {
  159. violations.push(
  160. violation({
  161. cwd,
  162. rule: "disable-count",
  163. file,
  164. detail: String(disableCount),
  165. module,
  166. message: `文件包含 ${disableCount} 条 lint disable`,
  167. }),
  168. );
  169. }
  170. if (
  171. path.basename(file) === "contract.ts" &&
  172. countPublicMethods(source) > policy.global.maxPublicMethods
  173. ) {
  174. violations.push(
  175. violation({
  176. cwd,
  177. rule: "max-public-methods",
  178. file,
  179. detail: String(countPublicMethods(source)),
  180. module,
  181. message: `契约公开方法超过上限 ${policy.global.maxPublicMethods}`,
  182. }),
  183. );
  184. }
  185. const importerLayer = layerForFile(file, module);
  186. const layerOrder = module.layerOrder ?? [];
  187. for (const { specifier, typeOnly } of declarations) {
  188. if (
  189. importerLayer === "domain" &&
  190. !typeOnly &&
  191. /^(node:|fs$|path$|http$|https$|net$|child_process$|timers$|electron$|electron\/)/.test(
  192. specifier,
  193. )
  194. ) {
  195. violations.push(
  196. violation({
  197. cwd,
  198. rule: "domain-io",
  199. file,
  200. detail: specifier,
  201. module,
  202. message: "domain 层不能依赖 IO、进程、网络、定时器或 electron",
  203. }),
  204. );
  205. }
  206. const target = resolveImport(file, specifier, knownFiles, workspace);
  207. if (!target) continue;
  208. const targetModule = modulesByFile.get(target);
  209. if (targetModule?.id === module.id) {
  210. const targetLayer = layerForFile(target, module);
  211. if (
  212. importerLayer &&
  213. targetLayer &&
  214. layerOrder.includes(importerLayer) &&
  215. layerOrder.includes(targetLayer) &&
  216. layerOrder.indexOf(importerLayer) < layerOrder.indexOf(targetLayer)
  217. ) {
  218. violations.push(
  219. violation({
  220. cwd,
  221. rule: "layer-direction",
  222. file,
  223. detail: target,
  224. module,
  225. message: `层 ${importerLayer} 不能依赖更高层 ${targetLayer}`,
  226. }),
  227. );
  228. }
  229. }
  230. // 修复原因:首版以 module.id === "ui" 触发,而 ui 是 unmanaged 模块,规则从未执行;改为按层触发。
  231. if (
  232. (importerLayer === "ui" || module.id === "ui") &&
  233. /(?:^|\/)(repo|repos|repository|runtime|services?)(?:\/|$)/i.test(
  234. posix(path.relative(cwd, target)),
  235. )
  236. ) {
  237. violations.push(
  238. violation({
  239. cwd,
  240. rule: "ui-implementation-import",
  241. file,
  242. detail: target,
  243. module,
  244. message:
  245. "UI 层不能直接依赖 Repo、Runtime 或 Service 实现;通过本模块 contract/port 访问",
  246. }),
  247. );
  248. }
  249. if (!targetModule || targetModule.id === module.id) continue;
  250. const declaredRequires = manifestRequiresByModule.get(module.id) ?? module.requires;
  251. if (!declaredRequires.includes(targetModule.id)) {
  252. violations.push(
  253. violation({
  254. cwd,
  255. rule: "module-dependency",
  256. file,
  257. detail: target,
  258. module,
  259. message: `模块 ${module.id} 未声明依赖 ${targetModule.id}(import "${specifier}")`,
  260. }),
  261. );
  262. }
  263. if (policy.global.forbidDeepImports && targetModule.publicEntrypoints.length > 0) {
  264. if (!publicEntrypointMatches(target, targetModule, cwd)) {
  265. violations.push(
  266. violation({
  267. cwd,
  268. rule: "deep-import",
  269. file,
  270. detail: target,
  271. module,
  272. message: `跨模块只能通过公开入口访问 ${posix(path.relative(cwd, target))}(import "${specifier}")`,
  273. }),
  274. );
  275. }
  276. }
  277. }
  278. if (importerLayer === "domain" && /\b(fetch|setTimeout|setInterval)\s*\(/.test(source)) {
  279. violations.push(
  280. violation({
  281. cwd,
  282. rule: "domain-io",
  283. file,
  284. detail: "runtime-call",
  285. module,
  286. message: "domain 层不能依赖 IO、进程、网络或定时器",
  287. }),
  288. );
  289. }
  290. }
  291. if (policy.global.forbidCycles)
  292. violations.push(...cycleViolations(edges, policy, modulesByFile, cwd));
  293. if (addedFiles) violations.push(...unmanagedNewFileViolations(addedFiles, policy, cwd));
  294. const baseline = await readBaseline(cwd);
  295. const baselineFingerprints = new Set(baseline.violations.map((item) => item.fingerprint));
  296. const changed = changedFiles
  297. ? new Set(changedFiles.map((file) => path.resolve(cwd, file)))
  298. : null;
  299. if (changed) {
  300. const reverse = new Map(files.map((file) => [file, []]));
  301. for (const [from, targets] of edges)
  302. for (const target of targets) reverse.get(target)?.push(from);
  303. const queue = [...changed];
  304. while (queue.length > 0) {
  305. const current = queue.shift();
  306. for (const dependent of reverse.get(current) ?? []) {
  307. if (!changed.has(dependent)) {
  308. changed.add(dependent);
  309. queue.push(dependent);
  310. }
  311. }
  312. }
  313. }
  314. const scoped = changed
  315. ? violations.filter((item) => item.global || changed.has(path.resolve(cwd, item.file)))
  316. : violations;
  317. const baselineViolations = scoped.filter((item) => baselineFingerprints.has(item.fingerprint));
  318. const newViolations = scoped.filter((item) => !baselineFingerprints.has(item.fingerprint));
  319. return {
  320. policy,
  321. violations: scoped,
  322. baselineViolations,
  323. newViolations,
  324. baseline,
  325. changedClosure: changed,
  326. };
  327. }
  328. /**
  329. * scope 为 --changed 的变更闭包。修复原因:首版直接用 scoped 结果覆盖整份 baseline,
  330. * `baseline:update -- --changed` 会把闭包之外的所有条目全部丢掉。
  331. */
  332. export async function updateBaseline({ cwd = process.cwd(), violations, scope = null }) {
  333. const filename = path.join(cwd, ".architecture-baseline.json");
  334. const previous = scope ? (await readBaseline(cwd)).violations : [];
  335. const kept = scope
  336. ? previous.filter((item) => !item.global && !scope.has(path.resolve(cwd, item.file)))
  337. : [];
  338. const merged = new Map();
  339. for (const item of [...kept, ...violations]) merged.set(item.fingerprint, item);
  340. const entries = [...merged.values()].sort((a, b) => a.fingerprint.localeCompare(b.fingerprint));
  341. await fs.writeFile(filename, `${JSON.stringify({ version: 1, violations: entries }, null, 2)}\n`);
  342. return entries;
  343. }
  344. export { loadPolicy };
  345. export { addedFilesFromGit, changedFilesFromGit, resolveDiffBase } from "./git-base.mjs";
  346. export { generateContext } from "./context.mjs";
  347. export { formatMarkdownReport, formatReport } from "./report.mjs";