ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/quality/checks/lib/qlib.ts

checks/lib/qlib.ts

122 líneas, 5.2 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // The shared part of the checks of the quality packages (quality, risks, testing).
  2. // On import it adds the record types of the layer "Quality" to the type map of speclib (the collections package),
  3. // as tasks/checks/lib/worklib.ts does for the layer "Work". Collections are found by the itemType of their page,
  4. // never by path; a relation field by the collection it leads to. Installed side by side in .shtukbase/packages/:
  5. // quality -> norms-core -> contours -> frame -> collections.
  6. import { type Project, type Rec, type Result, SchemaError, TYPES, TYPE_LABEL, addr, pystr } from '../../../collections/checks/lib/speclib.ts';
  7. export { addr };
  8. Object.assign(TYPES, {
  9. RISK: ['SystemRisk', 'Risk'],
  10. IND: ['Indicator'],
  11. MEAS: ['Measurement'],
  12. OUT: ['Outcome'],
  13. ASM: ['Assumption'],
  14. DS: ['Dataset'],
  15. QRUN: ['QualityRun'], // not RUN: that key is the agent run log of agents/lib/factlib.ts (type Run)
  16. QTEST: ['QualityTest'],
  17. AGENT: ['ProductAgent', 'Agent'],
  18. GOAL: ['Goal'],
  19. DEC: ['Decision'],
  20. });
  21. Object.assign(TYPE_LABEL, {
  22. RISK: 'risks', IND: 'indicators', MEAS: 'measurements', OUT: 'benefit in operation', ASM: 'assumptions', DS: 'datasets',
  23. QRUN: 'runs', QTEST: 'quality tests', AGENT: 'product agents', GOAL: 'goals', DEC: 'decisions',
  24. });
  25. /** Is the field filled: a list with a non-blank item, or a value that is not null, false or blank. */
  26. export function has(rec: Rec, field: string): boolean {
  27. const v = rec.fm[field];
  28. if (Array.isArray(v)) return v.some((x) => x !== null && x !== undefined && pystr(x).trim() !== '');
  29. if (v instanceof Date) return true;
  30. return v !== null && v !== undefined && v !== false && pystr(v).trim() !== '';
  31. }
  32. /** The fields of the list that are not filled. */
  33. export function missing(rec: Rec, fields: string[]): string[] {
  34. return fields.filter((f) => !has(rec, f));
  35. }
  36. /** The state of a record: the phase name without the folder and the `.md` end ('' when none). */
  37. export function state(rec: Rec, field = 'status'): string {
  38. const v = rec.fm[field];
  39. const s = v === null || v === undefined ? '' : pystr(v).trim().replace(/^["']|["']$/g, '');
  40. const last = s.split('/').pop() ?? '';
  41. return last.endsWith('.md') ? last.slice(0, -3) : last;
  42. }
  43. /** A date value as `YYYY-MM-DD`, or null when it is not a date. */
  44. export function day(v: unknown): string | null {
  45. if (v instanceof Date) return isNaN(v.getTime()) ? null : v.toISOString().slice(0, 10);
  46. const m = /^(\d{4}-\d{2}-\d{2})/.exec(pystr(v ?? '').trim());
  47. return m ? m[1] : null;
  48. }
  49. /** Today as `YYYY-MM-DD`; QUALITY_TODAY overrides it (for tests). */
  50. export function today(): string {
  51. return day(process.env.QUALITY_TODAY) ?? new Date().toISOString().slice(0, 10);
  52. }
  53. /** Days from a to b (both `YYYY-MM-DD`). */
  54. export function daysBetween(a: string, b: string): number {
  55. return Math.round((Date.parse(b + 'T00:00:00Z') - Date.parse(a + 'T00:00:00Z')) / 86_400_000);
  56. }
  57. /** A number value, or null. */
  58. export function num(v: unknown): number | null {
  59. if (typeof v === 'number') return Number.isFinite(v) ? v : null;
  60. const s = pystr(v ?? '').trim();
  61. if (!/^-?\d+(\.\d+)?$/.test(s)) return null;
  62. return Number(s);
  63. }
  64. /** Is the record live by its state category: arriving or working (or no contour / unknown phase). */
  65. export function live(p: Project, rec: Rec, key: string): boolean {
  66. const c = p.category(rec, key);
  67. return c === null || c === '?' || c === 'arriving' || c === 'working';
  68. }
  69. /** The relation field src → dst by the schema, or the fallback name when the schema has none. */
  70. export function fld(p: Project, src: string, dst: string, fallback: string): string {
  71. try {
  72. return p.field(src, dst, fallback) ?? fallback;
  73. } catch (e) {
  74. if (!(e instanceof SchemaError)) throw e;
  75. return fallback;
  76. }
  77. }
  78. /** Values of a relation field as project paths, even when the target collection is not installed. */
  79. export function refs(p: Project, rec: Rec, field: string, dst: string): string[] {
  80. if (p.coll(dst)) return p.links(rec, field, dst);
  81. const v = rec.fm[field];
  82. const out: string[] = [];
  83. for (const x of Array.isArray(v) ? v : v === null || v === undefined || v === '' ? [] : [v]) {
  84. let s = pystr(x).trim().replace(/^["']+|["']+$/g, '');
  85. const m = /^\[[^\]]*\]\(([^)]+)\)$/.exec(s);
  86. if (m) s = m[1];
  87. if (s) out.push(s.startsWith('/') ? s : '/' + s);
  88. }
  89. return out;
  90. }
  91. /** One requirement on the fields of the records of a type: when `when` holds, `fields` must be filled. */
  92. export type FieldRule = { when: (rec: Rec) => boolean; fields: string[]; why: string; fix: string; code: string };
  93. /** Checks the records of a type key against field rules; the scope is every record a rule applies to. */
  94. export function checkFields(p: Project, res: Result, key: string, rules: FieldRule[]): void {
  95. const reason = p.need(key);
  96. res.part(TYPE_LABEL[key], reason);
  97. if (reason) return;
  98. const scope = new Set<string>();
  99. for (const r of p.records(key)) {
  100. for (const rule of rules) {
  101. if (!rule.when(r)) continue;
  102. scope.add(addr(r.id));
  103. const gap = missing(r, rule.fields);
  104. if (gap.length) res.hole(addr(r.id), `${p.label(r, key)}: ${rule.why} — not filled: ${gap.join(', ')}`, rule.fix, rule.code);
  105. }
  106. }
  107. res.scope = [...scope];
  108. }