-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcss-api-resolver.ts
More file actions
198 lines (175 loc) · 6.32 KB
/
css-api-resolver.ts
File metadata and controls
198 lines (175 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/**
* CSS API Resolver — resolves every ::part(), CSS custom property, and slot
* reference in agent-generated code against the actual component CEM data.
*
* Returns a structured report showing:
* - Which references are valid vs invalid
* - Closest valid alternatives for typos/hallucinations
* - The component's full style API surface
*
* This is the anti-hallucination tool: agents call it to verify that every
* CSS reference actually exists on the target component before shipping code.
*/
import type { ComponentMetadata } from './cem.js';
// ─── Types ───────────────────────────────────────────────────────────────────
export interface ResolvedReference {
name: string;
valid: boolean;
description?: string;
suggestion?: string;
}
export interface ResolvedSection {
resolved: ResolvedReference[];
available: string[];
}
export interface ComponentApiSummary {
tagName: string;
partCount: number;
tokenCount: number;
slotCount: number;
hasStyleApi: boolean;
}
export interface CssApiResolution {
valid: boolean;
invalidCount: number;
parts: ResolvedSection;
tokens: ResolvedSection;
slots: ResolvedSection;
componentApi: ComponentApiSummary;
}
// ─── Levenshtein distance ────────────────────────────────────────────────────
function levenshtein(a: string, b: string): number {
const m = a.length;
const n = b.length;
const dp: number[][] = Array.from({ length: m + 1 }, () =>
Array.from({ length: n + 1 }, () => 0),
);
for (let i = 0; i <= m; i++) {
const row = dp[i];
if (row) row[0] = i;
}
for (let j = 0; j <= n; j++) {
const row = dp[0];
if (row) row[j] = j;
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
const prevRow = dp[i - 1];
const currRow = dp[i];
if (prevRow && currRow) {
currRow[j] = Math.min(
(prevRow[j] ?? 0) + 1,
(currRow[j - 1] ?? 0) + 1,
(prevRow[j - 1] ?? 0) + cost,
);
}
}
}
const lastRow = dp[m];
return lastRow ? (lastRow[n] ?? 0) : 0;
}
function findClosest(name: string, candidates: string[], maxDistance = 3): string | undefined {
let best: string | undefined;
let bestDist = maxDistance + 1;
for (const c of candidates) {
const d = levenshtein(name, c);
if (d < bestDist) {
bestDist = d;
best = c;
}
}
return best;
}
// ─── Extractors ──────────────────────────────────────────────────────────────
function extractPartNames(css: string): string[] {
const seen = new Set<string>();
const re = /::part\(([^)]+)\)/g;
let match;
while ((match = re.exec(css)) !== null) {
const name = match[1];
if (name) seen.add(name.trim());
}
return [...seen];
}
function extractComponentTokenDeclarations(css: string): string[] {
// Match CSS custom property declarations (--name: value) that are
// set ON the component host selector, not var() references to global tokens
const seen = new Set<string>();
const re = /\s(--[\w-]+)\s*:/g;
let match;
while ((match = re.exec(css)) !== null) {
const name = match[1];
if (name) seen.add(name);
}
return [...seen];
}
function extractSlotNames(html: string): string[] {
const seen = new Set<string>();
const re = /\bslot\s*=\s*["']([^"']+)["']/g;
let match;
while ((match = re.exec(html)) !== null) {
const name = match[1];
if (name) seen.add(name);
}
return [...seen];
}
// ─── Main Entry Point ───────────────────────────────────────────────────────
export function resolveCssApi(
css: string,
meta: ComponentMetadata,
html?: string,
): CssApiResolution {
const availableParts = meta.cssParts.map((p) => p.name);
const availableTokens = meta.cssProperties.map((p) => p.name);
const availableSlots = meta.slots.map((s) => s.name);
// Resolve parts
const usedParts = extractPartNames(css);
const resolvedParts: ResolvedReference[] = usedParts.map((name) => {
const part = meta.cssParts.find((p) => p.name === name);
if (part) {
return { name, valid: true, description: part.description };
}
const suggestion = findClosest(name, availableParts);
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
});
// Resolve tokens — only validate component-scoped custom properties
const usedTokens = extractComponentTokenDeclarations(css);
const resolvedTokens: ResolvedReference[] = usedTokens.map((name) => {
const token = meta.cssProperties.find((p) => p.name === name);
if (token) {
return { name, valid: true, description: token.description };
}
const suggestion = findClosest(name, availableTokens);
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
});
// Resolve slots (from HTML if provided)
const usedSlots = html ? extractSlotNames(html) : [];
const resolvedSlots: ResolvedReference[] = usedSlots.map((name) => {
const slot = meta.slots.find((s) => s.name === name);
if (slot) {
return { name, valid: true, description: slot.description };
}
const suggestion = findClosest(name, availableSlots);
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
});
const invalidCount =
resolvedParts.filter((r) => !r.valid).length +
resolvedTokens.filter((r) => !r.valid).length +
resolvedSlots.filter((r) => !r.valid).length;
return {
valid: invalidCount === 0,
invalidCount,
parts: { resolved: resolvedParts, available: availableParts },
tokens: { resolved: resolvedTokens, available: availableTokens },
slots: { resolved: resolvedSlots, available: availableSlots },
componentApi: {
tagName: meta.tagName,
partCount: meta.cssParts.length,
tokenCount: meta.cssProperties.length,
slotCount: meta.slots.length,
hasStyleApi:
meta.cssParts.length > 0 || meta.cssProperties.length > 0 || meta.slots.length > 0,
},
};
}