policy.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import { promises as fs } from "node:fs";
  2. import path from "node:path";
  3. import ts from "typescript";
  4. import { parse as parseYaml } from "yaml";
  5. import { SOURCE_EXTENSIONS, resolveSpecifier } from "./resolver.mjs";
  6. import { isSnapshotPath } from "./upstream-snapshot.mjs";
  7. export { SOURCE_EXTENSIONS };
  8. export function posix(value) {
  9. return value.split(path.sep).join("/");
  10. }
  11. export function isSourceFile(file) {
  12. return SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension));
  13. }
  14. async function walk(root, files) {
  15. let entries;
  16. try {
  17. entries = await fs.readdir(root, { withFileTypes: true });
  18. } catch {
  19. return;
  20. }
  21. for (const entry of entries) {
  22. if (["node_modules", "dist", "out", "coverage", ".git"].includes(entry.name)) continue;
  23. const target = path.join(root, entry.name);
  24. if (entry.isDirectory()) await walk(target, files);
  25. // 契约文档也是必需产物;只枚举源码会把实际存在的 CONTRACT.md 误报为缺失。
  26. else if (entry.isFile() && (isSourceFile(target) || entry.name === "CONTRACT.md"))
  27. files.push(target);
  28. }
  29. }
  30. function validatePolicy(raw, cwd) {
  31. if (!raw || raw.version !== 1 || !Array.isArray(raw.modules)) {
  32. throw new Error("architecture-policy.yaml 必须包含 version: 1 和 modules 数组");
  33. }
  34. const ids = new Set();
  35. const modules = raw.modules.map((module) => {
  36. if (!module?.id || ids.has(module.id))
  37. throw new Error(`模块 id 重复或为空: ${module?.id ?? ""}`);
  38. ids.add(module.id);
  39. if (!Array.isArray(module.roots) || module.roots.length === 0) {
  40. throw new Error(`模块 ${module.id} 必须声明 roots`);
  41. }
  42. return {
  43. id: module.id,
  44. roots: module.roots.map((root) => path.resolve(cwd, root)),
  45. managed: module.managed === true,
  46. requires: [...new Set(module.requires ?? [])],
  47. publicEntrypoints: (module.publicEntrypoints ?? []).map((entry) => posix(entry)),
  48. layers: module.layers ?? {},
  49. layerOrder: module.layerOrder ?? Object.keys(module.layers ?? {}),
  50. owner: module.owner ?? null,
  51. };
  52. });
  53. const moduleIds = new Set(modules.map((module) => module.id));
  54. for (const module of modules) {
  55. for (const dependency of module.requires) {
  56. if (!moduleIds.has(dependency))
  57. throw new Error(`模块 ${module.id} 依赖未知模块 ${dependency}`);
  58. }
  59. }
  60. const global = {
  61. maxFileLines: raw.global?.maxFileLines ?? 800,
  62. maxContractLines: raw.global?.maxContractLines ?? 300,
  63. forbidCycles: raw.global?.forbidCycles !== false,
  64. forbidDeepImports: raw.global?.forbidDeepImports !== false,
  65. managedOnly: raw.global?.managedOnly !== false,
  66. maxPublicMethods: raw.global?.maxPublicMethods ?? 12,
  67. // 新增源码文件必须落在 managed 模块内;这是"新代码走这套约束"的唯一机械保证。
  68. newFilesRequireManagedModule: raw.global?.newFilesRequireManagedModule !== false,
  69. newFileScopes: raw.global?.newFileScopes ?? ["packages", "apps"],
  70. // 规则生效时间点:首次进入 git 历史早于该日期的文件不受 unmanaged-new-file 追溯。
  71. // 原因:长期分支相对 merge-base 有几百个提交的"新增"文件,它们写在规则存在之前;
  72. // 用共享 baseline 兜会让各分支互相冲突,用生效日期则各分支一致且无需登记。
  73. newFilesEnforcedSince: raw.global?.newFilesEnforcedSince
  74. ? String(raw.global.newFilesEnforcedSince)
  75. : null,
  76. acceptedUpstreamCommits: raw.global?.acceptedUpstreamCommits ?? [],
  77. acceptedUpstreamSnapshot: raw.global?.acceptedUpstreamSnapshot ?? null,
  78. };
  79. if (
  80. !Array.isArray(global.acceptedUpstreamCommits) ||
  81. global.acceptedUpstreamCommits.some(
  82. (entry) =>
  83. !entry ||
  84. !/^[a-f0-9]{40}$/.test(entry.commit ?? "") ||
  85. !/^[a-f0-9]{40}$/.test(entry.previousHead ?? "") ||
  86. typeof entry.reason !== "string" ||
  87. !entry.reason.trim(),
  88. )
  89. ) {
  90. throw new Error("acceptedUpstreamCommits 必须包含完整 commit、previousHead SHA 和非空 reason");
  91. }
  92. if (
  93. global.acceptedUpstreamSnapshot !== null &&
  94. (!isSnapshotPath(global.acceptedUpstreamSnapshot) || global.acceptedUpstreamCommits.length)
  95. ) {
  96. throw new Error(
  97. "acceptedUpstreamSnapshot 必须为仓库相对路径,且不能与 acceptedUpstreamCommits 混用",
  98. );
  99. }
  100. const exceptions = (raw.exceptions ?? []).map((exception) => ({
  101. ...exception,
  102. paths: exception.paths ?? [],
  103. }));
  104. return { version: 1, modules, global, exceptions };
  105. }
  106. export function layerForFile(file, module) {
  107. const matches = module.roots
  108. .flatMap((root) =>
  109. Object.entries(module.layers).map(([name, directory]) => ({
  110. name,
  111. directory: path.resolve(root, directory),
  112. })),
  113. )
  114. .filter(({ directory }) => file === directory || file.startsWith(`${directory}${path.sep}`))
  115. .sort((a, b) => b.directory.length - a.directory.length);
  116. return matches[0]?.name ?? null;
  117. }
  118. export function publicEntrypointMatches(target, targetModule, cwd) {
  119. return targetModule.publicEntrypoints.some((entry) => {
  120. const candidates = [
  121. path.resolve(cwd, entry),
  122. ...targetModule.roots.map((root) => path.resolve(root, entry)),
  123. ];
  124. return candidates.includes(target);
  125. });
  126. }
  127. export function manifestRequires(source) {
  128. const match = source.match(/requires\s*:\s*\[([^\]]*)\]/s);
  129. if (!match) return null;
  130. return [...match[1].matchAll(/["']([^"']+)["']/g)].map((item) => item[1]);
  131. }
  132. export function countPublicMethods(source) {
  133. const sourceFile = ts.createSourceFile("contract.ts", source, ts.ScriptTarget.Latest, true);
  134. let count = 0;
  135. function visit(node) {
  136. if (ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) {
  137. for (const member of node.members) {
  138. if (
  139. ts.isMethodSignature(member) ||
  140. ts.isMethodDeclaration(member) ||
  141. ts.isCallSignatureDeclaration(member)
  142. )
  143. count += 1;
  144. }
  145. }
  146. ts.forEachChild(node, visit);
  147. }
  148. visit(sourceFile);
  149. return count;
  150. }
  151. export async function loadPolicy(cwd = process.cwd()) {
  152. const filename = path.join(cwd, "architecture-policy.yaml");
  153. const content = await fs.readFile(filename, "utf8");
  154. return validatePolicy(parseYaml(content), cwd);
  155. }
  156. export function moduleForFile(file, policy) {
  157. const candidates = policy.modules
  158. .filter((module) =>
  159. module.roots.some((root) => file === root || file.startsWith(`${root}${path.sep}`)),
  160. )
  161. .sort(
  162. (a, b) =>
  163. Math.max(...b.roots.map((root) => root.length)) -
  164. Math.max(...a.roots.map((root) => root.length)),
  165. );
  166. return candidates[0] ?? null;
  167. }
  168. export async function discoverFiles(policy) {
  169. const files = [];
  170. for (const module of policy.modules) {
  171. for (const root of module.roots) await walk(root, files);
  172. }
  173. return [...new Set(files)].sort();
  174. }
  175. export function resolveImport(from, specifier, knownFiles, workspace = null) {
  176. return resolveSpecifier(from, specifier, knownFiles, workspace);
  177. }
  178. /**
  179. * 返回 [{ specifier, typeOnly }]。typeOnly 覆盖 `import type {}`、`export type {}` 以及
  180. * 所有具名成员都是 `type` 修饰的情况;它们不产生运行时依赖,domain-io 不应把
  181. * `import type { Stats } from "node:fs"` 当成 IO。模块边界与深导入仍然按边计算。
  182. */
  183. export function importDeclarationsOf(file, source) {
  184. const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
  185. const imports = [];
  186. function visit(node) {
  187. if (ts.isImportDeclaration(node) && node.moduleSpecifier) {
  188. const clause = node.importClause;
  189. const named = clause?.namedBindings;
  190. const allMembersTypeOnly =
  191. !!clause &&
  192. !clause.name &&
  193. !!named &&
  194. ts.isNamedImports(named) &&
  195. named.elements.length > 0 &&
  196. named.elements.every((element) => element.isTypeOnly);
  197. imports.push({
  198. specifier: node.moduleSpecifier.text,
  199. typeOnly: !!clause?.isTypeOnly || allMembersTypeOnly,
  200. });
  201. } else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
  202. imports.push({ specifier: node.moduleSpecifier.text, typeOnly: !!node.isTypeOnly });
  203. } else if (
  204. ts.isImportEqualsDeclaration(node) &&
  205. ts.isExternalModuleReference(node.moduleReference) &&
  206. ts.isStringLiteral(node.moduleReference.expression)
  207. ) {
  208. imports.push({ specifier: node.moduleReference.expression.text, typeOnly: false });
  209. }
  210. ts.forEachChild(node, visit);
  211. }
  212. visit(sourceFile);
  213. return imports;
  214. }
  215. export function importsOf(file, source) {
  216. return importDeclarationsOf(file, source).map((item) => item.specifier);
  217. }
  218. export function isException(policy, rule, file, cwd) {
  219. const relative = posix(path.relative(cwd, file));
  220. return policy.exceptions.some(
  221. (exception) =>
  222. exception.rule === rule &&
  223. exception.paths.some(
  224. (pattern) => relative === pattern || relative.startsWith(pattern.replace(/\*\*$/, "")),
  225. ),
  226. );
  227. }