包文件→ .shtukbase/packages/design-components/checks/no-level-up.ts
checks/no-level-up.ts
35 行, 1.6 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // DSC-R03. A component uses only components of its own level or below (primitive < composite < block < page), and the
- // uses never go in a circle. A primitive that uses a composite is the usual mistake: the dependency points up.
- import { LEVELS } from '../lib/header.ts';
- import { collect } from '../lib/project.ts';
- import { report } from '../lib/report.ts';
- export const RULE = { id: 'dsc-r03', title: 'A component does not use a component of a higher level' };
- export function check(root = process.cwd()): string[] {
- const col = collect(root);
- const by = new Map(col.comps.map((c) => [c.id, c]));
- const out: string[] = [];
- for (const c of col.comps)
- for (const u of c.header.uses) {
- const used = by.get(u);
- if (used && LEVELS.indexOf(used.header.level) > LEVELS.indexOf(c.header.level))
- out.push(`${c.source}: ${c.header.level} "${c.id}" uses ${used.header.level} "${u}" — a component uses only its own level or below`);
- }
- // cycles: a depth-first walk; every cycle is named once
- const seen = new Set<string>();
- const walk = (id: string, path: string[]) => {
- const at = path.indexOf(id);
- if (at >= 0) {
- const ring = [...path.slice(at), id];
- const key = ring.slice(0, -1).sort().join('>');
- if (!seen.has(key)) { seen.add(key); out.push(`${by.get(id)!.source}: uses go in a circle: ${ring.join(' → ')}`); }
- return;
- }
- for (const u of by.get(id)?.header.uses ?? []) if (by.has(u)) walk(u, [...path, id]);
- };
- for (const id of by.keys()) walk(id, []);
- return out;
- }
- if (import.meta.main) report(check());