archivo del paquete→ .shtukbase/packages/collections/checks/lib/speclib.ts
checks/lib/speclib.ts
216 líneas, 9.8 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The shared part of the checks: a project read from disk (read-only), a rule's result, running a rule.
- // Collections are found by the `itemType` of their page, not by path; a relation field is found by the collection
- // it leads to; the state category (arriving / working / done / dropped) comes from the phase page of the contour.
- // A rule knows only types and the meaning of a link: rename a field or a folder in the schema and the rule follows.
- import { existsSync, readFileSync } from 'node:fs';
- import { join, resolve } from 'node:path';
- import { type Head, type Rec, loadCollection, normPath, normStatus, pystr, schemaProperties, truthy, walk } from './pages.ts';
- export * from './pages.ts';
- /** Record types the rules work with, by key. Several names in case a type has not settled yet. Packages may add keys. */
- export const TYPES: Record<string, string[]> = {
- BR: ['BusinessRequirement'], BOBJ: ['BusinessObject'], CAP: ['Capability'], REQ: ['Requirement'],
- SURF: ['Surface'], SCEN: ['Scenario'], AUTO: ['ProductAutomation'], INTENT: ['Intent'], REFUSAL: ['Refusal'],
- CONCEPT: ['Concept'], CHECK: ['Check'], GOLDEN: ['Golden'], ACTION: ['ProductAction', 'Action'],
- AC: ['AcceptanceCriterion'], STAGE: ['Stage'], OBLIGATION: ['Obligation'],
- COMPONENT: ['Component', 'SoftwareComponent', 'ArchComponent'],
- DESIGN: ['DesignPrimitive', 'DesignComposite', 'DesignBlock', 'DesignScreen'],
- };
- export const TYPE_LABEL: Record<string, string> = {
- BR: 'business requirements', BOBJ: 'business objects', CAP: 'capabilities', REQ: 'requirements', SURF: 'surfaces',
- SCEN: 'scenarios', AUTO: 'automations', INTENT: 'intents', REFUSAL: 'refusals', CONCEPT: 'concepts',
- CHECK: 'product tests', GOLDEN: 'golden examples', ACTION: 'product actions', AC: 'acceptance criteria',
- STAGE: 'deal stages', OBLIGATION: 'deal obligations', COMPONENT: 'components of the Software Architecture layer',
- DESIGN: 'components of the Design layer',
- };
- /** The schema is ambiguous or broken: the run stops with "schema error". */
- export class SchemaError extends Error {}
- /** Address of a record for a person: the path from the project root without the leading slash. */
- export function addr(rid: string): string {
- return rid.replace(/^\/+/, '');
- }
- const rtrim = (s: unknown) => String(s ?? '').replace(/\/+$/, '');
- const isMap = (v: unknown): v is Head => !!v && typeof v === 'object' && !Array.isArray(v);
- export class Project {
- readonly root: string;
- private colls: Record<string, string> | null = null;
- private allColls: Record<string, string[]> = {};
- private recs: Record<string, Rec[]> = {};
- private schemas: Record<string, Head> = {};
- private cats: Record<string, string> = {};
- constructor(root: string) {
- this.root = resolve(root);
- if (!existsSync(this.root)) throw new Error(`no project folder: ${this.root}`);
- }
- /** `{itemType: collection path}`. Collection pages are `<layer>.md` and `<layer>/<name>.md`, never deeper. */
- collections(): Record<string, string> {
- if (this.colls) return this.colls;
- const found: Record<string, string> = {};
- for (const [rel, files] of walk(this.root, (n, depth) => depth === 0 && !n.startsWith('.') && n !== 'deleted')) {
- for (const f of files.filter((x) => x.endsWith('.md'))) {
- const path = rel === '.' ? f : rel + '/' + f;
- const head = readFileSync(join(this.root, path), 'utf8').slice(0, 4096);
- if (!head.startsWith('---') || !/^type:\s*"?Collection"?\s*$/m.test(head)) continue;
- const t = /^itemType:\s*"?([A-Za-z]+)"?\s*$/m.exec(head)?.[1];
- if (!t || t === 'Collection') continue;
- const coll = '/' + path.slice(0, -3);
- found[t] ??= coll;
- (this.allColls[t] ??= []).push(coll);
- }
- }
- return (this.colls = found);
- }
- /** Path of the collection of a type key (`TASK`), or null if the project has none. */
- coll(key: string): string | null {
- for (const name of TYPES[key]) if (name in this.collections()) return this.collections()[name];
- return null;
- }
- /** Records of the collection of a type key; [] if there is no such collection. */
- records(key: string): Rec[] {
- const c = this.coll(key);
- if (c === null) return [];
- const folder = c.replace(/^\/+/, '');
- return (this.recs[c] ??= loadCollection(this.root, folder.split('/').pop()!, folder));
- }
- /** `{id: record}` of a type key. */
- index(key: string): Record<string, Rec> {
- return Object.fromEntries(this.records(key).map((r) => [r.id, r]));
- }
- /** `properties:` of the collection of a type key; {} if none. */
- schema(key: string): Head {
- const c = this.coll(key);
- if (c === null) return {};
- return (this.schemas[c] ??= schemaProperties(this.root, c.replace(/^\/+/, '') + '.md'));
- }
- /** Why there is no data ("no collection" / "empty"), or null when every collection of the keys exists and has records. */
- need(...keys: string[]): string | null {
- for (const k of keys) {
- const c = this.coll(k);
- if (c === null) return `the project has no collection of type ${TYPES[k][0]} (${TYPE_LABEL[k]})`;
- if (!this.records(k).length) return `collection ${c} (${TYPE_LABEL[k]}) is empty`;
- }
- return null;
- }
- // ------------------------------------------------------------ fields
- /** Name of the relation field in the schema of `src` that leads to the collection of `dst`; null if none.
- * Several: `hint` if it is one of them, else a SchemaError. */
- field(src: string, dst: string, hint?: string | null): string | null {
- const props = this.schema(src);
- const target = this.coll(dst);
- if (!Object.keys(props).length || !target) return null;
- const names = Object.entries(props).filter(([, v]) => isMap(v) && v.kind === 'relation' && rtrim(v.collection) === target).map(([k]) => k);
- if (hint && names.includes(hint)) return hint;
- if (names.length === 1) return names[0];
- if (!names.length) return null;
- throw new SchemaError(`in the schema ${this.coll(src)} several fields lead to ${names.join(', ')}`);
- }
- /** First field of the schema of `src` of this kind (`phase`, `select`...). */
- fieldOfKind(src: string, kind: string): string | null {
- for (const [k, v] of Object.entries(this.schema(src))) if (isMap(v) && v.kind === kind) return k;
- return null;
- }
- /** Short name of a record: the pinned text field (a number) or the file name. */
- label(rec: Rec, key: string): string {
- const f = Object.entries(this.schema(key)).find(([, v]) => isMap(v) && v.kind === 'text' && v.pinned)?.[0];
- const v = f ? rec.fm[f] : null;
- return truthy(v) ? pystr(v) : rec.file.slice(0, -3);
- }
- /** Values of a relation field of a record as project paths `/a/b.md`; a bare name goes into the collection of `dst`. */
- links(rec: Rec, field: string | null | undefined, dst: string): string[] {
- const v = field ? rec.fm[field] : null;
- if (v === null || v === undefined || v === '') return [];
- const target = this.coll(dst) || '';
- const out: string[] = [];
- for (const x of Array.isArray(v) ? v : [v]) {
- let s = pystr(x).trim().replace(/^["']+|["']+$/g, '');
- const m = /^\[[^\]]*\]\(([^)]+)\)$/.exec(s);
- if (m) s = m[1];
- if (s && !s.startsWith('/') && !s.includes('/') && target) s = target + '/' + s;
- const p = normPath(s, null, rec.id);
- if (p && !out.includes(p)) out.push(p);
- }
- return out;
- }
- // ------------------------------------------------------------ states
- /** State category of a record: arriving / working / done / dropped; '?' if the phase page has none; null if no contour or no state. */
- category(rec: Rec, key: string): string | null {
- const f = this.fieldOfKind(key, 'phase');
- if (!f) return null;
- let name = normStatus(rec.fm[f]);
- if (!name) return null;
- if (name.endsWith('.md')) name = name.slice(0, -3);
- const contour = rtrim(this.schema(key)[f].contour);
- const ck = contour + '\0' + name;
- if (!(ck in this.cats)) {
- const path = join(this.root, contour.replace(/^\/+/, ''), name + '.md');
- this.cats[ck] = existsSync(path) ? /^category:\s*"?(\w+)/m.exec(readFileSync(path, 'utf8').slice(0, 2048))?.[1] ?? '?' : '?';
- }
- return this.cats[ck];
- }
- /** Is the record in scope by its state? Without a contour or a state it counts as live. */
- live(rec: Rec, key: string, cats = ['arriving', 'working', 'done']): boolean {
- const c = this.category(rec, key);
- return c === null || c === '?' || cats.includes(c);
- }
- }
- // ---------------------------------------------------------------- result
- export type Hole = { record: string; missing: string; fix: string; code: string; field?: string };
- /** The outcome of one rule. */
- export class Result {
- scopeText: string;
- scope: string[] = []; // addresses of the units in scope
- holes: Hole[] = [];
- nodata: { part: string; reason: string }[] = [];
- checked: string[] = [];
- error: string | null = null;
- info: Record<string, any> = {};
- constructor(public rule: { id: string; title: string; scope?: string }) {
- this.scopeText = rule.scope ?? '';
- }
- /** Records a part of the rule; true when there is data and the part is checked. */
- part(name: string, reason: string | null): boolean {
- if (reason) this.nodata.push({ part: name, reason });
- else this.checked.push(name);
- return !reason;
- }
- hole(record: string, missing: string, fix: string, code: string): void {
- this.holes.push({ record, missing, fix, code });
- }
- }
- /** A rule is a module with `RULE` and `check(project, result)`. A SchemaError becomes `result.error`. */
- export type Rule = { RULE: { id: string; title: string; scope?: string }; check: (p: Project, res: Result) => void };
- export function runRule(mod: Rule, project: Project): Result {
- const res = new Result(mod.RULE);
- try {
- mod.check(project, res);
- } catch (e) {
- if (!(e instanceof SchemaError)) throw e;
- res.error = e.message;
- }
- return res;
- }