@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/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@rickycourtes/designrail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The design foundation for any web project: a token contract, layered parts every project builds on, and tooling to audit duplication, extract tokens, fix hardcoded values, gate drift and upgrade.",
5
+ "type": "module",
6
+ "bin": {
7
+ "designrail": "bin/designrail.js"
8
+ },
9
+ "exports": {
10
+ ".": "./src/index.js",
11
+ "./foundation.css": "./kit/foundation.css",
12
+ "./foundation.js": "./kit/foundation.js",
13
+ "./tokens.css": "./kit/tokens.css",
14
+ "./parts/*": "./kit/parts/*",
15
+ "./kit/*": "./kit/*",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "bin",
20
+ "src",
21
+ "kit",
22
+ "rules",
23
+ "schema.json",
24
+ "CHANGELOG.md",
25
+ "LICENSE"
26
+ ],
27
+ "scripts": {
28
+ "test": "mdtest",
29
+ "audit:fixture": "node bin/designrail.js audit fixtures/messy"
30
+ },
31
+ "engines": {
32
+ "node": ">=20"
33
+ },
34
+ "keywords": [
35
+ "design-system",
36
+ "design-tokens",
37
+ "css",
38
+ "lint",
39
+ "audit",
40
+ "components",
41
+ "refactor"
42
+ ],
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/rickycourtes/designrail.git"
46
+ },
47
+ "license": "MIT",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "devDependencies": {
52
+ "@rickycourtes/mdtest": "^0.1.0"
53
+ }
54
+ }
@@ -0,0 +1,70 @@
1
+ # Design rules
2
+
3
+ How this project builds its UI. Every bullet ends with a tag
4
+ `{id · checks}`: `check` means `designrail check` fails a change that breaks
5
+ it, `audit` means `designrail audit` reports it, `eye` means a person or an
6
+ agent has to look. Turn a rule off in `designrail.config.json` → `rules`.
7
+
8
+ ## Tokens
9
+
10
+ - **Read semantic tokens, never a literal.** Outside the token files no
11
+ colour, spacing, radius, font size, family or shadow is typed by hand: use
12
+ `var(--surface)`, `var(--space-12)`, `var(--radius-control)`. A value with
13
+ no token yet goes into the token files first. `designrail fix` rewrites the
14
+ ones that already have a token. {tokens.no-hardcoded · check: hardcoded}
15
+ - **Primitives are for token files.** `--gray-100` is what a colour is;
16
+ `--surface-raised` is what it is for. Parts read the second kind, so a theme
17
+ only re-points the semantic layer. The `--space-*`, `--radius-*` and
18
+ `--font-size-*` steps are the exception: a step says all a gap needs.
19
+ {tokens.semantic-only · check: primitive-direct}
20
+ - **Every var() resolves.** A token read anywhere is defined in a token file,
21
+ or listed in `runtimeTokens` when JS sets it. {tokens.resolves · check: unresolved}
22
+ - **A token nobody reads goes.** {tokens.used · check: unused}
23
+ - **One accent.** `--accent` is go, selected and primary; nothing else is
24
+ coloured except a state (`--danger`, `--success`, `--warning`). {tokens.one-accent · eye}
25
+ - **Spacing sits on the grid.** Every gap and pad is a step of the scale
26
+ (4px grid by default). {tokens.grid · audit}
27
+
28
+ ## Parts
29
+
30
+ - **Use the part we have; never draw it again.** Before anything new, find
31
+ the part in `ui/` (or `designrail specimens`) and use it as it is, variant
32
+ and all. A new look is a variant in the part's own file, never a restyle
33
+ where it is used. When no part fits, add the part, never a one-off.
34
+ {parts.reuse · audit: parts, markup}
35
+ - **Build on the foundation; restyle with knobs.** Parts come from
36
+ `@rickycourtes/designrail/foundation.css`. A project look for one is a variant class that
37
+ sets its knobs (`.btn.ink { --btn-bg: … }`), never `.btn { background: … }`
38
+ where it is used: that freezes the part against foundation updates. Placing
39
+ it (margin, grid, width) is fine. Eject a part only to own it for good.
40
+ {parts.knobs · check: part-restyle}
41
+ - **The theme sets the core.** `--surface`, `--text`, `--accent`,
42
+ `--text-on-accent` and `--font-ui` are the project's own; the rest derive.
43
+ {tokens.core · check: contract}
44
+ - **No copy-pasted rule blocks.** Two selectors with the same declarations
45
+ are one class. {parts.no-duplicates · check: duplicate-block}
46
+ - **A button is a choice, not a word on a surface.** It has a shape (fill,
47
+ rim or tint) and a label that names its result. `.btn.quiet` is the third
48
+ choice, beside a default or primary, never alone. {parts.buttons · eye}
49
+ - **An icon button is a 1:1 circle**, clear at rest, with an `aria-label`. {parts.icon-button · eye}
50
+
51
+ ## Layout
52
+
53
+ - **Siblings get a gap from their container**, never a margin of their own
54
+ (`.stack`, `.row`, `.actions`). {layout.gap · eye}
55
+ - **Space is proximity.** Inside a group is tighter than between groups,
56
+ which is tighter than the box's padding. {layout.proximity · eye}
57
+ - **A filled box pads every side, ends equal.** Text never sits closer to a
58
+ side than to the top. A label control's side pad is twice its top pad.
59
+ {layout.padding · eye}
60
+ - **Concentric corners.** A box inside a box: inner radius = outer radius −
61
+ padding. {layout.concentric · eye}
62
+ - **Touch targets are 44px** (`--control-h`), small buttons included (their
63
+ hit area). {layout.targets · eye}
64
+
65
+ ## Type and motion
66
+
67
+ - **Sentence case labels, no tracked-out capitals.** {type.case · check: tracked-caps}
68
+ - **Focus glow is for the keyboard only** (`:focus-visible`). {motion.focus · eye}
69
+ - **Motion uses the duration and easing tokens**, and stops under
70
+ `prefers-reduced-motion`. {motion.tokens · eye}
package/schema.json ADDED
@@ -0,0 +1,100 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "title": "designrail.config.json",
4
+ "type": "object",
5
+ "properties": {
6
+ "$schema": {
7
+ "type": "string"
8
+ },
9
+ "include": {
10
+ "type": "array",
11
+ "items": {
12
+ "type": "string"
13
+ },
14
+ "description": "Folders to scan, relative to the project root."
15
+ },
16
+ "exclude": {
17
+ "type": "array",
18
+ "items": {
19
+ "type": "string"
20
+ },
21
+ "description": "Globs left out (on top of .gitignore, .git, node_modules and .designrail)."
22
+ },
23
+ "tokens": {
24
+ "type": "array",
25
+ "items": {
26
+ "type": "string"
27
+ },
28
+ "description": "The files that define the design tokens."
29
+ },
30
+ "parts": {
31
+ "type": "string",
32
+ "description": "Where `designrail add` copies kit parts."
33
+ },
34
+ "grid": {
35
+ "type": "number",
36
+ "description": "The spacing grid in px."
37
+ },
38
+ "colorTolerance": {
39
+ "type": "number",
40
+ "description": "\u0394E OK under which two colours count as one."
41
+ },
42
+ "snap": {
43
+ "type": "number",
44
+ "description": "px within which `fix --snap` maps a length to a step."
45
+ },
46
+ "semanticOnly": {
47
+ "type": "boolean",
48
+ "description": "Outside token files, read semantic tokens only."
49
+ },
50
+ "allowPrimitives": {
51
+ "type": "array",
52
+ "items": {
53
+ "type": "string"
54
+ },
55
+ "description": "Primitive prefixes that may be read anywhere."
56
+ },
57
+ "runtimeTokens": {
58
+ "type": "array",
59
+ "items": {
60
+ "type": "string"
61
+ },
62
+ "description": "Custom properties set from JS (names or prefixes)."
63
+ },
64
+ "rules": {
65
+ "type": "object",
66
+ "additionalProperties": {
67
+ "enum": [
68
+ "error",
69
+ "warn",
70
+ "off"
71
+ ]
72
+ },
73
+ "properties": {
74
+ "hardcoded": {},
75
+ "unresolved": {},
76
+ "primitive-direct": {},
77
+ "duplicate-block": {},
78
+ "unused": {},
79
+ "tracked-caps": {},
80
+ "contract": {},
81
+ "part-restyle": {}
82
+ }
83
+ },
84
+ "maxFileBytes": {
85
+ "type": "number"
86
+ },
87
+ "foundation": {
88
+ "type": "string",
89
+ "description": "The foundation version the project is on (init writes it, upgrade --write moves it)."
90
+ },
91
+ "ejected": {
92
+ "type": "array",
93
+ "items": {
94
+ "type": "string"
95
+ },
96
+ "description": "Foundation parts the project owns a copy of."
97
+ }
98
+ },
99
+ "additionalProperties": false
100
+ }
package/src/audit.js ADDED
@@ -0,0 +1,217 @@
1
+ // Audit: how much design is hardcoded, how far values sprawl, which rule
2
+ // blocks and markup repeat, and which parts are drawn more than one way.
3
+ import { colorFacts, colorDistance } from './values.js';
4
+ import { declSet } from './model.js';
5
+
6
+ const STYLE_ORIGINS = new Set(['css', 'style', 'css-in-js']);
7
+
8
+ // Greedy clustering, most-used first: each value joins the first centre within `close`.
9
+ export function cluster(items, close) {
10
+ const sorted = [...items].sort((a, b) => b.count - a.count);
11
+ const groups = [];
12
+ for (const it of sorted) {
13
+ const g = groups.find((g) => close(g.centre, it));
14
+ if (g) { g.members.push(it); g.count += it.count; } else groups.push({ centre: it, members: [it], count: it.count });
15
+ }
16
+ return groups;
17
+ }
18
+
19
+ function tally(occ, pick) {
20
+ const m = new Map();
21
+ for (const o of occ) {
22
+ const k = pick(o);
23
+ if (k == null) continue;
24
+ if (!m.has(k)) m.set(k, { value: k, count: 0, files: new Set(), props: {}, at: [] });
25
+ const e = m.get(k);
26
+ e.count++;
27
+ e.files.add(o.file);
28
+ e.props[o.prop] = (e.props[o.prop] ?? 0) + 1;
29
+ if (e.at.length < 5) e.at.push(`${o.file}:${o.line}`);
30
+ }
31
+ return [...m.values()].sort((a, b) => b.count - a.count);
32
+ }
33
+
34
+ export function colorsOf(model) {
35
+ const items = tally(model.occ.filter((o) => o.lit.kind === 'color'), (o) => o.lit.hex);
36
+ for (const it of items) it.facts = colorFacts(it.value);
37
+ const groups = cluster(items, (a, b) => colorDistance(a.facts, b.facts) < model.cfg.colorTolerance);
38
+ return { items, groups, near: groups.filter((g) => g.members.length > 1) };
39
+ }
40
+
41
+ export function scaleOf(model, cat) {
42
+ const items = tally(model.occ.filter((o) => o.lit.kind === 'length' && o.lit.cat === cat), (o) => Math.abs(o.lit.px));
43
+ const grid = cat === 'font-size' ? 1 : model.cfg.grid;
44
+ const offGrid = items.filter((i) => i.value % grid !== 0 && !(cat === 'radius' && i.value >= 500));
45
+ const groups = cluster(items, (a, b) => Math.abs(a.value - b.value) <= model.cfg.snap);
46
+ return { items, offGrid, near: groups.filter((g) => g.members.length > 1), grid };
47
+ }
48
+
49
+ // Rules that only show, hide or move a part: app state, not a look to share.
50
+ const STATE = /^(display|visibility|opacity|pointer-events|transition(-[\w-]+)?|transform|z-index|cursor)$/;
51
+ const IGNORE_SEL = /^(@font-face|style@|css@|styled@|keyframes@|createGlobalStyle@|injectGlobal@)/;
52
+
53
+ export function duplicateBlocks(model, colors = colorsOf(model)) {
54
+ const colorMap = new Map();
55
+ for (const g of colors.groups) for (const m of g.members) colorMap.set(m.value, g.centre.value);
56
+ const rules = [];
57
+ for (const f of model.files) {
58
+ if (model.tokenFiles.has(f.path)) continue;
59
+ for (const r of f.rules) {
60
+ if (!STYLE_ORIGINS.has(r.origin) || !r.sel || IGNORE_SEL.test(r.sel)) continue;
61
+ if (r.decls.every((d) => STATE.test(d.prop) || d.prop.startsWith('--'))) continue;
62
+ const set = declSet(r, colorMap);
63
+ // Two declarations make a duplicate only outside state rules (:hover, :focus…).
64
+ if (set.length >= 3 || (set.length === 2 && !/:(?!:)/.test(r.sel.replace(/:(is|where|not|has)\(/g, '')))) rules.push({ file: f.path, sel: r.sel, line: r.line, media: r.media, set });
65
+ }
66
+ }
67
+ const exact = new Map();
68
+ for (const r of rules) {
69
+ const k = (r.media ?? '') + '|' + r.set.join(';');
70
+ if (!exact.has(k)) exact.set(k, []);
71
+ exact.get(k).push(r);
72
+ }
73
+ const groups = [...exact.values()].filter((g) => g.length > 1 && new Set(g.map((r) => r.file + r.sel)).size > 1)
74
+ .map((g) => ({ rules: g, decls: g[0].set })).sort((a, b) => b.rules.length * b.decls.length - a.rules.length * a.decls.length);
75
+ const inExact = new Set(groups.flatMap((g) => g.rules));
76
+
77
+ // Near duplicates: rules that share most declarations. An inverted index on
78
+ // each declaration (common ones like display:flex skipped) finds candidates.
79
+ const index = new Map();
80
+ rules.forEach((r, i) => r.set.forEach((d) => { if (!index.has(d)) index.set(d, []); index.get(d).push(i); }));
81
+ const near = [];
82
+ const rep = new Map();
83
+ for (const g of groups) for (const r of g.rules) rep.set(r, g.rules[0]);
84
+ const seenPair = new Set();
85
+ rules.forEach((r, i) => {
86
+ const counts = new Map();
87
+ for (const d of r.set) {
88
+ const list = index.get(d);
89
+ if (list.length > 40) continue;
90
+ for (const j of list) if (j > i) counts.set(j, (counts.get(j) ?? 0) + 1);
91
+ }
92
+ for (const [j, shared] of counts) {
93
+ const o = rules[j];
94
+ if (o.sel === r.sel) continue;
95
+ if (inExact.has(r) && inExact.has(o) && r.set.join() === o.set.join()) continue;
96
+ const jac = shared / (r.set.length + o.set.length - shared);
97
+ const pair = [rep.get(r) ?? r, rep.get(o) ?? o];
98
+ const pk = rules.indexOf(pair[0]) + ':' + rules.indexOf(pair[1]);
99
+ if (pair[0] === pair[1] || seenPair.has(pk)) continue;
100
+ if (shared >= 3 && r.set.length >= 3 && o.set.length >= 3 && jac >= 0.6 && seenPair.add(pk)) near.push({ a: r, b: o, shared, similarity: jac, diff: [...r.set.filter((d) => !o.set.includes(d)), ...o.set.filter((d) => !r.set.includes(d))] });
101
+ }
102
+ });
103
+ near.sort((x, y) => y.similarity * y.shared - x.similarity * x.shared);
104
+ return { groups, near, rules: rules.length, duplicated: inExact.size };
105
+ }
106
+
107
+ // Parts by role, found from class names: the same part drawn as different families.
108
+ export const ROLES = {
109
+ button: /^(btn|button|cta)$/,
110
+ field: /^(input|field|textfield|textbox|textarea|select)$/,
111
+ card: /^(card|panel|tile)$/,
112
+ pill: /^(badge|pill|chip|tag)$/,
113
+ dialog: /^(modal|dialog|sheet|drawer|lightbox)$/,
114
+ toast: /^(toast|snackbar|alert|notice|flash|banner)$/,
115
+ dropdown: /^(dropdown|menu|popover)$/,
116
+ };
117
+ const STRUCTURE = /^(group|groups|wrap|wrapper|container|list|row|rows|col|grid|icon|label|text|title|header|footer|body|content|inner|outer|area|bar|nav|item|items|close|overlay|backdrop|trigger|toggle|arrow|caret|link|image|img|actions|section|holder|box)$/;
118
+ const PAINT = /^(background|background-color|border|border-color|border-radius|padding|padding-inline|padding-block|box-shadow|color)$/;
119
+
120
+ export function redraws(model) {
121
+ const roles = {};
122
+ for (const f of model.files) {
123
+ if (model.tokenFiles.has(f.path)) continue;
124
+ for (const r of f.rules) {
125
+ if (!STYLE_ORIGINS.has(r.origin) || !r.sel) continue;
126
+ if (!r.decls.some((d) => PAINT.test(d.prop))) continue;
127
+ for (const part of r.sel.split(',')) {
128
+ const last = part.trim().split(/[\s>+~]+/).pop() ?? '';
129
+ const classes = [...last.matchAll(/\.([\w-]+)/g)].map((m) => m[1]).filter((c) => !c.includes('__'));
130
+ const el = /^(button|input|select|textarea|dialog)\b/.exec(last)?.[1];
131
+ const found = new Map();
132
+ for (const c of classes) {
133
+ const words = c.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_]+/).filter(Boolean);
134
+ const k = words.findIndex((w) => Object.values(ROLES).some((re) => re.test(w)));
135
+ if (k < 0 || words.slice(k + 1).some((w) => STRUCTURE.test(w))) continue;
136
+ const role = Object.keys(ROLES).find((n) => ROLES[n].test(words[k]));
137
+ const family = c.split('--')[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_]+/).slice(0, k + 1).join('-');
138
+ found.set(role, { family, cls: c });
139
+ }
140
+ if (el && !classes.length) found.set({ input: 'field', select: 'field', textarea: 'field' }[el] ?? el, { family: `<${el}>`, cls: el });
141
+ for (const [role, { family, cls }] of found) {
142
+ roles[role] ??= new Map();
143
+ if (!roles[role].has(family)) roles[role].set(family, { family, classes: new Set(), at: [], files: new Set() });
144
+ const fam = roles[role].get(family);
145
+ fam.classes.add(cls);
146
+ fam.files.add(f.path);
147
+ if (fam.at.length < 4) fam.at.push(`${f.path}:${r.line}`);
148
+ }
149
+ }
150
+ }
151
+ }
152
+ return Object.entries(roles).map(([role, m]) => ({ role, families: [...m.values()].sort((a, b) => b.classes.size - a.classes.size) }))
153
+ .filter((r) => r.families.length > 1 || r.families.some((f) => f.files.size > 2))
154
+ .sort((a, b) => b.families.length - a.families.length);
155
+ }
156
+
157
+ export function markupDupes(model) {
158
+ const occ = [];
159
+ for (const f of model.files) f.trees.forEach((t, i) => occ.push({ ...t, file: f.path, key: `${f.path}#${i}`, pkey: t.p >= 0 ? `${f.path}#${t.p}` : null }));
160
+ const by = (k, min) => {
161
+ const m = new Map();
162
+ for (const o of occ) if (o.size >= min) { if (!m.has(o[k])) m.set(o[k], []); m.get(o[k]).push(o); }
163
+ return [...m.values()].filter((g) => g.length > 1);
164
+ };
165
+ // Copies that are all siblings are a list (render it from data), not a component drawn twice.
166
+ const exact = by('e', 4).filter((g) => g.some((o) => o.cls) && new Set(g.map((o) => o.pkey ?? o.file)).size > 1);
167
+ const shape = by('s', 6).filter((g) => new Set(g.map((o) => o.e)).size > 1 && new Set(g.map((o) => o.file)).size > 1);
168
+ const maximal = (groups) => {
169
+ const where = new Map();
170
+ groups.forEach((g, i) => g.forEach((o) => where.set(o.key, i)));
171
+ return groups.filter((g) => {
172
+ const ps = g.map((o) => o.pkey && where.get(o.pkey));
173
+ return !(ps.every((p) => p != null && p === ps[0]) && groups[ps[0]].length === g.length);
174
+ });
175
+ };
176
+ const fmt = (g) => ({ size: g[0].size, count: g.length, files: new Set(g.map((o) => o.file)).size, label: g[0].label, kids: g[0].kids, at: g.slice(0, 6).map((o) => `${o.file}:${o.line}`) });
177
+ const score = (g) => g.size * g.count;
178
+ return {
179
+ exact: maximal(exact).map(fmt).sort((a, b) => score(b) - score(a)),
180
+ shape: maximal(shape).map(fmt).sort((a, b) => score(b) - score(a)),
181
+ };
182
+ }
183
+
184
+ export function audit(model) {
185
+ const colors = colorsOf(model);
186
+ const scales = Object.fromEntries(['space', 'radius', 'font-size'].map((c) => [c, scaleOf(model, c)]));
187
+ const kinds = (k) => tally(model.occ.filter((o) => o.lit.kind === k), (o) => o.lit.norm ?? o.lit.n ?? o.lit.ms ?? o.lit.raw);
188
+ const fonts = kinds('font');
189
+ const blocks = duplicateBlocks(model, colors);
190
+ const parts = redraws(model);
191
+ const markup = markupDupes(model);
192
+
193
+ const tokenRatio = model.slots ? model.tokenized / model.slots : 1;
194
+ const colorScore = colors.items.length ? 1 - Math.min(1, colors.near.reduce((a, g) => a + g.members.length - 1, 0) / colors.items.length + Math.max(0, colors.groups.length - 24) / 48) : 1;
195
+ // Off-grid uses against every spacing and radius declaration, tokens included.
196
+ const spaceSlots = (model.slotsBy.space ?? 0) + (model.slotsBy.radius ?? 0);
197
+ const offUses = [...scales.space.offGrid, ...scales.radius.offGrid].reduce((n, i) => n + i.count, 0);
198
+ const gridScore = spaceSlots ? Math.max(0, 1 - (offUses / spaceSlots) * 2) : 1;
199
+ const dupScore = blocks.rules ? 1 - Math.min(1, (blocks.duplicated + blocks.near.length) / blocks.rules * 2) : 1;
200
+ const extraFamilies = parts.reduce((a, r) => a + r.families.length - 1, 0);
201
+ const reuseScore = 1 - Math.min(1, extraFamilies / 24 + markup.exact.length / 80);
202
+ const breakdown = {
203
+ tokens: { score: Math.round(tokenRatio * 40), of: 40, note: `${model.tokenized}/${model.slots} design values come from tokens` },
204
+ colors: { score: Math.round(colorScore * 15), of: 15, note: `${colors.items.length} colours, ${colors.near.length} near-identical groups` },
205
+ scale: { score: Math.round(gridScore * 15), of: 15, note: `${offUses} of ${spaceSlots} spacing/radius values off the ${model.cfg.grid}px grid` },
206
+ duplication: { score: Math.round(dupScore * 15), of: 15, note: `${blocks.duplicated} rules in duplicate groups, ${blocks.near.length} near-duplicate pairs` },
207
+ reuse: { score: Math.round(reuseScore * 15), of: 15, note: `${extraFamilies} extra part families, ${markup.exact.length} repeated markup blocks` },
208
+ };
209
+ const score = Object.values(breakdown).reduce((a, b) => a + b.score, 0);
210
+ return {
211
+ score, breakdown, colors, scales, fonts,
212
+ weights: kinds('weight'), shadows: kinds('shadow'), durations: kinds('time'), z: kinds('z'),
213
+ blocks, parts, markup,
214
+ hardcoded: model.slots - model.tokenized,
215
+ tokenFiles: [...model.tokenFiles],
216
+ };
217
+ }
package/src/check.js ADDED
@@ -0,0 +1,141 @@
1
+ // Check: the drift gate. Every rule's hits on the project; with --staged or
2
+ // --base REF, only the hits the change adds (git is the baseline, there is no
3
+ // baseline file), so a messy codebase can adopt it today and only get cleaner.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { buildModel, slotOf } from './model.js';
6
+ import { analyze, ALL_EXT } from './sources.js';
7
+ import { duplicateBlocks } from './audit.js';
8
+ import { tokenIndex, primitivesOf } from './tokens.js';
9
+ import { matcher } from './fix.js';
10
+ import { CONTRACT } from './contract.js';
11
+ import { PARTS } from './kit.js';
12
+ import { splitTop } from './css.js';
13
+
14
+ // The tokens that make a project look like itself; the rest derive from them.
15
+ const CORE = ['--surface', '--text', '--accent', '--text-on-accent', '--font-ui'];
16
+ // Where a part is used may place it, never restyle it.
17
+ const LAYOUT = /^(margin(-[\w-]+)?|grid(-[\w-]+)?|flex(-[\w-]+)?|order|align-self|justify-self|place-self|(min-|max-)?(width|height|inline-size|block-size)|position|inset(-[\w-]+)?|top|right|bottom|left|z-index|display|visibility|opacity|pointer-events|transition(-[\w-]+)?|transform|animation(-[\w-]+)?|view-transition-name|contain)$/;
18
+ const HELPERS = new Set(['stack', 'row', 'tight', 'loose', 'muted', 'small', 'dot', 'inset', 'end', 'actions']);
19
+
20
+ // Classes the foundation's parts own: the first class each selector names
21
+ // (.btn in `.btn.primary`, .field in `.field > .label`).
22
+ export function foundationClasses(foundation) {
23
+ const out = new Set();
24
+ for (const f of foundation.files) {
25
+ if (!/parts\/(?!base)/.test(f.path)) continue;
26
+ for (const r of f.rules) for (const part of splitTop(r.sel ?? '')) {
27
+ const c = /\.([\w-]+)/.exec(part.split(/[\s>+~]+/)[0] ?? '')?.[1];
28
+ if (c && !HELPERS.has(c)) out.add(c);
29
+ }
30
+ }
31
+ return out;
32
+ }
33
+
34
+ const SLOTS = new Set(['color', 'space', 'radius', 'font-size', 'font', 'shadow']);
35
+
36
+ export function hits(model) {
37
+ const rules = model.cfg.rules;
38
+ const out = [];
39
+ const on = (r) => rules[r] && rules[r] !== 'off';
40
+ const hit = (rule, file, line, msg, key) => out.push({ rule, level: rules[rule], file, line, msg, key: `${rule}|${file}|${key}` });
41
+
42
+ if (on('hardcoded')) {
43
+ const { pick } = matcher(model);
44
+ for (const o of model.occ) {
45
+ const slot = slotOf(o.lit);
46
+ if (!SLOTS.has(slot) || (o.prop.startsWith('--') && slot !== 'color')) continue;
47
+ const m = pick(o);
48
+ hit('hardcoded', o.file, o.line, `${o.prop}: ${o.lit.raw}${m ? ` → var(${m.token.name})` : ' (no token holds it)'}`, `${o.sel}|${o.prop}|${o.lit.raw}`);
49
+ }
50
+ }
51
+ if (on('unresolved')) {
52
+ for (const [name, list] of model.uses) {
53
+ if (model.defs.has(name) || model.runtime.has(name) || model.cfg.runtimeTokens.some((p) => name.startsWith(p))) continue;
54
+ for (const u of list) if (!u.js && !u.external && !u.fallback) hit('unresolved', u.file, u.line, `var(${name}) is defined nowhere`, name);
55
+ }
56
+ }
57
+ const tokens = tokenIndex(model);
58
+ if (on('primitive-direct') && model.cfg.semanticOnly) {
59
+ const prims = primitivesOf(tokens);
60
+ for (const [name, list] of model.uses) {
61
+ if (!prims.has(name) || model.cfg.allowPrimitives.some((p) => name.startsWith(p))) continue;
62
+ for (const u of list) if (!u.inTokens && !u.js && !u.external) hit('primitive-direct', u.file, u.line, `${name} is a primitive; read the semantic token built on it`, name);
63
+ }
64
+ }
65
+ if (on('unused')) {
66
+ const api = new Set(CONTRACT.map((c) => c.name));
67
+ for (const t of tokens) if (!t.external && !api.has(t.name) && !model.uses.has(t.name) && !model.runtime.has(t.name)) hit('unused', t.file, t.line, `${t.name} is never read`, t.name);
68
+ }
69
+ if (on('duplicate-block')) {
70
+ for (const g of duplicateBlocks(model).groups) {
71
+ const [first, ...rest] = g.rules;
72
+ for (const r of rest) hit('duplicate-block', r.file, r.line, `${r.sel} repeats ${first.sel} (${first.file}:${first.line}), ${g.decls.length} declarations`, `${r.sel}|${g.decls.join(';')}`);
73
+ }
74
+ }
75
+ if (on('contract') && model.foundation) {
76
+ // The values that make a project look like itself. Left unset, it shows the foundation's.
77
+ for (const name of CORE) {
78
+ const own = (model.defs.get(name) ?? []).some((d) => !d.external);
79
+ if (!own) hit('contract', model.cfg.tokens[model.cfg.tokens.length - 1], 1, `${name} is the foundation's default; set it in your theme`, name);
80
+ }
81
+ }
82
+ if (on('part-restyle') && model.foundation) {
83
+ const parts = foundationClasses(model.foundation);
84
+ const own = new Set((model.cfg.ejected ?? []).flatMap((p) => PARTS[p] ?? []).map((f) => `${model.cfg.parts}/${f}`));
85
+ for (const f of model.files) {
86
+ if (model.tokenFiles.has(f.path) || own.has(f.path)) continue;
87
+ for (const r of f.rules) {
88
+ if (!['css', 'style', 'css-in-js'].includes(r.origin) || !r.sel) continue;
89
+ const looks = r.decls.filter((d) => !d.prop.startsWith('--') && !LAYOUT.test(d.prop));
90
+ if (!looks.length) continue;
91
+ for (const part of splitTop(r.sel)) {
92
+ const last = part.trim().split(/[\s>+~]+/).pop() ?? '';
93
+ const classes = [...last.matchAll(/\.([\w-]+)/g)].map((m) => m[1]);
94
+ const hitPart = classes.find((c) => parts.has(c));
95
+ if (!hitPart) continue;
96
+ hit('part-restyle', f.path, r.line, `${part.trim()} restyles .${hitPart} (${looks.map((d) => d.prop).slice(0, 3).join(', ')}); set its knobs (--${hitPart.split('-')[0]}-…) on a variant instead, so foundation updates still reach it`, `${part.trim()}|${looks.map((d) => d.prop).join(',')}`);
97
+ break;
98
+ }
99
+ }
100
+ }
101
+ }
102
+ if (on('tracked-caps')) {
103
+ for (const f of model.files) for (const r of f.rules) {
104
+ const up = r.decls.some((d) => d.prop === 'text-transform' && /uppercase/.test(d.value));
105
+ const ls = r.decls.find((d) => d.prop === 'letter-spacing' && (parseFloat(d.value) > 0.04 || /[1-9][\d.]*px/.test(d.value)));
106
+ if (up && ls) hit('tracked-caps', f.path, r.line, `${r.sel}: tracked-out capitals; use sentence case`, r.sel);
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+
112
+ function git(root, args) {
113
+ const r = spawnSync('git', args, { cwd: root, maxBuffer: 1 << 28, encoding: 'utf8' });
114
+ if (r.status) throw new Error(`git ${args.join(' ')}: ${r.stderr.trim()}`);
115
+ return r.stdout;
116
+ }
117
+
118
+ // The project as it was at `base` ('HEAD' or a ref), and as it is now (the
119
+ // index with `staged`, else the working tree). Unchanged files are shared.
120
+ export function baselines(project, { base = 'HEAD', staged = false }) {
121
+ const { root } = project;
122
+ const changed = new Set(git(root, staged ? ['diff', '--cached', '--name-only', base] : ['diff', '--name-only', base]).split('\n').filter((f) => ALL_EXT.test(f)));
123
+ if (!staged) for (const f of git(root, ['ls-files', '--others', '--exclude-standard']).split('\n')) if (ALL_EXT.test(f)) changed.add(f);
124
+ const show = (spec) => { const r = spawnSync('git', ['show', spec], { cwd: root, maxBuffer: 1 << 28, encoding: 'utf8' }); return r.status ? null : r.stdout; };
125
+ const keep = project.files.filter((f) => !changed.has(f.path));
126
+ const then = [...keep], now = staged ? [...keep] : [...project.files];
127
+ for (const rel of changed) {
128
+ const was = show(`${base}:${rel}`);
129
+ if (was != null) then.push({ path: rel, ...analyze(rel, was) });
130
+ if (staged) { const is = show(`:${rel}`); if (is != null) now.push({ path: rel, ...analyze(rel, is) }); }
131
+ }
132
+ return { then: buildModel({ ...project, files: then }), now: buildModel({ ...project, files: now }), changed: [...changed] };
133
+ }
134
+
135
+ // Hits in `now` beyond what `then` had: a count per key, so one more use of a
136
+ // hardcoded value is new even where the same value already drifted.
137
+ export function added(thenHits, nowHits) {
138
+ const seen = new Map();
139
+ for (const h of thenHits) seen.set(h.key, (seen.get(h.key) ?? 0) + 1);
140
+ return nowHits.filter((h) => { const n = seen.get(h.key) ?? 0; if (n > 0) { seen.set(h.key, n - 1); return false; } return true; });
141
+ }