ShtukbaseStandard
package file→ .shtukbase/packages/design-components/lib/yaml.ts

lib/yaml.ts

41 lines, 2.1 KB.

  1. // A small YAML writer for the front matter of component pages: top-level keys one per line, lists and small maps in
  2. // flow style, a map of maps (controls) one entry per line. Output is always valid YAML that reads back to the same data
  3. // (the tests prove it), and it is deterministic: the same data gives the same text, so `fresh` can compare files.
  4. const RESERVED = new Set(['true', 'false', 'null', 'yes', 'no', 'on', 'off', 'y', 'n', '~']);
  5. const PLAIN = /^[A-Za-z_/][A-Za-z0-9_\-/.]*$/;
  6. const KEY = /^[A-Za-z_][A-Za-z0-9_-]*$/;
  7. export function scalar(v: unknown): string {
  8. if (v === null || v === undefined) return 'null';
  9. if (typeof v === 'boolean') return v ? 'true' : 'false';
  10. if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';
  11. const s = String(v);
  12. return PLAIN.test(s) && !RESERVED.has(s.toLowerCase()) ? s : JSON.stringify(s);
  13. }
  14. const key = (k: string) => (KEY.test(k) && !RESERVED.has(k.toLowerCase()) ? k : JSON.stringify(k));
  15. /** A value on one line: `[a, b]`, `{k: v}`, or a scalar. */
  16. export function flow(v: unknown): string {
  17. if (Array.isArray(v)) return `[${v.map(flow).join(', ')}]`;
  18. if (v && typeof v === 'object') {
  19. const e = Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== undefined);
  20. return e.length ? `{${e.map(([k, x]) => `${key(k)}: ${flow(x)}`).join(', ')}}` : '{}';
  21. }
  22. return scalar(v);
  23. }
  24. /** `{a: 1, b: [x]}` → `a: 1\nb: [x]`; a map whose values are maps goes one entry per line under its key. */
  25. export function emit(data: Record<string, unknown>): string {
  26. const lines: string[] = [];
  27. for (const [k, v] of Object.entries(data)) {
  28. if (v === undefined) continue;
  29. const nested = v && typeof v === 'object' && !Array.isArray(v) && Object.values(v).length > 0 && Object.values(v).every((x) => x && typeof x === 'object' && !Array.isArray(x));
  30. if (nested) {
  31. lines.push(`${key(k)}:`);
  32. for (const [k2, v2] of Object.entries(v as Record<string, unknown>)) lines.push(` ${key(k2)}: ${flow(v2)}`);
  33. } else lines.push(`${key(k)}: ${flow(v)}`);
  34. }
  35. return lines.join('\n');
  36. }