@rickycourtes/designrail 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/extract.js ADDED
@@ -0,0 +1,271 @@
1
+ // Extract: turn the values a project already uses into a token system.
2
+ // Primitives are named for what they are (--gray-100, --space-8); semantic
3
+ // tokens say what they are for (--surface, --text-muted) and are inferred
4
+ // from where each value is used. What the project never says is derived from
5
+ // the contract, and marked so.
6
+ import { cluster, colorsOf, scaleOf, ROLES } from './audit.js';
7
+ import { CONTRACT, KIT_SPACE, roleOfProp } from './contract.js';
8
+
9
+ const HUES = [['red', 25], ['orange', 50], ['amber', 72], ['yellow', 98], ['lime', 125], ['green', 145], ['emerald', 162], ['teal', 182], ['cyan', 210], ['sky', 232], ['blue', 258], ['indigo', 275], ['violet', 292], ['purple', 305], ['fuchsia', 325], ['pink', 350], ['rose', 8]];
10
+ const STEP_L = [[50, 0.985], [100, 0.967], [200, 0.928], [300, 0.872], [400, 0.75], [500, 0.62], [600, 0.53], [700, 0.45], [800, 0.37], [900, 0.29], [950, 0.2]];
11
+
12
+ const hueName = (H) => HUES.reduce((best, [n, h]) => { const d = Math.min(Math.abs(H - h), 360 - Math.abs(H - h)); return d < best.d ? { n, d } : best; }, { n: 'red', d: 999 }).n;
13
+
14
+ // Lightness → step, as a continuous curve, so two close colours get 450 and 500 rather than clash.
15
+ function stepL(step) {
16
+ for (let i = 0; i < STEP_L.length - 1; i++) {
17
+ const [s0, l0] = STEP_L[i], [s1, l1] = STEP_L[i + 1];
18
+ if (step >= s0 && step <= s1) return l0 + ((l1 - l0) * (step - s0)) / (s1 - s0);
19
+ }
20
+ return step < 50 ? 1 : 0.15;
21
+ }
22
+ const CANDIDATE_STEPS = Array.from({ length: 39 }, (_, i) => 25 + i * 25);
23
+
24
+ // Grey: little chroma for its lightness. Near white or black a small chroma
25
+ // is already a visible tint (#fef2f2 is pink, not grey).
26
+ export const isNeutral = (f) => f.C < 0.035 && f.C / Math.max(0.02, Math.min(f.L, 1 - f.L)) < 0.25;
27
+
28
+ function colorName(f, taken) {
29
+ const pct = Math.round(f.alpha * 100);
30
+ const alpha = f.alpha < 1 ? `-a${pct}` : '';
31
+ if (f.C < 0.01 && f.L > 0.995) return free('--white' + alpha, taken);
32
+ if (f.C < 0.01 && f.L < 0.03) return free('--black' + alpha, taken);
33
+ const family = isNeutral(f) ? 'gray' : hueName(f.H);
34
+ const steps = [...CANDIDATE_STEPS].sort((a, b) => Math.abs(stepL(a) - f.L) - Math.abs(stepL(b) - f.L) || (a % 100 ? 1 : -1));
35
+ const first = steps.find((s) => s % 50 === 0 && !taken.has(`--${family}-${s}${alpha}`)) ;
36
+ const name = first && Math.abs(stepL(first) - f.L) < 0.06 ? `--${family}-${first}${alpha}` : `--${family}-${steps.find((s) => !taken.has(`--${family}-${s}${alpha}`))}${alpha}`;
37
+ return free(name, taken);
38
+ }
39
+
40
+ function free(name, taken) {
41
+ let n = name, i = 2;
42
+ while (taken.has(n)) n = `${name}-${i++}`;
43
+ taken.add(n);
44
+ return n;
45
+ }
46
+
47
+ const fmtPx = (n) => `${+n.toFixed(2)}px`;
48
+ const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
49
+ const firstFamily = (stack) => stack.split(',')[0].trim().replace(/^['"]|['"]$/g, '');
50
+
51
+ export function extract(model) {
52
+ const { cfg } = model;
53
+ const prim = [];
54
+ const sem = [];
55
+ const taken = new Set();
56
+ const byLiteral = new Map(); // literal key → primitive name
57
+
58
+ // --- colour primitives ----------------------------------------------------
59
+ const colors = colorsOf(model);
60
+ const colorTokens = [];
61
+ for (const g of colors.groups.sort((a, b) => a.centre.facts.L - b.centre.facts.L)) {
62
+ const f = g.centre.facts;
63
+ const name = colorName(f, taken);
64
+ const roles = {};
65
+ for (const m of g.members) for (const [p, n] of Object.entries(m.props)) { const r = roleOfProp(p); roles[r] = (roles[r] ?? 0) + n; }
66
+ const merged = g.members.slice(1).map((m) => m.value);
67
+ const t = { name, value: f.hex, facts: f, count: g.count, roles, note: `${g.count} use${g.count > 1 ? 's' : ''}${merged.length ? `; merges ${merged.slice(0, 4).join(' ')}` : ''}` };
68
+ colorTokens.push(t);
69
+ for (const m of g.members) byLiteral.set(m.value, name);
70
+ }
71
+ const fams = (t) => t.name.replace(/^--/, '').replace(/-a\d+$/, '').replace(/-\d+(-\d+)?$/, '');
72
+ colorTokens.sort((a, b) => (fams(a) === fams(b) ? b.facts.L - a.facts.L : fams(a) < fams(b) ? -1 : 1));
73
+ for (const t of colorTokens) prim.push({ section: 'colour', name: t.name, value: t.value, note: t.note });
74
+
75
+ // --- colour semantics -----------------------------------------------------
76
+ const opaque = colorTokens.filter((t) => t.facts.alpha === 1);
77
+ const neutral = opaque.filter((t) => isNeutral(t.facts));
78
+ const chroma = opaque.filter((t) => !isNeutral(t.facts) && t.facts.C >= 0.04);
79
+ const onPage = (prop) => model.occ.filter((o) => o.lit.kind === 'color' && /^(html|body|:root)$/.test((o.sel ?? '').trim()) && prop.test(o.prop)).map((o) => byLiteral.get(o.lit.hex))[0];
80
+ const use = (t, r) => t.roles[r] ?? 0;
81
+ const pageBg = opaque.find((t) => t.name === onPage(/^background/)) ?? [...neutral].sort((a, b) => use(b, 'bg') - use(a, 'bg'))[0];
82
+ const dark = pageBg ? pageBg.facts.L < 0.5 : false;
83
+ const set = (name, ref, why) => {
84
+ if (!ref || sem.some((s) => s.name === name)) return;
85
+ const r = ref.name ?? ref;
86
+ sem.push({ section: CONTRACT.find((c) => c.name === name)?.group ?? 'colour', name, value: r.startsWith('--') ? `var(${r})` : r, note: why });
87
+ };
88
+
89
+ if (pageBg) set('--surface', pageBg, 'the page background');
90
+ const otherBg = neutral.filter((t) => t !== pageBg && use(t, 'bg') > 0).sort((a, b) => use(b, 'bg') - use(a, 'bg'));
91
+ const lighter = otherBg.filter((t) => t.facts.L > pageBg?.facts.L);
92
+ const darker = otherBg.filter((t) => t.facts.L < pageBg?.facts.L);
93
+ set('--surface-raised', dark ? lighter[0] : lighter[0] ?? darker[0], 'most used background after the page');
94
+ set('--surface-sunken', dark ? darker[0] : darker.find((t) => t !== (lighter[0] ?? darker[0])), 'a background a step into the page');
95
+
96
+ // Body text: what body/html says, else the most used text colour that reads on the page.
97
+ const readable = (t) => !pageBg || Math.abs(t.facts.L - pageBg.facts.L) > 0.25;
98
+ const texts = neutral.filter((t) => use(t, 'text') > 0 && readable(t)).sort((a, b) => use(b, 'text') - use(a, 'text'));
99
+ const bodyText = opaque.find((t) => t.name === onPage(/^color$/));
100
+ if (bodyText) texts.splice(texts.indexOf(bodyText) >>> 0, texts.includes(bodyText) ? 1 : 0), texts.unshift(bodyText);
101
+ if (texts[0]) set('--text', texts[0], bodyText ? 'the body text colour' : 'most used text colour');
102
+ const towardPage = texts.slice(1).filter((t) => (dark ? t.facts.L < texts[0].facts.L : t.facts.L > texts[0].facts.L));
103
+ set('--text-muted', towardPage[0], 'second text colour');
104
+ const muted = towardPage[0];
105
+ set('--text-faint', muted && towardPage.slice(1).find((t) => (dark ? t.facts.L < muted.facts.L : t.facts.L > muted.facts.L)), 'a text colour fainter than muted');
106
+
107
+ const borders = opaque.concat(colorTokens.filter((t) => t.facts.alpha < 1)).filter((t) => use(t, 'border') > 0 && isNeutral(t.facts)).sort((a, b) => use(b, 'border') - use(a, 'border'));
108
+ if (borders[0]) set('--border', borders[0], 'most used border colour');
109
+ const strong = borders.slice(1).find((t) => Math.abs(t.facts.L - (pageBg?.facts.L ?? 1)) > Math.abs(borders[0].facts.L - (pageBg?.facts.L ?? 1)));
110
+ set('--border-strong', strong, 'a border further from the page');
111
+
112
+ const total = (t) => t.count;
113
+ const near = (t, lo, hi) => (lo < hi ? t.facts.H >= lo && t.facts.H < hi : t.facts.H >= lo || t.facts.H < hi);
114
+ const isRed = (t) => near(t, 0, 45) || near(t, 345, 360);
115
+ const isGreen = (t) => near(t, 120, 175);
116
+ const isAmber = (t) => near(t, 55, 110);
117
+ const byUse = [...chroma].sort((a, b) => total(b) - total(a));
118
+ const accent = byUse.find((t) => !isRed(t) && !isGreen(t)) ?? byUse[0];
119
+ if (accent) {
120
+ set('--accent', accent, 'most used colour that is not grey');
121
+ const hover = byUse.find((t) => t !== accent && hueName(t.facts.H) === hueName(accent.facts.H) && Math.abs(t.facts.L - accent.facts.L) < 0.15);
122
+ set('--accent-hover', hover, 'the accent’s nearest sibling');
123
+ // Text on the accent: what the project puts on it, else white unless the accent is pale.
124
+ const seen = {};
125
+ const byRule = new Map();
126
+ for (const o of model.occ) if (o.lit.kind === 'color') { const k = `${o.file}|${o.sel}|${o.media}`; if (!byRule.has(k)) byRule.set(k, []); byRule.get(k).push(o); }
127
+ for (const list of byRule.values()) {
128
+ if (!list.some((o) => /^background/.test(o.prop) && byLiteral.get(o.lit.hex) === accent.name)) continue;
129
+ for (const o of list) if (o.prop === 'color') { const n = byLiteral.get(o.lit.hex); seen[n] = (seen[n] ?? 0) + 1; }
130
+ }
131
+ const top = Object.entries(seen).sort((a, b) => b[1] - a[1])[0]?.[0];
132
+ set('--text-on-accent', top ?? (accent.facts.L < 0.75 ? opaque.find((t) => t.facts.L > 0.97) ?? '#ffffff' : texts[0] ?? '#111111'), top ? 'what the project sets on the accent' : 'reads on the accent');
133
+ }
134
+ set('--danger', byUse.find((t) => t !== accent && isRed(t)), 'most used red');
135
+ set('--success', byUse.find((t) => t !== accent && isGreen(t)), 'most used green');
136
+ set('--warning', byUse.find((t) => t !== accent && isAmber(t)), 'most used amber');
137
+
138
+ // --- spacing, radius, type size -------------------------------------------
139
+ const roleRules = (role) => model.occ.filter((o) => ROLES[role] && new RegExp(`[.\\-_](${ROLES[role].source.slice(2, -2)})\\b`, 'i').test(o.sel ?? ''));
140
+ for (const [cat, prefix, section] of [['space', '--space-', 'space'], ['radius', '--radius-', 'shape'], ['font-size', '--font-size-', 'type']]) {
141
+ const sc = scaleOf(model, cat);
142
+ const snap = cat === 'font-size' ? 0.5 : cfg.snap;
143
+ const groups = cluster(sc.items, (a, b) => Math.abs(a.value - b.value) <= snap);
144
+ const kept = new Map();
145
+ for (let gi = 0; gi < groups.length; gi++) {
146
+ const g = groups[gi];
147
+ let v = g.centre.value;
148
+ const onGrid = Math.round(v / sc.grid) * sc.grid;
149
+ if (cat !== 'font-size' && Math.abs(onGrid - v) <= cfg.snap && onGrid > 0) v = onGrid;
150
+ // A member the step moved out of reach stands on its own.
151
+ const far = g.members.filter((m) => Math.abs(m.value - v) > snap);
152
+ if (far.length) {
153
+ g.members = g.members.filter((m) => !far.includes(m));
154
+ g.count = g.members.reduce((n, m) => n + m.count, 0);
155
+ for (const m of far) groups.push({ centre: m, members: [m], count: m.count });
156
+ }
157
+ if (cat === 'radius' && v >= 500) { for (const m of g.members) byLiteral.set(`${cat}:${m.value}`, '--radius-full'); continue; }
158
+ if (g.count < 2 && v % sc.grid !== 0 && cat !== 'font-size') continue; // a one-off off the grid is a value to snap, not a step
159
+ const name = `${prefix}${String(+v.toFixed(2)).replace('.', '_')}`;
160
+ if (!kept.has(name)) kept.set(name, { v, count: 0, members: [] });
161
+ kept.get(name).count += g.count;
162
+ kept.get(name).members.push(...g.members.map((m) => m.value));
163
+ }
164
+ if (cat === 'space') for (const s of KIT_SPACE) if (![...kept.values()].some((k) => k.v === s)) kept.set(`--space-${s}`, { v: s, count: 0, members: [], derived: true });
165
+ for (const [name, k] of [...kept].sort((a, b) => a[1].v - b[1].v)) {
166
+ prim.push({ section, name, value: fmtPx(k.v), note: k.derived ? 'derived: the kit’s gap step' : `${k.count} use${k.count > 1 ? 's' : ''}${k.members.some((m) => m !== k.v) ? `; snaps ${k.members.filter((m) => m !== k.v).map(fmtPx).join(' ')}` : ''}` });
167
+ for (const m of k.members) byLiteral.set(`${cat}:${m}`, name);
168
+ }
169
+ if (cat === 'radius') {
170
+ prim.push({ section, name: '--radius-full', value: '999px', note: 'pills and circles' });
171
+ const mostIn = (role) => { const t = {}; for (const o of roleRules(role)) if (o.lit.cat === 'radius') { const n = byLiteral.get(`radius:${Math.abs(o.lit.px)}`); if (n) t[n] = (t[n] ?? 0) + 1; } return Object.entries(t).sort((a, b) => b[1] - a[1])[0]?.[0]; };
172
+ const common = [...kept].sort((a, b) => b[1].count - a[1].count).map(([n]) => n);
173
+ set('--radius-control', mostIn('button') ?? mostIn('field') ?? common.find((n) => kept.get(n).v <= 12), 'most used radius on buttons and fields');
174
+ set('--radius-card', mostIn('card') ?? mostIn('dialog') ?? common.find((n) => kept.get(n).v > 8 && kept.get(n).v <= 32), 'most used radius on cards and dialogs');
175
+ }
176
+ if (cat === 'font-size') {
177
+ const order = [...kept].sort((a, b) => b[1].count - a[1].count);
178
+ const bodyPx = model.occ.find((o) => o.lit.cat === 'font-size' && /^(html|body)$/.test((o.sel ?? '').trim()))?.lit.px;
179
+ const body = order.find(([, k]) => k.v === bodyPx) ?? order.find(([, k]) => k.v >= 13 && k.v <= 18);
180
+ if (body) {
181
+ set('--font-size-body', body[0], bodyPx === body[1].v ? 'the body size' : 'most used size between 13 and 18px');
182
+ set('--font-size-small', order.find(([, k]) => k.v < body[1].v && k.v >= 10)?.[0], 'most used size below body');
183
+ set('--font-size-title', order.find(([, k]) => k.v >= body[1].v * 1.2 && k.v <= 32)?.[0], 'most used size a step above body');
184
+ }
185
+ }
186
+ }
187
+
188
+ // --- fonts, weights, shadows, motion -------------------------------------
189
+ const fonts = new Map();
190
+ for (const o of model.occ) if (o.lit.kind === 'font') {
191
+ const fam = firstFamily(o.lit.raw);
192
+ if (!fonts.has(fam)) fonts.set(fam, { stack: o.lit.raw, count: 0, display: 0 });
193
+ const e = fonts.get(fam);
194
+ e.count++;
195
+ if (/\bh[1-3]\b|title|heading|display|hero/i.test(o.sel ?? '')) e.display++;
196
+ }
197
+ const fontList = [...fonts].sort((a, b) => b[1].count - a[1].count);
198
+ for (const [fam, e] of fontList) { const name = free(`--font-${slug(fam) || 'family'}`, taken); e.name = name; prim.push({ section: 'type', name, value: e.stack, note: `${e.count} use${e.count > 1 ? 's' : ''}` }); }
199
+ const mono = fontList.find(([f, e]) => /mono|courier|consolas|menlo|code/i.test(f + e.stack));
200
+ const ui = fontList.find((x) => x !== mono);
201
+ if (ui) set('--font-ui', ui[1].name, 'most used family');
202
+ const display = fontList.filter((x) => x !== mono && x !== ui).sort((a, b) => b[1].display - a[1].display)[0];
203
+ if (display?.[1].display) set('--font-display', display[1].name, 'the family headings use');
204
+ if (mono) set('--font-mono', mono[1].name, 'the monospace family');
205
+
206
+ const weights = new Map();
207
+ for (const o of model.occ) if (o.lit.kind === 'weight') weights.set(o.lit.n, (weights.get(o.lit.n) ?? 0) + 1);
208
+ for (const [w, n] of [...weights].sort((a, b) => a[0] - b[0])) prim.push({ section: 'type', name: `--weight-${w}`, value: String(w), note: `${n} use${n > 1 ? 's' : ''}` });
209
+ const strongW = [...weights].filter(([w]) => w >= 500).sort((a, b) => b[1] - a[1])[0];
210
+ if (strongW) set('--weight-strong', `--weight-${strongW[0]}`, 'most used bold weight');
211
+
212
+ const shadows = new Map();
213
+ for (const o of model.occ) if (o.lit.kind === 'shadow') { if (!shadows.has(o.lit.norm)) shadows.set(o.lit.norm, { raw: o.lit.raw, count: 0 }); shadows.get(o.lit.norm).count++; }
214
+ const blurOf = (s) => Math.max(0, ...[...s.matchAll(/(-?[\d.]+)px/g)].map((m) => Math.abs(parseFloat(m[1]))));
215
+ const shadowList = [...shadows.values()].sort((a, b) => blurOf(a.raw) - blurOf(b.raw));
216
+ shadowList.forEach((s, i) => { s.name = `--shadow-${i + 1}`; prim.push({ section: 'shape', name: s.name, value: s.raw, note: `${s.count} use${s.count > 1 ? 's' : ''}` }); byLiteral.set(`shadow:${[...shadows].find(([, v]) => v === s)[0]}`, s.name); });
217
+ if (shadowList.length) {
218
+ set('--shadow-raised', [...shadowList].sort((a, b) => b.count - a.count)[0].name, 'most used shadow');
219
+ if (shadowList.length > 1) set('--shadow-overlay', shadowList[shadowList.length - 1].name, 'the deepest shadow');
220
+ }
221
+
222
+ const durations = new Map();
223
+ for (const o of model.occ) if (o.lit.kind === 'time') durations.set(o.lit.ms, (durations.get(o.lit.ms) ?? 0) + 1);
224
+ for (const [ms, n] of [...durations].sort((a, b) => a[0] - b[0])) prim.push({ section: 'motion', name: `--duration-${Math.round(ms)}`, value: `${Math.round(ms)}ms`, note: `${n} use${n > 1 ? 's' : ''}` });
225
+ const fast = [...durations].filter(([ms]) => ms <= 200 && ms > 0).sort((a, b) => b[1] - a[1])[0];
226
+ const base = [...durations].filter(([ms]) => ms > 200 && ms <= 500).sort((a, b) => b[1] - a[1])[0];
227
+ if (fast) set('--duration-fast', `--duration-${Math.round(fast[0])}`, 'most used short duration');
228
+ if (base) set('--duration-base', `--duration-${Math.round(base[0])}`, 'most used open/close duration');
229
+
230
+ // --- what the project never says: derived from the contract ----------------
231
+ for (const c of CONTRACT) {
232
+ if (sem.some((s) => s.name === c.name) || prim.some((p) => p.name === c.name)) continue;
233
+ if (c.name === '--text-on-accent') { sem.push({ section: 'colour', name: c.name, value: '#ffffff', note: 'derived' }); continue; }
234
+ if (c.name === '--surface' || c.name === '--text' || c.name === '--accent') {
235
+ const v = { '--surface': dark ? '#111111' : '#ffffff', '--text': dark ? '#f2f2f2' : '#1a1a1a', '--accent': '#2563eb' }[c.name];
236
+ sem.push({ section: 'colour', name: c.name, value: v, note: 'derived: the project has none' });
237
+ continue;
238
+ }
239
+ if (c.derive) sem.push({ section: c.group, name: c.name, value: c.derive, note: 'derived' });
240
+ }
241
+ const order = CONTRACT.map((c) => c.name);
242
+ sem.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name));
243
+ return { primitives: prim, semantic: sem, dark, byLiteral };
244
+ }
245
+
246
+ const SECTIONS = ['colour', 'space', 'shape', 'type', 'motion'];
247
+
248
+ export function toCss(list, header) {
249
+ const lines = [header, '', ':root {'];
250
+ for (const sec of SECTIONS) {
251
+ const items = list.filter((t) => t.section === sec);
252
+ if (!items.length) continue;
253
+ lines.push(` /* --- ${sec} ${'-'.repeat(Math.max(3, 66 - sec.length))} */`);
254
+ const w = Math.min(28, Math.max(...items.map((t) => t.name.length)) + 1);
255
+ for (const t of items) lines.push(` ${(t.name + ':').padEnd(w + 1)}${t.value};${t.note ? ` /* ${t.note} */` : ''}`);
256
+ lines.push('');
257
+ }
258
+ if (lines[lines.length - 1] === '') lines.pop();
259
+ lines.push('}', '');
260
+ return lines.join('\n');
261
+ }
262
+
263
+ // W3C Design Tokens (DTCG) JSON, for Figma plugins and Style Dictionary.
264
+ export function toDtcg({ primitives, semantic }) {
265
+ const type = (t) => (t.section === 'colour' ? 'color' : t.section === 'motion' ? (t.name.includes('ease') ? 'cubicBezier' : 'duration') : t.name.startsWith('--font-size') ? 'dimension' : t.name.startsWith('--font') ? 'fontFamily' : t.name.startsWith('--weight') ? 'fontWeight' : t.name.startsWith('--shadow') ? 'shadow' : 'dimension');
266
+ const ref = (v) => v.replace(/var\((--[\w-]+)\)/g, (_, n) => `{${n.slice(2)}}`);
267
+ const out = { primitive: {}, semantic: {} };
268
+ for (const t of primitives) out.primitive[t.name.slice(2)] = { $type: type(t), $value: t.value, ...(t.note ? { $description: t.note } : {}) };
269
+ for (const t of semantic) out.semantic[t.name.slice(2)] = { $type: type(t), $value: ref(t.value).replace(/^\{([\w-]+)\}$/, (_, n) => `{${semantic.some((s) => s.name === '--' + n) ? 'semantic' : 'primitive'}.${n}}`), ...(t.note ? { $description: t.note } : {}) };
270
+ return JSON.stringify(out, null, 2) + '\n';
271
+ }
package/src/fix.js ADDED
@@ -0,0 +1,104 @@
1
+ // Fix: rewrite hardcoded design values as the tokens that hold them. A diff by
2
+ // default; `--write` applies it. Colours pick the semantic token whose job
3
+ // matches the property (a background gets --surface, not --text), lengths the
4
+ // scale step that equals them, or with --snap the one within `snap` px.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { colorDistance, colorFacts } from './values.js';
8
+ import { roleOfProp } from './contract.js';
9
+ import { tokenIndex, firstFamily } from './tokens.js';
10
+
11
+ export function matcher(model, { snap = false } = {}) {
12
+ const tokens = tokenIndex(model);
13
+ const allowed = (t) => model.cfg.allowPrimitives.some((p) => t.name.startsWith(p));
14
+ const pick = (o) => {
15
+ const { lit, prop } = o;
16
+ if (lit.kind === 'color') {
17
+ const role = roleOfProp(prop);
18
+ const facts = colorFactsOf(lit.hex);
19
+ const c = tokens.filter((t) => t.color).map((t) => ({ t, d: colorDistance(t.color, facts) }))
20
+ .filter((x) => x.d < model.cfg.colorTolerance)
21
+ .map((x) => ({ ...x, pen: !x.t.semantic ? 2 : x.t.role === role ? 0 : x.t.role === 'any' ? 1 : 9 }))
22
+ .filter((x) => x.pen < 9)
23
+ .sort((a, b) => ((b.d < 0.002) - (a.d < 0.002)) || a.pen - b.pen || a.d - b.d);
24
+ return c[0] && { token: c[0].t, exact: c[0].d < 0.002 };
25
+ }
26
+ if (lit.kind === 'length' && ['space', 'radius', 'font-size'].includes(lit.cat) && lit.unit !== 'em') {
27
+ const px = Math.abs(lit.px);
28
+ const c = tokens.filter((t) => t.px != null && t.cat === lit.cat && t.px > 0)
29
+ .map((t) => ({ t, d: Math.abs(t.px - px) }))
30
+ .filter((x) => x.d < 0.01 || (snap && x.d <= model.cfg.snap))
31
+ .sort((a, b) => a.d - b.d || (allowed(b.t) - allowed(a.t)) || (b.t.semantic - a.t.semantic));
32
+ return c[0] && { token: c[0].t, exact: c[0].d < 0.01, negative: lit.px < 0 };
33
+ }
34
+ if (lit.kind === 'font') {
35
+ const fam = firstFamily(lit.raw);
36
+ const c = tokens.filter((t) => t.font === fam).sort((a, b) => b.semantic - a.semantic);
37
+ return c[0] && { token: c[0], exact: true };
38
+ }
39
+ if (lit.kind === 'shadow') {
40
+ const c = tokens.filter((t) => t.shadow === lit.norm).sort((a, b) => b.semantic - a.semantic);
41
+ return c[0] && { token: c[0], exact: true };
42
+ }
43
+ if (lit.kind === 'time') {
44
+ const c = tokens.filter((t) => t.ms === lit.ms && /duration|time|speed/.test(t.name)).sort((a, b) => b.semantic - a.semantic);
45
+ return c[0] && { token: c[0], exact: true };
46
+ }
47
+ return null;
48
+ };
49
+ return { tokens, pick };
50
+ }
51
+
52
+ const factsCache = new Map();
53
+ function colorFactsOf(hex) {
54
+ if (!factsCache.has(hex)) factsCache.set(hex, colorFacts(hex));
55
+ return factsCache.get(hex);
56
+ }
57
+
58
+ export function planFix(model, opts = {}) {
59
+ const { pick, tokens } = matcher(model, opts);
60
+ const edits = new Map();
61
+ const missed = {};
62
+ for (const o of model.occ) {
63
+ if (o.prop.startsWith('--') && o.lit.kind !== 'color') continue;
64
+ if (!['color', 'length', 'font', 'shadow', 'time'].includes(o.lit.kind)) continue;
65
+ if (o.lit.kind === 'length' && !['space', 'radius', 'font-size'].includes(o.lit.cat)) continue;
66
+ const m = pick(o);
67
+ if (!m) { const k = o.lit.kind === 'length' ? o.lit.cat : o.lit.kind; missed[k] ??= new Map(); missed[k].set(o.lit.hex ?? o.lit.raw, (missed[k].get(o.lit.hex ?? o.lit.raw) ?? 0) + 1); continue; }
68
+ const ref = `var(${m.token.name})`;
69
+ const js = o.origin === 'js-object' ? findDecl(model, o) : null;
70
+ let start, end, text;
71
+ if (js?.js === 'number') { start = js.vstart; end = js.vend; text = `'${m.negative ? `calc(${ref} * -1)` : ref}'`; }
72
+ else { start = o.vstart + o.lit.at; end = start + o.lit.raw.length; text = m.negative ? `calc(${ref} * -1)` : ref; }
73
+ if (!edits.has(o.file)) edits.set(o.file, []);
74
+ edits.get(o.file).push({ start, end, text, from: o.lit.raw, line: o.line, exact: m.exact, token: m.token.name });
75
+ }
76
+ for (const [f, list] of edits) {
77
+ list.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));
78
+ const kept = [];
79
+ for (const e of list) if (!kept.length || e.start >= kept[kept.length - 1].end) kept.push(e);
80
+ edits.set(f, kept);
81
+ }
82
+ return { edits, missed, tokens: tokens.length };
83
+ }
84
+
85
+ function findDecl(model, o) {
86
+ const f = model.files.find((x) => x.path === o.file);
87
+ for (const r of f.rules) for (const d of r.decls) if (d.vstart === o.vstart) return d;
88
+ return null;
89
+ }
90
+
91
+ export function applyFix(root, edits) {
92
+ let n = 0;
93
+ for (const [file, list] of edits) {
94
+ const p = path.join(root, file);
95
+ let text = fs.readFileSync(p, 'utf8');
96
+ for (const e of [...list].sort((a, b) => b.start - a.start)) {
97
+ if (text.slice(e.start, e.end) !== e.from && !(text.slice(e.start, e.end) + 'px' === e.from)) continue;
98
+ text = text.slice(0, e.start) + e.text + text.slice(e.end);
99
+ n++;
100
+ }
101
+ fs.writeFileSync(p, text);
102
+ }
103
+ return n;
104
+ }
package/src/index.js ADDED
@@ -0,0 +1,16 @@
1
+ // The library API, for build plugins and scripts that want the same answers as the CLI.
2
+ export { loadProject, loadConfig, VERSION } from './project.js';
3
+ export { buildModel } from './model.js';
4
+ export { audit } from './audit.js';
5
+ export { extract, toCss, toDtcg } from './extract.js';
6
+ export { planFix, applyFix } from './fix.js';
7
+ export { hits, baselines, added } from './check.js';
8
+ export { traceSelector, traceToken } from './trace.js';
9
+ export { specimens } from './specimens.js';
10
+ export { ejectParts, PARTS } from './kit.js';
11
+ export { planUpgrade, applyUpgrade } from './upgrade.js';
12
+ export { findFoundation } from './project.js';
13
+ export { CONTRACT } from './contract.js';
14
+ export { analyze } from './sources.js';
15
+ export { parseCss } from './css.js';
16
+ export { parseColor, literals } from './values.js';
package/src/init.js ADDED
@@ -0,0 +1,47 @@
1
+ // init: config, the design rules, and (with --agents) a pointer for AI
2
+ // coding agents, so a Claude session in the project uses its parts and tokens.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { listFiles, DEFAULT_CONFIG, findFoundation } from './project.js';
7
+ import { isTokenFile } from './model.js';
8
+ import { analyze } from './sources.js';
9
+
10
+ const RULES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'rules', 'DESIGN.md');
11
+
12
+ const AGENT_BLOCK = `
13
+ ## Design system (designrail)
14
+
15
+ Before touching UI, read \`DESIGN.md\`. Build from the parts in \`{parts}/\` and
16
+ the tokens in {tokens}, on top of the designrail foundation (\`@rickycourtes/designrail/foundation.css\`). Restyle a foundation part with its knobs on a variant, never by editing it; never type a colour, spacing, radius or font size by
17
+ hand. Run \`npx designrail check\` before committing; \`npx designrail trace <selector>\`
18
+ shows where a value comes from. A part the foundation lacks: write it in \`{parts}/\` from tokens; \`npx designrail eject <part>\` only to own a copy.
19
+ `;
20
+
21
+ export function init(root, { agents = false, force = false } = {}) {
22
+ const done = [];
23
+ const cfgPath = path.join(root, 'designrail.config.json');
24
+ const cfg = { ...DEFAULT_CONFIG };
25
+ // Point `tokens` at files that already hold the project's tokens, if any.
26
+ const found = listFiles(root, cfg).filter((f) => /\.(css|scss|less)$/.test(f))
27
+ .filter((f) => { try { return isTokenFile({ path: f, ...analyze(f, fs.readFileSync(path.join(root, f), 'utf8')) }, { ...cfg, tokens: [] }); } catch { return false; } });
28
+ const tokens = found.length ? found : cfg.tokens;
29
+ if (!fs.existsSync(cfgPath) || force) {
30
+ const foundation = findFoundation(root, cfg);
31
+ const out = { ...(foundation ? { foundation: foundation.version } : {}), $schema: 'https://raw.githubusercontent.com/rickycourtes/designrail/main/schema.json', include: cfg.include, exclude: cfg.exclude.filter((e) => !['.git', '.designrail', 'node_modules'].includes(e)), tokens, parts: fs.existsSync(path.join(root, 'src')) ? 'src/ui' : 'ui', grid: cfg.grid, semanticOnly: cfg.semanticOnly, allowPrimitives: cfg.allowPrimitives, runtimeTokens: [], rules: cfg.rules };
32
+ fs.writeFileSync(cfgPath, JSON.stringify(out, null, 2) + '\n');
33
+ done.push(`designrail.config.json${found.length ? ` (tokens found in ${found.join(', ')})` : ''}`);
34
+ }
35
+ const rulesPath = path.join(root, 'DESIGN.md');
36
+ if (!fs.existsSync(rulesPath) || force) { fs.copyFileSync(RULES, rulesPath); done.push('DESIGN.md'); }
37
+ if (agents) {
38
+ const target = ['CLAUDE.md', 'AGENTS.md'].map((f) => path.join(root, f)).find((f) => fs.existsSync(f)) ?? path.join(root, 'CLAUDE.md');
39
+ const now = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : '';
40
+ if (!now.includes('Design system (designrail)')) {
41
+ const parts = JSON.parse(fs.readFileSync(cfgPath, 'utf8')).parts;
42
+ fs.appendFileSync(target, AGENT_BLOCK.replaceAll('{parts}', parts).replace('{tokens}', tokens.map((t) => `\`${t}\``).join(' and ')));
43
+ done.push(path.basename(target));
44
+ }
45
+ }
46
+ return done;
47
+ }
package/src/kit.js ADDED
@@ -0,0 +1,99 @@
1
+ // The kit: list parts, and `eject` one into a project. A project normally
2
+ // imports the parts from the foundation (@rickycourtes/designrail/foundation.css) so every
3
+ // update reaches it; ejecting copies a part in for the project to own, and
4
+ // from then on that part no longer follows the foundation. Any token the part
5
+ // reads that the project lacks (no foundation installed) is added to its token
6
+ // file, derived from the contract so it follows the project's colours.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { parseCss } from './css.js';
11
+ import { CONTRACT } from './contract.js';
12
+ import { saveConfig } from './project.js';
13
+
14
+ export const KIT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'kit');
15
+
16
+ export const PARTS = {
17
+ base: ['base.css'],
18
+ button: ['button.css'],
19
+ field: ['field.css'],
20
+ card: ['card.css'],
21
+ pill: ['pill.css'],
22
+ dropdown: ['dropdown.css', 'dropdown.js'],
23
+ toast: ['toast.css', 'toast.js'],
24
+ sheet: ['sheet.css'],
25
+ };
26
+
27
+ export function partAbout(name) {
28
+ const css = fs.readFileSync(path.join(KIT, 'parts', PARTS[name][0]), 'utf8');
29
+ return /\/\*\s*[\w-]+:\s*([^.\n]*)/.exec(css)?.[1]?.trim() ?? '';
30
+ }
31
+
32
+ function kitTokens() {
33
+ const { rules } = parseCss(fs.readFileSync(path.join(KIT, 'tokens.css'), 'utf8'));
34
+ const m = new Map();
35
+ for (const r of rules) if (r.sel === ':root') for (const d of r.decls) m.set(d.prop, d.value);
36
+ const resolve = (v, depth = 0) => (depth > 8 ? v : v.replace(/var\((--[\w-]+)\)/g, (all, n) => (m.has(n) ? resolve(m.get(n), depth + 1) : all)));
37
+ return { raw: m, resolve };
38
+ }
39
+
40
+ // The value a missing token gets: the contract's derivation (built on other
41
+ // contract names, so it follows the project), else the kit's literal.
42
+ function defaultFor(name, kit) {
43
+ const c = CONTRACT.find((x) => x.name === name);
44
+ if (c?.derive) return c.derive;
45
+ const sp = /^--space-(\d+)$/.exec(name);
46
+ if (sp) return `${sp[1]}px`;
47
+ if (kit.raw.has(name)) return kit.resolve(kit.raw.get(name));
48
+ return null;
49
+ }
50
+
51
+ export function ejectParts(model, names, { force = false, dry = false } = {}) {
52
+ const { root, cfg } = model;
53
+ const from = model.foundation?.dir ?? KIT;
54
+ const kit = kitTokens();
55
+ const copied = [], skipped = [];
56
+ const reads = new Set(), local = new Set();
57
+ for (const name of names) {
58
+ if (!PARTS[name]) throw new Error(`no part "${name}"; parts: ${Object.keys(PARTS).join(', ')}`);
59
+ for (const file of PARTS[name]) {
60
+ const src = path.join(from, 'parts', file);
61
+ const dest = path.join(root, cfg.parts, file);
62
+ const text = fs.readFileSync(src, 'utf8');
63
+ if (file.endsWith('.css')) {
64
+ for (const m of text.matchAll(/var\((--[\w-]+)/g)) reads.add(m[1]);
65
+ for (const m of text.matchAll(/(--[\w-]+)\s*:/g)) local.add(m[1]);
66
+ }
67
+ if (fs.existsSync(dest) && !force) { skipped.push(path.join(cfg.parts, file)); continue; }
68
+ if (!dry) { fs.mkdirSync(path.dirname(dest), { recursive: true }); fs.writeFileSync(dest, text); }
69
+ copied.push(path.join(cfg.parts, file));
70
+ }
71
+ }
72
+ // Close over derivations: --fill reads --text, so a project without --text needs both.
73
+ const missing = new Map();
74
+ const want = [...reads].filter((n) => !local.has(n));
75
+ while (want.length) {
76
+ const n = want.shift();
77
+ if (model.defs.has(n) || missing.has(n)) continue;
78
+ const v = defaultFor(n, kit);
79
+ if (v == null) continue;
80
+ missing.set(n, v);
81
+ for (const m of v.matchAll(/var\((--[\w-]+)/g)) want.push(m[1]);
82
+ }
83
+ let tokenFile = null;
84
+ if (missing.size) {
85
+ const existing = [...model.tokenFiles];
86
+ const semantic = existing.find((f) => model.files.find((x) => x.path === f)?.rules.some((r) => r.decls.some((d) => /var\(/.test(d.value))));
87
+ tokenFile = semantic ?? existing[0] ?? cfg.tokens[cfg.tokens.length - 1];
88
+ const order = CONTRACT.map((c) => c.name);
89
+ const lines = [...missing].sort((a, b) => (order.indexOf(a[0]) + 1 || 999) - (order.indexOf(b[0]) + 1 || 999) || (a[0] < b[0] ? -1 : 1)).map(([n, v]) => ` ${n}: ${v};`);
90
+ const block = `\n/* --- added by designrail eject ${names.join(' ')}: tokens these parts read that the project had none of. Point them at your own values. --- */\n:root {\n${lines.join('\n')}\n}\n`;
91
+ if (!dry) {
92
+ const p = path.join(root, tokenFile);
93
+ fs.mkdirSync(path.dirname(p), { recursive: true });
94
+ fs.appendFileSync(p, block);
95
+ }
96
+ }
97
+ if (!dry && copied.length) saveConfig(root, { ejected: [...new Set([...(cfg.ejected ?? []), ...names])] });
98
+ return { copied, skipped, missing: [...missing], tokenFile };
99
+ }
package/src/markup.js ADDED
@@ -0,0 +1,94 @@
1
+ // Markup → element trees → fingerprints of every subtree, so the same
2
+ // structure drawn in two places shows up as one candidate component.
3
+ // Reads HTML, Vue/Svelte/Astro templates and JSX. Pure: no fs.
4
+
5
+ const VOID = new Set('area base br col embed hr img input link meta param source track wbr'.split(' '));
6
+ const SKIP = new Set(['html', 'head', 'body', 'template', 'slot', 'script', 'style', 'svg', 'path', 'g', 'circle', 'rect', 'line', 'polyline', 'polygon', 'defs', 'use', 'symbol']);
7
+ const blank = (s) => s.replace(/[^\n]/g, ' ');
8
+
9
+ // FNV-1a, 32-bit, as base36: short stable keys for the cache.
10
+ export function hash(s) {
11
+ let h = 0x811c9dc5;
12
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); }
13
+ return (h >>> 0).toString(36);
14
+ }
15
+
16
+ const lineAt = (starts, i) => {
17
+ let lo = 0, hi = starts.length - 1;
18
+ while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= i) lo = mid; else hi = mid - 1; }
19
+ return lo + 1;
20
+ };
21
+
22
+ function classesOf(attrs) {
23
+ const out = [];
24
+ for (const m of attrs.matchAll(/\b(?:class|className)\s*=\s*(?:(["'])([^"']*)\1|\{\s*(["'`])([^"'`]*)\3\s*\}|\{([^}]*)\})/g)) {
25
+ const s = m[2] ?? m[4] ?? (m[5] ? [...m[5].matchAll(/(["'`])([^"'`]*)\1/g)].map((x) => x[2]).join(' ') : '');
26
+ for (const c of s.split(/\s+/)) if (c && !c.includes('${') && !/[{}<>]/.test(c)) out.push(c);
27
+ }
28
+ return [...new Set(out)].sort();
29
+ }
30
+
31
+ export function markupTrees(text, starts, path) {
32
+ const isJs = /\.(m?[jt]sx?|cjs)$/.test(path);
33
+ let src = text.replace(/<!--[\s\S]*?-->/g, blank);
34
+ if (!isJs) src = src.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, blank);
35
+ else src = src.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, blank);
36
+
37
+ const root = { tag: '#root', classes: [], children: [], line: 0 };
38
+ const stack = [root];
39
+ const tagRe = /<(\/?)([A-Za-z][\w.:-]*)/g;
40
+ let m;
41
+ while ((m = tagRe.exec(src))) {
42
+ if (isJs && !m[1]) {
43
+ // `<` after a value is a comparison or a generic, not JSX.
44
+ const before = src.slice(Math.max(0, m.index - 12), m.index);
45
+ if (/[\w)\].$]\s*$/.test(before) && !/\breturn\s*$/.test(before)) continue;
46
+ }
47
+ let i = m.index + m[0].length, depth = 0, quote = '';
48
+ for (; i < src.length; i++) {
49
+ const c = src[i];
50
+ if (quote) { if (c === quote) quote = ''; continue; }
51
+ if (c === '"' || c === "'" || (c === '`' && isJs)) quote = c;
52
+ else if (c === '{') depth++;
53
+ else if (c === '}') depth--;
54
+ else if (c === '>' && depth <= 0) break;
55
+ else if (c === '<' && depth <= 0 && !isJs) break;
56
+ }
57
+ const attrs = src.slice(m.index + m[0].length, i);
58
+ tagRe.lastIndex = i;
59
+ const tag = m[2].toLowerCase() === m[2] ? m[2] : m[2]; // keep case: <Card> is a component
60
+ const lower = tag.toLowerCase();
61
+ if (m[1]) {
62
+ for (let k = stack.length - 1; k > 0; k--) if (stack[k].tag === tag) { stack.length = k; break; }
63
+ continue;
64
+ }
65
+ if (SKIP.has(lower)) continue;
66
+ const node = { tag, classes: classesOf(attrs), children: [], line: lineAt(starts, m.index), parent: stack[stack.length - 1] };
67
+ node.parent.children.push(node);
68
+ if (!(attrs.trimEnd().endsWith('/') || VOID.has(lower))) stack.push(node);
69
+ }
70
+
71
+ const out = [];
72
+ const index = new Map();
73
+ (function visit(n) {
74
+ n.children.forEach(visit);
75
+ if (n === root) return;
76
+ const kids = n.children;
77
+ n.size = 1 + kids.reduce((a, k) => a + k.size, 0);
78
+ n.exact = `${n.tag}${n.classes.map((c) => '.' + c).join('')}(${kids.map((k) => k.exact).join(',')})`;
79
+ n.shape = `${n.tag}(${kids.map((k) => k.shape).join(',')})`;
80
+ })(root);
81
+ (function emit(n, parent) {
82
+ for (const k of n.children) {
83
+ let me = parent;
84
+ if (k.size >= 3) {
85
+ me = out.length;
86
+ index.set(k, me);
87
+ const label = `${k.tag}${k.classes.slice(0, 2).map((c) => '.' + c).join('')}`;
88
+ out.push({ e: hash(k.exact), s: hash(k.shape), size: k.size, line: k.line, label, kids: k.children.map((c) => c.tag + (c.classes[0] ? '.' + c.classes[0] : '')).slice(0, 4).join(', '), p: parent, cls: k.classes.length > 0 });
89
+ }
90
+ emit(k, me);
91
+ }
92
+ })(root, -1);
93
+ return out;
94
+ }