@getchomp/mcp 0.0.0-stage → 0.2.43
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/LICENSE +21 -0
- package/README.md +15 -2
- package/dist/conventionsReference.d.ts +84 -0
- package/dist/conventionsReference.js +313 -0
- package/dist/designSystem/astScanner.d.ts +153 -0
- package/dist/designSystem/astScanner.js +2014 -0
- package/dist/designSystem/baseline.d.ts +65 -0
- package/dist/designSystem/baseline.js +136 -0
- package/dist/designSystem/color.d.ts +35 -0
- package/dist/designSystem/color.js +265 -0
- package/dist/designSystem/config.d.ts +183 -0
- package/dist/designSystem/config.js +469 -0
- package/dist/designSystem/contrast.d.ts +55 -0
- package/dist/designSystem/contrast.js +377 -0
- package/dist/designSystem/cssParser.d.ts +63 -0
- package/dist/designSystem/cssParser.js +469 -0
- package/dist/designSystem/merges.d.ts +57 -0
- package/dist/designSystem/merges.js +94 -0
- package/dist/designSystem/preprocessors.d.ts +46 -0
- package/dist/designSystem/preprocessors.js +1108 -0
- package/dist/designSystem/presentation.d.ts +45 -0
- package/dist/designSystem/presentation.js +796 -0
- package/dist/designSystem/styleVectors.d.ts +27 -0
- package/dist/designSystem/styleVectors.js +484 -0
- package/dist/designSystem/tokens.d.ts +39 -0
- package/dist/designSystem/tokens.js +409 -0
- package/dist/designSystem/topology.d.ts +64 -0
- package/dist/designSystem/topology.js +254 -0
- package/dist/designSystem/types.d.ts +857 -0
- package/dist/designSystem/types.js +113 -0
- package/dist/designSystem/typography.d.ts +25 -0
- package/dist/designSystem/typography.js +244 -0
- package/dist/designSystem/uiShapes.d.ts +74 -0
- package/dist/designSystem/uiShapes.js +285 -0
- package/dist/designSystem/valueClusters.d.ts +76 -0
- package/dist/designSystem/valueClusters.js +281 -0
- package/dist/designSystemPlugin.d.ts +321 -0
- package/dist/designSystemPlugin.js +4730 -0
- package/dist/enrichNodesPlugin.d.ts +160 -0
- package/dist/enrichNodesPlugin.js +957 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1298 -0
- package/dist/intelligence.d.ts +502 -0
- package/dist/intelligence.js +3058 -0
- package/dist/pluginRunner.d.ts +364 -0
- package/dist/pluginRunner.js +1096 -0
- package/dist/plugins/design-system/index.d.ts +14 -0
- package/dist/plugins/design-system/index.js +241 -0
- package/dist/plugins/enrich-nodes/index.d.ts +388 -0
- package/dist/plugins/enrich-nodes/index.js +697 -0
- package/dist/plugins/index.d.ts +15 -0
- package/dist/plugins/index.js +20 -0
- package/dist/plugins/local-shims/index.d.ts +121 -0
- package/dist/plugins/local-shims/index.js +237 -0
- package/dist/shimsPlugin.d.ts +134 -0
- package/dist/shimsPlugin.js +1392 -0
- package/package.json +39 -3
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/mcp/src/designSystem/uiShapes.ts
|
|
3
|
+
*
|
|
4
|
+
* Authorized atom ownership checks, sibling atom overlap detection, and
|
|
5
|
+
* stateful UI shape detection (`Tabs`, `SegmentedControl`, `BadgePill`)
|
|
6
|
+
* with anti-double-counting absorption of inner raw `<button>` hits.
|
|
7
|
+
*/
|
|
8
|
+
import { extractStyleVectorFromClassesAndInline, extractStyleVectorFromCssRule, } from "./styleVectors.js";
|
|
9
|
+
function normalizeName(raw) {
|
|
10
|
+
return raw.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
|
|
11
|
+
}
|
|
12
|
+
const ATOM_TARGET_ALIASES = {
|
|
13
|
+
button: ["button", "btn", "iconbutton", "cta"],
|
|
14
|
+
badge: ["badge", "pill", "chip", "tag", "statuspill"],
|
|
15
|
+
input: ["input", "textfield", "textinput", "searchinput"],
|
|
16
|
+
select: ["select", "dropdown", "combobox"],
|
|
17
|
+
textarea: ["textarea", "multilineinput"],
|
|
18
|
+
checkbox: ["checkbox", "check"],
|
|
19
|
+
switch: ["switch", "toggle"],
|
|
20
|
+
tabs: ["tabs", "tablist", "tabstrip"],
|
|
21
|
+
segmentedcontrol: ["segmentedcontrol", "segmented", "togglegroup", "switcher"],
|
|
22
|
+
modal: ["modal", "dialog", "sheet", "popup"],
|
|
23
|
+
link: ["link", "anchor", "navlink"],
|
|
24
|
+
};
|
|
25
|
+
export function doesComponentNameMatchAtom(componentName, atomTarget) {
|
|
26
|
+
const normComp = normalizeName(componentName);
|
|
27
|
+
const normAtom = normalizeName(atomTarget);
|
|
28
|
+
if (!normComp || !normAtom)
|
|
29
|
+
return false;
|
|
30
|
+
if (normComp === normAtom || normComp.endsWith(normAtom))
|
|
31
|
+
return true;
|
|
32
|
+
const aliases = ATOM_TARGET_ALIASES[normAtom] ?? [normAtom];
|
|
33
|
+
return aliases.some((alias) => normComp === alias || normComp.endsWith(alias) || normComp.startsWith(`${alias}primitive`));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Determines whether a component is an **authorized owner** of a raw DOM primitive (`atomTarget`).
|
|
37
|
+
* Placing a multi-element wrapper (like a labeled trigger slot, stepper, or drawer row) inside
|
|
38
|
+
* an `atoms/` file no longer blanket-exempts it from atom reuse audits.
|
|
39
|
+
*/
|
|
40
|
+
export function isAuthorizedAtomOwner(params) {
|
|
41
|
+
if (params.atomicTier !== "ATOM")
|
|
42
|
+
return false;
|
|
43
|
+
if (params.jsxCustomComponentCount > 0)
|
|
44
|
+
return false;
|
|
45
|
+
const targetLower = params.atomTarget.toLowerCase();
|
|
46
|
+
// Pure compact leaf matching its own semantic atom role is authorized
|
|
47
|
+
if (doesComponentNameMatchAtom(params.componentName, params.atomTarget)) {
|
|
48
|
+
const canonical = params.canonicalAtomsByTarget.get(targetLower);
|
|
49
|
+
// If another canonical atom owns this role (e.g. `Badge` vs `DiffBadge`), only the canonical one is authorized
|
|
50
|
+
if (canonical && canonical.toLowerCase() !== params.componentName.toLowerCase()) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Picks the canonical shared component name for each `atomTarget` across the repo
|
|
59
|
+
* (prefers exact name match, then `ATOM` tier with highest in-degree / lowest DOM bloat).
|
|
60
|
+
*/
|
|
61
|
+
export function resolveCanonicalAtomsByTarget(profiles, atomCatalog) {
|
|
62
|
+
const canonical = new Map();
|
|
63
|
+
const targetNames = [
|
|
64
|
+
...new Set([...atomCatalog.map((d) => d.name), "Badge", "Tabs", "SegmentedControl"]),
|
|
65
|
+
];
|
|
66
|
+
for (const p of profiles) {
|
|
67
|
+
if (p.atomicTier !== "ATOM" && p.atomicTier !== "MOLECULE")
|
|
68
|
+
continue;
|
|
69
|
+
for (const targetName of targetNames) {
|
|
70
|
+
if (!doesComponentNameMatchAtom(p.label, targetName))
|
|
71
|
+
continue;
|
|
72
|
+
const exactMatch = normalizeName(p.label) === normalizeName(targetName) ? 100 : 0;
|
|
73
|
+
const atomTierBonus = p.atomicTier === "ATOM" ? 50 : 0;
|
|
74
|
+
const usageBonus = Math.min(30, p.usageCount * 2);
|
|
75
|
+
const compactBonus = p.jsxDomElementCount <= 4 ? 10 : 0;
|
|
76
|
+
const score = exactMatch + atomTierBonus + usageBonus + compactBonus;
|
|
77
|
+
const targetKey = targetName.toLowerCase();
|
|
78
|
+
const prev = canonical.get(targetKey);
|
|
79
|
+
if (!prev || score > prev.score) {
|
|
80
|
+
canonical.set(targetKey, {
|
|
81
|
+
name: p.label,
|
|
82
|
+
label: p.label,
|
|
83
|
+
entityId: p.entityId,
|
|
84
|
+
filePath: p.filePath,
|
|
85
|
+
score,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const out = new Map();
|
|
91
|
+
for (const [k, v] of canonical.entries()) {
|
|
92
|
+
out.set(k, { name: v.name, label: v.label, entityId: v.entityId, filePath: v.filePath });
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
function parseVectorPx(raw) {
|
|
97
|
+
if (!raw)
|
|
98
|
+
return undefined;
|
|
99
|
+
const m = /^(-?\d*\.?\d+)px$/i.exec(raw.trim());
|
|
100
|
+
return m ? Number(m[1]) : undefined;
|
|
101
|
+
}
|
|
102
|
+
function isPillStyleVector(vec, classes) {
|
|
103
|
+
if (classes.includes("rounded-full"))
|
|
104
|
+
return true;
|
|
105
|
+
if (!vec)
|
|
106
|
+
return false;
|
|
107
|
+
const radiusPx = parseVectorPx(vec.borderRadius);
|
|
108
|
+
if (radiusPx !== undefined && radiusPx >= 999)
|
|
109
|
+
return true;
|
|
110
|
+
const heightPx = parseVectorPx(vec.height) ?? parseVectorPx(vec.minHeight);
|
|
111
|
+
const fontSizePx = parseVectorPx(vec.fontSize);
|
|
112
|
+
const hasChrome = Boolean(vec.background || vec.borderWidth || vec.borderColor);
|
|
113
|
+
if (!hasChrome)
|
|
114
|
+
return false;
|
|
115
|
+
if (heightPx !== undefined && heightPx <= 22 && (fontSizePx === undefined || fontSizePx <= 11.5)) {
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
if (fontSizePx !== undefined && fontSizePx <= 10.5 && radiusPx !== undefined && radiusPx >= 3) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
export function analyzeUiShapesAndSiblingOverlaps(params) {
|
|
124
|
+
const suppressedRawDomIndicesByEntity = new Map();
|
|
125
|
+
const unextractedShapesByEntity = new Map();
|
|
126
|
+
const siblingAtomOverlapsByEntity = new Map();
|
|
127
|
+
const allUnextractedShapes = [];
|
|
128
|
+
const allSiblingAtomOverlaps = [];
|
|
129
|
+
// 1. Pre-count shapeKind occurrences across components
|
|
130
|
+
const shapeComponentSets = {
|
|
131
|
+
Tabs: new Set(),
|
|
132
|
+
SegmentedControl: new Set(),
|
|
133
|
+
BadgePill: new Set(),
|
|
134
|
+
};
|
|
135
|
+
for (const comp of params.components) {
|
|
136
|
+
for (const cand of comp.bucket.uiShapeCandidates) {
|
|
137
|
+
if (cand.shapeKind === "BadgePill" && doesComponentNameMatchAtom(comp.name, "Badge")) {
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (cand.shapeKind === "Tabs" && doesComponentNameMatchAtom(comp.name, "Tabs")) {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (cand.shapeKind === "SegmentedControl" &&
|
|
144
|
+
doesComponentNameMatchAtom(comp.name, "SegmentedControl")) {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
shapeComponentSets[cand.shapeKind].add(comp.entityId);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const resolveCandidateStyleVector = (classes, inlineStyle) => {
|
|
151
|
+
const merged = {};
|
|
152
|
+
for (const c of classes) {
|
|
153
|
+
for (const r of params.cssRulesByClass.get(c) ?? []) {
|
|
154
|
+
Object.assign(merged, extractStyleVectorFromCssRule(r, params.tokenMaps));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
Object.assign(merged, extractStyleVectorFromClassesAndInline(classes, inlineStyle, params.tokenMaps));
|
|
158
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
159
|
+
};
|
|
160
|
+
for (const comp of params.components) {
|
|
161
|
+
const b = comp.bucket;
|
|
162
|
+
// 2. Sibling Atom Overlap detection:
|
|
163
|
+
// (a) ATOM/MOLECULE named like an alias (e.g. `DiffBadge`) without rendering the canonical atom (`Badge`)
|
|
164
|
+
for (const [targetLower, canonical] of params.canonicalAtomsByTarget.entries()) {
|
|
165
|
+
if (canonical.entityId === comp.entityId)
|
|
166
|
+
continue;
|
|
167
|
+
if (b.renderedComponents.has(canonical.name) || b.renderedComponents.has(canonical.label)) {
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const isBadgeLikeAtom = targetLower === "badge" &&
|
|
171
|
+
comp.atomicTier === "ATOM" &&
|
|
172
|
+
doesComponentNameMatchAtom(comp.name, "Badge");
|
|
173
|
+
const isButtonLikeAtom = targetLower === "button" &&
|
|
174
|
+
comp.atomicTier === "ATOM" &&
|
|
175
|
+
b.rawDomPrimitives.some((p) => p.atomicTarget.toLowerCase() === "button") &&
|
|
176
|
+
!doesComponentNameMatchAtom(comp.name, "Button");
|
|
177
|
+
if (isBadgeLikeAtom || isButtonLikeAtom) {
|
|
178
|
+
const finding = {
|
|
179
|
+
componentName: comp.label,
|
|
180
|
+
entityId: comp.entityId,
|
|
181
|
+
atomTarget: targetLower === "badge" ? "Badge" : "Button",
|
|
182
|
+
tagOrRole: isBadgeLikeAtom ? "badge-pill" : "<button>",
|
|
183
|
+
existingSharedComponent: canonical.label,
|
|
184
|
+
filePath: comp.filePath,
|
|
185
|
+
lineNumber: comp.lineNumber ?? b.lineNumber,
|
|
186
|
+
snippet: b.rootElement?.snippet ?? "",
|
|
187
|
+
reason: isBadgeLikeAtom
|
|
188
|
+
? `'${comp.label}' implements an independent pill/badge ATOM while canonical '${canonical.label}' exists; parameterize and compose '${canonical.label}' instead.`
|
|
189
|
+
: `'${comp.label}' renders a raw <button> ATOM without composing canonical '${canonical.label}'.`,
|
|
190
|
+
};
|
|
191
|
+
let list = siblingAtomOverlapsByEntity.get(comp.entityId);
|
|
192
|
+
if (!list) {
|
|
193
|
+
list = [];
|
|
194
|
+
siblingAtomOverlapsByEntity.set(comp.entityId, list);
|
|
195
|
+
}
|
|
196
|
+
list.push(finding);
|
|
197
|
+
allSiblingAtomOverlaps.push(finding);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// 3. Process unextracted UI shapes & absorb inner raw buttons to prevent double counting
|
|
201
|
+
const suppressedSet = new Set();
|
|
202
|
+
const offsetToIndices = new Map();
|
|
203
|
+
for (let i = 0; i < b.rawDomOffsets.length; i++) {
|
|
204
|
+
const off = b.rawDomOffsets[i];
|
|
205
|
+
let arr = offsetToIndices.get(off);
|
|
206
|
+
if (!arr) {
|
|
207
|
+
arr = [];
|
|
208
|
+
offsetToIndices.set(off, arr);
|
|
209
|
+
}
|
|
210
|
+
arr.push(i);
|
|
211
|
+
}
|
|
212
|
+
const compShapes = [];
|
|
213
|
+
for (const cand of b.uiShapeCandidates) {
|
|
214
|
+
if (cand.shapeKind === "Tabs" && doesComponentNameMatchAtom(comp.name, "Tabs"))
|
|
215
|
+
continue;
|
|
216
|
+
if (cand.shapeKind === "SegmentedControl" &&
|
|
217
|
+
doesComponentNameMatchAtom(comp.name, "SegmentedControl")) {
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (cand.shapeKind === "BadgePill" && doesComponentNameMatchAtom(comp.name, "Badge")) {
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const targetAtomKey = cand.shapeKind === "Tabs"
|
|
224
|
+
? "tabs"
|
|
225
|
+
: cand.shapeKind === "SegmentedControl"
|
|
226
|
+
? "segmentedcontrol"
|
|
227
|
+
: "badge";
|
|
228
|
+
const existingCanonical = params.canonicalAtomsByTarget.get(targetAtomKey);
|
|
229
|
+
const sharedAtomExists = Boolean(existingCanonical && existingCanonical.entityId !== comp.entityId);
|
|
230
|
+
const styleVector = resolveCandidateStyleVector(cand.itemClasses.length > 0 ? cand.itemClasses : cand.containerClasses, cand.inlineStyle);
|
|
231
|
+
if (cand.shapeKind === "BadgePill" &&
|
|
232
|
+
!isPillStyleVector(styleVector, cand.containerClasses)) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
// Single inline pill span without `<Badge>` and only 1 site isn't a hard bypass warning
|
|
236
|
+
if (cand.shapeKind === "BadgePill" &&
|
|
237
|
+
!sharedAtomExists &&
|
|
238
|
+
shapeComponentSets.BadgePill.size < 2 &&
|
|
239
|
+
!cand.containerClasses.includes("rounded-full")) {
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
// Suppress inner raw button hits for Tabs / SegmentedControl into this single shape finding
|
|
243
|
+
for (const btnOff of cand.absorbedButtonStarts) {
|
|
244
|
+
for (const idx of offsetToIndices.get(btnOff) ?? []) {
|
|
245
|
+
suppressedSet.add(idx);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const occCount = shapeComponentSets[cand.shapeKind].size;
|
|
249
|
+
const tone = sharedAtomExists || occCount >= 2 ? "warn" : "info";
|
|
250
|
+
const finding = {
|
|
251
|
+
shapeKind: cand.shapeKind,
|
|
252
|
+
componentName: comp.label,
|
|
253
|
+
entityId: comp.entityId,
|
|
254
|
+
filePath: cand.filePath,
|
|
255
|
+
lineNumber: cand.lineNumber,
|
|
256
|
+
snippet: cand.snippet,
|
|
257
|
+
sharedAtomExists,
|
|
258
|
+
...(existingCanonical ? { existingSharedComponent: existingCanonical.label } : {}),
|
|
259
|
+
tone,
|
|
260
|
+
...(cand.variantCount !== undefined ? { variantCount: cand.variantCount } : {}),
|
|
261
|
+
...(styleVector ? { styleVector } : {}),
|
|
262
|
+
detail: sharedAtomExists
|
|
263
|
+
? `Unextracted ${cand.shapeKind} control inline in '${comp.label}' bypasses existing '${existingCanonical.label}' atom.`
|
|
264
|
+
: occCount >= 2
|
|
265
|
+
? `Repeated ${cand.shapeKind} pattern across ${occCount} components — extract a shared <${cand.shapeKind}> atom.`
|
|
266
|
+
: `Single-site ${cand.shapeKind} pattern inside '${comp.label}' — extract when reused across >= 2 surfaces.`,
|
|
267
|
+
};
|
|
268
|
+
compShapes.push(finding);
|
|
269
|
+
allUnextractedShapes.push(finding);
|
|
270
|
+
}
|
|
271
|
+
if (suppressedSet.size > 0) {
|
|
272
|
+
suppressedRawDomIndicesByEntity.set(comp.entityId, suppressedSet);
|
|
273
|
+
}
|
|
274
|
+
if (compShapes.length > 0) {
|
|
275
|
+
unextractedShapesByEntity.set(comp.entityId, compShapes);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
suppressedRawDomIndicesByEntity,
|
|
280
|
+
unextractedShapesByEntity,
|
|
281
|
+
siblingAtomOverlapsByEntity,
|
|
282
|
+
allUnextractedShapes,
|
|
283
|
+
allSiblingAtomOverlaps,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/mcp/src/designSystem/valueClusters.ts
|
|
3
|
+
*
|
|
4
|
+
* Bottom-up derivation: collects hardcoded color and length literals from every scanned
|
|
5
|
+
* surface (CSS rules, TS/TSX, inline styles, arbitrary Tailwind) and clusters near-identical
|
|
6
|
+
* values (`#333333`, `#323232`, `#343434`) into candidate tokens, matching each cluster to an
|
|
7
|
+
* existing token when one is perceptually close. Fully deterministic; no naming conventions
|
|
8
|
+
* are assumed.
|
|
9
|
+
*/
|
|
10
|
+
import { rgbaToHex } from "./color.js";
|
|
11
|
+
import type { DesignSystemConfig } from "./config.js";
|
|
12
|
+
export type LiteralKind = "color" | "length";
|
|
13
|
+
export type LiteralSurface = "css-rule" | "string-literal" | "jsx-prop" | "inline-style" | "tailwind-arbitrary" | "canvas";
|
|
14
|
+
export interface LiteralValueOccurrence {
|
|
15
|
+
kind: LiteralKind;
|
|
16
|
+
/** Raw source text, e.g. `#333`, `rgba(0,0,0,.5)`, `12px`. */
|
|
17
|
+
value: string;
|
|
18
|
+
surface: LiteralSurface;
|
|
19
|
+
/** CSS property / JSX prop / Tailwind class that carries the value, when known. */
|
|
20
|
+
context?: string;
|
|
21
|
+
filePath: string;
|
|
22
|
+
lineNumber: number;
|
|
23
|
+
snippet: string;
|
|
24
|
+
}
|
|
25
|
+
export type LengthCategory = "space" | "type" | "radius" | "shadow";
|
|
26
|
+
export interface DerivedTokenProposal {
|
|
27
|
+
kind: LiteralKind;
|
|
28
|
+
/** For lengths: which kind of scale the cluster belongs to (tokens only match within a category). */
|
|
29
|
+
category?: LengthCategory;
|
|
30
|
+
/** Most frequent member; used as the cluster's representative value. */
|
|
31
|
+
representative: string;
|
|
32
|
+
members: Array<{
|
|
33
|
+
value: string;
|
|
34
|
+
count: number;
|
|
35
|
+
}>;
|
|
36
|
+
occurrenceCount: number;
|
|
37
|
+
distinctFileCount: number;
|
|
38
|
+
surfaces: LiteralSurface[];
|
|
39
|
+
/** Existing token that already covers this cluster. */
|
|
40
|
+
existingTokenMatch?: {
|
|
41
|
+
name: string;
|
|
42
|
+
value: string;
|
|
43
|
+
match: "exact" | "near";
|
|
44
|
+
distance: number;
|
|
45
|
+
};
|
|
46
|
+
/** Generic descriptive name (hue family + lightness step); *a human must rename it*. */
|
|
47
|
+
suggestedTokenName?: string;
|
|
48
|
+
recommendation: string;
|
|
49
|
+
evidence: Array<{
|
|
50
|
+
filePath: string;
|
|
51
|
+
lineNumber: number;
|
|
52
|
+
snippet: string;
|
|
53
|
+
}>;
|
|
54
|
+
}
|
|
55
|
+
export interface ResolvedTokenValue {
|
|
56
|
+
name: string;
|
|
57
|
+
/** Raw resolved value text (a color or a length). */
|
|
58
|
+
value: string;
|
|
59
|
+
}
|
|
60
|
+
interface ParsedLength {
|
|
61
|
+
px: number;
|
|
62
|
+
}
|
|
63
|
+
export declare function parseCssLengthToPx(raw: string): ParsedLength | null;
|
|
64
|
+
/** Removes `var(...)` expressions (including fallbacks) so only literal values remain. */
|
|
65
|
+
export declare function stripVarExpressions(value: string): string;
|
|
66
|
+
export declare function extractColorLiterals(value: string): string[];
|
|
67
|
+
export declare function extractLengthLiterals(value: string): string[];
|
|
68
|
+
export declare function isLengthSensitiveProperty(prop: string): boolean;
|
|
69
|
+
/** Extracts the bracket payload of a Tailwind arbitrary class, e.g. `text-[10px]` → `10px`. */
|
|
70
|
+
export declare function arbitraryTailwindValue(className: string): string | null;
|
|
71
|
+
/** Category of a length literal, from the CSS property / Tailwind class carrying it. */
|
|
72
|
+
export declare function lengthCategoryOfContext(context: string | undefined): LengthCategory;
|
|
73
|
+
/** Category of an existing token from its name; `null` when the name does not say. */
|
|
74
|
+
export declare function lengthCategoryOfTokenName(name: string): LengthCategory | null;
|
|
75
|
+
export declare function clusterLiteralValues(occurrences: LiteralValueOccurrence[], tokenValues: ResolvedTokenValue[], clustering: DesignSystemConfig["clustering"]): DerivedTokenProposal[];
|
|
76
|
+
export { rgbaToHex };
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/mcp/src/designSystem/valueClusters.ts
|
|
3
|
+
*
|
|
4
|
+
* Bottom-up derivation: collects hardcoded color and length literals from every scanned
|
|
5
|
+
* surface (CSS rules, TS/TSX, inline styles, arbitrary Tailwind) and clusters near-identical
|
|
6
|
+
* values (`#333333`, `#323232`, `#343434`) into candidate tokens, matching each cluster to an
|
|
7
|
+
* existing token when one is perceptually close. Fully deterministic; no naming conventions
|
|
8
|
+
* are assumed.
|
|
9
|
+
*/
|
|
10
|
+
import { describeColor, oklabDistance, parseCssColorString, rgbaToHex, toOklab, } from "./color.js";
|
|
11
|
+
export function parseCssLengthToPx(raw) {
|
|
12
|
+
const m = raw.trim().toLowerCase().match(/^(-?\d*\.?\d+)(px|rem|em)$/);
|
|
13
|
+
if (!m)
|
|
14
|
+
return null;
|
|
15
|
+
const n = Number(m[1]);
|
|
16
|
+
if (!Number.isFinite(n))
|
|
17
|
+
return null;
|
|
18
|
+
return { px: m[2] === "px" ? n : n * 16 };
|
|
19
|
+
}
|
|
20
|
+
const COLOR_LITERAL_SCAN_RE = /#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b|(?:rgba?|hsla?|oklch|oklab)\(\s*[^()]+\)/g;
|
|
21
|
+
const LENGTH_LITERAL_SCAN_RE = /(?<![\w.#-])-?\d*\.?\d+(?:px|rem|em)\b/g;
|
|
22
|
+
/** Removes `var(...)` expressions (including fallbacks) so only literal values remain. */
|
|
23
|
+
export function stripVarExpressions(value) {
|
|
24
|
+
let out = "";
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i < value.length) {
|
|
27
|
+
if (value.startsWith("var(", i)) {
|
|
28
|
+
let depth = 0;
|
|
29
|
+
let j = i + 3;
|
|
30
|
+
for (; j < value.length; j++) {
|
|
31
|
+
if (value[j] === "(")
|
|
32
|
+
depth++;
|
|
33
|
+
else if (value[j] === ")") {
|
|
34
|
+
depth--;
|
|
35
|
+
if (depth === 0)
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
out += " ";
|
|
40
|
+
i = j + 1;
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
out += value[i];
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
export function extractColorLiterals(value) {
|
|
50
|
+
return [...stripVarExpressions(value).matchAll(COLOR_LITERAL_SCAN_RE)]
|
|
51
|
+
.map((m) => m[0])
|
|
52
|
+
.filter((c) => parseCssColorString(c) !== null);
|
|
53
|
+
}
|
|
54
|
+
export function extractLengthLiterals(value) {
|
|
55
|
+
return [...stripVarExpressions(value).matchAll(LENGTH_LITERAL_SCAN_RE)]
|
|
56
|
+
.map((m) => m[0])
|
|
57
|
+
.filter((l) => {
|
|
58
|
+
const px = parseCssLengthToPx(l)?.px;
|
|
59
|
+
return px !== undefined && px !== 0;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/** CSS properties whose length literals are design decisions (spacing, size, radius, type). */
|
|
63
|
+
const LENGTH_SENSITIVE_PROP_RE = /^(?:margin|padding|gap|row-gap|column-gap|top|right|bottom|left|inset|width|height|min-width|min-height|max-width|max-height|border-radius|font-size|letter-spacing|line-height|box-shadow|text-indent)(?:-[a-z-]+)?$/;
|
|
64
|
+
export function isLengthSensitiveProperty(prop) {
|
|
65
|
+
return LENGTH_SENSITIVE_PROP_RE.test(prop.toLowerCase());
|
|
66
|
+
}
|
|
67
|
+
/** Extracts the bracket payload of a Tailwind arbitrary class, e.g. `text-[10px]` → `10px`. */
|
|
68
|
+
export function arbitraryTailwindValue(className) {
|
|
69
|
+
const m = className.match(/-\[([^\]]+)\]$/);
|
|
70
|
+
return m ? m[1].replace(/_/g, " ") : null;
|
|
71
|
+
}
|
|
72
|
+
/** Category of a length literal, from the CSS property / Tailwind class carrying it. */
|
|
73
|
+
export function lengthCategoryOfContext(context) {
|
|
74
|
+
const c = (context ?? "").toLowerCase();
|
|
75
|
+
if (/font-?size|^text-|letter|tracking|leading|line-?height/.test(c))
|
|
76
|
+
return "type";
|
|
77
|
+
if (/radius|^rounded/.test(c))
|
|
78
|
+
return "radius";
|
|
79
|
+
if (/shadow/.test(c))
|
|
80
|
+
return "shadow";
|
|
81
|
+
return "space";
|
|
82
|
+
}
|
|
83
|
+
/** Category of an existing token from its name; `null` when the name does not say. */
|
|
84
|
+
export function lengthCategoryOfTokenName(name) {
|
|
85
|
+
const n = name.toLowerCase();
|
|
86
|
+
if (/font|text|type|leading|tracking|line-?height/.test(n))
|
|
87
|
+
return "type";
|
|
88
|
+
if (/radius|round/.test(n))
|
|
89
|
+
return "radius";
|
|
90
|
+
if (/shadow/.test(n))
|
|
91
|
+
return "shadow";
|
|
92
|
+
if (/(?:^|[-_])(?:geom|geometry|canvas|grid|col|row|node|edge|macro|station|board)(?:[-_]|$)/.test(n)) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
if (/space|spacing|gap|size|width|height|pad|margin|inset|gutter/.test(n))
|
|
96
|
+
return "space";
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
function colorDistance(a, b) {
|
|
100
|
+
return oklabDistance(a.lab, b.lab) + Math.abs(a.rgba.a - b.rgba.a) * 0.5;
|
|
101
|
+
}
|
|
102
|
+
function pushEvidence(target, occ) {
|
|
103
|
+
if (target.length >= 5)
|
|
104
|
+
return;
|
|
105
|
+
if (target.some((e) => e.filePath === occ.filePath && e.lineNumber === occ.lineNumber))
|
|
106
|
+
return;
|
|
107
|
+
target.push({ filePath: occ.filePath, lineNumber: occ.lineNumber, snippet: occ.snippet });
|
|
108
|
+
}
|
|
109
|
+
export function clusterLiteralValues(occurrences, tokenValues, clustering) {
|
|
110
|
+
const proposals = [];
|
|
111
|
+
// ----- Colors -----
|
|
112
|
+
const colorByRaw = new Map();
|
|
113
|
+
for (const occ of occurrences) {
|
|
114
|
+
if (occ.kind !== "color")
|
|
115
|
+
continue;
|
|
116
|
+
const key = occ.value.trim().toLowerCase();
|
|
117
|
+
let entry = colorByRaw.get(key);
|
|
118
|
+
if (!entry) {
|
|
119
|
+
const rgba = parseCssColorString(key);
|
|
120
|
+
if (!rgba)
|
|
121
|
+
continue;
|
|
122
|
+
entry = { raw: occ.value.trim(), rgba, lab: toOklab(rgba), count: 0, occs: [] };
|
|
123
|
+
colorByRaw.set(key, entry);
|
|
124
|
+
}
|
|
125
|
+
entry.count++;
|
|
126
|
+
entry.occs.push(occ);
|
|
127
|
+
}
|
|
128
|
+
const tokenColors = tokenValues
|
|
129
|
+
.map((t) => {
|
|
130
|
+
const rgba = parseCssColorString(t.value);
|
|
131
|
+
return rgba ? { name: t.name, value: t.value, rgba, lab: toOklab(rgba) } : null;
|
|
132
|
+
})
|
|
133
|
+
.filter((t) => t !== null);
|
|
134
|
+
const sortedColors = [...colorByRaw.values()].sort((a, b) => b.count - a.count || a.raw.localeCompare(b.raw));
|
|
135
|
+
const colorClusters = [];
|
|
136
|
+
for (const entry of sortedColors) {
|
|
137
|
+
const home = colorClusters.find((c) => colorDistance(entry, c.rep) <= clustering.colorThreshold);
|
|
138
|
+
if (home)
|
|
139
|
+
home.members.push(entry);
|
|
140
|
+
else
|
|
141
|
+
colorClusters.push({ rep: entry, members: [entry] });
|
|
142
|
+
}
|
|
143
|
+
for (const cluster of colorClusters) {
|
|
144
|
+
const occurrenceCount = cluster.members.reduce((n, m) => n + m.count, 0);
|
|
145
|
+
let best;
|
|
146
|
+
for (const t of tokenColors) {
|
|
147
|
+
const d = colorDistance(cluster.rep, t);
|
|
148
|
+
if (!best || d < best.d)
|
|
149
|
+
best = { name: t.name, value: t.value, d };
|
|
150
|
+
}
|
|
151
|
+
const hasTokenMatch = best !== undefined && best.d <= clustering.tokenMatchThreshold;
|
|
152
|
+
if (!hasTokenMatch && occurrenceCount < clustering.minOccurrences)
|
|
153
|
+
continue;
|
|
154
|
+
const evidence = [];
|
|
155
|
+
const files = new Set();
|
|
156
|
+
const surfaces = new Set();
|
|
157
|
+
for (const m of cluster.members) {
|
|
158
|
+
for (const o of m.occs) {
|
|
159
|
+
files.add(o.filePath);
|
|
160
|
+
surfaces.add(o.surface);
|
|
161
|
+
pushEvidence(evidence, o);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const desc = describeColor(cluster.rep.rgba);
|
|
165
|
+
const distinctValues = cluster.members.length;
|
|
166
|
+
proposals.push({
|
|
167
|
+
kind: "color",
|
|
168
|
+
representative: cluster.rep.raw,
|
|
169
|
+
members: cluster.members.map((m) => ({ value: m.raw, count: m.count })),
|
|
170
|
+
occurrenceCount,
|
|
171
|
+
distinctFileCount: files.size,
|
|
172
|
+
surfaces: [...surfaces].sort(),
|
|
173
|
+
...(hasTokenMatch && best
|
|
174
|
+
? {
|
|
175
|
+
existingTokenMatch: {
|
|
176
|
+
name: best.name,
|
|
177
|
+
value: best.value,
|
|
178
|
+
match: best.d <= 0.008 ? "exact" : "near",
|
|
179
|
+
distance: Math.round(best.d * 1000) / 1000,
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
: {}),
|
|
183
|
+
suggestedTokenName: `--color-${desc.family}-${desc.step}`,
|
|
184
|
+
recommendation: hasTokenMatch && best
|
|
185
|
+
? `Replace ${occurrenceCount} hardcoded color occurrence(s) (${distinctValues} distinct value(s)) with existing token ${best.name}.`
|
|
186
|
+
: `Introduce one semantic token (suggested descriptor ${`--color-${desc.family}-${desc.step}`}; rename by role) covering ${distinctValues} near-identical value(s) across ${files.size} file(s) (${occurrenceCount} occurrences).`,
|
|
187
|
+
evidence,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
// ----- Lengths (clustered per category so a padding value never matches a font-size token) -----
|
|
191
|
+
for (const category of ["space", "type", "radius", "shadow"]) {
|
|
192
|
+
const lengthByPx = new Map();
|
|
193
|
+
for (const occ of occurrences) {
|
|
194
|
+
if (occ.kind !== "length" || lengthCategoryOfContext(occ.context) !== category)
|
|
195
|
+
continue;
|
|
196
|
+
const px = parseCssLengthToPx(occ.value)?.px;
|
|
197
|
+
if (px === undefined || px === 0)
|
|
198
|
+
continue;
|
|
199
|
+
const key = Math.round(px * 100) / 100;
|
|
200
|
+
let e = lengthByPx.get(key);
|
|
201
|
+
if (!e) {
|
|
202
|
+
e = { count: 0, raws: new Map(), occs: [] };
|
|
203
|
+
lengthByPx.set(key, e);
|
|
204
|
+
}
|
|
205
|
+
e.count++;
|
|
206
|
+
e.raws.set(occ.value.trim(), (e.raws.get(occ.value.trim()) ?? 0) + 1);
|
|
207
|
+
e.occs.push(occ);
|
|
208
|
+
}
|
|
209
|
+
const tokenLengths = tokenValues
|
|
210
|
+
.filter((t) => lengthCategoryOfTokenName(t.name) === category)
|
|
211
|
+
.map((t) => {
|
|
212
|
+
const px = parseCssLengthToPx(t.value)?.px;
|
|
213
|
+
return px !== undefined ? { name: t.name, value: t.value, px } : null;
|
|
214
|
+
})
|
|
215
|
+
.filter((t) => t !== null);
|
|
216
|
+
const sortedLengths = [...lengthByPx.entries()].sort((a, b) => b[1].count - a[1].count || a[0] - b[0]);
|
|
217
|
+
const lengthClusters = [];
|
|
218
|
+
for (const [px, data] of sortedLengths) {
|
|
219
|
+
const home = lengthClusters.find((c) => Math.abs(px - c.rep) <= Math.max(clustering.lengthTolerancePx, Math.abs(c.rep) * 0.04));
|
|
220
|
+
if (home)
|
|
221
|
+
home.members.push([px, data]);
|
|
222
|
+
else
|
|
223
|
+
lengthClusters.push({ rep: px, members: [[px, data]] });
|
|
224
|
+
}
|
|
225
|
+
for (const cluster of lengthClusters) {
|
|
226
|
+
const occurrenceCount = cluster.members.reduce((n, [, d]) => n + d.count, 0);
|
|
227
|
+
let best;
|
|
228
|
+
for (const t of tokenLengths) {
|
|
229
|
+
const d = Math.abs(t.px - cluster.rep);
|
|
230
|
+
if (!best || d < best.d)
|
|
231
|
+
best = { name: t.name, value: t.value, d };
|
|
232
|
+
}
|
|
233
|
+
const hasTokenMatch = best !== undefined &&
|
|
234
|
+
best.d <= Math.max(clustering.lengthTolerancePx, Math.abs(cluster.rep) * 0.04);
|
|
235
|
+
if (!hasTokenMatch && occurrenceCount < clustering.minOccurrences)
|
|
236
|
+
continue;
|
|
237
|
+
const members = [];
|
|
238
|
+
const evidence = [];
|
|
239
|
+
const files = new Set();
|
|
240
|
+
const surfaces = new Set();
|
|
241
|
+
for (const [, d] of cluster.members) {
|
|
242
|
+
for (const [raw, count] of d.raws.entries())
|
|
243
|
+
members.push({ value: raw, count });
|
|
244
|
+
for (const o of d.occs) {
|
|
245
|
+
files.add(o.filePath);
|
|
246
|
+
surfaces.add(o.surface);
|
|
247
|
+
pushEvidence(evidence, o);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
members.sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
|
|
251
|
+
proposals.push({
|
|
252
|
+
kind: "length",
|
|
253
|
+
category,
|
|
254
|
+
representative: members[0]?.value ?? `${cluster.rep}px`,
|
|
255
|
+
members,
|
|
256
|
+
occurrenceCount,
|
|
257
|
+
distinctFileCount: files.size,
|
|
258
|
+
surfaces: [...surfaces].sort(),
|
|
259
|
+
...(hasTokenMatch && best
|
|
260
|
+
? {
|
|
261
|
+
existingTokenMatch: {
|
|
262
|
+
name: best.name,
|
|
263
|
+
value: best.value,
|
|
264
|
+
match: best.d <= 0.5 ? "exact" : "near",
|
|
265
|
+
distance: Math.round(best.d * 100) / 100,
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
: {}),
|
|
269
|
+
recommendation: hasTokenMatch && best
|
|
270
|
+
? `Replace ${occurrenceCount} hardcoded length occurrence(s) with existing token ${best.name}.`
|
|
271
|
+
: `Snap ${members.length} near-identical length value(s) (${occurrenceCount} occurrences, ~${Math.round(cluster.rep * 100) / 100}px) onto one spacing/size token.`,
|
|
272
|
+
evidence,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
proposals.sort((a, b) => Number(Boolean(b.existingTokenMatch)) - Number(Boolean(a.existingTokenMatch)) ||
|
|
277
|
+
b.occurrenceCount - a.occurrenceCount ||
|
|
278
|
+
a.representative.localeCompare(b.representative));
|
|
279
|
+
return proposals.slice(0, clustering.maxClusters);
|
|
280
|
+
}
|
|
281
|
+
export { rgbaToHex };
|