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

lib/header.ts

223 lines, 11.3 KB.

  1. // The component header: one YAML block in the first comment of a component file, `<!---` … `--->` in HTML and
  2. // `/*---` … `---*/` in TS/TSX/JS (build contract of the wave DSN, section 4; the control schema is section 5).
  3. // One parser for both; other packages (the HTML and React libraries) import it to test their own headers:
  4. // import { parseHeader } from '../../design-components/lib/header.ts';
  5. // Pure: no files are read except by `readHeader`. Bun only, no dependencies (Bun has a YAML parser built in).
  6. import { readFileSync } from 'node:fs';
  7. export const LEVELS = ['primitive', 'composite', 'block', 'shell', 'page'] as const;
  8. export type Level = (typeof LEVELS)[number];
  9. /** The shadcn registry type of each level (design: "Naming: what comes from shadcn"). */
  10. export const REGISTRY_TYPES: Record<Level, string> = {
  11. primitive: 'registry:ui',
  12. composite: 'registry:component',
  13. block: 'registry:block',
  14. shell: 'registry:block',
  15. page: 'registry:page',
  16. };
  17. export const CONTROL_KINDS = ['select', 'segment', 'bool', 'range', 'swatch', 'text'] as const;
  18. export type ControlKind = (typeof CONTROL_KINDS)[number];
  19. export type Control = {
  20. kind: ControlKind;
  21. label?: string;
  22. options?: (string | number)[];
  23. default?: string | number | boolean;
  24. min?: number;
  25. max?: number;
  26. step?: number;
  27. unit?: string;
  28. section?: string;
  29. colors?: unknown;
  30. };
  31. export type Header = {
  32. id: string;
  33. title: string;
  34. level: Level;
  35. description: string;
  36. uses: string[];
  37. parts: string[];
  38. states: string[];
  39. status: string[];
  40. controls: Record<string, Control>;
  41. cssProperties: string[];
  42. };
  43. export type Parsed = {
  44. /** The header as data, or null when the comment is missing or has problems. */
  45. header: Header | null;
  46. /** One line per problem, each starting with the `where` label. Empty when `header` is set. */
  47. problems: string[];
  48. /** True when the file has a header comment at all (valid or not): the file is a component file. */
  49. found: boolean;
  50. /** The YAML text between the markers. */
  51. raw: string | null;
  52. /** Where the comment lies in the file: offsets of its first character and of the one after its last. */
  53. start: number;
  54. end: number;
  55. /** `html` for `<!---`, `ts` for `/*---`. */
  56. lang: 'html' | 'ts' | null;
  57. };
  58. const KEBAB = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
  59. const CONTROL_NAME = /^[a-z][a-z0-9-]*$/;
  60. const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
  61. /** `package-card` → `Package card`. */
  62. export function titleOf(id: string): string {
  63. const s = id.replace(/-/g, ' ');
  64. return s.charAt(0).toUpperCase() + s.slice(1);
  65. }
  66. /** `package-card` → `PackageCard`. */
  67. export function pascal(id: string): string {
  68. return id.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
  69. }
  70. /** The file kind by its name: `html` (the HTML implementation), `react` (TS/TSX/JS/JSX), or null (not a code file). */
  71. export function kindOf(file: string): 'html' | 'react' | null {
  72. if (/\.html?$/i.test(file)) return 'html';
  73. if (/\.(tsx?|jsx?|mjs|mts)$/i.test(file) && !/\.(test|spec|stories|story)\.[a-z]+$/i.test(file) && !/\.d\.ts$/i.test(file)) return 'react';
  74. return null;
  75. }
  76. const PREFIX = /^(?:\s|['"]use (?:client|server)['"];?|\/\/[^\n]*)*/;
  77. /** Finds the header comment. It must come first in the file: only blanks, a BOM, `'use client'` and `//` lines may precede it. */
  78. export function findHeader(text: string): { raw: string; start: number; end: number; lang: 'html' | 'ts' } | null {
  79. const body = text.replace(/^/, '');
  80. const shift = text.length - body.length;
  81. const lead = PREFIX.exec(body)![0].length;
  82. const at = body.slice(lead);
  83. let open: string, close: string, lang: 'html' | 'ts';
  84. if (at.startsWith('<!---')) [open, close, lang] = ['<!---', '--->', 'html'];
  85. else if (at.startsWith('/*---')) [open, close, lang] = ['/*---', '---*/', 'ts'];
  86. else return null;
  87. const inner = lead + open.length;
  88. const stop = body.indexOf(close, inner);
  89. if (stop < 0) return { raw: body.slice(inner), start: shift + lead, end: text.length, lang };
  90. return { raw: body.slice(inner, stop), start: shift + lead, end: shift + stop + close.length, lang };
  91. }
  92. /** Removes the common indentation (and a leading ` * ` gutter some editors add) so the YAML parses. */
  93. function dedent(raw: string): string {
  94. const lines = raw.replace(/\r\n?/g, '\n').split('\n');
  95. while (lines.length && !lines[0].trim()) lines.shift();
  96. while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
  97. const gutter = lines.length > 0 && lines.every((l) => !l.trim() || /^\s*\*(\s|$)/.test(l));
  98. const body = gutter ? lines.map((l) => l.replace(/^\s*\*\s?/, '')) : lines;
  99. const indent = Math.min(...body.filter((l) => l.trim()).map((l) => /^ */.exec(l)![0].length));
  100. return body.map((l) => (Number.isFinite(indent) ? l.slice(Math.min(indent, /^ */.exec(l)![0].length)) : l)).join('\n');
  101. }
  102. const strList = (v: unknown, name: string, bad: string[], rule?: RegExp): string[] => {
  103. if (v === undefined || v === null) return [];
  104. if (!Array.isArray(v)) { bad.push(`${name} must be a list`); return []; }
  105. const out: string[] = [];
  106. for (const x of v) {
  107. const s = typeof x === 'number' ? String(x) : x;
  108. if (typeof s !== 'string' || !s.trim()) bad.push(`${name} has an item that is not a word`);
  109. else if (rule && !rule.test(s)) bad.push(`${name}: "${s}" is not valid here`);
  110. else out.push(s);
  111. }
  112. return out;
  113. };
  114. const optStr = (c: Record<string, unknown>, k: string, name: string, bad: string[]) => {
  115. if (c[k] !== undefined && typeof c[k] !== 'string') bad.push(`${name}.${k} must be text`);
  116. };
  117. const optNum = (c: Record<string, unknown>, k: string, name: string, bad: string[]) => {
  118. if (c[k] !== undefined && (typeof c[k] !== 'number' || !Number.isFinite(c[k]))) bad.push(`${name}.${k} must be a number`);
  119. };
  120. /** The control schema of section 5: `{<name>: {kind, label?, options?, default?, min?, max?, step?, unit?, section?, colors?}}`. */
  121. export function validateControls(controls: unknown, where = 'controls'): string[] {
  122. const bad: string[] = [];
  123. if (controls === undefined || controls === null) return bad;
  124. if (!isObj(controls)) return [`${where} must be a map of controls`];
  125. for (const [key, c] of Object.entries(controls)) {
  126. const name = `${where}.${key}`;
  127. if (!CONTROL_NAME.test(key)) bad.push(`${name}: a control name is lower case with dashes (it becomes data-${key})`);
  128. if (!isObj(c)) { bad.push(`${name} must be a map with at least "kind"`); continue; }
  129. if (!CONTROL_KINDS.includes(c.kind as ControlKind)) { bad.push(`${name}.kind "${String(c.kind)}" is not one of ${CONTROL_KINDS.join(', ')}`); continue; }
  130. for (const k of ['label', 'unit', 'section']) optStr(c, k, name, bad);
  131. for (const k of ['min', 'max', 'step']) optNum(c, k, name, bad);
  132. const kind = c.kind as ControlKind;
  133. const opts = c.options;
  134. if (kind === 'select' || kind === 'segment' || kind === 'swatch') {
  135. if (!Array.isArray(opts) || !opts.length) bad.push(`${name}: a ${kind} control needs "options" (a list)`);
  136. else if (opts.some((o) => typeof o !== 'string' && typeof o !== 'number')) bad.push(`${name}.options must be words, numbers or colours`);
  137. else {
  138. if (kind === 'segment' && (opts.length < 2 || opts.length > 4)) bad.push(`${name}: a segment control has 2 to 4 options, not ${opts.length}`);
  139. if (c.default !== undefined && kind !== 'swatch' && !opts.includes(c.default as string)) bad.push(`${name}.default "${String(c.default)}" is not among the options`);
  140. }
  141. } else if (opts !== undefined) bad.push(`${name}: a ${kind} control has no "options"`);
  142. if (kind === 'bool' && c.default !== undefined && typeof c.default !== 'boolean') bad.push(`${name}.default must be true or false`);
  143. if (kind === 'text' && c.default !== undefined && typeof c.default !== 'string') bad.push(`${name}.default must be text`);
  144. if (kind === 'range') {
  145. if (typeof c.min !== 'number' || typeof c.max !== 'number') bad.push(`${name}: a range control needs "min" and "max"`);
  146. else if (c.min >= c.max) bad.push(`${name}: "min" must be less than "max"`);
  147. if (typeof c.step === 'number' && c.step <= 0) bad.push(`${name}.step must be above 0`);
  148. if (c.default !== undefined) {
  149. if (typeof c.default !== 'number') bad.push(`${name}.default must be a number`);
  150. else if (typeof c.min === 'number' && typeof c.max === 'number' && (c.default < c.min || c.default > c.max)) bad.push(`${name}.default is outside min…max`);
  151. }
  152. }
  153. }
  154. return bad;
  155. }
  156. /** Parses the header of a file's text. `where` (a path) starts every problem line. */
  157. export function parseHeader(text: string, where = 'header'): Parsed {
  158. const f = findHeader(text);
  159. const fail = (problems: string[]): Parsed => ({
  160. header: null, problems: problems.map((p) => `${where}: ${p}`), found: !!f, raw: f?.raw ?? null, start: f?.start ?? -1, end: f?.end ?? -1, lang: f?.lang ?? null,
  161. });
  162. if (!f) return fail([]);
  163. const close = f.lang === 'html' ? '--->' : '---*/';
  164. if (!text.slice(f.start, f.end).endsWith(close)) return fail([`the header comment is not closed (it must end with ${close})`]);
  165. let data: unknown;
  166. // A bare `12-3` is a string to us; Bun's YAML would read the number before the dash.
  167. const yaml = dedent(f.raw).replace(/^(\s*(?:[\w-]+:\s+)?)(\d+(?:-\d+)+)(\s*)$/gm, '$1"$2"$3');
  168. try {
  169. data = Bun.YAML.parse(yaml);
  170. } catch (e) {
  171. return fail([`the header is not valid YAML — ${(e as Error).message.split('\n')[0]}`]);
  172. }
  173. if (!isObj(data)) return fail(['the header must be a YAML map (id, level, …)']);
  174. const bad: string[] = [];
  175. const id = data.id;
  176. if (typeof id !== 'string' || !KEBAB.test(id)) bad.push(`id "${String(id)}" must be kebab-case (letters, digits, dashes)`);
  177. if (!LEVELS.includes(data.level as Level)) bad.push(`level "${String(data.level)}" is not one of ${LEVELS.join(', ')}`);
  178. for (const k of ['title', 'description']) if (data[k] !== undefined && typeof data[k] !== 'string') bad.push(`${k} must be text`);
  179. const uses = strList(data.uses, 'uses', bad, KEBAB);
  180. const parts = strList(data.parts, 'parts', bad);
  181. const states = strList(data.states, 'states', bad);
  182. const status = strList(data.status, 'status', bad);
  183. const cssProperties = strList(data.cssProperties, 'cssProperties', bad, /^--[\w-]+$/);
  184. bad.push(...validateControls(data.controls));
  185. if (typeof id === 'string' && uses.includes(id)) bad.push('uses itself');
  186. if (bad.length) return fail(bad);
  187. const header: Header = {
  188. id: id as string,
  189. title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : titleOf(id as string),
  190. level: data.level as Level,
  191. description: typeof data.description === 'string' ? data.description.trim() : '',
  192. uses, parts, states, status,
  193. controls: (data.controls ?? {}) as Record<string, Control>,
  194. cssProperties,
  195. };
  196. return { header, problems: [], found: true, raw: f.raw, start: f.start, end: f.end, lang: f.lang };
  197. }
  198. /** Reads a file and parses its header. `where` defaults to the path given. */
  199. export function readHeader(path: string, where = path): Parsed {
  200. return parseHeader(readFileSync(path, 'utf8'), where);
  201. }
  202. /** The text of a file without its header comment (and the blank line after it). */
  203. export function stripHeader(text: string): string {
  204. const f = findHeader(text);
  205. return f ? (text.slice(0, f.start) + text.slice(f.end)).replace(/^\s*\n/, '') : text;
  206. }