ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/agents/lib/factlib.ts

lib/factlib.ts

112 líneas, 4.6 KB.

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

  1. // The shared part of the factory packages (agents, automations, runs, alarms): record types, field helpers,
  2. // times, links that must lead to a page, and files that must exist. Read-only, Bun only, no dependencies.
  3. // The parsing of pages is the library of the package collections; the packages runs, automations and alarms
  4. // require agents and import this file from `.shtukbase/packages/agents/lib/factlib.ts`.
  5. import { existsSync, statSync } from 'node:fs';
  6. import { dirname, isAbsolute, join, resolve } from 'node:path';
  7. import { type Project, type Rec, TYPES, TYPE_LABEL, normPath, pystr } from '../../collections/checks/lib/speclib.ts';
  8. export * from '../../collections/checks/lib/speclib.ts';
  9. Object.assign(TYPES, {
  10. AGENT: ['Worker', 'Assistant', 'Specialist'],
  11. FACTION: ['Action'],
  12. AUTOMATION: ['Automation'],
  13. RUN: ['Run'],
  14. ALARM: ['Alarm'],
  15. });
  16. Object.assign(TYPE_LABEL, {
  17. AGENT: 'agents', FACTION: 'actions', AUTOMATION: 'automations', RUN: 'runs', ALARM: 'alarms',
  18. });
  19. /** Page types an agent description may have (the node reads the same three). */
  20. export const AGENT_TYPES = ['Worker', 'Assistant', 'Specialist'];
  21. /** Is the value filled: a list with a non-blank item, a map with a key, or a non-blank scalar. */
  22. export function filled(v: unknown): boolean {
  23. if (v === null || v === undefined || v === false) return false;
  24. if (Array.isArray(v)) return v.some((x) => filled(x));
  25. if (v instanceof Date) return true;
  26. if (typeof v === 'object') return Object.keys(v as object).length > 0;
  27. return pystr(v).trim() !== '';
  28. }
  29. /** Is the field of the record filled. */
  30. export function has(rec: Rec, field: string): boolean {
  31. return filled(rec.fm[field]);
  32. }
  33. /** A scalar as trimmed text ('' for nothing). */
  34. export function text(v: unknown): string {
  35. if (v === null || v === undefined) return '';
  36. if (v instanceof Date) return v.toISOString();
  37. return pystr(v).trim();
  38. }
  39. /** A map value or null. */
  40. export function map(v: unknown): Record<string, any> | null {
  41. return v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date) ? (v as Record<string, any>) : null;
  42. }
  43. /** An ISO date or date-time → milliseconds, or null when it is not one. A bare date is midnight UTC. */
  44. export function time(v: unknown): number | null {
  45. if (v instanceof Date) return v.getTime();
  46. const s = text(v);
  47. if (!/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/.test(s)) return null;
  48. const iso = s.length === 10 ? s + 'T00:00:00Z' : s.replace(' ', 'T');
  49. const ms = Date.parse(/(Z|[+-]\d{2}:?\d{2})$/.test(iso) ? iso : iso + 'Z');
  50. return Number.isNaN(ms) ? null : ms;
  51. }
  52. /** A positive whole number, or null. */
  53. export function count(v: unknown): number | null {
  54. const n = typeof v === 'number' ? v : /^\d+$/.test(text(v)) ? Number(text(v)) : NaN;
  55. return Number.isInteger(n) && n > 0 ? n : null;
  56. }
  57. /** A link value (path, `[[x]]`, `[t](x)`) → the project page `/a/b.md` it names, or null. */
  58. export function target(rec: Rec, v: unknown): string | null {
  59. return normPath(v, null, rec.id);
  60. }
  61. /** Does the project page exist (`/a/b.md`, a folder page `/a/b/index.md` counts too). */
  62. export function pageExists(p: Project, page: string): boolean {
  63. const f = join(p.root, page);
  64. return existsSync(f) || existsSync(f.replace(/\.md$/, '/index.md'));
  65. }
  66. /** The nearest folder at or above `from` that holds `.git`, or null. */
  67. export function repoRoot(from: string): string | null {
  68. let d = resolve(from);
  69. for (;;) {
  70. if (existsSync(join(d, '.git'))) return d;
  71. const up = dirname(d);
  72. if (up === d) return null;
  73. d = up;
  74. }
  75. }
  76. /** A file path written on a page: from the project root, then from the repository root above it. The found path,
  77. * or null. A leading `/` means the project root. */
  78. export function findFile(p: Project, path: string): string | null {
  79. const rel = path.trim().replace(/^\.\//, '');
  80. if (!rel) return null;
  81. if (isAbsolute(rel) && !rel.startsWith('/')) return existsSync(rel) ? rel : null;
  82. const bases = [p.root, repoRoot(p.root)].filter((x): x is string => !!x);
  83. for (const b of bases) {
  84. const f = join(b, rel.replace(/^\/+/, ''));
  85. if (existsSync(f) && statSync(f).isFile()) return f;
  86. }
  87. return null;
  88. }
  89. /** The phase name of a status value (`/runs/contours/runs/done` → `done`), lower case; '' when empty. */
  90. export function phase(v: unknown): string {
  91. const s = text(v).replace(/^\/+|\/+$/g, '');
  92. return s.split('/').pop()!.replace(/\.md$/, '').toLowerCase();
  93. }
  94. /** Records of a type key and the address of its collection; an empty list when the project has no such collection. */
  95. export function recordsOf(p: Project, key: string): Rec[] {
  96. return p.coll(key) ? p.records(key) : [];
  97. }