index.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import { gitFileNames } from "./git-file-names.mjs";
  2. import { promises as fs } from "node:fs";
  3. import path from "node:path";
  4. import { createHash } from "node:crypto";
  5. import {
  6. countPublicMethods,
  7. discoverFiles,
  8. importsOf,
  9. isException,
  10. layerForFile,
  11. loadPolicy,
  12. manifestRequires,
  13. moduleForFile,
  14. posix,
  15. publicEntrypointMatches,
  16. resolveImport,
  17. } from "./policy.mjs";
  18. function fingerprint(rule, file, detail = "") {
  19. return createHash("sha256").update(`${rule}\0${file}\0${detail}`).digest("hex").slice(0, 16);
  20. }
  21. function violation({ rule, file, detail, message, module, global = false }) {
  22. return {
  23. rule,
  24. file: posix(file),
  25. module: module?.id ?? null,
  26. detail,
  27. message,
  28. fingerprint: fingerprint(rule, posix(file), detail),
  29. global,
  30. };
  31. }
  32. function cycleViolations(edges, policy, modulesByFile) {
  33. const state = new Map();
  34. const stack = [];
  35. const cycles = [];
  36. function visit(node) {
  37. state.set(node, 1);
  38. stack.push(node);
  39. for (const next of edges.get(node) ?? []) {
  40. if (!modulesByFile.get(next)?.managed && policy.global.managedOnly) continue;
  41. if (state.get(next) === 1) {
  42. const index = stack.indexOf(next);
  43. cycles.push(stack.slice(index).concat(next));
  44. } else if (!state.get(next)) visit(next);
  45. }
  46. stack.pop();
  47. state.set(node, 2);
  48. }
  49. for (const node of edges.keys()) if (!state.get(node)) visit(node);
  50. const unique = new Map();
  51. for (const cycle of cycles) {
  52. const detail = [...new Set(cycle)].sort().join(" -> ");
  53. const file = cycle[0];
  54. unique.set(
  55. detail,
  56. violation({
  57. rule: "cycle",
  58. file,
  59. detail,
  60. module: modulesByFile.get(file),
  61. message: `检测到循环依赖:${cycle.map((item) => posix(item)).join(" -> ")}`,
  62. global: true,
  63. }),
  64. );
  65. }
  66. return [...unique.values()];
  67. }
  68. async function readBaseline(cwd) {
  69. try {
  70. return JSON.parse(await fs.readFile(path.join(cwd, ".architecture-baseline.json"), "utf8"));
  71. } catch {
  72. return { version: 1, violations: [] };
  73. }
  74. }
  75. export async function checkArchitecture({ cwd = process.cwd(), changedFiles = null } = {}) {
  76. const policy = await loadPolicy(cwd);
  77. const files = await discoverFiles(policy);
  78. const knownFiles = new Set(files);
  79. const modulesByFile = new Map(files.map((file) => [file, moduleForFile(file, policy)]));
  80. const edges = new Map(files.map((file) => [file, []]));
  81. const violations = [];
  82. const manifestRequiresByModule = new Map();
  83. const today = new Date().toISOString().slice(0, 10);
  84. for (const exception of policy.exceptions) {
  85. if (exception.expires && exception.expires < today) {
  86. violations.push(
  87. violation({
  88. rule: "expired-exception",
  89. file: path.join(cwd, "architecture-policy.yaml"),
  90. detail: exception.id ?? exception.rule,
  91. message: `例外 ${exception.id ?? exception.rule} 已于 ${exception.expires} 过期`,
  92. global: true,
  93. }),
  94. );
  95. }
  96. }
  97. for (const module of policy.modules.filter((item) => item.managed)) {
  98. const moduleFiles = files.filter((file) => modulesByFile.get(file)?.id === module.id);
  99. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  100. if (manifest)
  101. manifestRequiresByModule.set(
  102. module.id,
  103. manifestRequires(await fs.readFile(manifest, "utf8")) ?? module.requires,
  104. );
  105. const required = ["module.ts", "contract.ts"];
  106. for (const artifact of required) {
  107. if (!moduleFiles.some((file) => path.basename(file) === artifact)) {
  108. const file = module.roots[0];
  109. violations.push(
  110. violation({
  111. rule: "missing-module-artifact",
  112. file,
  113. detail: artifact,
  114. module,
  115. message: `模块 ${module.id} 缺少 ${artifact}`,
  116. }),
  117. );
  118. }
  119. }
  120. }
  121. for (const file of files) {
  122. const module = modulesByFile.get(file);
  123. if (!module || (policy.global.managedOnly && !module.managed)) continue;
  124. const source = await fs.readFile(file, "utf8");
  125. const lines = source.split(/\r?\n/).length;
  126. if (lines > policy.global.maxFileLines && !isException(policy, "max-file-lines", file, cwd)) {
  127. violations.push(
  128. violation({
  129. rule: "max-file-lines",
  130. file,
  131. detail: String(lines),
  132. module,
  133. message: `文件 ${lines} 行,超过上限 ${policy.global.maxFileLines} 行`,
  134. }),
  135. );
  136. }
  137. if (path.basename(file).startsWith("contract.") && lines > policy.global.maxContractLines) {
  138. violations.push(
  139. violation({
  140. rule: "max-contract-lines",
  141. file,
  142. detail: String(lines),
  143. module,
  144. message: `契约 ${lines} 行,超过上限 ${policy.global.maxContractLines} 行`,
  145. }),
  146. );
  147. }
  148. const disableCount = source
  149. .split(/\r?\n/)
  150. .filter((line) => /(?:oxlint|eslint)-disable/.test(line)).length;
  151. if (disableCount > 0 && !isException(policy, "disable-count", file, cwd)) {
  152. violations.push(
  153. violation({
  154. rule: "disable-count",
  155. file,
  156. detail: String(disableCount),
  157. module,
  158. message: `文件包含 ${disableCount} 条 lint disable`,
  159. }),
  160. );
  161. }
  162. if (
  163. path.basename(file) === "contract.ts" &&
  164. countPublicMethods(source) > policy.global.maxPublicMethods
  165. ) {
  166. violations.push(
  167. violation({
  168. rule: "max-public-methods",
  169. file,
  170. detail: String(countPublicMethods(source)),
  171. module,
  172. message: `契约公开方法超过上限 ${policy.global.maxPublicMethods}`,
  173. }),
  174. );
  175. }
  176. const importerLayer = layerForFile(file, module);
  177. const layerOrder = module.layerOrder ?? [];
  178. for (const specifier of importsOf(file, source)) {
  179. if (
  180. importerLayer === "domain" &&
  181. /^(node:|fs$|path$|http$|https$|net$|child_process$|timers$)/.test(specifier)
  182. ) {
  183. violations.push(
  184. violation({
  185. rule: "domain-io",
  186. file,
  187. detail: specifier,
  188. module,
  189. message: "domain 层不能依赖 IO、进程、网络或定时器",
  190. }),
  191. );
  192. }
  193. const target = resolveImport(file, specifier, knownFiles);
  194. if (!target) continue;
  195. edges.get(file).push(target);
  196. const targetModule = modulesByFile.get(target);
  197. if (targetModule?.id === module.id) {
  198. const targetLayer = layerForFile(target, module);
  199. if (
  200. importerLayer &&
  201. targetLayer &&
  202. layerOrder.includes(importerLayer) &&
  203. layerOrder.includes(targetLayer) &&
  204. layerOrder.indexOf(importerLayer) < layerOrder.indexOf(targetLayer)
  205. ) {
  206. violations.push(
  207. violation({
  208. rule: "layer-direction",
  209. file,
  210. detail: target,
  211. module,
  212. message: `层 ${importerLayer} 不能依赖更高层 ${targetLayer}`,
  213. }),
  214. );
  215. }
  216. }
  217. if (module.id === "ui" && /(?:^|\/)(repo|runtime|services?)(?:\/|$)/i.test(posix(target))) {
  218. violations.push(
  219. violation({
  220. rule: "ui-implementation-import",
  221. file,
  222. detail: target,
  223. module,
  224. message: "UI 层不能直接依赖 Repo、Runtime 或 Service 实现",
  225. }),
  226. );
  227. }
  228. if (!targetModule || targetModule.id === module.id) {
  229. continue;
  230. }
  231. const declaredRequires = manifestRequiresByModule.get(module.id) ?? module.requires;
  232. if (!declaredRequires.includes(targetModule.id)) {
  233. violations.push(
  234. violation({
  235. rule: "module-dependency",
  236. file,
  237. detail: target,
  238. module,
  239. message: `模块 ${module.id} 未声明依赖 ${targetModule.id}`,
  240. }),
  241. );
  242. }
  243. if (policy.global.forbidDeepImports && targetModule.publicEntrypoints.length > 0) {
  244. const targetRelative = posix(path.relative(cwd, target));
  245. const allowed = publicEntrypointMatches(target, targetModule, cwd);
  246. if (!allowed) {
  247. violations.push(
  248. violation({
  249. rule: "deep-import",
  250. file,
  251. detail: target,
  252. module,
  253. message: `跨模块只能通过公开入口访问 ${targetRelative}`,
  254. }),
  255. );
  256. }
  257. }
  258. }
  259. if (importerLayer === "domain" && /\b(fetch|setTimeout|setInterval)\s*\(/.test(source)) {
  260. violations.push(
  261. violation({
  262. rule: "domain-io",
  263. file,
  264. detail: "runtime-call",
  265. module,
  266. message: "domain 层不能依赖 IO、进程、网络或定时器",
  267. }),
  268. );
  269. }
  270. }
  271. if (policy.global.forbidCycles) violations.push(...cycleViolations(edges, policy, modulesByFile));
  272. const baseline = await readBaseline(cwd);
  273. const baselineFingerprints = new Set(baseline.violations.map((item) => item.fingerprint));
  274. const changed = changedFiles
  275. ? new Set(changedFiles.map((file) => path.resolve(cwd, file)))
  276. : null;
  277. if (changed) {
  278. const reverse = new Map(files.map((file) => [file, []]));
  279. for (const [from, targets] of edges)
  280. for (const target of targets) reverse.get(target)?.push(from);
  281. const queue = [...changed];
  282. while (queue.length > 0) {
  283. const current = queue.shift();
  284. for (const dependent of reverse.get(current) ?? []) {
  285. if (!changed.has(dependent)) {
  286. changed.add(dependent);
  287. queue.push(dependent);
  288. }
  289. }
  290. }
  291. }
  292. const scoped = changed
  293. ? violations.filter((item) => item.global || changed.has(path.resolve(cwd, item.file)))
  294. : violations;
  295. const baselineViolations = scoped.filter((item) => baselineFingerprints.has(item.fingerprint));
  296. const newViolations = scoped.filter((item) => !baselineFingerprints.has(item.fingerprint));
  297. return { policy, violations: scoped, baselineViolations, newViolations, baseline };
  298. }
  299. export async function updateBaseline({ cwd = process.cwd(), violations }) {
  300. const entries = [...violations].sort((a, b) => a.fingerprint.localeCompare(b.fingerprint));
  301. const filename = path.join(cwd, ".architecture-baseline.json");
  302. await fs.writeFile(filename, `${JSON.stringify({ version: 1, violations: entries }, null, 2)}\n`);
  303. return entries;
  304. }
  305. export async function changedFilesFromGit(cwd = process.cwd()) {
  306. const [diff, untracked] = await Promise.all([
  307. gitFileNames(cwd, ["diff", "--name-only", "-z", "HEAD"]),
  308. gitFileNames(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
  309. ]);
  310. return [...new Set([...diff, ...untracked])];
  311. }
  312. export async function generateContext({ cwd = process.cwd(), moduleId }) {
  313. const policy = await loadPolicy(cwd);
  314. const module = policy.modules.find((item) => item.id === moduleId);
  315. if (!module) throw new Error(`未知模块: ${moduleId}`);
  316. const files = await discoverFiles(policy);
  317. const moduleFiles = files.filter((file) => moduleForFile(file, policy)?.id === moduleId);
  318. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  319. const contracts = moduleFiles.filter((file) => path.basename(file).startsWith("contract."));
  320. const dependencyContracts = module.requires.flatMap((dependencyId) => {
  321. const dependencyFiles = files.filter(
  322. (file) => moduleForFile(file, policy)?.id === dependencyId,
  323. );
  324. return dependencyFiles
  325. .filter((file) => path.basename(file) === "contract.ts")
  326. .map((file) => `- ${posix(path.relative(cwd, file))}`);
  327. });
  328. return [
  329. `# Architecture context: ${module.id}`,
  330. `owner: ${module.owner ?? "unassigned"}`,
  331. `managed: ${module.managed}`,
  332. `requires: ${module.requires.join(", ") || "none"}`,
  333. "",
  334. "## Files",
  335. ...(manifest ? [`- ${posix(path.relative(cwd, manifest))}`] : ["- module.ts: missing"]),
  336. ...contracts.map((file) => `- ${posix(path.relative(cwd, file))}`),
  337. ...module.publicEntrypoints.map((entry) => `- public: ${entry}`),
  338. "",
  339. "## Direct dependency contracts",
  340. ...(dependencyContracts.length > 0 ? dependencyContracts : ["- none discovered"]),
  341. "",
  342. "## Boundaries",
  343. "- Cross-module imports must use declared requirements and public entrypoints.",
  344. "- Add a contract example before exposing a new capability.",
  345. ].join("\n");
  346. }
  347. export function formatReport(result) {
  348. const lines = [
  349. `architecture: ${result.newViolations.length === 0 ? "OK" : "FAILED"}`,
  350. `violations: ${result.violations.length}`,
  351. `baseline: ${result.baselineViolations.length}`,
  352. `new: ${result.newViolations.length}`,
  353. ];
  354. for (const item of result.newViolations)
  355. lines.push(`- ${item.rule} ${item.file}: ${item.message}`);
  356. return lines.join("\n");
  357. }
  358. export function formatMarkdownReport(result) {
  359. const lines = [
  360. `# Architecture report`,
  361. "",
  362. `- Status: **${result.newViolations.length === 0 ? "OK" : "FAILED"}**`,
  363. `- Violations: ${result.violations.length}`,
  364. `- Baseline: ${result.baselineViolations.length}`,
  365. `- New: ${result.newViolations.length}`,
  366. ];
  367. if (result.newViolations.length > 0) {
  368. lines.push("", "## New violations", "", "| Rule | File | Message |", "| --- | --- | --- |");
  369. for (const item of result.newViolations)
  370. lines.push(`| ${item.rule} | ${item.file} | ${item.message.replaceAll("|", "\\|")} |`);
  371. }
  372. return lines.join("\n");
  373. }
  374. export { loadPolicy };