impeccable 2.0.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.
@@ -0,0 +1,2131 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Anti-Pattern Detector for Impeccable
5
+ *
6
+ * Universal file — auto-detects environment (browser vs Node) and adapts.
7
+ *
8
+ * Node usage:
9
+ * node detect-antipatterns.mjs [file-or-dir...] # jsdom for HTML, regex for rest
10
+ * node detect-antipatterns.mjs https://... # Puppeteer (auto)
11
+ * node detect-antipatterns.mjs --fast [files...] # regex-only (skip jsdom)
12
+ * node detect-antipatterns.mjs --json # JSON output
13
+ *
14
+ * Browser usage:
15
+ * <script src="detect-antipatterns-browser.js"></script>
16
+ * Re-scan: window.impeccableScan()
17
+ *
18
+ * Exit codes: 0 = clean, 2 = findings
19
+ */
20
+
21
+ // ─── Environment ────────────────────────────────────────────────────────────
22
+
23
+ const IS_BROWSER = typeof window !== 'undefined';
24
+ const IS_NODE = !IS_BROWSER;
25
+
26
+ // @browser-strip-start
27
+ let fs, path;
28
+ if (!IS_BROWSER) {
29
+ fs = (await import('node:fs')).default;
30
+ path = (await import('node:path')).default;
31
+ }
32
+ // @browser-strip-end
33
+
34
+ // ─── Section 1: Constants ───────────────────────────────────────────────────
35
+
36
+ const SAFE_TAGS = new Set([
37
+ 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
38
+ 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
39
+ 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
40
+ 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
41
+ 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
42
+ ]);
43
+
44
+ const OVERUSED_FONTS = new Set([
45
+ 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
46
+ ]);
47
+
48
+ const GENERIC_FONTS = new Set([
49
+ 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
50
+ 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
51
+ '-apple-system', 'blinkmacsystemfont', 'segoe ui',
52
+ 'inherit', 'initial', 'unset', 'revert',
53
+ ]);
54
+
55
+ const ANTIPATTERNS = [
56
+ {
57
+ id: 'side-tab',
58
+ name: 'Side-tab accent border',
59
+ description:
60
+ 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
61
+ },
62
+ {
63
+ id: 'border-accent-on-rounded',
64
+ name: 'Border accent on rounded element',
65
+ description:
66
+ 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
67
+ },
68
+ {
69
+ id: 'overused-font',
70
+ name: 'Overused font',
71
+ description:
72
+ 'Inter, Roboto, Open Sans, Lato, Montserrat, and Arial are used on millions of sites. Choose a distinctive font that gives your interface personality.',
73
+ },
74
+ {
75
+ id: 'single-font',
76
+ name: 'Single font for everything',
77
+ description:
78
+ 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
79
+ },
80
+ {
81
+ id: 'flat-type-hierarchy',
82
+ name: 'Flat type hierarchy',
83
+ description:
84
+ 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
85
+ },
86
+ {
87
+ id: 'pure-black-white',
88
+ name: 'Pure black background',
89
+ description:
90
+ 'Pure #000000 as a background color looks harsh and unnatural. Tint it slightly toward your brand hue (e.g., oklch(12% 0.01 250)) for a more refined feel.',
91
+ },
92
+ {
93
+ id: 'gray-on-color',
94
+ name: 'Gray text on colored background',
95
+ description:
96
+ 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
97
+ },
98
+ {
99
+ id: 'low-contrast',
100
+ name: 'Low contrast text',
101
+ description:
102
+ 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
103
+ },
104
+ {
105
+ id: 'gradient-text',
106
+ name: 'Gradient text',
107
+ description:
108
+ 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
109
+ },
110
+ {
111
+ id: 'ai-color-palette',
112
+ name: 'AI color palette',
113
+ description:
114
+ 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
115
+ },
116
+ {
117
+ id: 'nested-cards',
118
+ name: 'Nested cards',
119
+ description:
120
+ 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
121
+ },
122
+ {
123
+ id: 'monotonous-spacing',
124
+ name: 'Monotonous spacing',
125
+ description:
126
+ 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
127
+ },
128
+ {
129
+ id: 'everything-centered',
130
+ name: 'Everything centered',
131
+ description:
132
+ 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
133
+ },
134
+ {
135
+ id: 'bounce-easing',
136
+ name: 'Bounce or elastic easing',
137
+ description:
138
+ 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
139
+ },
140
+ {
141
+ id: 'layout-transition',
142
+ name: 'Layout property animation',
143
+ description:
144
+ 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
145
+ },
146
+ {
147
+ id: 'dark-glow',
148
+ name: 'Dark mode with glowing accents',
149
+ description:
150
+ 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
151
+ },
152
+ {
153
+ id: 'line-length',
154
+ name: 'Line length too long',
155
+ description:
156
+ 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
157
+ },
158
+ {
159
+ id: 'cramped-padding',
160
+ name: 'Cramped padding',
161
+ description:
162
+ 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
163
+ },
164
+ {
165
+ id: 'tight-leading',
166
+ name: 'Tight line height',
167
+ description:
168
+ 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
169
+ },
170
+ {
171
+ id: 'skipped-heading',
172
+ name: 'Skipped heading level',
173
+ description:
174
+ 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
175
+ },
176
+ {
177
+ id: 'justified-text',
178
+ name: 'Justified text',
179
+ description:
180
+ 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
181
+ },
182
+ {
183
+ id: 'tiny-text',
184
+ name: 'Tiny body text',
185
+ description:
186
+ 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
187
+ },
188
+ {
189
+ id: 'all-caps-body',
190
+ name: 'All-caps body text',
191
+ description:
192
+ 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
193
+ },
194
+ {
195
+ id: 'wide-tracking',
196
+ name: 'Wide letter spacing on body text',
197
+ description:
198
+ 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
199
+ },
200
+ ];
201
+
202
+ // ─── Section 2: Color Utilities ─────────────────────────────────────────────
203
+
204
+ function isNeutralColor(color) {
205
+ if (!color || color === 'transparent') return true;
206
+ const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
207
+ if (!m) return true;
208
+ return (Math.max(+m[1], +m[2], +m[3]) - Math.min(+m[1], +m[2], +m[3])) < 30;
209
+ }
210
+
211
+ function parseRgb(color) {
212
+ if (!color || color === 'transparent') return null;
213
+ const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
214
+ if (!m) return null;
215
+ return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
216
+ }
217
+
218
+ function relativeLuminance({ r, g, b }) {
219
+ const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
220
+ c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
221
+ );
222
+ return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
223
+ }
224
+
225
+ function contrastRatio(c1, c2) {
226
+ const l1 = relativeLuminance(c1);
227
+ const l2 = relativeLuminance(c2);
228
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
229
+ }
230
+
231
+ function parseGradientColors(bgImage) {
232
+ if (!bgImage || !bgImage.includes('gradient')) return [];
233
+ return [...bgImage.matchAll(/rgba?\([^)]+\)/g)]
234
+ .map(m => parseRgb(m[0]))
235
+ .filter(Boolean);
236
+ }
237
+
238
+ function hasChroma(c, threshold = 30) {
239
+ if (!c) return false;
240
+ return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
241
+ }
242
+
243
+ function getHue(c) {
244
+ if (!c) return 0;
245
+ const r = c.r / 255, g = c.g / 255, b = c.b / 255;
246
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
247
+ if (max === min) return 0;
248
+ const d = max - min;
249
+ let h;
250
+ if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
251
+ else if (max === g) h = ((b - r) / d + 2) / 6;
252
+ else h = ((r - g) / d + 4) / 6;
253
+ return Math.round(h * 360);
254
+ }
255
+
256
+ function colorToHex(c) {
257
+ if (!c) return '?';
258
+ return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
259
+ }
260
+
261
+ // ─── Section 3: Pure Detection ──────────────────────────────────────────────
262
+
263
+ function checkBorders(tag, widths, colors, radius) {
264
+ if (SAFE_TAGS.has(tag)) return [];
265
+ const findings = [];
266
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
267
+
268
+ for (const side of sides) {
269
+ const w = widths[side];
270
+ if (w < 1 || isNeutralColor(colors[side])) continue;
271
+
272
+ const otherSides = sides.filter(s => s !== side);
273
+ const maxOther = Math.max(...otherSides.map(s => widths[s]));
274
+ if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
275
+
276
+ const sn = side.toLowerCase();
277
+ const isSide = side === 'Left' || side === 'Right';
278
+
279
+ if (isSide) {
280
+ if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
281
+ else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
282
+ } else {
283
+ if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
284
+ }
285
+ }
286
+
287
+ return findings;
288
+ }
289
+
290
+ function checkColors(opts) {
291
+ const { tag, textColor, bgColor, effectiveBg, fontSize, fontWeight, hasDirectText, bgClip, bgImage, classList } = opts;
292
+ if (SAFE_TAGS.has(tag)) return [];
293
+ const findings = [];
294
+
295
+ // Pure black background (only solid or near-solid, not semi-transparent overlays)
296
+ if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
297
+ findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
298
+ }
299
+
300
+ if (hasDirectText && textColor) {
301
+ // Skip background-dependent checks if we can't determine the background (e.g. gradient)
302
+ if (effectiveBg) {
303
+ // Gray on colored background
304
+ const textLum = relativeLuminance(textColor);
305
+ const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
306
+ if (isGray && hasChroma(effectiveBg, 40)) {
307
+ findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${colorToHex(effectiveBg)}` });
308
+ }
309
+
310
+ // Low contrast (WCAG AA)
311
+ const ratio = contrastRatio(textColor, effectiveBg);
312
+ const isHeading = ['h1', 'h2', 'h3'].includes(tag);
313
+ const isLargeText = fontSize >= 18 || (fontSize >= 14 && fontWeight >= 700) || isHeading;
314
+ const threshold = isLargeText ? 3.0 : 4.5;
315
+ if (ratio < threshold) {
316
+ findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(effectiveBg)}` });
317
+ }
318
+ }
319
+
320
+ // AI palette: purple/violet on headings
321
+ if (hasChroma(textColor, 50)) {
322
+ const hue = getHue(textColor);
323
+ if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
324
+ findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
325
+ }
326
+ }
327
+ }
328
+
329
+ // Gradient text
330
+ if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
331
+ findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
332
+ }
333
+
334
+ // Tailwind class checks
335
+ if (classList) {
336
+ const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
337
+ if (/\bbg-black\b/.test(classStr)) {
338
+ findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
339
+ }
340
+
341
+ const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
342
+ const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
343
+ if (grayMatch && colorBgMatch) {
344
+ findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
345
+ }
346
+
347
+ if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
348
+ findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
349
+ }
350
+
351
+ const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
352
+ if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
353
+ findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
354
+ }
355
+
356
+ if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
357
+ findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
358
+ }
359
+ }
360
+
361
+ return findings;
362
+ }
363
+
364
+ function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
365
+ if (!hasShadow && !hasBorder) return false;
366
+ return hasRadius || hasBg;
367
+ }
368
+
369
+ const LAYOUT_TRANSITION_PROPS = new Set([
370
+ 'width', 'height', 'padding', 'margin',
371
+ 'max-height', 'max-width', 'min-height', 'min-width',
372
+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
373
+ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
374
+ ]);
375
+
376
+ function checkMotion(opts) {
377
+ const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
378
+ if (SAFE_TAGS.has(tag)) return [];
379
+ const findings = [];
380
+
381
+ // --- Bounce/elastic easing ---
382
+ if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
383
+ findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
384
+ }
385
+ if (classList && /\banimate-bounce\b/.test(classList)) {
386
+ findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
387
+ }
388
+
389
+ // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
390
+ if (timingFunctions) {
391
+ const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
392
+ let m;
393
+ while ((m = bezierRe.exec(timingFunctions)) !== null) {
394
+ const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
395
+ if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
396
+ findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
397
+ break;
398
+ }
399
+ }
400
+ }
401
+
402
+ // --- Layout property transition ---
403
+ if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
404
+ const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
405
+ const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
406
+ if (layoutFound.length > 0) {
407
+ findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
408
+ }
409
+ }
410
+
411
+ return findings;
412
+ }
413
+
414
+ function checkGlow(opts) {
415
+ const { boxShadow, effectiveBg } = opts;
416
+ if (!boxShadow || boxShadow === 'none') return [];
417
+ if (!effectiveBg) return [];
418
+
419
+ // Only flag on dark backgrounds (luminance < 0.1)
420
+ const bgLum = relativeLuminance(effectiveBg);
421
+ if (bgLum >= 0.1) return [];
422
+
423
+ // Split multiple shadows (commas not inside parentheses)
424
+ const parts = boxShadow.split(/,(?![^(]*\))/);
425
+ for (const shadow of parts) {
426
+ const colorMatch = shadow.match(/rgba?\([^)]+\)/);
427
+ if (!colorMatch) continue;
428
+ const color = parseRgb(colorMatch[0]);
429
+ if (!color || !hasChroma(color, 30)) continue;
430
+
431
+ // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
432
+ const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
433
+ const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
434
+ const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
435
+ .map(m => parseFloat(m[1]));
436
+
437
+ // Third value is blur (offset-x, offset-y, blur, [spread])
438
+ if (pxVals.length >= 3 && pxVals[2] > 4) {
439
+ return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
440
+ }
441
+ }
442
+
443
+ return [];
444
+ }
445
+
446
+ /**
447
+ * Regex-on-HTML checks shared between browser and Node page-level detection.
448
+ * These don't need DOM access, just the raw HTML string.
449
+ */
450
+ function checkHtmlPatterns(html) {
451
+ const findings = [];
452
+
453
+ // --- Color ---
454
+
455
+ // Pure black background
456
+ const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
457
+ if (pureBlackBgRe.test(html)) {
458
+ findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
459
+ }
460
+
461
+ // AI color palette: purple/violet
462
+ const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
463
+ if (purpleHexRe.test(html)) {
464
+ const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
465
+ if (purpleTextRe.test(html)) {
466
+ findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
467
+ }
468
+ }
469
+
470
+ // Gradient text (background-clip: text + gradient)
471
+ const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
472
+ let gm;
473
+ while ((gm = gradientRe.exec(html)) !== null) {
474
+ const start = Math.max(0, gm.index - 200);
475
+ const context = html.substring(start, gm.index + gm[0].length + 200);
476
+ if (/gradient/i.test(context)) {
477
+ findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
478
+ break;
479
+ }
480
+ }
481
+ if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
482
+ findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
483
+ }
484
+
485
+ // --- Layout ---
486
+
487
+ // Monotonous spacing
488
+ const spacingValues = [];
489
+ const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
490
+ let sm;
491
+ while ((sm = spacingRe.exec(html)) !== null) {
492
+ const v = parseInt(sm[1], 10);
493
+ if (v > 0 && v < 200) spacingValues.push(v);
494
+ }
495
+ const gapRe = /gap\s*:\s*(\d+)px/gi;
496
+ while ((sm = gapRe.exec(html)) !== null) {
497
+ spacingValues.push(parseInt(sm[1], 10));
498
+ }
499
+ const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
500
+ while ((sm = twSpaceRe.exec(html)) !== null) {
501
+ spacingValues.push(parseInt(sm[1], 10) * 4);
502
+ }
503
+ const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
504
+ while ((sm = remSpacingRe.exec(html)) !== null) {
505
+ const v = Math.round(parseFloat(sm[1]) * 16);
506
+ if (v > 0 && v < 200) spacingValues.push(v);
507
+ }
508
+ const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
509
+ if (roundedSpacing.length >= 10) {
510
+ const counts = {};
511
+ for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
512
+ const maxCount = Math.max(...Object.values(counts));
513
+ const dominantPct = maxCount / roundedSpacing.length;
514
+ const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
515
+ if (dominantPct > 0.6 && unique.length <= 3) {
516
+ const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
517
+ findings.push({
518
+ id: 'monotonous-spacing',
519
+ snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
520
+ });
521
+ }
522
+ }
523
+
524
+ // --- Motion ---
525
+
526
+ // Bounce/elastic animation names
527
+ const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
528
+ if (bounceRe.test(html)) {
529
+ findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
530
+ }
531
+
532
+ // Overshoot cubic-bezier
533
+ const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
534
+ let bm;
535
+ while ((bm = bezierRe.exec(html)) !== null) {
536
+ const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
537
+ if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
538
+ findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
539
+ break;
540
+ }
541
+ }
542
+
543
+ // Layout property transitions
544
+ const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
545
+ let tm;
546
+ while ((tm = transRe.exec(html)) !== null) {
547
+ const val = tm[1].toLowerCase();
548
+ if (/\ball\b/.test(val)) continue;
549
+ const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
550
+ if (found) {
551
+ findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
552
+ break;
553
+ }
554
+ }
555
+
556
+ // --- Dark glow ---
557
+
558
+ const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
559
+ const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
560
+ if (darkBgRe.test(html) || twDarkBg.test(html)) {
561
+ const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
562
+ let shm;
563
+ while ((shm = shadowRe.exec(html)) !== null) {
564
+ const val = shm[1];
565
+ const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
566
+ if (!colorMatch) continue;
567
+ const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
568
+ if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
569
+ const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
570
+ if (pxVals.length >= 3 && pxVals[2] > 4) {
571
+ findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
572
+ break;
573
+ }
574
+ }
575
+ }
576
+
577
+ return findings;
578
+ }
579
+
580
+ // ─── Section 4: resolveBackground (unified) ─────────────────────────────────
581
+
582
+ function resolveBackground(el, win) {
583
+ let current = el;
584
+ while (current && current.nodeType === 1) {
585
+ const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
586
+
587
+ // If this element has a gradient background, it's opaque but we can't determine the color
588
+ const bgImage = style.backgroundImage || '';
589
+ if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
590
+ return null;
591
+ }
592
+
593
+ let bg = parseRgb(style.backgroundColor);
594
+ if (!IS_BROWSER && (!bg || bg.a < 0.1)) {
595
+ // jsdom doesn't decompose background shorthand — parse raw style attr
596
+ const rawStyle = current.getAttribute?.('style') || '';
597
+ const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
598
+ const inlineBg = bgMatch ? bgMatch[1].trim() : '';
599
+ // Check for gradient in inline style too
600
+ if (/gradient/i.test(inlineBg)) return null;
601
+ bg = parseRgb(inlineBg);
602
+ if (!bg && inlineBg) {
603
+ const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
604
+ if (hexMatch) {
605
+ const h = hexMatch[1];
606
+ if (h.length === 6) {
607
+ bg = { r: parseInt(h.slice(0,2), 16), g: parseInt(h.slice(2,4), 16), b: parseInt(h.slice(4,6), 16), a: 1 };
608
+ } else {
609
+ bg = { r: parseInt(h[0]+h[0], 16), g: parseInt(h[1]+h[1], 16), b: parseInt(h[2]+h[2], 16), a: 1 };
610
+ }
611
+ }
612
+ }
613
+ }
614
+ if (bg && bg.a > 0.1) {
615
+ if (IS_BROWSER || bg.a >= 0.5) return bg;
616
+ }
617
+ current = current.parentElement;
618
+ }
619
+ return { r: 255, g: 255, b: 255 };
620
+ }
621
+
622
+ // ─── Section 5: Element Adapters ────────────────────────────────────────────
623
+
624
+ // Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
625
+
626
+ function checkElementBordersDOM(el) {
627
+ const tag = el.tagName.toLowerCase();
628
+ if (SAFE_TAGS.has(tag)) return [];
629
+ const rect = el.getBoundingClientRect();
630
+ if (rect.width < 20 || rect.height < 20) return [];
631
+ const style = getComputedStyle(el);
632
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
633
+ const widths = {}, colors = {};
634
+ for (const s of sides) {
635
+ widths[s] = parseFloat(style[`border${s}Width`]) || 0;
636
+ colors[s] = style[`border${s}Color`] || '';
637
+ }
638
+ return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
639
+ }
640
+
641
+ function checkElementColorsDOM(el) {
642
+ const tag = el.tagName.toLowerCase();
643
+ if (SAFE_TAGS.has(tag)) return [];
644
+ const rect = el.getBoundingClientRect();
645
+ if (rect.width < 10 || rect.height < 10) return [];
646
+ const style = getComputedStyle(el);
647
+ const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
648
+ return checkColors({
649
+ tag,
650
+ textColor: parseRgb(style.color),
651
+ bgColor: parseRgb(style.backgroundColor),
652
+ effectiveBg: resolveBackground(el),
653
+ fontSize: parseFloat(style.fontSize) || 16,
654
+ fontWeight: parseInt(style.fontWeight) || 400,
655
+ hasDirectText,
656
+ bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
657
+ bgImage: style.backgroundImage || '',
658
+ classList: el.getAttribute('class') || '',
659
+ });
660
+ }
661
+
662
+ function checkElementMotionDOM(el) {
663
+ const tag = el.tagName.toLowerCase();
664
+ if (SAFE_TAGS.has(tag)) return [];
665
+ const style = getComputedStyle(el);
666
+ return checkMotion({
667
+ tag,
668
+ transitionProperty: style.transitionProperty || '',
669
+ animationName: style.animationName || '',
670
+ timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
671
+ classList: el.getAttribute('class') || '',
672
+ });
673
+ }
674
+
675
+ function checkElementGlowDOM(el) {
676
+ const tag = el.tagName.toLowerCase();
677
+ const style = getComputedStyle(el);
678
+ if (!style.boxShadow || style.boxShadow === 'none') return [];
679
+ // Use parent's background — glow radiates outward, so the surrounding context matters
680
+ // If resolveBackground returns null (gradient), try to infer from the gradient colors
681
+ let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
682
+ if (!parentBg) {
683
+ // Gradient background — sample its colors to determine if it's dark
684
+ let cur = el.parentElement;
685
+ while (cur && cur.nodeType === 1) {
686
+ const bgImage = getComputedStyle(cur).backgroundImage || '';
687
+ const gradColors = parseGradientColors(bgImage);
688
+ if (gradColors.length > 0) {
689
+ // Average the gradient colors
690
+ const avg = { r: 0, g: 0, b: 0 };
691
+ for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
692
+ avg.r = Math.round(avg.r / gradColors.length);
693
+ avg.g = Math.round(avg.g / gradColors.length);
694
+ avg.b = Math.round(avg.b / gradColors.length);
695
+ parentBg = avg;
696
+ break;
697
+ }
698
+ cur = cur.parentElement;
699
+ }
700
+ }
701
+ return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
702
+ }
703
+
704
+ function checkElementAIPaletteDOM(el) {
705
+ const style = getComputedStyle(el);
706
+ const findings = [];
707
+
708
+ // Check gradient backgrounds for purple/violet or cyan
709
+ const bgImage = style.backgroundImage || '';
710
+ const gradColors = parseGradientColors(bgImage);
711
+ for (const c of gradColors) {
712
+ if (hasChroma(c, 50)) {
713
+ const hue = getHue(c);
714
+ if (hue >= 260 && hue <= 310) {
715
+ findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
716
+ break;
717
+ }
718
+ if (hue >= 160 && hue <= 200) {
719
+ findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
720
+ break;
721
+ }
722
+ }
723
+ }
724
+
725
+ // Check for neon text (vivid cyan/purple color on dark background)
726
+ const textColor = parseRgb(style.color);
727
+ if (textColor && hasChroma(textColor, 80)) {
728
+ const hue = getHue(textColor);
729
+ const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
730
+ if (isAIPalette) {
731
+ const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
732
+ // Also check gradient parents
733
+ let effectiveBg = parentBg;
734
+ if (!effectiveBg) {
735
+ let cur = el.parentElement;
736
+ while (cur && cur.nodeType === 1) {
737
+ const gi = getComputedStyle(cur).backgroundImage || '';
738
+ const gc = parseGradientColors(gi);
739
+ if (gc.length > 0) {
740
+ const avg = { r: 0, g: 0, b: 0 };
741
+ for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
742
+ avg.r = Math.round(avg.r / gc.length);
743
+ avg.g = Math.round(avg.g / gc.length);
744
+ avg.b = Math.round(avg.b / gc.length);
745
+ effectiveBg = avg;
746
+ break;
747
+ }
748
+ cur = cur.parentElement;
749
+ }
750
+ }
751
+ if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
752
+ const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
753
+ findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
754
+ }
755
+ }
756
+ }
757
+
758
+ return findings;
759
+ }
760
+
761
+ const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
762
+
763
+ function checkElementQualityDOM(el) {
764
+ const tag = el.tagName.toLowerCase();
765
+ // Skip browser extension injected elements
766
+ const elId = el.id || '';
767
+ if (elId.startsWith('claude-') || elId.startsWith('cic-')) return [];
768
+ const style = getComputedStyle(el);
769
+ const findings = [];
770
+
771
+ const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
772
+ const textLen = el.textContent?.trim().length || 0;
773
+ const fontSize = parseFloat(style.fontSize) || 16;
774
+ const rect = el.getBoundingClientRect();
775
+
776
+ // --- Line length too long ---
777
+ // Only flag if text is long enough to actually fill the line (>80 chars)
778
+ if (hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > 80) {
779
+ const charsPerLine = rect.width / (fontSize * 0.5);
780
+ if (charsPerLine > 85) {
781
+ findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <80)` });
782
+ }
783
+ }
784
+
785
+ // --- Cramped padding (skip small elements like labels/badges) ---
786
+ if (hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
787
+ const borders = {
788
+ top: parseFloat(style.borderTopWidth) || 0,
789
+ right: parseFloat(style.borderRightWidth) || 0,
790
+ bottom: parseFloat(style.borderBottomWidth) || 0,
791
+ left: parseFloat(style.borderLeftWidth) || 0,
792
+ };
793
+ // Need at least 2 borders (a container), or a non-transparent background
794
+ const borderCount = Object.values(borders).filter(w => w > 0).length;
795
+ const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
796
+ if (borderCount >= 2 || hasBg) {
797
+ // Only check padding on sides that have borders or where bg creates containment
798
+ const paddings = [];
799
+ if (hasBg || borders.top > 0) paddings.push(parseFloat(style.paddingTop) || 0);
800
+ if (hasBg || borders.right > 0) paddings.push(parseFloat(style.paddingRight) || 0);
801
+ if (hasBg || borders.bottom > 0) paddings.push(parseFloat(style.paddingBottom) || 0);
802
+ if (hasBg || borders.left > 0) paddings.push(parseFloat(style.paddingLeft) || 0);
803
+ if (paddings.length > 0) {
804
+ const minPad = Math.min(...paddings);
805
+ if (minPad < 8) {
806
+ findings.push({ id: 'cramped-padding', snippet: `${minPad}px padding (need >=8px)` });
807
+ }
808
+ }
809
+ }
810
+ }
811
+
812
+ // --- Tight line height ---
813
+ if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
814
+ const lineHeight = parseFloat(style.lineHeight);
815
+ if (lineHeight && lineHeight !== NaN) {
816
+ const ratio = lineHeight / fontSize;
817
+ if (ratio < 1.3 && ratio > 0) {
818
+ findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
819
+ }
820
+ }
821
+ }
822
+
823
+
824
+ // --- Justified text (without hyphens) ---
825
+ if (hasDirectText && style.textAlign === 'justify') {
826
+ const hyphens = style.hyphens || style.webkitHyphens || '';
827
+ if (hyphens !== 'auto') {
828
+ findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
829
+ }
830
+ }
831
+
832
+ // --- Tiny body text ---
833
+ if (hasDirectText && textLen > 20 && fontSize < 12) {
834
+ if (!['sub', 'sup', 'code', 'kbd', 'samp', 'var'].includes(tag)) {
835
+ findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
836
+ }
837
+ }
838
+
839
+ // --- All-caps body text ---
840
+ if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
841
+ if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
842
+ findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
843
+ }
844
+ }
845
+
846
+ // --- Wide letter spacing on body text ---
847
+ if (hasDirectText && textLen > 20) {
848
+ const tracking = parseFloat(style.letterSpacing);
849
+ if (tracking > 0 && style.textTransform !== 'uppercase') {
850
+ const trackingEm = tracking / fontSize;
851
+ if (trackingEm > 0.05) {
852
+ findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
853
+ }
854
+ }
855
+ }
856
+
857
+ return findings;
858
+ }
859
+
860
+ function checkPageQualityDOM() {
861
+ const findings = [];
862
+
863
+ // --- Skipped heading levels ---
864
+ const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
865
+ let prevLevel = 0;
866
+ for (const h of headings) {
867
+ const level = parseInt(h.tagName[1]);
868
+ if (prevLevel > 0 && level > prevLevel + 1) {
869
+ findings.push({ type: 'skipped-heading', detail: `h${prevLevel} followed by h${level} (missing h${prevLevel + 1})` });
870
+ }
871
+ prevLevel = level;
872
+ }
873
+
874
+ return findings;
875
+ }
876
+
877
+ // Node adapters — take pre-extracted jsdom computed style
878
+
879
+ function checkElementBorders(tag, style) {
880
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
881
+ const widths = {}, colors = {};
882
+ for (const s of sides) {
883
+ widths[s] = parseFloat(style[`border${s}Width`]) || 0;
884
+ colors[s] = style[`border${s}Color`] || '';
885
+ }
886
+ return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
887
+ }
888
+
889
+ function checkElementColors(el, style, tag, window) {
890
+ const hasText = el.textContent?.trim().length > 0;
891
+ const hasDirectText = hasText && [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
892
+
893
+ return checkColors({
894
+ tag,
895
+ textColor: parseRgb(style.color),
896
+ bgColor: parseRgb(style.backgroundColor),
897
+ effectiveBg: resolveBackground(el, window),
898
+ fontSize: parseFloat(style.fontSize) || 16,
899
+ fontWeight: parseInt(style.fontWeight) || 400,
900
+ hasDirectText,
901
+ bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
902
+ bgImage: style.backgroundImage || '',
903
+ classList: el.getAttribute?.('class') || el.className || '',
904
+ });
905
+ }
906
+
907
+ function checkElementMotion(tag, style) {
908
+ return checkMotion({
909
+ tag,
910
+ transitionProperty: style.transitionProperty || '',
911
+ animationName: style.animationName || '',
912
+ timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
913
+ classList: '',
914
+ });
915
+ }
916
+
917
+ function checkElementGlow(tag, style, effectiveBg) {
918
+ if (!style.boxShadow || style.boxShadow === 'none') return [];
919
+ return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
920
+ }
921
+
922
+ // ─── Section 6: Page-Level Checks ───────────────────────────────────────────
923
+
924
+ // Browser page-level checks — use document/getComputedStyle globals
925
+
926
+ function checkTypography() {
927
+ const findings = [];
928
+ const fonts = new Set();
929
+ const overusedFound = new Set();
930
+
931
+ for (const sheet of document.styleSheets) {
932
+ let rules;
933
+ try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
934
+ if (!rules) continue;
935
+ for (const rule of rules) {
936
+ if (rule.type !== 1) continue;
937
+ const ff = rule.style?.fontFamily;
938
+ if (!ff) continue;
939
+ const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
940
+ const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
941
+ if (primary) {
942
+ fonts.add(primary);
943
+ if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
944
+ }
945
+ }
946
+ }
947
+
948
+ const html = document.documentElement.outerHTML;
949
+ const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
950
+ let m;
951
+ while ((m = gfRe.exec(html)) !== null) {
952
+ for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) {
953
+ fonts.add(f);
954
+ if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
955
+ }
956
+ }
957
+
958
+ for (const font of overusedFound) {
959
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font}` });
960
+ }
961
+ if (fonts.size === 1 && document.querySelectorAll('*').length >= 20) {
962
+ findings.push({ type: 'single-font', detail: `only font used is ${[...fonts][0]}` });
963
+ }
964
+
965
+ const sizes = new Set();
966
+ for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
967
+ const fs = parseFloat(getComputedStyle(el).fontSize);
968
+ if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
969
+ }
970
+ if (sizes.size >= 3) {
971
+ const sorted = [...sizes].sort((a, b) => a - b);
972
+ const ratio = sorted[sorted.length - 1] / sorted[0];
973
+ if (ratio < 2.0) {
974
+ findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
975
+ }
976
+ }
977
+
978
+ return findings;
979
+ }
980
+
981
+ function isCardLikeDOM(el) {
982
+ const tag = el.tagName.toLowerCase();
983
+ if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
984
+ const style = getComputedStyle(el);
985
+ const cls = el.getAttribute('class') || '';
986
+ const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
987
+ const hasBorder = /\bborder\b/.test(cls);
988
+ const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
989
+ const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
990
+ return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
991
+ }
992
+
993
+ function checkLayout() {
994
+ const findings = [];
995
+ const flaggedEls = new Set();
996
+
997
+ for (const el of document.querySelectorAll('*')) {
998
+ if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
999
+ const cls = el.getAttribute('class') || '';
1000
+ const style = getComputedStyle(el);
1001
+ if (style.position === 'absolute' || style.position === 'fixed') continue;
1002
+ if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
1003
+ if ((el.textContent?.trim().length || 0) < 10) continue;
1004
+ const rect = el.getBoundingClientRect();
1005
+ if (rect.width < 50 || rect.height < 30) continue;
1006
+
1007
+ let parent = el.parentElement;
1008
+ while (parent) {
1009
+ if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
1010
+ parent = parent.parentElement;
1011
+ }
1012
+ }
1013
+
1014
+ for (const el of flaggedEls) {
1015
+ let isAncestor = false;
1016
+ for (const other of flaggedEls) {
1017
+ if (other !== el && el.contains(other)) { isAncestor = true; break; }
1018
+ }
1019
+ if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
1020
+ }
1021
+
1022
+ return findings;
1023
+ }
1024
+
1025
+ // Node page-level checks — take document/window as parameters
1026
+
1027
+ function checkPageTypography(doc, win) {
1028
+ const findings = [];
1029
+
1030
+ const fonts = new Set();
1031
+ const overusedFound = new Set();
1032
+
1033
+ for (const sheet of doc.styleSheets) {
1034
+ let rules;
1035
+ try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
1036
+ if (!rules) continue;
1037
+ for (const rule of rules) {
1038
+ if (rule.type !== 1) continue;
1039
+ const ff = rule.style?.fontFamily;
1040
+ if (!ff) continue;
1041
+ const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
1042
+ const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
1043
+ if (primary) {
1044
+ fonts.add(primary);
1045
+ if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ // Check Google Fonts links in HTML
1051
+ const html = doc.documentElement?.outerHTML || '';
1052
+ const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
1053
+ let m;
1054
+ while ((m = gfRe.exec(html)) !== null) {
1055
+ const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
1056
+ for (const f of families) {
1057
+ fonts.add(f);
1058
+ if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
1059
+ }
1060
+ }
1061
+
1062
+ // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
1063
+ const ffRe = /font-family\s*:\s*([^;}]+)/gi;
1064
+ let fm;
1065
+ while ((fm = ffRe.exec(html)) !== null) {
1066
+ for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
1067
+ if (f && !GENERIC_FONTS.has(f)) {
1068
+ fonts.add(f);
1069
+ if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
1070
+ }
1071
+ }
1072
+ }
1073
+
1074
+ for (const font of overusedFound) {
1075
+ findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
1076
+ }
1077
+
1078
+ // Single font
1079
+ if (fonts.size === 1) {
1080
+ const els = doc.querySelectorAll('*');
1081
+ if (els.length >= 20) {
1082
+ findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
1083
+ }
1084
+ }
1085
+
1086
+ // Flat type hierarchy
1087
+ const sizes = new Set();
1088
+ const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
1089
+ for (const el of textEls) {
1090
+ const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
1091
+ // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
1092
+ if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
1093
+ }
1094
+ if (sizes.size >= 3) {
1095
+ const sorted = [...sizes].sort((a, b) => a - b);
1096
+ const ratio = sorted[sorted.length - 1] / sorted[0];
1097
+ if (ratio < 2.0) {
1098
+ findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
1099
+ }
1100
+ }
1101
+
1102
+ return findings;
1103
+ }
1104
+
1105
+ function isCardLike(el, win) {
1106
+ const tag = el.tagName.toLowerCase();
1107
+ if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
1108
+
1109
+ const style = win.getComputedStyle(el);
1110
+ const rawStyle = el.getAttribute?.('style') || '';
1111
+ const cls = el.getAttribute?.('class') || '';
1112
+
1113
+ const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
1114
+ /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
1115
+ const hasBorder = /\bborder\b/.test(cls);
1116
+ const hasRadius = (parseFloat(style.borderRadius) || 0) > 0 ||
1117
+ /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
1118
+ const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
1119
+ /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
1120
+
1121
+ return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
1122
+ }
1123
+
1124
+ function checkPageLayout(doc, win) {
1125
+ const findings = [];
1126
+
1127
+ // Nested cards
1128
+ const allEls = doc.querySelectorAll('*');
1129
+ const flaggedEls = new Set();
1130
+ for (const el of allEls) {
1131
+ if (!isCardLike(el, win)) continue;
1132
+ if (flaggedEls.has(el)) continue;
1133
+
1134
+ const tag = el.tagName.toLowerCase();
1135
+ const cls = el.getAttribute?.('class') || '';
1136
+ const rawStyle = el.getAttribute?.('style') || '';
1137
+
1138
+ if (['pre', 'code'].includes(tag)) continue;
1139
+ if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
1140
+ if ((el.textContent?.trim().length || 0) < 10) continue;
1141
+ if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
1142
+
1143
+ // Walk up to find card-like ancestor
1144
+ let parent = el.parentElement;
1145
+ while (parent) {
1146
+ if (isCardLike(parent, win)) {
1147
+ flaggedEls.add(el);
1148
+ break;
1149
+ }
1150
+ parent = parent.parentElement;
1151
+ }
1152
+ }
1153
+
1154
+ // Only report innermost nested cards
1155
+ for (const el of flaggedEls) {
1156
+ let isAncestorOfFlagged = false;
1157
+ for (const other of flaggedEls) {
1158
+ if (other !== el && el.contains(other)) {
1159
+ isAncestorOfFlagged = true;
1160
+ break;
1161
+ }
1162
+ }
1163
+ if (!isAncestorOfFlagged) {
1164
+ findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
1165
+ }
1166
+ }
1167
+
1168
+ // Everything centered
1169
+ const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
1170
+ let centeredCount = 0;
1171
+ let totalText = 0;
1172
+ for (const el of textEls) {
1173
+ const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
1174
+ if (!hasDirectText) continue;
1175
+ totalText++;
1176
+
1177
+ let cur = el;
1178
+ let isCentered = false;
1179
+ while (cur && cur.nodeType === 1) {
1180
+ const rawStyle = cur.getAttribute?.('style') || '';
1181
+ const cls = cur.getAttribute?.('class') || '';
1182
+ if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
1183
+ isCentered = true;
1184
+ break;
1185
+ }
1186
+ if (cur.tagName === 'BODY') break;
1187
+ cur = cur.parentElement;
1188
+ }
1189
+ if (isCentered) centeredCount++;
1190
+ }
1191
+
1192
+ if (totalText >= 5 && centeredCount / totalText > 0.7) {
1193
+ findings.push({
1194
+ id: 'everything-centered',
1195
+ snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
1196
+ });
1197
+ }
1198
+
1199
+ return findings;
1200
+ }
1201
+
1202
+ // ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
1203
+
1204
+ if (IS_BROWSER) {
1205
+ const LABEL_BG = 'oklch(55% 0.25 350)';
1206
+ const OUTLINE_COLOR = 'oklch(60% 0.25 350)';
1207
+
1208
+ // Inject hover styles via CSS (more reliable than JS event listeners)
1209
+ const styleEl = document.createElement('style');
1210
+ styleEl.textContent = `
1211
+ .impeccable-overlay:not(.impeccable-banner) {
1212
+ pointer-events: none;
1213
+ outline: 2px solid ${OUTLINE_COLOR};
1214
+ border-radius: 4px;
1215
+ transition: outline-color 0.3s ease;
1216
+ }
1217
+ .impeccable-overlay.impeccable-hover {
1218
+ outline-color: rgba(0,0,0,0.85);
1219
+ z-index: 100001 !important;
1220
+ }
1221
+ .impeccable-label-name,
1222
+ .impeccable-label-detail {
1223
+ transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
1224
+ }
1225
+ .impeccable-label-detail {
1226
+ position: absolute; top: 100%; left: 0;
1227
+ }
1228
+ .impeccable-overlay.impeccable-hover .impeccable-label-name,
1229
+ .impeccable-overlay.impeccable-hover .impeccable-label-detail {
1230
+ transform: translateY(-100%);
1231
+ }
1232
+ .impeccable-hidden .impeccable-overlay:not(.impeccable-banner) {
1233
+ display: none !important;
1234
+ }
1235
+ `;
1236
+ (document.head || document.documentElement).appendChild(styleEl);
1237
+
1238
+ const overlays = [];
1239
+ const TYPE_LABELS = {};
1240
+ for (const ap of ANTIPATTERNS) {
1241
+ TYPE_LABELS[ap.id] = ap.name.toLowerCase().substring(0, 26);
1242
+ }
1243
+
1244
+ function isInFixedContext(el) {
1245
+ let p = el;
1246
+ while (p && p !== document.body) {
1247
+ if (getComputedStyle(p).position === 'fixed') return true;
1248
+ p = p.parentElement;
1249
+ }
1250
+ return false;
1251
+ }
1252
+
1253
+ function positionOverlay(overlay) {
1254
+ const el = overlay._targetEl;
1255
+ if (!el) return;
1256
+ const rect = el.getBoundingClientRect();
1257
+ if (overlay._isFixed) {
1258
+ // Viewport-relative coords for fixed targets
1259
+ overlay.style.top = `${rect.top - 2}px`;
1260
+ overlay.style.left = `${rect.left - 2}px`;
1261
+ } else {
1262
+ // Document-relative coords for normal targets
1263
+ overlay.style.top = `${rect.top + scrollY - 2}px`;
1264
+ overlay.style.left = `${rect.left + scrollX - 2}px`;
1265
+ }
1266
+ overlay.style.width = `${rect.width + 4}px`;
1267
+ overlay.style.height = `${rect.height + 4}px`;
1268
+ }
1269
+
1270
+ function repositionOverlays() {
1271
+ for (const o of overlays) {
1272
+ if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
1273
+ positionOverlay(o);
1274
+ }
1275
+ }
1276
+
1277
+ let resizeRAF;
1278
+ const onResize = () => {
1279
+ cancelAnimationFrame(resizeRAF);
1280
+ resizeRAF = requestAnimationFrame(repositionOverlays);
1281
+ };
1282
+ window.addEventListener('resize', onResize);
1283
+
1284
+ // Track target element visibility via IntersectionObserver.
1285
+ // Uses a huge rootMargin so all *rendered* elements count as intersecting,
1286
+ // while display:none / closed <details> / hidden modals etc. do not.
1287
+ // This is event-driven -- no polling needed.
1288
+ const visibilityObserver = new IntersectionObserver((entries) => {
1289
+ for (const entry of entries) {
1290
+ const overlay = entry.target._impeccableOverlay;
1291
+ if (!overlay) continue;
1292
+ if (entry.isIntersecting) {
1293
+ overlay.style.display = '';
1294
+ positionOverlay(overlay);
1295
+ } else {
1296
+ overlay.style.display = 'none';
1297
+ }
1298
+ }
1299
+ }, { rootMargin: '99999px' });
1300
+
1301
+ // Reposition overlays after CSS transitions end (e.g. reveal animations).
1302
+ // Listens at document level so it catches transitions on ancestor elements
1303
+ // (the transform may be on a parent, not the flagged element itself).
1304
+ document.addEventListener('transitionend', (e) => {
1305
+ if (e.propertyName !== 'transform') return;
1306
+ for (const o of overlays) {
1307
+ if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
1308
+ if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
1309
+ positionOverlay(o);
1310
+ }
1311
+ }
1312
+ });
1313
+
1314
+ const highlight = function(el, findings) {
1315
+ const fixed = isInFixedContext(el);
1316
+ const rect = el.getBoundingClientRect();
1317
+ const outline = document.createElement('div');
1318
+ outline.className = 'impeccable-overlay';
1319
+ outline._targetEl = el;
1320
+ outline._isFixed = fixed;
1321
+ Object.assign(outline.style, {
1322
+ position: fixed ? 'fixed' : 'absolute',
1323
+ top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
1324
+ left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
1325
+ width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
1326
+ zIndex: '99999', boxSizing: 'border-box',
1327
+ });
1328
+
1329
+ const typeText = findings.map(f => TYPE_LABELS[f.type || f.id] || f.type || f.id).join(', ');
1330
+ const detailText = findings.map(f => f.detail || f.snippet).join(' | ');
1331
+
1332
+ const label = document.createElement('div');
1333
+ label.className = 'impeccable-label';
1334
+ Object.assign(label.style, {
1335
+ position: 'absolute', top: '-22px', left: '0',
1336
+ clipPath: 'inset(0 -999px)',
1337
+ });
1338
+
1339
+ const rowBase = {
1340
+ padding: '2px 8px', borderRadius: '3px', whiteSpace: 'nowrap',
1341
+ fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
1342
+ color: 'white', lineHeight: '16px',
1343
+ };
1344
+
1345
+ const nameRow = document.createElement('div');
1346
+ nameRow.className = 'impeccable-label-name';
1347
+ nameRow.textContent = typeText;
1348
+ Object.assign(nameRow.style, { ...rowBase, background: LABEL_BG, fontFamily: 'system-ui, sans-serif' });
1349
+ label.appendChild(nameRow);
1350
+
1351
+ const detailRow = document.createElement('div');
1352
+ detailRow.className = 'impeccable-label-detail';
1353
+ detailRow.textContent = detailText;
1354
+ Object.assign(detailRow.style, { ...rowBase, background: 'rgba(0,0,0,0.85)', fontFamily: 'ui-monospace, monospace', fontWeight: '400' });
1355
+ label.appendChild(detailRow);
1356
+
1357
+ outline.appendChild(label);
1358
+
1359
+ // Start hidden; the IntersectionObserver will show it once the target is rendered
1360
+ outline.style.display = 'none';
1361
+ el._impeccableOverlay = outline;
1362
+ visibilityObserver.observe(el);
1363
+
1364
+ // Drive hover state from the target element so pointer events pass through
1365
+ el.addEventListener('mouseenter', () => outline.classList.add('impeccable-hover'));
1366
+ el.addEventListener('mouseleave', () => outline.classList.remove('impeccable-hover'));
1367
+
1368
+ document.body.appendChild(outline);
1369
+ overlays.push(outline);
1370
+ };
1371
+
1372
+ const showPageBanner = function(findings) {
1373
+ if (!findings.length) return;
1374
+ const banner = document.createElement('div');
1375
+ banner.className = 'impeccable-overlay impeccable-banner';
1376
+ Object.assign(banner.style, {
1377
+ position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
1378
+ background: LABEL_BG, color: 'white',
1379
+ fontFamily: 'system-ui, sans-serif', fontSize: '13px',
1380
+ display: 'flex', alignItems: 'center', pointerEvents: 'auto',
1381
+ height: '36px',
1382
+ });
1383
+
1384
+ // Scrollable findings area
1385
+ const scrollArea = document.createElement('div');
1386
+ Object.assign(scrollArea.style, {
1387
+ flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
1388
+ display: 'flex', gap: '8px', alignItems: 'center',
1389
+ padding: '0 12px', scrollSnapType: 'x mandatory',
1390
+ scrollbarWidth: 'none',
1391
+ });
1392
+ for (const f of findings) {
1393
+ const tag = document.createElement('span');
1394
+ tag.textContent = `${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
1395
+ Object.assign(tag.style, {
1396
+ background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
1397
+ borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
1398
+ whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
1399
+ });
1400
+ scrollArea.appendChild(tag);
1401
+ }
1402
+ banner.appendChild(scrollArea);
1403
+
1404
+ // Controls area (always visible on the right)
1405
+ const controls = document.createElement('div');
1406
+ Object.assign(controls.style, {
1407
+ display: 'flex', alignItems: 'center', gap: '2px',
1408
+ padding: '0 8px', flexShrink: '0',
1409
+ });
1410
+
1411
+ // Toggle visibility button
1412
+ const toggle = document.createElement('button');
1413
+ toggle.textContent = '\u25C9'; // circle with dot (visible state)
1414
+ toggle.title = 'Toggle overlay visibility';
1415
+ Object.assign(toggle.style, {
1416
+ background: 'none', border: 'none',
1417
+ color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
1418
+ opacity: '0.85', transition: 'opacity 0.15s',
1419
+ });
1420
+ let overlaysVisible = true;
1421
+ toggle.addEventListener('click', () => {
1422
+ overlaysVisible = !overlaysVisible;
1423
+ document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
1424
+ toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
1425
+ toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
1426
+ });
1427
+ controls.appendChild(toggle);
1428
+
1429
+ // Close button
1430
+ const close = document.createElement('button');
1431
+ close.textContent = '\u00d7';
1432
+ close.title = 'Dismiss banner';
1433
+ Object.assign(close.style, {
1434
+ background: 'none', border: 'none',
1435
+ color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
1436
+ });
1437
+ close.addEventListener('click', () => banner.remove());
1438
+ controls.appendChild(close);
1439
+
1440
+ banner.appendChild(controls);
1441
+ document.body.appendChild(banner);
1442
+ overlays.push(banner);
1443
+ };
1444
+
1445
+ const printSummary = function(allFindings) {
1446
+ if (allFindings.length === 0) {
1447
+ console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
1448
+ return;
1449
+ }
1450
+ console.group(
1451
+ `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
1452
+ 'color: oklch(60% 0.25 350); font-weight: bold'
1453
+ );
1454
+ for (const { el, findings } of allFindings) {
1455
+ for (const f of findings) {
1456
+ console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
1457
+ 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
1458
+ }
1459
+ }
1460
+ console.groupEnd();
1461
+ };
1462
+
1463
+ const scan = function() {
1464
+ for (const o of overlays) o.remove();
1465
+ overlays.length = 0;
1466
+ visibilityObserver.disconnect();
1467
+ const allFindings = [];
1468
+
1469
+ for (const el of document.querySelectorAll('*')) {
1470
+ if (el.classList.contains('impeccable-overlay') ||
1471
+ el.classList.contains('impeccable-label') ||
1472
+ el.classList.contains('impeccable-tooltip')) continue;
1473
+ // Skip browser extension elements (Claude, etc.)
1474
+ const elId = el.id || '';
1475
+ if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
1476
+
1477
+ const findings = [
1478
+ ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1479
+ ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1480
+ ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1481
+ ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1482
+ ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1483
+ ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1484
+ ];
1485
+
1486
+ if (findings.length > 0) {
1487
+ highlight(el, findings);
1488
+ allFindings.push({ el, findings });
1489
+ }
1490
+ }
1491
+
1492
+ const pageLevelFindings = [];
1493
+
1494
+ const typoFindings = checkTypography();
1495
+ if (typoFindings.length > 0) {
1496
+ pageLevelFindings.push(...typoFindings);
1497
+ allFindings.push({ el: document.body, findings: typoFindings });
1498
+ }
1499
+
1500
+ const layoutFindings = checkLayout();
1501
+ for (const f of layoutFindings) {
1502
+ const el = f.el || document.body;
1503
+ delete f.el;
1504
+ // Merge into existing overlay if this element already has one
1505
+ const existing = el._impeccableOverlay;
1506
+ if (existing) {
1507
+ const nameRow = existing.querySelector('.impeccable-label-name');
1508
+ const detailRow = existing.querySelector('.impeccable-label-detail');
1509
+ const newType = TYPE_LABELS[f.type] || f.type;
1510
+ if (nameRow) nameRow.textContent += ', ' + newType;
1511
+ if (detailRow) detailRow.textContent += ' | ' + (f.detail || '');
1512
+ } else {
1513
+ highlight(el, [f]);
1514
+ }
1515
+ allFindings.push({ el, findings: [f] });
1516
+ }
1517
+
1518
+ // Page-level quality checks (headings, etc.)
1519
+ const qualityFindings = checkPageQualityDOM();
1520
+ if (qualityFindings.length > 0) {
1521
+ pageLevelFindings.push(...qualityFindings);
1522
+ allFindings.push({ el: document.body, findings: qualityFindings });
1523
+ }
1524
+
1525
+ // Regex-on-HTML checks (shared with Node)
1526
+ const htmlPatternFindings = checkHtmlPatterns(document.documentElement.outerHTML);
1527
+ if (htmlPatternFindings.length > 0) {
1528
+ const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet }));
1529
+ pageLevelFindings.push(...mapped);
1530
+ allFindings.push({ el: document.body, findings: mapped });
1531
+ }
1532
+
1533
+ if (pageLevelFindings.length > 0) {
1534
+ showPageBanner(pageLevelFindings);
1535
+ }
1536
+
1537
+ printSummary(allFindings);
1538
+ return allFindings;
1539
+ };
1540
+
1541
+ if (document.readyState === 'loading') {
1542
+ document.addEventListener('DOMContentLoaded', () => setTimeout(scan, 100));
1543
+ } else {
1544
+ setTimeout(scan, 100);
1545
+ }
1546
+
1547
+ window.impeccableScan = scan;
1548
+ }
1549
+
1550
+ // ─── Section 8: Node Engine ─────────────────────────────────────────────────
1551
+ // @browser-strip-start
1552
+
1553
+ function getAP(id) {
1554
+ return ANTIPATTERNS.find(a => a.id === id);
1555
+ }
1556
+
1557
+ function finding(id, filePath, snippet, line = 0) {
1558
+ const ap = getAP(id);
1559
+ return { antipattern: id, name: ap.name, description: ap.description, file: filePath, line, snippet };
1560
+ }
1561
+
1562
+ /** Check if content looks like a full page (not a component/partial) */
1563
+ function isFullPage(content) {
1564
+ const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
1565
+ return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
1566
+ }
1567
+
1568
+ // ---------------------------------------------------------------------------
1569
+ // jsdom detection (default for HTML files)
1570
+ // ---------------------------------------------------------------------------
1571
+
1572
+ async function detectHtml(filePath) {
1573
+ let JSDOM;
1574
+ try {
1575
+ ({ JSDOM } = await import('jsdom'));
1576
+ } catch {
1577
+ const content = fs.readFileSync(filePath, 'utf-8');
1578
+ return detectText(content, filePath);
1579
+ }
1580
+
1581
+ const html = fs.readFileSync(filePath, 'utf-8');
1582
+ const resolvedPath = path.resolve(filePath);
1583
+ const fileDir = path.dirname(resolvedPath);
1584
+
1585
+ // Inline linked local stylesheets so jsdom can see them
1586
+ let processedHtml = html;
1587
+ const linkRes = [
1588
+ /<link[^>]+rel=["']stylesheet["'][^>]*href=["']([^"']+)["'][^>]*>/gi,
1589
+ /<link[^>]+href=["']([^"']+)["'][^>]*rel=["']stylesheet["'][^>]*>/gi,
1590
+ ];
1591
+ for (const re of linkRes) {
1592
+ let m;
1593
+ while ((m = re.exec(html)) !== null) {
1594
+ const href = m[1];
1595
+ if (/^(https?:)?\/\//.test(href)) continue;
1596
+ const cssPath = path.resolve(fileDir, href);
1597
+ try {
1598
+ const css = fs.readFileSync(cssPath, 'utf-8');
1599
+ processedHtml = processedHtml.replace(m[0], `<style>/* ${href} */\n${css}\n</style>`);
1600
+ } catch { /* skip unreadable */ }
1601
+ }
1602
+ }
1603
+
1604
+ const dom = new JSDOM(processedHtml, {
1605
+ url: `file://${resolvedPath}`,
1606
+ });
1607
+ const { window } = dom;
1608
+ const { document } = window;
1609
+
1610
+ const findings = [];
1611
+
1612
+ // Element-level checks (borders + colors + motion)
1613
+ for (const el of document.querySelectorAll('*')) {
1614
+ const tag = el.tagName.toLowerCase();
1615
+ const style = window.getComputedStyle(el);
1616
+ for (const f of checkElementBorders(tag, style)) {
1617
+ findings.push(finding(f.id, filePath, f.snippet));
1618
+ }
1619
+ for (const f of checkElementColors(el, style, tag, window)) {
1620
+ findings.push(finding(f.id, filePath, f.snippet));
1621
+ }
1622
+ for (const f of checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window))) {
1623
+ findings.push(finding(f.id, filePath, f.snippet));
1624
+ }
1625
+ for (const f of checkElementMotion(tag, style)) {
1626
+ findings.push(finding(f.id, filePath, f.snippet));
1627
+ }
1628
+ }
1629
+
1630
+ // Page-level checks (only for full pages, not partials)
1631
+ if (isFullPage(html)) {
1632
+ for (const f of checkPageTypography(document, window)) {
1633
+ findings.push(finding(f.id, filePath, f.snippet));
1634
+ }
1635
+ for (const f of checkPageLayout(document, window)) {
1636
+ findings.push(finding(f.id, filePath, f.snippet));
1637
+ }
1638
+ for (const f of checkHtmlPatterns(html)) {
1639
+ findings.push(finding(f.id, filePath, f.snippet));
1640
+ }
1641
+ }
1642
+
1643
+ window.close();
1644
+ return findings;
1645
+ }
1646
+
1647
+ // ---------------------------------------------------------------------------
1648
+ // Puppeteer detection (for URLs)
1649
+ // ---------------------------------------------------------------------------
1650
+
1651
+ async function detectUrl(url) {
1652
+ let puppeteer;
1653
+ try {
1654
+ puppeteer = await import('puppeteer');
1655
+ } catch {
1656
+ throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
1657
+ }
1658
+
1659
+ // Read the browser detection script — reuse it instead of reimplementing
1660
+ const browserScriptPath = path.resolve(
1661
+ path.dirname(new URL(import.meta.url).pathname),
1662
+ 'detect-antipatterns-browser.js'
1663
+ );
1664
+ let browserScript;
1665
+ try {
1666
+ browserScript = fs.readFileSync(browserScriptPath, 'utf-8');
1667
+ } catch {
1668
+ throw new Error(`Browser script not found at ${browserScriptPath}`);
1669
+ }
1670
+
1671
+ const browser = await puppeteer.default.launch({ headless: true });
1672
+ const page = await browser.newPage();
1673
+ await page.setViewport({ width: 1280, height: 800 });
1674
+ await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
1675
+
1676
+ // Inject the browser detection script and collect results
1677
+ await page.evaluate(browserScript);
1678
+ const results = await page.evaluate(() => {
1679
+ if (!window.impeccableScan) return [];
1680
+ const allFindings = window.impeccableScan();
1681
+ return allFindings.flatMap(({ findings }) =>
1682
+ findings.map(f => ({ id: f.type, snippet: f.detail }))
1683
+ );
1684
+ });
1685
+
1686
+ await browser.close();
1687
+ return results.map(f => finding(f.id, url, f.snippet));
1688
+ }
1689
+
1690
+ // ---------------------------------------------------------------------------
1691
+ // Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
1692
+ // ---------------------------------------------------------------------------
1693
+
1694
+ const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
1695
+ const hasBorderRadius = (line) => /border-radius/i.test(line);
1696
+ const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
1697
+
1698
+ function isNeutralBorderColor(str) {
1699
+ const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
1700
+ if (!m) return false;
1701
+ const c = m[1].toLowerCase();
1702
+ if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
1703
+ const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
1704
+ if (hex) {
1705
+ const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
1706
+ return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
1707
+ }
1708
+ const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
1709
+ if (shex) {
1710
+ const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
1711
+ return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
1712
+ }
1713
+ return false;
1714
+ }
1715
+
1716
+ const REGEX_MATCHERS = [
1717
+ // --- Side-tab ---
1718
+ { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
1719
+ test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
1720
+ fmt: (m) => m[0] },
1721
+ { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
1722
+ test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
1723
+ fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
1724
+ { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
1725
+ test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
1726
+ fmt: (m) => m[0] },
1727
+ { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
1728
+ test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
1729
+ fmt: (m) => m[0] },
1730
+ { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
1731
+ test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
1732
+ fmt: (m) => m[0] },
1733
+ { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
1734
+ test: (m) => +m[1] >= 3,
1735
+ fmt: (m) => m[0] },
1736
+ // --- Border accent on rounded ---
1737
+ { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
1738
+ test: (m, line) => hasRounded(line) && +m[1] >= 1,
1739
+ fmt: (m) => m[0] },
1740
+ { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
1741
+ test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
1742
+ fmt: (m) => m[0] },
1743
+ // --- Overused font ---
1744
+ { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica)\b/gi,
1745
+ test: () => true,
1746
+ fmt: (m) => m[0] },
1747
+ { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat)\b/gi,
1748
+ test: () => true,
1749
+ fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
1750
+ // --- Pure black background ---
1751
+ { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
1752
+ test: () => true,
1753
+ fmt: (m) => m[0] },
1754
+ // --- Gradient text ---
1755
+ { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
1756
+ test: (m, line) => /gradient/i.test(line),
1757
+ fmt: () => 'background-clip: text + gradient' },
1758
+ // --- Gradient text (Tailwind) ---
1759
+ { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
1760
+ test: (m, line) => /\bbg-gradient-to-/i.test(line),
1761
+ fmt: () => 'bg-clip-text + bg-gradient' },
1762
+ // --- Tailwind pure black background ---
1763
+ { id: 'pure-black-white', regex: /\bbg-black\b/g,
1764
+ test: () => true,
1765
+ fmt: (m) => m[0] },
1766
+ // --- Tailwind gray on colored bg ---
1767
+ { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
1768
+ test: (m, line) => /\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/.test(line),
1769
+ fmt: (m, line) => { const bg = line.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/); return `${m[0]} on ${bg?.[0] || '?'}`; } },
1770
+ // --- Tailwind AI palette ---
1771
+ { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
1772
+ test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
1773
+ fmt: (m) => `${m[0]} on heading` },
1774
+ { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
1775
+ test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
1776
+ fmt: (m) => `${m[0]} gradient` },
1777
+ // --- Bounce/elastic easing ---
1778
+ { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
1779
+ test: () => true,
1780
+ fmt: () => 'animate-bounce (Tailwind)' },
1781
+ { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
1782
+ test: () => true,
1783
+ fmt: (m) => m[0] },
1784
+ { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
1785
+ test: (m) => {
1786
+ const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
1787
+ return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
1788
+ },
1789
+ fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
1790
+ // --- Layout property transition ---
1791
+ { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
1792
+ test: (m) => {
1793
+ const val = m[1].toLowerCase();
1794
+ if (/\ball\b/.test(val)) return false;
1795
+ return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
1796
+ },
1797
+ fmt: (m) => {
1798
+ const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
1799
+ return `transition: ${found ? found.join(', ') : m[1].trim()}`;
1800
+ } },
1801
+ { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
1802
+ test: (m) => {
1803
+ const val = m[1].toLowerCase();
1804
+ if (/\ball\b/.test(val)) return false;
1805
+ return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
1806
+ },
1807
+ fmt: (m) => {
1808
+ const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
1809
+ return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
1810
+ } },
1811
+ ];
1812
+
1813
+ const REGEX_ANALYZERS = [
1814
+ // Single font
1815
+ (content, filePath) => {
1816
+ const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
1817
+ const fonts = new Set();
1818
+ let m;
1819
+ while ((m = fontFamilyRe.exec(content)) !== null) {
1820
+ for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
1821
+ if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
1822
+ }
1823
+ }
1824
+ const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
1825
+ while ((m = gfRe.exec(content)) !== null) {
1826
+ for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
1827
+ }
1828
+ if (fonts.size !== 1 || content.split('\n').length < 20) return [];
1829
+ const name = [...fonts][0];
1830
+ const lines = content.split('\n');
1831
+ let line = 1;
1832
+ for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
1833
+ return [finding('single-font', filePath, `only font used is ${name}`, line)];
1834
+ },
1835
+ // Flat type hierarchy
1836
+ (content, filePath) => {
1837
+ const sizes = new Set();
1838
+ const REM = 16;
1839
+ let m;
1840
+ const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
1841
+ while ((m = sizeRe.exec(content)) !== null) {
1842
+ const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
1843
+ if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
1844
+ }
1845
+ const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
1846
+ while ((m = clampRe.exec(content)) !== null) {
1847
+ sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
1848
+ sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
1849
+ }
1850
+ const TW = { 'text-xs': 12, 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24, 'text-3xl': 30, 'text-4xl': 36, 'text-5xl': 48, 'text-6xl': 60, 'text-7xl': 72, 'text-8xl': 96, 'text-9xl': 128 };
1851
+ for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
1852
+ if (sizes.size < 3) return [];
1853
+ const sorted = [...sizes].sort((a, b) => a - b);
1854
+ const ratio = sorted[sorted.length - 1] / sorted[0];
1855
+ if (ratio >= 2.0) return [];
1856
+ const lines = content.split('\n');
1857
+ let line = 1;
1858
+ for (let i = 0; i < lines.length; i++) { if (/font-size/i.test(lines[i]) || /\btext-(?:xs|sm|base|lg|xl|\d)/i.test(lines[i])) { line = i + 1; break; } }
1859
+ return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
1860
+ },
1861
+ // Monotonous spacing (regex)
1862
+ (content, filePath) => {
1863
+ const vals = [];
1864
+ let m;
1865
+ const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
1866
+ while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
1867
+ const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
1868
+ while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
1869
+ const gapRe = /gap\s*:\s*(\d+)px/gi;
1870
+ while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
1871
+ const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
1872
+ while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
1873
+ const rounded = vals.map(v => Math.round(v / 4) * 4);
1874
+ if (rounded.length < 10) return [];
1875
+ const counts = {};
1876
+ for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
1877
+ const maxCount = Math.max(...Object.values(counts));
1878
+ const pct = maxCount / rounded.length;
1879
+ const unique = [...new Set(rounded)].filter(v => v > 0);
1880
+ if (pct <= 0.6 || unique.length > 3) return [];
1881
+ const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
1882
+ return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
1883
+ },
1884
+ // Everything centered (regex)
1885
+ (content, filePath) => {
1886
+ const lines = content.split('\n');
1887
+ let centered = 0, total = 0;
1888
+ for (const line of lines) {
1889
+ if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
1890
+ total++;
1891
+ if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
1892
+ }
1893
+ }
1894
+ if (total < 5 || centered / total <= 0.7) return [];
1895
+ return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
1896
+ },
1897
+ // Dark glow (page-level: dark bg + colored box-shadow with blur)
1898
+ (content, filePath) => {
1899
+ // Check if page has a dark background
1900
+ const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
1901
+ const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
1902
+ const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
1903
+ if (!hasDarkBg) return [];
1904
+
1905
+ // Check for colored box-shadow with blur > 4px
1906
+ const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
1907
+ let m;
1908
+ while ((m = shadowRe.exec(content)) !== null) {
1909
+ const val = m[1];
1910
+ const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
1911
+ if (!colorMatch) continue;
1912
+ const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
1913
+ if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
1914
+ // Check blur: look for pattern like "0 0 20px" (third number > 4)
1915
+ const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
1916
+ if (pxVals.length >= 3 && pxVals[2] > 4) {
1917
+ const lines = content.substring(0, m.index).split('\n');
1918
+ return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
1919
+ }
1920
+ }
1921
+ return [];
1922
+ },
1923
+ ];
1924
+
1925
+ function detectText(content, filePath) {
1926
+ const findings = [];
1927
+ const lines = content.split('\n');
1928
+
1929
+ for (const matcher of REGEX_MATCHERS) {
1930
+ for (let i = 0; i < lines.length; i++) {
1931
+ const line = lines[i];
1932
+ matcher.regex.lastIndex = 0;
1933
+ let m;
1934
+ while ((m = matcher.regex.exec(line)) !== null) {
1935
+ if (matcher.test(m, line)) {
1936
+ findings.push(finding(matcher.id, filePath, matcher.fmt(m, line), i + 1));
1937
+ }
1938
+ }
1939
+ }
1940
+ }
1941
+
1942
+ // Page-level analyzers only run on full pages
1943
+ if (isFullPage(content)) {
1944
+ for (const analyzer of REGEX_ANALYZERS) {
1945
+ findings.push(...analyzer(content, filePath));
1946
+ }
1947
+ }
1948
+
1949
+ return findings;
1950
+ }
1951
+
1952
+ // ---------------------------------------------------------------------------
1953
+ // File walker
1954
+ // ---------------------------------------------------------------------------
1955
+
1956
+ const SKIP_DIRS = new Set([
1957
+ 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
1958
+ '.svelte-kit', '__pycache__', '.turbo', '.vercel',
1959
+ ]);
1960
+
1961
+ const SCANNABLE_EXTENSIONS = new Set([
1962
+ '.html', '.htm', '.css', '.scss', '.less',
1963
+ '.jsx', '.tsx', '.js', '.ts',
1964
+ '.vue', '.svelte', '.astro',
1965
+ ]);
1966
+
1967
+ const HTML_EXTENSIONS = new Set(['.html', '.htm']);
1968
+
1969
+ function walkDir(dir) {
1970
+ const files = [];
1971
+ let entries;
1972
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
1973
+ for (const entry of entries) {
1974
+ if (SKIP_DIRS.has(entry.name)) continue;
1975
+ const full = path.join(dir, entry.name);
1976
+ if (entry.isDirectory()) files.push(...walkDir(full));
1977
+ else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
1978
+ }
1979
+ return files;
1980
+ }
1981
+
1982
+ // ---------------------------------------------------------------------------
1983
+ // Output formatting
1984
+ // ---------------------------------------------------------------------------
1985
+
1986
+ function formatFindings(findings, jsonMode) {
1987
+ if (jsonMode) return JSON.stringify(findings, null, 2);
1988
+
1989
+ const grouped = {};
1990
+ for (const f of findings) {
1991
+ if (!grouped[f.file]) grouped[f.file] = [];
1992
+ grouped[f.file].push(f);
1993
+ }
1994
+ const out = [];
1995
+ for (const [file, items] of Object.entries(grouped)) {
1996
+ out.push(`\n${file}`);
1997
+ for (const item of items) {
1998
+ out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
1999
+ out.push(` → ${item.description}`);
2000
+ }
2001
+ }
2002
+ out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
2003
+ return out.join('\n');
2004
+ }
2005
+
2006
+ // ---------------------------------------------------------------------------
2007
+ // Stdin handling
2008
+ // ---------------------------------------------------------------------------
2009
+
2010
+ async function handleStdin() {
2011
+ const chunks = [];
2012
+ for await (const chunk of process.stdin) chunks.push(chunk);
2013
+ const input = Buffer.concat(chunks).toString('utf-8');
2014
+ try {
2015
+ const parsed = JSON.parse(input);
2016
+ const fp = parsed?.tool_input?.file_path;
2017
+ if (fp && fs.existsSync(fp)) {
2018
+ return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
2019
+ ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
2020
+ }
2021
+ } catch { /* not JSON */ }
2022
+ return detectText(input, '<stdin>');
2023
+ }
2024
+
2025
+ // ---------------------------------------------------------------------------
2026
+ // CLI
2027
+ // ---------------------------------------------------------------------------
2028
+
2029
+ function printUsage() {
2030
+ console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
2031
+
2032
+ Scan files or URLs for UI anti-patterns and design quality issues.
2033
+
2034
+ Options:
2035
+ --fast Regex-only mode (skip jsdom, faster but misses linked stylesheets)
2036
+ --json Output results as JSON
2037
+ --help Show this help message
2038
+
2039
+ Detection modes:
2040
+ HTML files jsdom with computed styles (default, catches linked CSS)
2041
+ Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
2042
+ URLs Puppeteer full browser rendering (auto-detected)
2043
+ --fast Forces regex for all files
2044
+
2045
+ Examples:
2046
+ impeccable detect src/
2047
+ impeccable detect index.html
2048
+ impeccable detect https://example.com
2049
+ impeccable detect --fast --json .`);
2050
+ }
2051
+
2052
+ async function main() {
2053
+ const args = process.argv.slice(2);
2054
+ const jsonMode = args.includes('--json');
2055
+ const helpMode = args.includes('--help');
2056
+ const fastMode = args.includes('--fast');
2057
+ const targets = args.filter(a => !a.startsWith('--'));
2058
+
2059
+ if (helpMode) { printUsage(); process.exit(0); }
2060
+
2061
+ let allFindings = [];
2062
+
2063
+ if (!process.stdin.isTTY && targets.length === 0) {
2064
+ allFindings = await handleStdin();
2065
+ } else {
2066
+ const paths = targets.length > 0 ? targets : [process.cwd()];
2067
+
2068
+ for (const target of paths) {
2069
+ if (/^https?:\/\//i.test(target)) {
2070
+ try { allFindings.push(...await detectUrl(target)); }
2071
+ catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
2072
+ continue;
2073
+ }
2074
+
2075
+ const resolved = path.resolve(target);
2076
+ let stat;
2077
+ try { stat = fs.statSync(resolved); }
2078
+ catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
2079
+
2080
+ if (stat.isDirectory()) {
2081
+ for (const file of walkDir(resolved)) {
2082
+ const ext = path.extname(file).toLowerCase();
2083
+ if (!fastMode && HTML_EXTENSIONS.has(ext)) {
2084
+ allFindings.push(...await detectHtml(file));
2085
+ } else {
2086
+ allFindings.push(...detectText(fs.readFileSync(file, 'utf-8'), file));
2087
+ }
2088
+ }
2089
+ } else if (stat.isFile()) {
2090
+ const ext = path.extname(resolved).toLowerCase();
2091
+ if (!fastMode && HTML_EXTENSIONS.has(ext)) {
2092
+ allFindings.push(...await detectHtml(resolved));
2093
+ } else {
2094
+ allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
2095
+ }
2096
+ }
2097
+ }
2098
+ }
2099
+
2100
+ if (allFindings.length > 0) {
2101
+ process.stderr.write(formatFindings(allFindings, jsonMode) + '\n');
2102
+ process.exit(2);
2103
+ }
2104
+ if (jsonMode) process.stdout.write('[]\n');
2105
+ process.exit(0);
2106
+ }
2107
+
2108
+ // ---------------------------------------------------------------------------
2109
+ // Entry point
2110
+ // ---------------------------------------------------------------------------
2111
+
2112
+ if (!IS_BROWSER) {
2113
+ const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
2114
+ process.argv[1]?.endsWith('detect-antipatterns.mjs/');
2115
+ if (isMainModule) main();
2116
+ }
2117
+
2118
+ // @browser-strip-end
2119
+
2120
+ // ─── Section 9: Exports ─────────────────────────────────────────────────────
2121
+ // @browser-strip-start
2122
+
2123
+ export {
2124
+ ANTIPATTERNS, SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS,
2125
+ checkElementBorders, checkElementMotion, checkElementGlow, checkPageTypography, checkPageLayout, isNeutralColor, isFullPage,
2126
+ detectHtml, detectUrl, detectText,
2127
+ walkDir, formatFindings, SCANNABLE_EXTENSIONS, SKIP_DIRS,
2128
+ main as detectCli,
2129
+ };
2130
+
2131
+ // @browser-strip-end