archivo del paquete→ .shtukbase/packages/design-tokens/actions/tokenslib.ts
actions/tokenslib.ts
260 líneas, 15.7 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // Design tokens in the format of the W3C Design Tokens Community Group (DTCG, https://www.designtokens.org/tr/2025.10/format/):
- // read, validate, resolve references and turn into CSS custom properties. The working directory is the project root.
- // Settings on /design/tokens.md: source (tokens file), dark (optional file of dark-scheme overrides), out (CSS file),
- // prefix (of the custom property names), darkSelector.
- import { existsSync, readFileSync } from 'node:fs';
- import { join } from 'node:path';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- export const PAGE = 'design/tokens.md';
- export const TYPES = ['color', 'dimension', 'fontFamily', 'fontWeight', 'duration', 'cubicBezier', 'number', 'strokeStyle', 'border', 'transition', 'shadow', 'gradient', 'typography'];
- const GROUP_KEYS = new Set(['$type', '$description', '$extensions', '$deprecated', '$extends', '$root']);
- const TOKEN_KEYS = new Set(['$value', '$type', '$description', '$extensions', '$deprecated']);
- const WEIGHTS: Record<string, number> = {
- thin: 100, hairline: 100, 'extra-light': 200, 'ultra-light': 200, light: 300, normal: 400, regular: 400, book: 400,
- medium: 500, 'semi-bold': 600, 'demi-bold': 600, bold: 700, 'extra-bold': 800, 'ultra-bold': 800, black: 900, heavy: 900,
- 'extra-black': 950, 'ultra-black': 950,
- };
- const STROKES = ['solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'outset', 'inset'];
- const SPACES = ['srgb', 'srgb-linear', 'hsl', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec2020', 'xyz-d65', 'xyz-d50'];
- export type Config = { source: string; dark: string; out: string; prefix: string; darkSelector: string };
- export function config(root = process.cwd(), over: Partial<Config> = {}): Config {
- const p = join(root, PAGE);
- const fm = existsSync(p) ? readPage(p).fm : {};
- const s = (v: unknown, d: string) => (typeof v === 'string' && v.trim() ? v.trim().replace(/^\/+/, '') : d);
- return { source: s(fm.source, 'design/tokens.json'), dark: s(fm.dark, ''), out: s(fm.out, 'design/tokens.css'), prefix: typeof fm.prefix === 'string' ? fm.prefix : '', darkSelector: s(fm.darkSelector, '.dark'), ...over };
- }
- /** The settings of a style package's tokens (token contract, `/design/contract.md`): `/design/<id>/tokens.json` and
- * `tokens.dark.json` build into `/design/<id>/tokens.css`, the dark scheme on `.dark, [data-theme="dark"]`, no prefix. */
- export const styleConfig = (id: string): Config => ({
- source: `design/${id}/tokens.json`, dark: `design/${id}/tokens.dark.json`, out: `design/${id}/tokens.css`, prefix: '', darkSelector: '.dark, [data-theme="dark"]',
- });
- export type Token = { path: string; value: unknown; type: string | null; file: string };
- const REF = /^\{([^{}]+)\}$/;
- const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
- /** Every token of a tokens tree, with the type it inherits from its groups. Problems with the tree go to `bad`. */
- export function collect(tree: unknown, file: string, bad: string[]): Map<string, Token> {
- const out = new Map<string, Token>();
- const walk = (node: unknown, path: string[], type: string | null) => {
- if (!isObj(node)) { bad.push(`${file}: ${path.join('.') || '(root)'} — not an object`); return; }
- const where = path.join('.') || '(root)';
- if ('$value' in node) {
- for (const k of Object.keys(node)) if (!TOKEN_KEYS.has(k)) bad.push(`${file}: ${where} — extra field ${k} in the token`);
- const own = node.$type;
- if (own !== undefined && (typeof own !== 'string' || !TYPES.includes(own))) bad.push(`${file}: ${where} — unknown $type ${JSON.stringify(own)}`);
- out.set(where, { path: where, value: node.$value, type: typeof own === 'string' && TYPES.includes(own) ? own : type, file });
- return;
- }
- let t = type;
- if (node.$type !== undefined) {
- if (typeof node.$type !== 'string' || !TYPES.includes(node.$type)) bad.push(`${file}: ${where} — unknown group $type ${JSON.stringify(node.$type)}`);
- else t = node.$type;
- }
- for (const [k, v] of Object.entries(node)) {
- if (k.startsWith('$')) { if (!GROUP_KEYS.has(k)) bad.push(`${file}: ${where} — unknown group field ${k}`); continue; }
- if (/[{}.]/.test(k)) { bad.push(`${file}: ${[...path, k].join('.')} — a name cannot contain { } or a dot`); continue; }
- walk(v, [...path, k], t);
- }
- };
- walk(tree, [], null);
- return out;
- }
- export function readTree(rel: string, root = process.cwd()): { tree: unknown; error: string | null } {
- const p = join(root, rel);
- if (!existsSync(p)) return { tree: null, error: `${rel}: the file is missing` };
- try {
- return { tree: JSON.parse(readFileSync(p, 'utf8')), error: null };
- } catch (e) {
- return { tree: null, error: `${rel}: not JSON — ${(e as Error).message}` };
- }
- }
- /** Final type of a token: its own or its group's, else that of the token it references. */
- export function typeOf(t: Token, all: Map<string, Token>, seen = new Set<string>()): string | null {
- if (t.type) return t.type;
- const m = typeof t.value === 'string' ? REF.exec(t.value) : null;
- if (!m || seen.has(t.path)) return null;
- seen.add(t.path);
- const target = all.get(m[1]);
- return target ? typeOf(target, all, seen) : null;
- }
- const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
- const unitValue = (v: unknown, units: string[]) =>
- (isObj(v) && num(v.value) && units.includes(String(v.unit))) || (typeof v === 'string' && new RegExp(`^-?\\d*\\.?\\d+(${units.join('|')})$`).test(v)) || v === 0;
- /** Problems with one value of a type (sub-values of composites may be references, checked elsewhere). */
- export function valueProblem(type: string, v: unknown): string | null {
- if (typeof v === 'string' && REF.test(v)) return null;
- switch (type) {
- case 'color':
- if (typeof v === 'string') return /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8}|[0-9a-fA-F]{3})$/.test(v) ? null : 'color is hex (#rrggbb) or an object {colorSpace, components}';
- if (!isObj(v) || !SPACES.includes(String(v.colorSpace))) return `color: colorSpace is one of ${SPACES.join(', ')}`;
- if (!Array.isArray(v.components) || v.components.length !== 3 || v.components.some((c) => !num(c) && c !== 'none')) return 'color: components are three numbers';
- if (v.alpha !== undefined && !(num(v.alpha) && (v.alpha as number) >= 0 && (v.alpha as number) <= 1)) return 'color: alpha from 0 to 1';
- return null;
- case 'dimension': return unitValue(v, ['px', 'rem']) ? null : 'dimension is {value, unit: px|rem}';
- case 'duration': return unitValue(v, ['ms', 's']) ? null : 'duration is {value, unit: ms|s}';
- case 'number': return num(v) ? null : 'number';
- case 'fontFamily': return typeof v === 'string' || (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string')) ? null : 'font is a string or a list of strings';
- case 'fontWeight': return (num(v) && (v as number) >= 1 && (v as number) <= 1000) || (typeof v === 'string' && v in WEIGHTS) ? null : 'weight is a number 1–1000 or a word (bold, regular…)';
- case 'cubicBezier': return Array.isArray(v) && v.length === 4 && v.every(num) && [v[0], v[2]].every((x) => x >= 0 && x <= 1) ? null : 'curve is [x1, y1, x2, y2], x from 0 to 1';
- case 'strokeStyle': return (typeof v === 'string' && STROKES.includes(v)) || (isObj(v) && Array.isArray(v.dashArray) && typeof v.lineCap === 'string') ? null : `stroke is ${STROKES.join(', ')} or {dashArray, lineCap}`;
- case 'border': return fields(v, { color: 'color', width: 'dimension', style: 'strokeStyle' });
- case 'transition': return fields(v, { duration: 'duration', delay: 'duration', timingFunction: 'cubicBezier' });
- case 'typography': return fields(v, { fontFamily: 'fontFamily', fontSize: 'dimension', fontWeight: 'fontWeight', letterSpacing: 'dimension', lineHeight: 'number' });
- case 'shadow': {
- const layers = Array.isArray(v) ? v : [v];
- for (const l of layers) {
- const p = fields(l, { color: 'color', offsetX: 'dimension', offsetY: 'dimension', blur: 'dimension', spread: 'dimension' });
- if (p) return p;
- }
- return null;
- }
- case 'gradient':
- if (!Array.isArray(v) || !v.length) return 'gradient is a list of {color, position}';
- for (const s of v) { const p = fields(s, { color: 'color', position: 'number' }); if (p) return p; }
- return null;
- }
- return null;
- }
- function fields(v: unknown, spec: Record<string, string>): string | null {
- if (!isObj(v)) return `composite value is an object with the fields ${Object.keys(spec).join(', ')}`;
- for (const [k, t] of Object.entries(spec)) {
- if (!(k in v)) return `no field ${k}`;
- const p = valueProblem(t, v[k]);
- if (p) return `${k}: ${p}`;
- }
- return null;
- }
- /** Every reference string inside a value, with the type it must point at (null: any). */
- export function refs(type: string | null, v: unknown): { ref: string; type: string | null }[] {
- const out: { ref: string; type: string | null }[] = [];
- const sub: Record<string, Record<string, string>> = {
- border: { color: 'color', width: 'dimension', style: 'strokeStyle' },
- transition: { duration: 'duration', delay: 'duration', timingFunction: 'cubicBezier' },
- typography: { fontFamily: 'fontFamily', fontSize: 'dimension', fontWeight: 'fontWeight', letterSpacing: 'dimension', lineHeight: 'number' },
- shadow: { color: 'color', offsetX: 'dimension', offsetY: 'dimension', blur: 'dimension', spread: 'dimension' },
- gradient: { color: 'color', position: 'number' },
- };
- const visit = (x: unknown, t: string | null) => {
- if (typeof x === 'string') { const m = REF.exec(x); if (m) out.push({ ref: m[1], type: t }); return; }
- if (Array.isArray(x)) { for (const y of x) visit(y, t && sub[t] ? t : null); return; }
- if (isObj(x) && t && sub[t]) for (const [k, kt] of Object.entries(sub[t])) if (k in x) visit(x[k], kt);
- };
- visit(v, type);
- return out;
- }
- /** All problems of the tokens: structure, types, values, references (missing, wrong type, cycles). */
- export function validate(root = process.cwd(), over: Partial<Config> = {}): { problems: string[]; tokens: Map<string, Token>; dark: Map<string, Token> } {
- const c = config(root, over);
- const problems: string[] = [];
- const base = readTree(c.source, root);
- if (base.error) return { problems: [base.error], tokens: new Map(), dark: new Map() };
- const tokens = collect(base.tree, c.source, problems);
- let dark = new Map<string, Token>();
- if (c.dark) {
- const d = readTree(c.dark, root);
- if (d.error) problems.push(d.error);
- else {
- dark = collect(d.tree, c.dark, problems);
- for (const [p, t] of dark) {
- if (!tokens.has(p)) problems.push(`${c.dark}: ${p} — no such token in ${c.source}`);
- else if (!t.type) t.type = (tokens.get(p) as Token).type; // the dark value has the type of the token it overrides
- }
- }
- }
- for (const set of [tokens, dark]) {
- for (const t of set.values()) {
- const all = set === dark ? new Map([...tokens, ...dark]) : tokens;
- const type = typeOf(t, all);
- if (!type) { problems.push(`${t.file}: ${t.path} — the type is set neither on the token nor on the group`); continue; }
- const p = valueProblem(type, t.value);
- if (p) problems.push(`${t.file}: ${t.path} — ${p}`);
- for (const r of refs(type, t.value)) {
- const target = all.get(r.ref);
- if (!target) { problems.push(`${t.file}: ${t.path} — the reference {${r.ref}} leads nowhere`); continue; }
- const tt = typeOf(target, all);
- if (r.type && tt && tt !== r.type) problems.push(`${t.file}: ${t.path} — the reference {${r.ref}} points to ${tt}, but ${r.type} is needed`);
- }
- // Cycles: follow whole-value references.
- const seen = [t.path];
- let cur: Token | undefined = t;
- while (cur && typeof cur.value === 'string' && REF.test(cur.value)) {
- const next = (REF.exec(cur.value) as RegExpExecArray)[1];
- if (seen.includes(next)) { problems.push(`${t.file}: ${t.path} — circular references: ${[...seen, next].join(' → ')}`); break; }
- seen.push(next);
- cur = all.get(next);
- }
- }
- }
- return { problems, tokens, dark };
- }
- export const varName = (path: string, prefix: string) => `--${prefix}${path.split('.').join('-')}`.replace(/[^\w-]/g, '-').toLowerCase();
- function css(type: string | null, v: unknown, prefix: string): string {
- if (typeof v === 'string') { const m = REF.exec(v); if (m) return `var(${varName(m[1], prefix)})`; }
- const r = (x: unknown, t: string) => css(t, x, prefix);
- switch (type) {
- case 'color': {
- if (typeof v === 'string') return v;
- const o = v as { colorSpace: string; components: (number | 'none')[]; alpha?: number; hex?: string };
- const a = o.alpha === undefined || o.alpha === 1 ? '' : ` / ${o.alpha}`;
- if (o.hex && !a) return o.hex;
- const c = o.components.map(String);
- if (['hsl', 'hwb'].includes(o.colorSpace)) return `${o.colorSpace}(${c[0]} ${c[1]}% ${c[2]}%${a})`;
- if (['lab', 'lch', 'oklab', 'oklch'].includes(o.colorSpace)) return `${o.colorSpace}(${c.join(' ')}${a})`;
- return `color(${o.colorSpace} ${c.join(' ')}${a})`;
- }
- case 'dimension': case 'duration':
- return typeof v === 'object' && v ? `${(v as any).value}${(v as any).unit}` : String(v);
- case 'fontFamily': return (Array.isArray(v) ? v : [v]).map((f) => (/^[\w-]+$/.test(String(f)) ? String(f) : `"${f}"`)).join(', ');
- case 'fontWeight': return String(typeof v === 'string' ? WEIGHTS[v] ?? v : v);
- case 'cubicBezier': return `cubic-bezier(${(v as number[]).join(', ')})`;
- case 'strokeStyle': return typeof v === 'string' ? v : 'dashed';
- case 'border': { const o = v as any; return `${r(o.width, 'dimension')} ${r(o.style, 'strokeStyle')} ${r(o.color, 'color')}`; }
- case 'transition': { const o = v as any; return `${r(o.duration, 'duration')} ${r(o.timingFunction, 'cubicBezier')} ${r(o.delay, 'duration')}`; }
- case 'shadow':
- return (Array.isArray(v) ? v : [v]).map((l: any) => `${l.inset ? 'inset ' : ''}${r(l.offsetX, 'dimension')} ${r(l.offsetY, 'dimension')} ${r(l.blur, 'dimension')} ${r(l.spread, 'dimension')} ${r(l.color, 'color')}`).join(', ');
- case 'gradient': return (v as any[]).map((s) => `${r(s.color, 'color')} ${Math.round(Number(s.position) * 1000) / 10}%`).join(', ');
- }
- return String(v);
- }
- /** Custom property lines of a set of tokens (typography fans out into one property per field). */
- function lines(set: Map<string, Token>, all: Map<string, Token>, prefix: string): string[] {
- const out: string[] = [];
- for (const t of set.values()) {
- const type = typeOf(t, all);
- const name = varName(t.path, prefix);
- if (type === 'typography' && !(typeof t.value === 'string')) {
- const o = t.value as Record<string, unknown>;
- const kinds: Record<string, string> = { fontFamily: 'fontFamily', fontSize: 'dimension', fontWeight: 'fontWeight', letterSpacing: 'dimension', lineHeight: 'number' };
- for (const [k, kt] of Object.entries(kinds)) if (k in o) out.push(` ${name}-${k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}: ${css(kt, o[k], prefix)};`);
- continue;
- }
- out.push(` ${name}: ${css(type, t.value, prefix)};`);
- }
- return out;
- }
- /** The CSS file the tokens give. */
- export function build(root = process.cwd(), over: Partial<Config> = {}): { text: string; problems: string[] } {
- const c = config(root, over);
- const { problems, tokens, dark } = validate(root, over);
- if (problems.length) return { text: '', problems };
- let text = `/* Built from ${c.source}${c.dark ? ` and ${c.dark}` : ''} by \`shtuk run design-tokens build\`. Do not edit: edit the tokens and build again. */\n:root {\n${lines(tokens, tokens, c.prefix).join('\n')}\n}\n`;
- if (dark.size) text += `\n${c.darkSelector} {\n${lines(dark, new Map([...tokens, ...dark]), c.prefix).join('\n')}\n}\n`;
- return { text, problems };
- }