ShtukbaseStandard
файл пакета→ .shtukbase/packages/icons/lib/registry.ts

lib/registry.ts

177 строк, 9.4 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // The icon registry of a set (the convention /icons/conventions/icon-set.md): one JSON file per set, one record per
  2. // icon, so the same meaning keeps one icon and agents reuse before they draw. Pure parts take data; `loadSets` reads.
  3. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  4. import { join } from 'node:path';
  5. export type IconRecord = {
  6. name: string; // kebab-case; the Lucide name where Lucide has the concept
  7. file: string; // the flat drawing, from the project root
  8. description: string; // one line: what it draws
  9. use: string; // where it fits
  10. avoid?: string; // where it does not
  11. aliases?: string[]; // words to find it by
  12. group?: string; // the colour group
  13. added?: { date?: string; by?: string; from?: string; why?: string };
  14. };
  15. export type Registry = { version?: number; set?: string; prefix?: string; viewBox?: string; style?: string; icons: IconRecord[] };
  16. export type IconSet = { id: string; path: string; dir: string; registry: Registry };
  17. export const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
  18. /** The rules for agents (the owner, 29.11.2026); the prompt prints them and the convention quotes them. */
  19. export const REUSE_RULES = [
  20. 'Search the registry by meaning and by aliases before you draw.',
  21. 'Reuse when the meaning matches: the same thing gets the same icon, in every package.',
  22. 'Draw a new icon only when no record means the same thing, and say in its record why the near ones did not fit.',
  23. 'One meaning has one icon; one icon is not reused for things that only look alike.',
  24. 'The balance: fewer than one new icon per few packages is normal; a new icon for a synonym is a mistake.',
  25. ];
  26. /** Every registry under /design/<set>/registry.json, or the ones the settings name (`sets:`). */
  27. export function loadSets(root: string, only: string[] = []): { sets: IconSet[]; errors: string[] } {
  28. const errors: string[] = [];
  29. const paths = only.length ? only : (existsSync(join(root, 'design')) ? readdirSync(join(root, 'design')).sort()
  30. .filter((n) => !n.startsWith('.') && statSync(join(root, 'design', n)).isDirectory() && existsSync(join(root, 'design', n, 'registry.json')))
  31. .map((n) => `/design/${n}/registry.json`) : []);
  32. const sets: IconSet[] = [];
  33. for (const p of paths) {
  34. const abs = join(root, p.replace(/^\/+/, ''));
  35. if (!existsSync(abs)) { errors.push(`${p}: no such registry`); continue; }
  36. try {
  37. const reg = JSON.parse(readFileSync(abs, 'utf8')) as Registry;
  38. if (!reg || !Array.isArray(reg.icons)) { errors.push(`${p}: no "icons" list`); continue; }
  39. const dir = p.replace(/\/registry\.json$/, '');
  40. sets.push({ id: reg.set || dir.split('/').pop() || 'set', path: p, dir, registry: reg });
  41. } catch (e) { errors.push(`${p}: not JSON (${(e as Error).message})`); }
  42. }
  43. return { sets, errors };
  44. }
  45. /** The SVG files a set holds: every .svg under its folder whose path has /flat/ (the drawings), from the root. */
  46. export function setFiles(root: string, set: IconSet): string[] {
  47. const out: string[] = [];
  48. const walk = (rel: string) => {
  49. const abs = join(root, rel.slice(1));
  50. if (!existsSync(abs)) return;
  51. for (const n of readdirSync(abs).sort()) {
  52. const r = `${rel}/${n}`;
  53. if (statSync(join(abs, n)).isDirectory()) walk(r);
  54. else if (n.toLowerCase().endsWith('.svg')) out.push(r);
  55. }
  56. };
  57. walk(`${set.dir}/flat`);
  58. return out;
  59. }
  60. export type Finding = { level: 'error' | 'warn'; text: string };
  61. /**
  62. * The registry and the files agree: every SVG has a record, every record has a file; names are kebab-case and
  63. * unique; no alias is shared or is another icon's name; every record has a description and a use. A near
  64. * duplicate (the same drawing, or the same aliases) is a warning: it reports, it does not fail.
  65. * files: the SVG paths the set holds; read: the text of a file (for the drawing comparison).
  66. */
  67. export function checkRegistry(reg: Registry, files: string[], read: (path: string) => string | null, where = 'registry'): Finding[] {
  68. const f: Finding[] = [];
  69. const err = (text: string) => f.push({ level: 'error', text: `${where}: ${text}` });
  70. const warn = (text: string) => f.push({ level: 'warn', text: `${where}: ${text}` });
  71. const names = new Map<string, number>();
  72. const words = new Map<string, string>(); // a name or an alias -> the icon it belongs to
  73. const recFiles = new Set<string>();
  74. for (const r of reg.icons) {
  75. const n = String(r?.name ?? '');
  76. if (!n) { err('a record without a name'); continue; }
  77. names.set(n, (names.get(n) ?? 0) + 1);
  78. if (!NAME_RE.test(n)) err(`"${n}": the name is not kebab-case`);
  79. if (!r.file) err(`"${n}": no file`);
  80. else {
  81. recFiles.add(r.file);
  82. if (read(r.file) === null) err(`"${n}": the file ${r.file} does not exist → draw it or drop the record`);
  83. }
  84. if (!String(r.description ?? '').trim()) err(`"${n}": no description (one line: what it draws)`);
  85. if (!String(r.use ?? '').trim()) err(`"${n}": no use (where it fits)`);
  86. }
  87. for (const [n, c] of names) if (c > 1) err(`the name "${n}" is used by ${c} records → one meaning, one icon`);
  88. for (const r of reg.icons) if (r?.name) words.set(r.name, r.name);
  89. for (const r of reg.icons) {
  90. for (const a of r?.aliases ?? []) {
  91. const w = String(a).trim().toLowerCase();
  92. if (!w) continue;
  93. const owner = words.get(w);
  94. if (owner && owner !== r.name) err(`"${r.name}": the alias "${w}" is ${names.has(w) ? 'the name of' : 'also an alias of'} "${owner}" → keep a word for one icon`);
  95. else words.set(w, r.name);
  96. }
  97. }
  98. for (const p of files) if (!recFiles.has(p)) err(`${p} has no record → add one (name, description, use, aliases) or remove the file`);
  99. // near duplicates: the same shapes (colours aside), or the same set of aliases
  100. const sig = new Map<string, string>();
  101. for (const r of reg.icons) {
  102. if (!r?.file) continue;
  103. const t = read(r.file);
  104. if (t === null) continue;
  105. const s = shapeSignature(t);
  106. if (s && sig.has(s)) warn(`"${r.name}" draws the same shapes as "${sig.get(s)}" → one meaning, one icon: merge them, or redraw one if the meanings differ`);
  107. else if (s) sig.set(s, r.name);
  108. }
  109. const al = new Map<string, string>();
  110. for (const r of reg.icons) {
  111. const k = [...new Set((r?.aliases ?? []).map((a) => String(a).toLowerCase()))].sort().join('|');
  112. if (k && al.has(k)) warn(`"${r.name}" has the same aliases as "${al.get(k)}" → are they one meaning?`);
  113. else if (k) al.set(k, r.name);
  114. }
  115. return f;
  116. }
  117. /**
  118. * The health lines of one set in the shape of /base/conventions.md: `health icon-set/<set>: full`, else a `missing` line
  119. * (the errors) and an `extra` line (the near duplicates), each followed by its details, indented.
  120. */
  121. export function healthLines(set: string, findings: Finding[]): string[] {
  122. const errs = findings.filter((f) => f.level === 'error'), warns = findings.filter((f) => f.level === 'warn');
  123. const subject = `health icon-set/${set}`;
  124. if (!errs.length && !warns.length) return [`${subject}: full`];
  125. const out: string[] = [];
  126. const short = (f: Finding) => f.text.replace(/^[^:]*: /, '').replace(/ → .*$/, '');
  127. if (errs.length) out.push(`${subject}: missing: ${errs.length} (${errs.slice(0, 3).map(short).join('; ')}${errs.length > 3 ? '; …' : ''})`, ...errs.map((f) => ` ${f.text}`));
  128. if (warns.length) out.push(`${subject}: extra: ${warns.length} near duplicate(s)`, ...warns.map((f) => ` ${f.text}`));
  129. return out;
  130. }
  131. const GEOM = new Set(['d', 'x', 'y', 'width', 'height', 'rx', 'ry', 'cx', 'cy', 'r', 'points', 'x1', 'y1', 'x2', 'y2', 'transform']);
  132. /** The shapes of a drawing without their colours, order-free: two drawings that differ only in colour match. */
  133. export function shapeSignature(svg: string): string {
  134. const out: string[] = [];
  135. const re = /<(path|rect|circle|ellipse|polygon|polyline|line)\b([^>]*)>/g;
  136. let m: RegExpExecArray | null;
  137. while ((m = re.exec(svg))) {
  138. const attrs: string[] = [];
  139. const ar = /([\w:-]+)\s*=\s*"([^"]*)"/g;
  140. let a: RegExpExecArray | null;
  141. while ((a = ar.exec(m[2]))) if (GEOM.has(a[1])) attrs.push(`${a[1]}=${a[2].replace(/\s+/g, ' ').trim()}`);
  142. out.push(`${m[1]}:${attrs.sort().join(',')}`);
  143. }
  144. return out.sort().join('|');
  145. }
  146. /** Searches a registry by meaning: the words of the query against name, aliases, description and use. Best first. */
  147. export function search(reg: Registry, query: string, limit = 8): { rec: IconRecord; score: number }[] {
  148. const q = tokens(query);
  149. if (!q.length) return [];
  150. const out: { rec: IconRecord; score: number }[] = [];
  151. for (const r of reg.icons) {
  152. const name = tokens(r.name), al = (r.aliases ?? []).flatMap(tokens), desc = tokens(r.description ?? ''), use = tokens(r.use ?? '');
  153. let score = 0;
  154. for (const w of q) {
  155. if (name.includes(w)) score += 5;
  156. else if (al.includes(w)) score += 4;
  157. else if (name.some((x) => stem(x) === stem(w)) || al.some((x) => stem(x) === stem(w))) score += 3;
  158. if (desc.some((x) => stem(x) === stem(w))) score += 1;
  159. if (use.some((x) => stem(x) === stem(w))) score += 1;
  160. }
  161. if (score) out.push({ rec: r, score });
  162. }
  163. return out.sort((a, b) => b.score - a.score || a.rec.name.localeCompare(b.rec.name)).slice(0, limit);
  164. }
  165. const STOP = new Set(['a', 'an', 'the', 'of', 'and', 'or', 'in', 'on', 'to', 'for', 'with', 'by', 'is', 'its', 'it', 'use', 'package']);
  166. const tokens = (s: string) => String(s).toLowerCase().split(/[^a-z0-9]+/).filter((w) => w && !STOP.has(w));
  167. const stem = (w: string) => w.replace(/(ies|es|s|ing|ed)$/, '');