impeccable 2.1.8 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3567 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Anti-Pattern Detector for Impeccable
5
- * Copyright (c) 2026 Paul Bakaus
6
- * SPDX-License-Identifier: Apache-2.0
7
- *
8
- * Universal file — auto-detects environment (browser vs Node) and adapts.
9
- *
10
- * Node usage:
11
- * node detect-antipatterns.mjs [file-or-dir...] # jsdom for HTML, regex for rest
12
- * node detect-antipatterns.mjs https://... # Puppeteer (auto)
13
- * node detect-antipatterns.mjs --fast [files...] # regex-only (skip jsdom)
14
- * node detect-antipatterns.mjs --json # JSON output
15
- *
16
- * Browser usage:
17
- * <script src="detect-antipatterns-browser.js"></script>
18
- * Re-scan: window.impeccableScan()
19
- *
20
- * Exit codes: 0 = clean, 2 = findings
21
- */
22
-
23
- // ─── Environment ────────────────────────────────────────────────────────────
24
-
25
- const IS_BROWSER = typeof window !== 'undefined';
26
- const IS_NODE = !IS_BROWSER;
27
-
28
- // @browser-strip-start
29
- let fs, path, fileURLToPath;
30
- if (!IS_BROWSER) {
31
- fs = (await import('node:fs')).default;
32
- path = (await import('node:path')).default;
33
- fileURLToPath = (await import('node:url')).fileURLToPath;
34
- }
35
- // @browser-strip-end
36
-
37
- // ─── Section 1: Constants ───────────────────────────────────────────────────
38
-
39
- const SAFE_TAGS = new Set([
40
- 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
41
- 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
42
- 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
43
- 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
44
- 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
45
- ]);
46
-
47
- // Per-check safe-tags override for the border (side-tab / border-accent)
48
- // rule. We intentionally re-allow <label> here because card-shaped clickable
49
- // labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
50
- // canonical side-tab anti-pattern shapes and must be detected. The rule's
51
- // other preconditions (non-neutral color, width >= 2px on a single side,
52
- // radius > 0 or width >= 3, element size >= 20x20 in the browser path)
53
- // already filter out plain inline form labels so this does not introduce
54
- // false positives. See modern-color-borders.html for the test matrix.
55
- const BORDER_SAFE_TAGS = new Set(
56
- [...SAFE_TAGS].filter(t => t !== 'label')
57
- );
58
-
59
- const OVERUSED_FONTS = new Set([
60
- 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
61
- ]);
62
-
63
- // Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
64
- // Keys are font names, values are arrays of hostname suffixes where the font is allowed.
65
- const GOOGLE_DOMAINS = [
66
- 'google.com', 'youtube.com', 'android.com', 'chromium.org',
67
- 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
68
- ];
69
- const BRAND_FONT_DOMAINS = {
70
- 'roboto': GOOGLE_DOMAINS,
71
- 'google sans': GOOGLE_DOMAINS,
72
- 'product sans': GOOGLE_DOMAINS,
73
- };
74
-
75
- function isBrandFontOnOwnDomain(font) {
76
- if (typeof location === 'undefined') return false;
77
- const allowed = BRAND_FONT_DOMAINS[font];
78
- if (!allowed) return false;
79
- const host = location.hostname.toLowerCase();
80
- return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
81
- }
82
-
83
- const GENERIC_FONTS = new Set([
84
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
85
- 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
86
- '-apple-system', 'blinkmacsystemfont', 'segoe ui',
87
- 'inherit', 'initial', 'unset', 'revert',
88
- ]);
89
-
90
- const ANTIPATTERNS = [
91
- // ── AI slop: tells that something was AI-generated ──
92
- {
93
- id: 'side-tab',
94
- category: 'slop',
95
- name: 'Side-tab accent border',
96
- description:
97
- '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.',
98
- skillSection: 'Visual Details',
99
- skillGuideline: 'colored accent stripe',
100
- },
101
- {
102
- id: 'border-accent-on-rounded',
103
- category: 'slop',
104
- name: 'Border accent on rounded element',
105
- description:
106
- 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
107
- skillSection: 'Visual Details',
108
- skillGuideline: 'colored accent stripe',
109
- },
110
- {
111
- id: 'overused-font',
112
- category: 'slop',
113
- name: 'Overused font',
114
- description:
115
- 'Inter, Roboto, Open Sans, Lato, Montserrat, and Arial are used on millions of sites. Choose a distinctive font that gives your interface personality.',
116
- skillSection: 'Typography',
117
- skillGuideline: 'overused fonts like Inter',
118
- },
119
- {
120
- id: 'single-font',
121
- category: 'slop',
122
- name: 'Single font for everything',
123
- description:
124
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
125
- skillSection: 'Typography',
126
- skillGuideline: 'only one font family for the entire page',
127
- },
128
- {
129
- id: 'flat-type-hierarchy',
130
- category: 'slop',
131
- name: 'Flat type hierarchy',
132
- description:
133
- '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).',
134
- skillSection: 'Typography',
135
- skillGuideline: 'flat type hierarchy',
136
- },
137
- {
138
- id: 'gradient-text',
139
- category: 'slop',
140
- name: 'Gradient text',
141
- description:
142
- 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
143
- skillSection: 'Color & Contrast',
144
- skillGuideline: 'gradient text for',
145
- },
146
- {
147
- id: 'ai-color-palette',
148
- category: 'slop',
149
- name: 'AI color palette',
150
- description:
151
- 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
152
- skillSection: 'Color & Contrast',
153
- skillGuideline: 'AI color palette',
154
- },
155
- {
156
- id: 'nested-cards',
157
- category: 'slop',
158
- name: 'Nested cards',
159
- description:
160
- 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
161
- skillSection: 'Layout & Space',
162
- skillGuideline: 'Nest cards inside cards',
163
- },
164
- {
165
- id: 'monotonous-spacing',
166
- category: 'slop',
167
- name: 'Monotonous spacing',
168
- description:
169
- 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
170
- skillSection: 'Layout & Space',
171
- skillGuideline: 'same spacing everywhere',
172
- },
173
- {
174
- id: 'everything-centered',
175
- category: 'slop',
176
- name: 'Everything centered',
177
- description:
178
- 'Every text element is center-aligned. Left-aligned text with asymmetric layouts feels more designed. Center only hero sections and CTAs.',
179
- skillSection: 'Layout & Space',
180
- skillGuideline: 'Center everything',
181
- },
182
- {
183
- id: 'bounce-easing',
184
- category: 'slop',
185
- name: 'Bounce or elastic easing',
186
- description:
187
- 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
188
- skillSection: 'Motion',
189
- skillGuideline: 'bounce or elastic easing',
190
- },
191
- {
192
- id: 'dark-glow',
193
- category: 'slop',
194
- name: 'Dark mode with glowing accents',
195
- description:
196
- '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.',
197
- skillSection: 'Color & Contrast',
198
- skillGuideline: 'dark mode with glowing accents',
199
- },
200
- {
201
- id: 'icon-tile-stack',
202
- category: 'slop',
203
- name: 'Icon tile stacked above heading',
204
- description:
205
- 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
206
- skillSection: 'Typography',
207
- skillGuideline: 'large icons with rounded corners above every heading',
208
- },
209
-
210
- // ── Quality: general design and accessibility issues ──
211
- {
212
- id: 'pure-black-white',
213
- category: 'quality',
214
- name: 'Pure black background',
215
- description:
216
- '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.',
217
- skillSection: 'Color & Contrast',
218
- skillGuideline: 'pure black (#000)',
219
- },
220
- {
221
- id: 'gray-on-color',
222
- category: 'quality',
223
- name: 'Gray text on colored background',
224
- description:
225
- 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
226
- skillSection: 'Color & Contrast',
227
- skillGuideline: 'gray text on colored backgrounds',
228
- },
229
- {
230
- id: 'low-contrast',
231
- category: 'quality',
232
- name: 'Low contrast text',
233
- description:
234
- '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.',
235
- },
236
- {
237
- id: 'layout-transition',
238
- category: 'quality',
239
- name: 'Layout property animation',
240
- description:
241
- 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
242
- skillSection: 'Motion',
243
- skillGuideline: 'Animate layout properties',
244
- },
245
- {
246
- id: 'line-length',
247
- category: 'quality',
248
- name: 'Line length too long',
249
- description:
250
- '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.',
251
- skillSection: 'Layout & Space',
252
- skillGuideline: 'wrap beyond ~80 characters',
253
- },
254
- {
255
- id: 'cramped-padding',
256
- category: 'quality',
257
- name: 'Cramped padding',
258
- description:
259
- 'Text is too close to the edge of its container. Add at least 8px (ideally 12-16px) of padding inside bordered or colored containers.',
260
- },
261
- {
262
- id: 'tight-leading',
263
- category: 'quality',
264
- name: 'Tight line height',
265
- description:
266
- '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.',
267
- },
268
- {
269
- id: 'skipped-heading',
270
- category: 'quality',
271
- name: 'Skipped heading level',
272
- description:
273
- '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.',
274
- },
275
- {
276
- id: 'justified-text',
277
- category: 'quality',
278
- name: 'Justified text',
279
- description:
280
- '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.',
281
- },
282
- {
283
- id: 'tiny-text',
284
- category: 'quality',
285
- name: 'Tiny body text',
286
- description:
287
- 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
288
- },
289
- {
290
- id: 'all-caps-body',
291
- category: 'quality',
292
- name: 'All-caps body text',
293
- description:
294
- '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.',
295
- skillSection: 'Typography',
296
- skillGuideline: 'long body passages in uppercase',
297
- },
298
- {
299
- id: 'wide-tracking',
300
- category: 'quality',
301
- name: 'Wide letter spacing on body text',
302
- description:
303
- 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
304
- },
305
- ];
306
-
307
- // ─── Section 2: Color Utilities ─────────────────────────────────────────────
308
-
309
- function isNeutralColor(color) {
310
- if (!color || color === 'transparent') return true;
311
-
312
- // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
313
- const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
314
- if (rgb) {
315
- return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
316
- }
317
-
318
- // oklch()/lch() — chroma is the second numeric component.
319
- // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
320
- // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
321
- // literally (it does NOT convert them to rgb).
322
- const oklch = color.match(/oklch\(\s*[\d.%-]+\s+([\d.-]+)/i);
323
- if (oklch) return parseFloat(oklch[1]) < 0.02;
324
- const lch = color.match(/lch\(\s*[\d.%-]+\s+([\d.-]+)/i);
325
- if (lch) return parseFloat(lch[1]) < 3;
326
-
327
- // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
328
- // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
329
- const oklab = color.match(/oklab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
330
- if (oklab) {
331
- const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
332
- return Math.hypot(a, b) < 0.02;
333
- }
334
- const lab = color.match(/lab\(\s*[\d.%-]+\s+([\d.-]+)\s+([\d.-]+)/i);
335
- if (lab) {
336
- const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
337
- return Math.hypot(a, b) < 3;
338
- }
339
-
340
- // hsl/hsla — saturation is the second numeric component (percent).
341
- // Modern jsdom usually converts hsl() to rgb, but handle it directly for
342
- // safety across versions and for any engine that preserves the format.
343
- const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
344
- if (hsl) return parseFloat(hsl[1]) < 10;
345
-
346
- // hwb(hue whiteness% blackness%) — a pixel is fully gray when
347
- // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
348
- const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
349
- if (hwb) {
350
- const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
351
- return (1 - Math.min(100, w + b) / 100) < 0.1;
352
- }
353
-
354
- // Unknown / unrecognized format — err on the side of DETECTING rather
355
- // than silently skipping. This is the opposite of the previous default,
356
- // which was the root cause of the oklch bug.
357
- return false;
358
- }
359
-
360
- function parseRgb(color) {
361
- if (!color || color === 'transparent') return null;
362
- const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
363
- if (!m) return null;
364
- return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
365
- }
366
-
367
- function relativeLuminance({ r, g, b }) {
368
- const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
369
- c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
370
- );
371
- return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
372
- }
373
-
374
- function contrastRatio(c1, c2) {
375
- const l1 = relativeLuminance(c1);
376
- const l2 = relativeLuminance(c2);
377
- return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
378
- }
379
-
380
- function parseGradientColors(bgImage) {
381
- if (!bgImage || !bgImage.includes('gradient')) return [];
382
- const colors = [];
383
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
384
- const c = parseRgb(m[0]);
385
- if (c) colors.push(c);
386
- }
387
- for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
388
- const h = m[1];
389
- if (h.length === 6) {
390
- colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
391
- } else {
392
- colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
393
- }
394
- }
395
- return colors;
396
- }
397
-
398
- function hasChroma(c, threshold = 30) {
399
- if (!c) return false;
400
- return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
401
- }
402
-
403
- function getHue(c) {
404
- if (!c) return 0;
405
- const r = c.r / 255, g = c.g / 255, b = c.b / 255;
406
- const max = Math.max(r, g, b), min = Math.min(r, g, b);
407
- if (max === min) return 0;
408
- const d = max - min;
409
- let h;
410
- if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
411
- else if (max === g) h = ((b - r) / d + 2) / 6;
412
- else h = ((r - g) / d + 4) / 6;
413
- return Math.round(h * 360);
414
- }
415
-
416
- function colorToHex(c) {
417
- if (!c) return '?';
418
- return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
419
- }
420
-
421
- // ─── Section 3: Pure Detection ──────────────────────────────────────────────
422
-
423
- function checkBorders(tag, widths, colors, radius) {
424
- if (BORDER_SAFE_TAGS.has(tag)) return [];
425
- const findings = [];
426
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
427
-
428
- for (const side of sides) {
429
- const w = widths[side];
430
- if (w < 1 || isNeutralColor(colors[side])) continue;
431
-
432
- const otherSides = sides.filter(s => s !== side);
433
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
434
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
435
-
436
- const sn = side.toLowerCase();
437
- const isSide = side === 'Left' || side === 'Right';
438
-
439
- if (isSide) {
440
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
441
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
442
- } else {
443
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
444
- }
445
- }
446
-
447
- return findings;
448
- }
449
-
450
- // Returns true if the given text is composed entirely of emoji characters
451
- // (plus whitespace / variation selectors). Emojis render as multicolor glyphs
452
- // regardless of CSS `color`, so contrast checks against the element's text
453
- // color are meaningless for these nodes.
454
- const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
455
- const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
456
- function isEmojiOnlyText(text) {
457
- if (!text) return false;
458
- if (!EMOJI_CHAR_RE.test(text)) return false;
459
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
460
- }
461
-
462
- function checkColors(opts) {
463
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
464
- if (SAFE_TAGS.has(tag)) return [];
465
- const findings = [];
466
-
467
- // Pure black background (only solid or near-solid, not semi-transparent overlays)
468
- if (bgColor && bgColor.a >= 0.9 && bgColor.r === 0 && bgColor.g === 0 && bgColor.b === 0) {
469
- findings.push({ id: 'pure-black-white', snippet: '#000000 background' });
470
- }
471
-
472
- if (hasDirectText && textColor && !isEmojiOnly) {
473
- // Run background-dependent checks against either a solid bg or, if the
474
- // ancestor is a gradient, against every gradient stop (use the worst case).
475
- const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
476
- if (bgs) {
477
- // Gray on colored background — flag if every stop is chromatic
478
- const textLum = relativeLuminance(textColor);
479
- const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
480
- if (isGray && bgs.every(b => hasChroma(b, 40))) {
481
- const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
482
- findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
483
- }
484
-
485
- // Low contrast (WCAG AA) — worst case across all bg stops
486
- const ratios = bgs.map(b => contrastRatio(textColor, b));
487
- let worstIdx = 0;
488
- for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
489
- const ratio = ratios[worstIdx];
490
- const isHeading = ['h1', 'h2', 'h3'].includes(tag);
491
- const isLargeText = fontSize >= 18 || (fontSize >= 14 && fontWeight >= 700) || isHeading;
492
- const threshold = isLargeText ? 3.0 : 4.5;
493
- if (ratio < threshold) {
494
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
495
- }
496
- }
497
-
498
- // AI palette: purple/violet on headings
499
- if (hasChroma(textColor, 50)) {
500
- const hue = getHue(textColor);
501
- if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
502
- findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
503
- }
504
- }
505
- }
506
-
507
- // Gradient text
508
- if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
509
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
510
- }
511
-
512
- // Tailwind class checks
513
- if (classList) {
514
- const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
515
- if (/\bbg-black\b(?!\/)/.test(classStr)) {
516
- findings.push({ id: 'pure-black-white', snippet: 'bg-black' });
517
- }
518
-
519
- const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
520
- const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
521
- if (grayMatch && colorBgMatch) {
522
- findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
523
- }
524
-
525
- if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
526
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
527
- }
528
-
529
- const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
530
- if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
531
- findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
532
- }
533
-
534
- if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
535
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
536
- }
537
- }
538
-
539
- return findings;
540
- }
541
-
542
- function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
543
- if (!hasShadow && !hasBorder) return false;
544
- return hasRadius || hasBg;
545
- }
546
-
547
- const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
548
-
549
- // Pure check: given a heading and metrics about its previousElementSibling,
550
- // decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
551
- //
552
- // Triggers when ALL of the following hold for the sibling:
553
- // • size 32–128px on both axes (not too small, not a hero image)
554
- // • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
555
- // • has a non-transparent background-color, background-image, OR a visible border
556
- // (covers solid colors, white-with-border, gradients — anything that visually
557
- // defines a tile)
558
- // • border-radius < width/2 (excludes round avatars; rounded squares pass)
559
- // • contains an <svg> or icon-class <i> element that's smaller than the tile
560
- // • the tile sits above the heading (its bottom is above the heading's top)
561
- function checkIconTile(opts) {
562
- const { headingTag, headingText, headingTop,
563
- siblingTag, siblingWidth, siblingHeight, siblingBottom,
564
- siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
565
- hasIconChild, iconChildWidth } = opts;
566
- if (!HEADING_TAGS.has(headingTag)) return [];
567
- if (!siblingTag) return [];
568
- // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
569
- if (HEADING_TAGS.has(siblingTag)) return [];
570
-
571
- // Size window: 32–128px on each axis
572
- if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
573
- if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
574
-
575
- // Squarish aspect ratio
576
- const ratio = siblingWidth / siblingHeight;
577
- if (ratio < 0.7 || ratio > 1.4) return [];
578
-
579
- // Must have something that visually defines the tile
580
- const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
581
- || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
582
- const borderVisible = siblingBorderWidth > 0;
583
- if (!bgVisible && !borderVisible) return [];
584
-
585
- // Exclude circles (avatars). Rounded squares pass.
586
- if (siblingBorderRadius >= siblingWidth / 2) return [];
587
-
588
- // Must contain an icon element smaller than the tile
589
- if (!hasIconChild) return [];
590
- if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
591
-
592
- // Vertical stacking: tile must end above where the heading starts.
593
- // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
594
- if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
595
-
596
- const text = (headingText || '').trim().slice(0, 60);
597
- return [{
598
- id: 'icon-tile-stack',
599
- snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
600
- }];
601
- }
602
-
603
- const LAYOUT_TRANSITION_PROPS = new Set([
604
- 'width', 'height', 'padding', 'margin',
605
- 'max-height', 'max-width', 'min-height', 'min-width',
606
- 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
607
- 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
608
- ]);
609
-
610
- function checkMotion(opts) {
611
- const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
612
- if (SAFE_TAGS.has(tag)) return [];
613
- const findings = [];
614
-
615
- // --- Bounce/elastic easing ---
616
- if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
617
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
618
- }
619
- if (classList && /\banimate-bounce\b/.test(classList)) {
620
- findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
621
- }
622
-
623
- // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
624
- if (timingFunctions) {
625
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
626
- let m;
627
- while ((m = bezierRe.exec(timingFunctions)) !== null) {
628
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
629
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
630
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
631
- break;
632
- }
633
- }
634
- }
635
-
636
- // --- Layout property transition ---
637
- if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
638
- const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
639
- const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
640
- if (layoutFound.length > 0) {
641
- findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
642
- }
643
- }
644
-
645
- return findings;
646
- }
647
-
648
- function checkGlow(opts) {
649
- const { boxShadow, effectiveBg } = opts;
650
- if (!boxShadow || boxShadow === 'none') return [];
651
- if (!effectiveBg) return [];
652
-
653
- // Only flag on dark backgrounds (luminance < 0.1)
654
- const bgLum = relativeLuminance(effectiveBg);
655
- if (bgLum >= 0.1) return [];
656
-
657
- // Split multiple shadows (commas not inside parentheses)
658
- const parts = boxShadow.split(/,(?![^(]*\))/);
659
- for (const shadow of parts) {
660
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
661
- if (!colorMatch) continue;
662
- const color = parseRgb(colorMatch[0]);
663
- if (!color || !hasChroma(color, 30)) continue;
664
-
665
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
666
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
667
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
668
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
669
- .map(m => parseFloat(m[1]));
670
-
671
- // Third value is blur (offset-x, offset-y, blur, [spread])
672
- if (pxVals.length >= 3 && pxVals[2] > 4) {
673
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
674
- }
675
- }
676
-
677
- return [];
678
- }
679
-
680
- /**
681
- * Regex-on-HTML checks shared between browser and Node page-level detection.
682
- * These don't need DOM access, just the raw HTML string.
683
- */
684
- function checkHtmlPatterns(html) {
685
- const findings = [];
686
-
687
- // --- Color ---
688
-
689
- // Pure black background
690
- const pureBlackBgRe = /background(?:-color)?\s*:\s*(?:#000000|#000|rgb\(\s*0,\s*0,\s*0\s*\))\b/gi;
691
- if (pureBlackBgRe.test(html)) {
692
- findings.push({ id: 'pure-black-white', snippet: 'Pure #000 background' });
693
- }
694
-
695
- // AI color palette: purple/violet
696
- const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
697
- if (purpleHexRe.test(html)) {
698
- const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
699
- if (purpleTextRe.test(html)) {
700
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
701
- }
702
- }
703
-
704
- // Gradient text (background-clip: text + gradient)
705
- const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
706
- let gm;
707
- while ((gm = gradientRe.exec(html)) !== null) {
708
- const start = Math.max(0, gm.index - 200);
709
- const context = html.substring(start, gm.index + gm[0].length + 200);
710
- if (/gradient/i.test(context)) {
711
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
712
- break;
713
- }
714
- }
715
- if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
716
- findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
717
- }
718
-
719
- // --- Layout ---
720
-
721
- // Monotonous spacing
722
- const spacingValues = [];
723
- const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
724
- let sm;
725
- while ((sm = spacingRe.exec(html)) !== null) {
726
- const v = parseInt(sm[1], 10);
727
- if (v > 0 && v < 200) spacingValues.push(v);
728
- }
729
- const gapRe = /gap\s*:\s*(\d+)px/gi;
730
- while ((sm = gapRe.exec(html)) !== null) {
731
- spacingValues.push(parseInt(sm[1], 10));
732
- }
733
- const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
734
- while ((sm = twSpaceRe.exec(html)) !== null) {
735
- spacingValues.push(parseInt(sm[1], 10) * 4);
736
- }
737
- const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
738
- while ((sm = remSpacingRe.exec(html)) !== null) {
739
- const v = Math.round(parseFloat(sm[1]) * 16);
740
- if (v > 0 && v < 200) spacingValues.push(v);
741
- }
742
- const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
743
- if (roundedSpacing.length >= 10) {
744
- const counts = {};
745
- for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
746
- const maxCount = Math.max(...Object.values(counts));
747
- const dominantPct = maxCount / roundedSpacing.length;
748
- const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
749
- if (dominantPct > 0.6 && unique.length <= 3) {
750
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
751
- findings.push({
752
- id: 'monotonous-spacing',
753
- snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
754
- });
755
- }
756
- }
757
-
758
- // --- Motion ---
759
-
760
- // Bounce/elastic animation names
761
- const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
762
- if (bounceRe.test(html)) {
763
- findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
764
- }
765
-
766
- // Overshoot cubic-bezier
767
- const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
768
- let bm;
769
- while ((bm = bezierRe.exec(html)) !== null) {
770
- const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
771
- if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
772
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
773
- break;
774
- }
775
- }
776
-
777
- // Layout property transitions
778
- const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
779
- let tm;
780
- while ((tm = transRe.exec(html)) !== null) {
781
- const val = tm[1].toLowerCase();
782
- if (/\ball\b/.test(val)) continue;
783
- const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
784
- if (found) {
785
- findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
786
- break;
787
- }
788
- }
789
-
790
- // --- Dark glow ---
791
-
792
- 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;
793
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
794
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
795
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
796
- let shm;
797
- while ((shm = shadowRe.exec(html)) !== null) {
798
- const val = shm[1];
799
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
800
- if (!colorMatch) continue;
801
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
802
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
803
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
804
- if (pxVals.length >= 3 && pxVals[2] > 4) {
805
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
806
- break;
807
- }
808
- }
809
- }
810
-
811
- return findings;
812
- }
813
-
814
- // ─── Section 4: resolveBackground (unified) ─────────────────────────────────
815
-
816
- function resolveBackground(el, win) {
817
- let current = el;
818
- while (current && current.nodeType === 1) {
819
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
820
-
821
- // If this element has a background-image (gradient or url), it's visually
822
- // opaque but we can't determine the effective color — bail out so callers
823
- // don't get a false solid-color answer.
824
- const bgImage = style.backgroundImage || '';
825
- if (bgImage && bgImage !== 'none' && (/gradient/i.test(bgImage) || /url\s*\(/i.test(bgImage))) {
826
- return null;
827
- }
828
-
829
- let bg = parseRgb(style.backgroundColor);
830
- if (!IS_BROWSER && (!bg || bg.a < 0.1)) {
831
- // jsdom doesn't decompose background shorthand — parse raw style attr
832
- const rawStyle = current.getAttribute?.('style') || '';
833
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
834
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
835
- // Check for gradient or url() image in inline style too
836
- if (/gradient/i.test(inlineBg) || /url\s*\(/i.test(inlineBg)) return null;
837
- bg = parseRgb(inlineBg);
838
- if (!bg && inlineBg) {
839
- const hexMatch = inlineBg.match(/#([0-9a-f]{6}|[0-9a-f]{3})\b/i);
840
- if (hexMatch) {
841
- const h = hexMatch[1];
842
- if (h.length === 6) {
843
- bg = { r: parseInt(h.slice(0,2), 16), g: parseInt(h.slice(2,4), 16), b: parseInt(h.slice(4,6), 16), a: 1 };
844
- } else {
845
- bg = { r: parseInt(h[0]+h[0], 16), g: parseInt(h[1]+h[1], 16), b: parseInt(h[2]+h[2], 16), a: 1 };
846
- }
847
- }
848
- }
849
- }
850
- if (bg && bg.a > 0.1) {
851
- if (IS_BROWSER || bg.a >= 0.5) return bg;
852
- }
853
- current = current.parentElement;
854
- }
855
- return { r: 255, g: 255, b: 255 };
856
- }
857
-
858
- // Walk parents looking for a gradient background and return its color stops.
859
- // Used as a fallback when resolveBackground() returns null because the
860
- // effective background is a gradient (no single solid color to compare against).
861
- function resolveGradientStops(el, win) {
862
- let current = el;
863
- while (current && current.nodeType === 1) {
864
- const style = IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
865
- const bgImage = style.backgroundImage || '';
866
- if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
867
- const stops = parseGradientColors(bgImage);
868
- if (stops.length > 0) return stops;
869
- }
870
- if (!IS_BROWSER) {
871
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
872
- const rawStyle = current.getAttribute?.('style') || '';
873
- const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
874
- if (bgMatch && /gradient/i.test(bgMatch[1])) {
875
- const stops = parseGradientColors(bgMatch[1]);
876
- if (stops.length > 0) return stops;
877
- }
878
- }
879
- current = current.parentElement;
880
- }
881
- return null;
882
- }
883
-
884
- // Parse a single CSS length token to pixels. Accepts "12px", "50%", a
885
- // shorthand like "12px 4px" (uses the first value), or empty / null.
886
- // Returns the pixel value, or null when the input is unparseable.
887
- // Percentages convert against `widthPx` when one is supplied. Without a
888
- // usable width (jsdom returns "auto" for many real-world elements,
889
- // which parseFloat collapses to 0), fall back to the raw percentage
890
- // number so callers gating on `> 0` (border-accent-on-rounded,
891
- // isCardLike's hasRadius) still see a positive value, matching the
892
- // original parseFloat("50%") === 50 behavior.
893
- function parseRadiusToPx(value, widthPx) {
894
- if (!value || typeof value !== 'string') return null;
895
- const trimmed = value.trim();
896
- if (!trimmed) return null;
897
- const first = trimmed.split(/\s+/)[0];
898
- const num = parseFloat(first);
899
- if (Number.isNaN(num)) return null;
900
- if (/%$/.test(first)) {
901
- if (widthPx && widthPx > 0) return (num / 100) * widthPx;
902
- return num;
903
- }
904
- return num;
905
- }
906
-
907
- // jsdom from 29.0.2 onward returns "" for the `border-radius` shorthand
908
- // in computed style and "0" for longhand reads when the source rule used
909
- // the shorthand. The rule engine relied on parseFloat(style.borderRadius)
910
- // to identify circular avatars (border-radius >= width/2) and rounded
911
- // cards (border-radius > 0); both checks broke silently. This helper
912
- // recovers the radius via a chain of fallbacks. Browsers resolve the
913
- // shorthand correctly and exit on the first line.
914
- function resolveBorderRadiusPx(el, style, widthPx, win) {
915
- const fromComputed = parseRadiusToPx(style.borderRadius, widthPx);
916
- if (fromComputed !== null) return fromComputed;
917
-
918
- if (IS_BROWSER || !win) return 0;
919
-
920
- const fromLonghand = parseRadiusToPx(style.borderTopLeftRadius, widthPx);
921
- if (fromLonghand !== null && fromLonghand > 0) return fromLonghand;
922
-
923
- const fromInlineProp = parseRadiusToPx(el.style?.borderRadius, widthPx);
924
- if (fromInlineProp !== null) return fromInlineProp;
925
-
926
- const rawStyle = el.getAttribute?.('style') || '';
927
- const inlineMatch = rawStyle.match(/border-radius\s*:\s*([^;]+)/i);
928
- if (inlineMatch) {
929
- const fromRaw = parseRadiusToPx(inlineMatch[1].trim(), widthPx);
930
- if (fromRaw !== null) return fromRaw;
931
- }
932
-
933
- // Walk every stylesheet looking for matching rules. Take the maximum
934
- // pixel value across all matches so a circle declaration overridden by
935
- // a more specific rounded-square selector still registers as a circle
936
- // for the exclusion check (better to under-flag than to false-positive
937
- // on round avatars).
938
- let max = 0;
939
- const sheets = win.document?.styleSheets;
940
- if (sheets) {
941
- for (const sheet of sheets) {
942
- let rules;
943
- try { rules = sheet.cssRules || []; } catch { continue; }
944
- for (const rule of rules) {
945
- if (!rule.style || !rule.selectorText) continue;
946
- let matches = false;
947
- try { matches = el.matches(rule.selectorText); } catch { continue; }
948
- if (!matches) continue;
949
- const ruleValue = rule.style.borderRadius
950
- || (rule.style.getPropertyValue && rule.style.getPropertyValue('border-radius'))
951
- || rule.style.borderTopLeftRadius;
952
- const px = parseRadiusToPx(ruleValue, widthPx);
953
- if (px !== null && px > max) max = px;
954
- }
955
- }
956
- }
957
- return max;
958
- }
959
-
960
- // ─── Section 5: Element Adapters ────────────────────────────────────────────
961
-
962
- // Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
963
-
964
- function checkElementBordersDOM(el) {
965
- const tag = el.tagName.toLowerCase();
966
- if (BORDER_SAFE_TAGS.has(tag)) return [];
967
- const rect = el.getBoundingClientRect();
968
- if (rect.width < 20 || rect.height < 20) return [];
969
- const style = getComputedStyle(el);
970
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
971
- const widths = {}, colors = {};
972
- for (const s of sides) {
973
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
974
- colors[s] = style[`border${s}Color`] || '';
975
- }
976
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
977
- }
978
-
979
- function checkElementColorsDOM(el) {
980
- const tag = el.tagName.toLowerCase();
981
- if (SAFE_TAGS.has(tag)) return [];
982
- const rect = el.getBoundingClientRect();
983
- if (rect.width < 10 || rect.height < 10) return [];
984
- const style = getComputedStyle(el);
985
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
986
- const hasDirectText = directText.trim().length > 0;
987
- const effectiveBg = resolveBackground(el);
988
- return checkColors({
989
- tag,
990
- textColor: parseRgb(style.color),
991
- bgColor: parseRgb(style.backgroundColor),
992
- effectiveBg,
993
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
994
- fontSize: parseFloat(style.fontSize) || 16,
995
- fontWeight: parseInt(style.fontWeight) || 400,
996
- hasDirectText,
997
- isEmojiOnly: isEmojiOnlyText(directText),
998
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
999
- bgImage: style.backgroundImage || '',
1000
- classList: el.getAttribute('class') || '',
1001
- });
1002
- }
1003
-
1004
- function checkElementIconTileDOM(el) {
1005
- const tag = el.tagName.toLowerCase();
1006
- if (!HEADING_TAGS.has(tag)) return [];
1007
- const sibling = el.previousElementSibling;
1008
- if (!sibling) return [];
1009
-
1010
- const sibRect = sibling.getBoundingClientRect();
1011
- const headRect = el.getBoundingClientRect();
1012
- const sibStyle = getComputedStyle(sibling);
1013
-
1014
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
1015
- // may contain an emoji/symbol character directly as its only text content
1016
- // (the "card-icon" pattern from many AI-generated demos).
1017
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
1018
- const iconRect = iconChild?.getBoundingClientRect();
1019
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1020
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
1021
-
1022
- return checkIconTile({
1023
- headingTag: tag,
1024
- headingText: el.textContent || '',
1025
- headingTop: headRect.top,
1026
- siblingTag: sibling.tagName.toLowerCase(),
1027
- siblingWidth: sibRect.width,
1028
- siblingHeight: sibRect.height,
1029
- siblingBottom: sibRect.bottom,
1030
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
1031
- siblingBgImage: sibStyle.backgroundImage || '',
1032
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
1033
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
1034
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
1035
- iconChildWidth: iconRect?.width || 0,
1036
- });
1037
- }
1038
-
1039
- function checkElementMotionDOM(el) {
1040
- const tag = el.tagName.toLowerCase();
1041
- if (SAFE_TAGS.has(tag)) return [];
1042
- const style = getComputedStyle(el);
1043
- return checkMotion({
1044
- tag,
1045
- transitionProperty: style.transitionProperty || '',
1046
- animationName: style.animationName || '',
1047
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
1048
- classList: el.getAttribute('class') || '',
1049
- });
1050
- }
1051
-
1052
- function checkElementGlowDOM(el) {
1053
- const tag = el.tagName.toLowerCase();
1054
- const style = getComputedStyle(el);
1055
- if (!style.boxShadow || style.boxShadow === 'none') return [];
1056
- // Use parent's background — glow radiates outward, so the surrounding context matters
1057
- // If resolveBackground returns null (gradient), try to infer from the gradient colors
1058
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
1059
- if (!parentBg) {
1060
- // Gradient background — sample its colors to determine if it's dark
1061
- let cur = el.parentElement;
1062
- while (cur && cur.nodeType === 1) {
1063
- const bgImage = getComputedStyle(cur).backgroundImage || '';
1064
- const gradColors = parseGradientColors(bgImage);
1065
- if (gradColors.length > 0) {
1066
- // Average the gradient colors
1067
- const avg = { r: 0, g: 0, b: 0 };
1068
- for (const c of gradColors) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
1069
- avg.r = Math.round(avg.r / gradColors.length);
1070
- avg.g = Math.round(avg.g / gradColors.length);
1071
- avg.b = Math.round(avg.b / gradColors.length);
1072
- parentBg = avg;
1073
- break;
1074
- }
1075
- cur = cur.parentElement;
1076
- }
1077
- }
1078
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
1079
- }
1080
-
1081
- function checkElementAIPaletteDOM(el) {
1082
- const style = getComputedStyle(el);
1083
- const findings = [];
1084
-
1085
- // Check gradient backgrounds for purple/violet or cyan
1086
- const bgImage = style.backgroundImage || '';
1087
- const gradColors = parseGradientColors(bgImage);
1088
- for (const c of gradColors) {
1089
- if (hasChroma(c, 50)) {
1090
- const hue = getHue(c);
1091
- if (hue >= 260 && hue <= 310) {
1092
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient background' });
1093
- break;
1094
- }
1095
- if (hue >= 160 && hue <= 200) {
1096
- findings.push({ id: 'ai-color-palette', snippet: 'Cyan gradient background' });
1097
- break;
1098
- }
1099
- }
1100
- }
1101
-
1102
- // Check for neon text (vivid cyan/purple color on dark background)
1103
- const textColor = parseRgb(style.color);
1104
- if (textColor && hasChroma(textColor, 80)) {
1105
- const hue = getHue(textColor);
1106
- const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
1107
- if (isAIPalette) {
1108
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
1109
- // Also check gradient parents
1110
- let effectiveBg = parentBg;
1111
- if (!effectiveBg) {
1112
- let cur = el.parentElement;
1113
- while (cur && cur.nodeType === 1) {
1114
- const gi = getComputedStyle(cur).backgroundImage || '';
1115
- const gc = parseGradientColors(gi);
1116
- if (gc.length > 0) {
1117
- const avg = { r: 0, g: 0, b: 0 };
1118
- for (const c of gc) { avg.r += c.r; avg.g += c.g; avg.b += c.b; }
1119
- avg.r = Math.round(avg.r / gc.length);
1120
- avg.g = Math.round(avg.g / gc.length);
1121
- avg.b = Math.round(avg.b / gc.length);
1122
- effectiveBg = avg;
1123
- break;
1124
- }
1125
- cur = cur.parentElement;
1126
- }
1127
- }
1128
- if (effectiveBg && relativeLuminance(effectiveBg) < 0.1) {
1129
- const label = hue >= 260 ? 'Purple/violet' : 'Cyan';
1130
- findings.push({ id: 'ai-color-palette', snippet: `${label} neon text on dark background` });
1131
- }
1132
- }
1133
- }
1134
-
1135
- return findings;
1136
- }
1137
-
1138
- const QUALITY_TEXT_TAGS = new Set(['p', 'li', 'td', 'th', 'dd', 'blockquote', 'figcaption']);
1139
-
1140
- // Resolve a CSS font-size value to pixels by walking up the parent chain.
1141
- // Browsers resolve em/rem/% to px in getComputedStyle, but jsdom returns the
1142
- // specified value verbatim — so for the Node path we walk parents ourselves.
1143
- function resolveFontSizePx(el, win) {
1144
- const chain = []; // raw font-size strings, leaf → root
1145
- let cur = el;
1146
- while (cur && cur.nodeType === 1) {
1147
- const fs = (win ? win.getComputedStyle(cur) : getComputedStyle(cur)).fontSize;
1148
- chain.push(fs || '');
1149
- cur = cur.parentElement;
1150
- }
1151
- // Walk root → leaf, resolving each value relative to its parent context.
1152
- let px = 16; // root default
1153
- for (let i = chain.length - 1; i >= 0; i--) {
1154
- const v = chain[i];
1155
- if (!v || v === 'inherit') continue;
1156
- const num = parseFloat(v);
1157
- if (isNaN(num)) continue;
1158
- if (v.endsWith('px')) px = num;
1159
- else if (v.endsWith('rem')) px = num * 16;
1160
- else if (v.endsWith('em')) px = num * px;
1161
- else if (v.endsWith('%')) px = (num / 100) * px;
1162
- else px = num; // unitless — already resolved
1163
- }
1164
- return px;
1165
- }
1166
-
1167
- // Resolve a CSS length value (line-height, letter-spacing, etc.) given a
1168
- // known font-size context. Returns null for "normal" / unparseable values.
1169
- function resolveLengthPx(value, fontSizePx) {
1170
- if (!value || value === 'normal' || value === 'auto' || value === 'inherit') return null;
1171
- const num = parseFloat(value);
1172
- if (isNaN(num)) return null;
1173
- if (value.endsWith('px')) return num;
1174
- if (value.endsWith('rem')) return num * 16;
1175
- if (value.endsWith('em')) return num * fontSizePx;
1176
- if (value.endsWith('%')) return (num / 100) * fontSizePx;
1177
- // Unitless line-height = multiplier, return px equivalent
1178
- return num * fontSizePx;
1179
- }
1180
-
1181
- // Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
1182
- // jsdom and the browser). Two checks (line-length, cramped-padding) gate on
1183
- // element rect dimensions, which jsdom can't compute — pass `rect: null` from
1184
- // the Node adapter to skip those.
1185
- //
1186
- // Both adapters resolve font-size, line-height and letter-spacing to pixels
1187
- // before calling this so the pure function only deals with numbers.
1188
- function checkQuality(opts) {
1189
- const { el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax = 80 } = opts;
1190
- const findings = [];
1191
- // Skip browser extension injected elements
1192
- const elId = el.id || '';
1193
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) return findings;
1194
-
1195
- // --- Line length too long --- (browser-only: needs rect.width)
1196
- if (rect && hasDirectText && QUALITY_TEXT_TAGS.has(tag) && rect.width > 0 && textLen > lineMax) {
1197
- const charsPerLine = rect.width / (fontSize * 0.5);
1198
- if (charsPerLine > lineMax + 5) {
1199
- findings.push({ id: 'line-length', snippet: `~${Math.round(charsPerLine)} chars/line (aim for <${lineMax})` });
1200
- }
1201
- }
1202
-
1203
- // --- Cramped padding --- (browser-only: needs rect to skip small badges/labels)
1204
- // Vertical and horizontal thresholds are independent because line-height
1205
- // already provides built-in vertical breathing room (the line box is taller
1206
- // than the cap height), but horizontal has no equivalent. Both scale with
1207
- // font-size — bigger text demands proportionally more padding.
1208
- // vertical: max(4px, fontSize × 0.3)
1209
- // horizontal: max(8px, fontSize × 0.5)
1210
- if (rect && hasDirectText && textLen > 20 && rect.width > 100 && rect.height > 30) {
1211
- const borders = {
1212
- top: parseFloat(style.borderTopWidth) || 0,
1213
- right: parseFloat(style.borderRightWidth) || 0,
1214
- bottom: parseFloat(style.borderBottomWidth) || 0,
1215
- left: parseFloat(style.borderLeftWidth) || 0,
1216
- };
1217
- const borderCount = Object.values(borders).filter(w => w > 0).length;
1218
- const hasBg = style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)';
1219
- if (borderCount >= 2 || hasBg) {
1220
- const vPads = [], hPads = [];
1221
- if (hasBg || borders.top > 0) vPads.push(parseFloat(style.paddingTop) || 0);
1222
- if (hasBg || borders.bottom > 0) vPads.push(parseFloat(style.paddingBottom) || 0);
1223
- if (hasBg || borders.left > 0) hPads.push(parseFloat(style.paddingLeft) || 0);
1224
- if (hasBg || borders.right > 0) hPads.push(parseFloat(style.paddingRight) || 0);
1225
-
1226
- const vMin = vPads.length ? Math.min(...vPads) : Infinity;
1227
- const hMin = hPads.length ? Math.min(...hPads) : Infinity;
1228
- const vThresh = Math.max(4, fontSize * 0.3);
1229
- const hThresh = Math.max(8, fontSize * 0.5);
1230
-
1231
- // Emit at most one finding per element — pick whichever axis is worse.
1232
- if (vMin < vThresh) {
1233
- findings.push({ id: 'cramped-padding', snippet: `${vMin}px vertical padding (need ≥${vThresh.toFixed(1)}px for ${fontSize}px text)` });
1234
- } else if (hMin < hThresh) {
1235
- findings.push({ id: 'cramped-padding', snippet: `${hMin}px horizontal padding (need ≥${hThresh.toFixed(1)}px for ${fontSize}px text)` });
1236
- }
1237
- }
1238
- }
1239
-
1240
- // --- Tight line height ---
1241
- if (hasDirectText && textLen > 50 && !['h1','h2','h3','h4','h5','h6'].includes(tag)) {
1242
- if (lineHeightPx != null && fontSize > 0) {
1243
- const ratio = lineHeightPx / fontSize;
1244
- if (ratio > 0 && ratio < 1.3) {
1245
- findings.push({ id: 'tight-leading', snippet: `line-height ${ratio.toFixed(2)}x (need >=1.3)` });
1246
- }
1247
- }
1248
- }
1249
-
1250
- // --- Justified text (without hyphens) ---
1251
- if (hasDirectText && style.textAlign === 'justify') {
1252
- const hyphens = style.hyphens || style.webkitHyphens || '';
1253
- if (hyphens !== 'auto') {
1254
- findings.push({ id: 'justified-text', snippet: 'text-align: justify without hyphens: auto' });
1255
- }
1256
- }
1257
-
1258
- // --- Tiny body text ---
1259
- // Only flag actual body content, not UI labels (buttons, tabs, badges, captions, footer text, etc.)
1260
- if (hasDirectText && textLen > 20 && fontSize < 12) {
1261
- const skipTags = ['sub', 'sup', 'code', 'kbd', 'samp', 'var', 'caption', 'figcaption'];
1262
- const inUIContext = el.closest && el.closest('button, a, label, summary, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], nav, footer, [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="label" i], [class*="caption" i]');
1263
- const isUppercase = style.textTransform === 'uppercase';
1264
- if (!skipTags.includes(tag) && !inUIContext && !isUppercase) {
1265
- findings.push({ id: 'tiny-text', snippet: `${fontSize}px body text` });
1266
- }
1267
- }
1268
-
1269
- // --- All-caps body text ---
1270
- if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
1271
- if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
1272
- findings.push({ id: 'all-caps-body', snippet: `text-transform: uppercase on ${textLen} chars of body text` });
1273
- }
1274
- }
1275
-
1276
- // --- Wide letter spacing on body text ---
1277
- if (hasDirectText && textLen > 20 && style.textTransform !== 'uppercase') {
1278
- if (letterSpacingPx != null && letterSpacingPx > 0 && fontSize > 0) {
1279
- const trackingEm = letterSpacingPx / fontSize;
1280
- if (trackingEm > 0.05) {
1281
- findings.push({ id: 'wide-tracking', snippet: `letter-spacing: ${trackingEm.toFixed(2)}em on body text` });
1282
- }
1283
- }
1284
- }
1285
-
1286
- return findings;
1287
- }
1288
-
1289
- function checkElementQualityDOM(el) {
1290
- const tag = el.tagName.toLowerCase();
1291
- const style = getComputedStyle(el);
1292
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
1293
- const textLen = el.textContent?.trim().length || 0;
1294
- // Browser getComputedStyle resolves everything to px — direct parseFloat
1295
- // works.
1296
- const fontSize = parseFloat(style.fontSize) || 16;
1297
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1298
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1299
- const rect = el.getBoundingClientRect();
1300
- const lineMax = (typeof window !== 'undefined' && window.__IMPECCABLE_CONFIG__?.lineLengthMax) || 80;
1301
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect, lineMax });
1302
- }
1303
-
1304
- // Pure page-level skipped-heading walk. Takes a Document so it works in both
1305
- // the browser and jsdom.
1306
- function checkPageQualityFromDoc(doc) {
1307
- const findings = [];
1308
- const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
1309
- let prevLevel = 0;
1310
- let prevText = '';
1311
- for (const h of headings) {
1312
- const level = parseInt(h.tagName[1]);
1313
- const text = (h.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 60);
1314
- if (prevLevel > 0 && level > prevLevel + 1) {
1315
- findings.push({
1316
- id: 'skipped-heading',
1317
- snippet: `<h${prevLevel}> "${prevText}" followed by <h${level}> "${text}" (missing h${prevLevel + 1})`,
1318
- });
1319
- }
1320
- prevLevel = level;
1321
- prevText = text;
1322
- }
1323
- return findings;
1324
- }
1325
-
1326
- // Browser adapter (returns the legacy { type, detail } shape used by the overlay loop)
1327
- function checkPageQualityDOM() {
1328
- return checkPageQualityFromDoc(document).map(f => ({ type: f.id, detail: f.snippet }));
1329
- }
1330
-
1331
- // Node adapters — take pre-extracted jsdom computed style
1332
-
1333
- // jsdom doesn't lay out OR resolve em/rem/% to px — so we pre-resolve every
1334
- // CSS length the rule needs ourselves (walking the parent chain for
1335
- // font-size inheritance), and pass `rect: null` to skip the two rules that
1336
- // genuinely need element rects (line-length, cramped-padding).
1337
- function checkElementQuality(el, style, tag, window) {
1338
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 10);
1339
- const textLen = el.textContent?.trim().length || 0;
1340
- const fontSize = resolveFontSizePx(el, window);
1341
- const lineHeightPx = resolveLengthPx(style.lineHeight, fontSize);
1342
- const letterSpacingPx = resolveLengthPx(style.letterSpacing, fontSize);
1343
- return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null });
1344
- }
1345
-
1346
- function checkElementBorders(tag, style, overrides, resolvedRadius) {
1347
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
1348
- const widths = {}, colors = {};
1349
- for (const s of sides) {
1350
- widths[s] = parseFloat(style[`border${s}Width`]) || 0;
1351
- colors[s] = style[`border${s}Color`] || '';
1352
- // jsdom silently drops any border shorthand containing var(), leaving
1353
- // both width and color empty on the computed style. When the detectHtml
1354
- // pre-pass pulled a resolved value off the rule, use it to fill in the
1355
- // missing side so the side-tab check can run. Real browsers resolve
1356
- // var() natively, so this fallback is a no-op in the browser path.
1357
- if (widths[s] === 0 && overrides && overrides[s]) {
1358
- widths[s] = overrides[s].width;
1359
- colors[s] = overrides[s].color;
1360
- } else if (colors[s] && colors[s].startsWith('var(') && overrides && overrides[s]) {
1361
- // Longhand case: jsdom kept the width but left the color as the
1362
- // literal `var(...)` string. Substitute the resolved color.
1363
- colors[s] = overrides[s].color;
1364
- }
1365
- }
1366
- // resolvedRadius lets the caller pre-resolve the radius via
1367
- // resolveBorderRadiusPx so the value survives jsdom 29.1.0's broken
1368
- // shorthand serialization. Falls back to the computed value for tests
1369
- // and browser callers that don't pre-resolve.
1370
- const radius = resolvedRadius != null
1371
- ? resolvedRadius
1372
- : (parseFloat(style.borderRadius) || 0);
1373
- return checkBorders(tag, widths, colors, radius);
1374
- }
1375
-
1376
- function checkElementColors(el, style, tag, window) {
1377
- const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1378
- const hasDirectText = directText.trim().length > 0;
1379
-
1380
- const effectiveBg = resolveBackground(el, window);
1381
- return checkColors({
1382
- tag,
1383
- textColor: parseRgb(style.color),
1384
- bgColor: parseRgb(style.backgroundColor),
1385
- effectiveBg,
1386
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
1387
- fontSize: parseFloat(style.fontSize) || 16,
1388
- fontWeight: parseInt(style.fontWeight) || 400,
1389
- hasDirectText,
1390
- isEmojiOnly: isEmojiOnlyText(directText),
1391
- bgClip: style.webkitBackgroundClip || style.backgroundClip || '',
1392
- bgImage: style.backgroundImage || '',
1393
- classList: el.getAttribute?.('class') || el.className || '',
1394
- });
1395
- }
1396
-
1397
- function checkElementIconTile(el, tag, window) {
1398
- if (!HEADING_TAGS.has(tag)) return [];
1399
- const sibling = el.previousElementSibling;
1400
- if (!sibling) return [];
1401
-
1402
- const sibStyle = window.getComputedStyle(sibling);
1403
- // jsdom doesn't lay out — read explicit pixel dimensions from CSS instead.
1404
- const sibWidth = parseFloat(sibStyle.width) || 0;
1405
- const sibHeight = parseFloat(sibStyle.height) || 0;
1406
-
1407
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
1408
- let iconWidth = 0;
1409
- if (iconChild) {
1410
- const iconStyle = window.getComputedStyle(iconChild);
1411
- iconWidth = parseFloat(iconStyle.width) || parseFloat(iconChild.getAttribute('width')) || 0;
1412
- }
1413
- // Or: tile contains an emoji/symbol character directly as its only content
1414
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1415
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
1416
-
1417
- return checkIconTile({
1418
- headingTag: tag,
1419
- headingText: el.textContent || '',
1420
- headingTop: 0, // jsdom: no layout, skip vertical-stacking gate
1421
- siblingTag: sibling.tagName.toLowerCase(),
1422
- siblingWidth: sibWidth,
1423
- siblingHeight: sibHeight,
1424
- siblingBottom: 0,
1425
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
1426
- siblingBgImage: sibStyle.backgroundImage || '',
1427
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
1428
- siblingBorderRadius: resolveBorderRadiusPx(sibling, sibStyle, sibWidth, window),
1429
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
1430
- iconChildWidth: iconWidth,
1431
- });
1432
- }
1433
-
1434
- function checkElementMotion(tag, style) {
1435
- return checkMotion({
1436
- tag,
1437
- transitionProperty: style.transitionProperty || '',
1438
- animationName: style.animationName || '',
1439
- timingFunctions: [style.animationTimingFunction, style.transitionTimingFunction].filter(Boolean).join(' '),
1440
- classList: '',
1441
- });
1442
- }
1443
-
1444
- function checkElementGlow(tag, style, effectiveBg) {
1445
- if (!style.boxShadow || style.boxShadow === 'none') return [];
1446
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
1447
- }
1448
-
1449
- // ─── Section 6: Page-Level Checks ───────────────────────────────────────────
1450
-
1451
- // Browser page-level checks — use document/getComputedStyle globals
1452
-
1453
- function checkTypography() {
1454
- const findings = [];
1455
-
1456
- // Walk actual text-bearing elements and tally font usage by *computed style*.
1457
- // This is much more accurate than scanning CSS rules — it ignores rules that
1458
- // exist in the stylesheet but apply to nothing (e.g. demo classes showing
1459
- // anti-patterns), and counts what the user actually sees.
1460
- const fontUsage = new Map(); // primary font name → count of elements
1461
- let totalTextElements = 0;
1462
- for (const el of document.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, td, th, dd, blockquote, figcaption, a, button, label, span')) {
1463
- // Skip impeccable's own elements
1464
- if (el.closest && el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
1465
- // Only count elements that actually have visible direct text
1466
- const hasText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length > 0);
1467
- if (!hasText) continue;
1468
- const style = getComputedStyle(el);
1469
- const ff = style.fontFamily;
1470
- if (!ff) continue;
1471
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
1472
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
1473
- if (!primary) continue;
1474
- fontUsage.set(primary, (fontUsage.get(primary) || 0) + 1);
1475
- totalTextElements++;
1476
- }
1477
-
1478
- if (totalTextElements >= 20) {
1479
- // A font is "primary" if it's used by at least 15% of text elements
1480
- const PRIMARY_THRESHOLD = 0.15;
1481
- for (const [font, count] of fontUsage) {
1482
- const share = count / totalTextElements;
1483
- if (share < PRIMARY_THRESHOLD) continue;
1484
- if (!OVERUSED_FONTS.has(font)) continue;
1485
- if (isBrandFontOnOwnDomain(font)) continue;
1486
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
1487
- }
1488
-
1489
- // Single-font check: only one distinct primary font across all text
1490
- if (fontUsage.size === 1) {
1491
- const only = [...fontUsage.keys()][0];
1492
- findings.push({ type: 'single-font', detail: `only font used is ${only}` });
1493
- }
1494
- }
1495
-
1496
- const sizes = new Set();
1497
- for (const el of document.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,a,li,td,th,label,button,div')) {
1498
- const fs = parseFloat(getComputedStyle(el).fontSize);
1499
- if (fs > 0 && fs < 200) sizes.add(Math.round(fs * 10) / 10);
1500
- }
1501
- if (sizes.size >= 3) {
1502
- const sorted = [...sizes].sort((a, b) => a - b);
1503
- const ratio = sorted[sorted.length - 1] / sorted[0];
1504
- if (ratio < 2.0) {
1505
- findings.push({ type: 'flat-type-hierarchy', detail: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
1506
- }
1507
- }
1508
-
1509
- return findings;
1510
- }
1511
-
1512
- function isCardLikeDOM(el) {
1513
- const tag = el.tagName.toLowerCase();
1514
- if (SAFE_TAGS.has(tag) || ['input','select','textarea','img','video','canvas','picture'].includes(tag)) return false;
1515
- const style = getComputedStyle(el);
1516
- const cls = el.getAttribute('class') || '';
1517
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') || /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls);
1518
- const hasBorder = /\bborder\b/.test(cls);
1519
- const hasRadius = parseFloat(style.borderRadius) > 0 || /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls);
1520
- const hasBg = (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') || /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls);
1521
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
1522
- }
1523
-
1524
- function checkLayout() {
1525
- const findings = [];
1526
- const flaggedEls = new Set();
1527
-
1528
- for (const el of document.querySelectorAll('*')) {
1529
- if (!isCardLikeDOM(el) || flaggedEls.has(el)) continue;
1530
- const cls = el.getAttribute('class') || '';
1531
- const style = getComputedStyle(el);
1532
- if (style.position === 'absolute' || style.position === 'fixed') continue;
1533
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
1534
- if ((el.textContent?.trim().length || 0) < 10) continue;
1535
- const rect = el.getBoundingClientRect();
1536
- if (rect.width < 50 || rect.height < 30) continue;
1537
-
1538
- let parent = el.parentElement;
1539
- while (parent) {
1540
- if (isCardLikeDOM(parent)) { flaggedEls.add(el); break; }
1541
- parent = parent.parentElement;
1542
- }
1543
- }
1544
-
1545
- for (const el of flaggedEls) {
1546
- let isAncestor = false;
1547
- for (const other of flaggedEls) {
1548
- if (other !== el && el.contains(other)) { isAncestor = true; break; }
1549
- }
1550
- if (!isAncestor) findings.push({ type: 'nested-cards', detail: 'Card inside card', el });
1551
- }
1552
-
1553
- return findings;
1554
- }
1555
-
1556
- // Node page-level checks — take document/window as parameters
1557
-
1558
- function checkPageTypography(doc, win) {
1559
- const findings = [];
1560
-
1561
- const fonts = new Set();
1562
- const overusedFound = new Set();
1563
-
1564
- for (const sheet of doc.styleSheets) {
1565
- let rules;
1566
- try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
1567
- if (!rules) continue;
1568
- for (const rule of rules) {
1569
- if (rule.type !== 1) continue;
1570
- const ff = rule.style?.fontFamily;
1571
- if (!ff) continue;
1572
- const stack = ff.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
1573
- const primary = stack.find(f => f && !GENERIC_FONTS.has(f));
1574
- if (primary) {
1575
- fonts.add(primary);
1576
- if (OVERUSED_FONTS.has(primary)) overusedFound.add(primary);
1577
- }
1578
- }
1579
- }
1580
-
1581
- // Check Google Fonts links in HTML
1582
- const html = doc.documentElement?.outerHTML || '';
1583
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
1584
- let m;
1585
- while ((m = gfRe.exec(html)) !== null) {
1586
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
1587
- for (const f of families) {
1588
- fonts.add(f);
1589
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
1590
- }
1591
- }
1592
-
1593
- // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
1594
- const ffRe = /font-family\s*:\s*([^;}]+)/gi;
1595
- let fm;
1596
- while ((fm = ffRe.exec(html)) !== null) {
1597
- for (const f of fm[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
1598
- if (f && !GENERIC_FONTS.has(f)) {
1599
- fonts.add(f);
1600
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
1601
- }
1602
- }
1603
- }
1604
-
1605
- for (const font of overusedFound) {
1606
- findings.push({ id: 'overused-font', snippet: `Primary font: ${font}` });
1607
- }
1608
-
1609
- // Single font
1610
- if (fonts.size === 1) {
1611
- const els = doc.querySelectorAll('*');
1612
- if (els.length >= 20) {
1613
- findings.push({ id: 'single-font', snippet: `only font used is ${[...fonts][0]}` });
1614
- }
1615
- }
1616
-
1617
- // Flat type hierarchy
1618
- const sizes = new Set();
1619
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, a, li, td, th, label, button, div');
1620
- for (const el of textEls) {
1621
- const fontSize = parseFloat(win.getComputedStyle(el).fontSize);
1622
- // Filter out sub-8px values (jsdom doesn't resolve relative units properly)
1623
- if (fontSize >= 8 && fontSize < 200) sizes.add(Math.round(fontSize * 10) / 10);
1624
- }
1625
- if (sizes.size >= 3) {
1626
- const sorted = [...sizes].sort((a, b) => a - b);
1627
- const ratio = sorted[sorted.length - 1] / sorted[0];
1628
- if (ratio < 2.0) {
1629
- findings.push({ id: 'flat-type-hierarchy', snippet: `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)` });
1630
- }
1631
- }
1632
-
1633
- return findings;
1634
- }
1635
-
1636
- function isCardLike(el, win) {
1637
- const tag = el.tagName.toLowerCase();
1638
- if (SAFE_TAGS.has(tag) || ['input', 'select', 'textarea', 'img', 'video', 'canvas', 'picture'].includes(tag)) return false;
1639
-
1640
- const style = win.getComputedStyle(el);
1641
- const rawStyle = el.getAttribute?.('style') || '';
1642
- const cls = el.getAttribute?.('class') || '';
1643
-
1644
- const hasShadow = (style.boxShadow && style.boxShadow !== 'none') ||
1645
- /\bshadow(?:-sm|-md|-lg|-xl|-2xl)?\b/.test(cls) || /box-shadow/i.test(rawStyle);
1646
- const hasBorder = /\bborder\b/.test(cls);
1647
- const widthPx = parseFloat(style.width) || 0;
1648
- const hasRadius = resolveBorderRadiusPx(el, style, widthPx, win) > 0 ||
1649
- /\brounded(?:-sm|-md|-lg|-xl|-2xl|-full)?\b/.test(cls) || /border-radius/i.test(rawStyle);
1650
- const hasBg = /\bbg-(?:white|gray-\d+|slate-\d+)\b/.test(cls) ||
1651
- /background(?:-color)?\s*:\s*(?!transparent)/i.test(rawStyle);
1652
-
1653
- return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
1654
- }
1655
-
1656
- function checkPageLayout(doc, win) {
1657
- const findings = [];
1658
-
1659
- // Nested cards
1660
- const allEls = doc.querySelectorAll('*');
1661
- const flaggedEls = new Set();
1662
- for (const el of allEls) {
1663
- if (!isCardLike(el, win)) continue;
1664
- if (flaggedEls.has(el)) continue;
1665
-
1666
- const tag = el.tagName.toLowerCase();
1667
- const cls = el.getAttribute?.('class') || '';
1668
- const rawStyle = el.getAttribute?.('style') || '';
1669
-
1670
- if (['pre', 'code'].includes(tag)) continue;
1671
- if (/\b(?:absolute|fixed)\b/.test(cls) || /position\s*:\s*(?:absolute|fixed)/i.test(rawStyle)) continue;
1672
- if ((el.textContent?.trim().length || 0) < 10) continue;
1673
- if (/\b(?:dropdown|popover|tooltip|menu|modal|dialog)\b/i.test(cls)) continue;
1674
-
1675
- // Walk up to find card-like ancestor
1676
- let parent = el.parentElement;
1677
- while (parent) {
1678
- if (isCardLike(parent, win)) {
1679
- flaggedEls.add(el);
1680
- break;
1681
- }
1682
- parent = parent.parentElement;
1683
- }
1684
- }
1685
-
1686
- // Only report innermost nested cards
1687
- for (const el of flaggedEls) {
1688
- let isAncestorOfFlagged = false;
1689
- for (const other of flaggedEls) {
1690
- if (other !== el && el.contains(other)) {
1691
- isAncestorOfFlagged = true;
1692
- break;
1693
- }
1694
- }
1695
- if (!isAncestorOfFlagged) {
1696
- findings.push({ id: 'nested-cards', snippet: `Card inside card (${el.tagName.toLowerCase()})` });
1697
- }
1698
- }
1699
-
1700
- // Everything centered
1701
- const textEls = doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, div, button');
1702
- let centeredCount = 0;
1703
- let totalText = 0;
1704
- for (const el of textEls) {
1705
- const hasDirectText = [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim().length >= 3);
1706
- if (!hasDirectText) continue;
1707
- totalText++;
1708
-
1709
- let cur = el;
1710
- let isCentered = false;
1711
- while (cur && cur.nodeType === 1) {
1712
- const rawStyle = cur.getAttribute?.('style') || '';
1713
- const cls = cur.getAttribute?.('class') || '';
1714
- if (/text-align\s*:\s*center/i.test(rawStyle) || /\btext-center\b/.test(cls)) {
1715
- isCentered = true;
1716
- break;
1717
- }
1718
- if (cur.tagName === 'BODY') break;
1719
- cur = cur.parentElement;
1720
- }
1721
- if (isCentered) centeredCount++;
1722
- }
1723
-
1724
- if (totalText >= 5 && centeredCount / totalText > 0.7) {
1725
- findings.push({
1726
- id: 'everything-centered',
1727
- snippet: `${centeredCount}/${totalText} text elements centered (${Math.round(centeredCount / totalText * 100)}%)`,
1728
- });
1729
- }
1730
-
1731
- return findings;
1732
- }
1733
-
1734
- // ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
1735
-
1736
- if (IS_BROWSER) {
1737
- // Detect extension mode via the script tag's data attribute or the document element fallback.
1738
- // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
1739
- const _myScript = document.currentScript;
1740
- const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
1741
- || document.documentElement.dataset.impeccableExtension === 'true';
1742
-
1743
- const BRAND_COLOR = 'oklch(55% 0.25 350)';
1744
- const BRAND_COLOR_HOVER = 'oklch(45% 0.25 350)';
1745
- const LABEL_BG = BRAND_COLOR;
1746
- const OUTLINE_COLOR = BRAND_COLOR;
1747
-
1748
- // Inject hover styles via CSS (more reliable than JS event listeners)
1749
- const styleEl = document.createElement('style');
1750
- styleEl.textContent = `
1751
- @keyframes impeccable-reveal {
1752
- from { opacity: 0; }
1753
- to { opacity: 1; }
1754
- }
1755
- .impeccable-overlay:not(.impeccable-banner) {
1756
- pointer-events: none;
1757
- outline: 2px solid ${OUTLINE_COLOR};
1758
- border-radius: 4px;
1759
- transition: outline-color 0.15s ease;
1760
- animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
1761
- animation-play-state: paused;
1762
- border-top-left-radius: 0;
1763
- }
1764
- .impeccable-overlay.impeccable-visible {
1765
- animation-play-state: running;
1766
- }
1767
- .impeccable-overlay.impeccable-hover {
1768
- outline-color: ${BRAND_COLOR_HOVER};
1769
- z-index: 100001 !important;
1770
- }
1771
- .impeccable-overlay.impeccable-hover .impeccable-label {
1772
- background: ${BRAND_COLOR_HOVER};
1773
- }
1774
- .impeccable-overlay.impeccable-spotlight {
1775
- z-index: 100002 !important;
1776
- }
1777
- .impeccable-overlay.impeccable-spotlight-dimmed {
1778
- opacity: 0.15 !important;
1779
- animation: none !important;
1780
- filter: blur(3px);
1781
- }
1782
- .impeccable-spotlight-backdrop {
1783
- position: fixed;
1784
- top: 0; left: 0; right: 0; bottom: 0;
1785
- backdrop-filter: blur(3px) brightness(0.6);
1786
- -webkit-backdrop-filter: blur(3px) brightness(0.6);
1787
- pointer-events: none;
1788
- z-index: 99998;
1789
- opacity: 0;
1790
- outline: none !important;
1791
- animation: none !important;
1792
- }
1793
- .impeccable-spotlight-backdrop.impeccable-visible {
1794
- opacity: 1;
1795
- }
1796
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
1797
- display: none !important;
1798
- }
1799
- .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
1800
- display: none !important;
1801
- }
1802
- `;
1803
- (document.head || document.documentElement).appendChild(styleEl);
1804
-
1805
- // Spotlight backdrop element (created lazily on first use)
1806
- let spotlightBackdrop = null;
1807
- let spotlightTarget = null;
1808
- let spotlightTimer = null;
1809
-
1810
- function getSpotlightBackdrop() {
1811
- if (!spotlightBackdrop) {
1812
- spotlightBackdrop = document.createElement('div');
1813
- spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
1814
- document.body.appendChild(spotlightBackdrop);
1815
- }
1816
- return spotlightBackdrop;
1817
- }
1818
-
1819
- function updateSpotlightClipPath() {
1820
- if (!spotlightBackdrop || !spotlightTarget) return;
1821
- const r = spotlightTarget.getBoundingClientRect();
1822
- // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
1823
- const inset = 4;
1824
- const radius = 6; // outline border-radius (4) + outline width (2)
1825
- const x1 = r.left - inset;
1826
- const y1 = r.top - inset;
1827
- const x2 = r.right + inset;
1828
- const y2 = r.bottom + inset;
1829
- const vw = window.innerWidth;
1830
- const vh = window.innerHeight;
1831
- // Outer rect + rounded inner rect (evenodd creates a hole)
1832
- const path = `M0 0H${vw}V${vh}H0Z M${x1 + radius} ${y1}H${x2 - radius}A${radius} ${radius} 0 0 1 ${x2} ${y1 + radius}V${y2 - radius}A${radius} ${radius} 0 0 1 ${x2 - radius} ${y2}H${x1 + radius}A${radius} ${radius} 0 0 1 ${x1} ${y2 - radius}V${y1 + radius}A${radius} ${radius} 0 0 1 ${x1 + radius} ${y1}Z`;
1833
- spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
1834
- }
1835
-
1836
- function showSpotlight(target) {
1837
- if (!target || !target.getBoundingClientRect) return;
1838
- // Respect the spotlightBlur setting: if disabled, don't show the backdrop
1839
- if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
1840
- spotlightTarget = target;
1841
- return;
1842
- }
1843
- spotlightTarget = target;
1844
- const bd = getSpotlightBackdrop();
1845
- updateSpotlightClipPath();
1846
- bd.classList.add('impeccable-visible');
1847
- }
1848
-
1849
- function hideSpotlight() {
1850
- spotlightTarget = null;
1851
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
1852
- if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
1853
- }
1854
-
1855
- function isInViewport(el) {
1856
- const r = el.getBoundingClientRect();
1857
- return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
1858
- }
1859
-
1860
- // Reposition spotlight on scroll/resize
1861
- window.addEventListener('scroll', () => {
1862
- if (spotlightTarget) updateSpotlightClipPath();
1863
- }, { passive: true });
1864
- window.addEventListener('resize', () => {
1865
- if (spotlightTarget) updateSpotlightClipPath();
1866
- });
1867
-
1868
- const overlays = [];
1869
- const TYPE_LABELS = {};
1870
- const RULE_CATEGORY = {};
1871
- for (const ap of ANTIPATTERNS) {
1872
- TYPE_LABELS[ap.id] = ap.name.toLowerCase();
1873
- RULE_CATEGORY[ap.id] = ap.category || 'quality';
1874
- }
1875
-
1876
- function isInFixedContext(el) {
1877
- let p = el;
1878
- while (p && p !== document.body) {
1879
- if (getComputedStyle(p).position === 'fixed') return true;
1880
- p = p.parentElement;
1881
- }
1882
- return false;
1883
- }
1884
-
1885
- function positionOverlay(overlay) {
1886
- const el = overlay._targetEl;
1887
- if (!el) return;
1888
- const rect = el.getBoundingClientRect();
1889
- if (overlay._isFixed) {
1890
- // Viewport-relative coords for fixed targets
1891
- overlay.style.top = `${rect.top - 2}px`;
1892
- overlay.style.left = `${rect.left - 2}px`;
1893
- } else {
1894
- // Document-relative coords for normal targets
1895
- overlay.style.top = `${rect.top + scrollY - 2}px`;
1896
- overlay.style.left = `${rect.left + scrollX - 2}px`;
1897
- }
1898
- overlay.style.width = `${rect.width + 4}px`;
1899
- overlay.style.height = `${rect.height + 4}px`;
1900
- }
1901
-
1902
- function repositionOverlays() {
1903
- for (const o of overlays) {
1904
- if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
1905
- // Skip overlays whose target is currently hidden (display: none on the overlay)
1906
- if (o.style.display === 'none') continue;
1907
- positionOverlay(o);
1908
- }
1909
- }
1910
-
1911
- let resizeRAF;
1912
- const onResize = () => {
1913
- cancelAnimationFrame(resizeRAF);
1914
- resizeRAF = requestAnimationFrame(repositionOverlays);
1915
- };
1916
- window.addEventListener('resize', onResize);
1917
- // Reposition on scroll too -- catches sticky/parallax shifts
1918
- window.addEventListener('scroll', onResize, { passive: true });
1919
- // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
1920
- if (typeof ResizeObserver !== 'undefined') {
1921
- const bodyResizeObserver = new ResizeObserver(onResize);
1922
- bodyResizeObserver.observe(document.body);
1923
- }
1924
-
1925
- // Track target element visibility via IntersectionObserver.
1926
- // Uses a huge rootMargin so all *rendered* elements count as intersecting,
1927
- // while display:none / closed <details> / hidden modals etc. do not.
1928
- // This is event-driven -- no polling needed.
1929
- let overlayIndex = 0;
1930
- const visibilityObserver = new IntersectionObserver((entries) => {
1931
- for (const entry of entries) {
1932
- const overlay = entry.target._impeccableOverlay;
1933
- if (!overlay) continue;
1934
- if (entry.isIntersecting) {
1935
- overlay.style.display = '';
1936
- positionOverlay(overlay);
1937
- if (!overlay._revealed) {
1938
- overlay._revealed = true;
1939
- if (firstScanDone) {
1940
- // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
1941
- overlay.style.animation = 'none';
1942
- } else {
1943
- // Initial scan: staggered cascade reveal
1944
- overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
1945
- }
1946
- requestAnimationFrame(() => {
1947
- overlay.classList.add('impeccable-visible');
1948
- if (overlay._checkLabel) overlay._checkLabel();
1949
- });
1950
- }
1951
- } else {
1952
- overlay.style.display = 'none';
1953
- }
1954
- }
1955
- }, { rootMargin: '99999px' });
1956
-
1957
- // Reposition overlays after CSS transitions end (e.g. reveal animations).
1958
- // Listens at document level so it catches transitions on ancestor elements
1959
- // (the transform may be on a parent, not the flagged element itself).
1960
- document.addEventListener('transitionend', (e) => {
1961
- if (e.propertyName !== 'transform') return;
1962
- for (const o of overlays) {
1963
- if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
1964
- if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
1965
- positionOverlay(o);
1966
- }
1967
- }
1968
- });
1969
-
1970
- const highlight = function(el, findings) {
1971
- const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
1972
-
1973
- const fixed = isInFixedContext(el);
1974
- const rect = el.getBoundingClientRect();
1975
- const outline = document.createElement('div');
1976
- outline.className = 'impeccable-overlay';
1977
- outline._targetEl = el;
1978
- outline._isFixed = fixed;
1979
- Object.assign(outline.style, {
1980
- position: fixed ? 'fixed' : 'absolute',
1981
- top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
1982
- left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
1983
- width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
1984
- zIndex: '99999', boxSizing: 'border-box',
1985
- });
1986
-
1987
- // Build per-finding label entries: ✦ prefix for slop
1988
- const entries = findings.map(f => {
1989
- const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
1990
- const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
1991
- return { name: prefix + name, detail: f.detail || f.snippet };
1992
- });
1993
- const allText = entries.map(e => e.name).join(', ');
1994
-
1995
- const label = document.createElement('div');
1996
- label.className = 'impeccable-label';
1997
- Object.assign(label.style, {
1998
- position: 'absolute', bottom: '100%', left: '-2px',
1999
- display: 'flex', alignItems: 'center',
2000
- whiteSpace: 'nowrap',
2001
- fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
2002
- color: 'white', lineHeight: '14px',
2003
- background: LABEL_BG,
2004
- fontFamily: 'system-ui, sans-serif',
2005
- borderRadius: '4px 4px 0 0',
2006
- });
2007
-
2008
- const textSpan = document.createElement('span');
2009
- textSpan.style.padding = '3px 8px';
2010
- textSpan.textContent = allText;
2011
- label.appendChild(textSpan);
2012
-
2013
- // State for cycling mode
2014
- let cycleMode = false;
2015
- let cycleIndex = 0;
2016
- let isHovered = false;
2017
- let prevBtn, nextBtn;
2018
-
2019
- function updateCycleText() {
2020
- const e = entries[cycleIndex];
2021
- textSpan.textContent = isHovered ? e.detail : e.name;
2022
- }
2023
-
2024
- function enableCycleMode() {
2025
- if (cycleMode || entries.length < 2) return;
2026
- cycleMode = true;
2027
-
2028
- const btnStyle = {
2029
- background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
2030
- fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
2031
- fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
2032
- pointerEvents: 'auto',
2033
- };
2034
-
2035
- const navGroup = document.createElement('span');
2036
- Object.assign(navGroup.style, {
2037
- display: 'inline-flex', alignItems: 'center', flexShrink: '0',
2038
- });
2039
-
2040
- prevBtn = document.createElement('button');
2041
- prevBtn.textContent = '\u2039';
2042
- Object.assign(prevBtn.style, btnStyle);
2043
- prevBtn.style.paddingLeft = '6px';
2044
- prevBtn.addEventListener('click', (e) => {
2045
- e.stopPropagation();
2046
- cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
2047
- updateCycleText();
2048
- });
2049
-
2050
- nextBtn = document.createElement('button');
2051
- nextBtn.textContent = '\u203A';
2052
- Object.assign(nextBtn.style, btnStyle);
2053
- nextBtn.style.paddingRight = '2px';
2054
- nextBtn.addEventListener('click', (e) => {
2055
- e.stopPropagation();
2056
- cycleIndex = (cycleIndex + 1) % entries.length;
2057
- updateCycleText();
2058
- });
2059
-
2060
- navGroup.appendChild(prevBtn);
2061
- navGroup.appendChild(nextBtn);
2062
- label.insertBefore(navGroup, textSpan);
2063
- textSpan.style.padding = '3px 8px 3px 4px';
2064
- updateCycleText();
2065
- }
2066
-
2067
- outline.appendChild(label);
2068
-
2069
- // Start hidden; the IntersectionObserver will show it once the target is rendered
2070
- outline.style.display = 'none';
2071
- outline._staggerIndex = overlayIndex++;
2072
- el._impeccableOverlay = outline;
2073
- visibilityObserver.observe(el);
2074
-
2075
- // After first paint, check label width vs outline
2076
- outline._checkLabel = () => {
2077
- if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
2078
- enableCycleMode();
2079
- }
2080
- };
2081
-
2082
- // Hover: show detail text, darken
2083
- el.addEventListener('mouseenter', () => {
2084
- isHovered = true;
2085
- outline.classList.add('impeccable-hover');
2086
- outline.style.outlineColor = BRAND_COLOR_HOVER;
2087
- label.style.background = BRAND_COLOR_HOVER;
2088
- if (cycleMode) {
2089
- updateCycleText();
2090
- } else {
2091
- textSpan.textContent = entries.map(e => e.detail).join(' | ');
2092
- }
2093
- });
2094
- el.addEventListener('mouseleave', () => {
2095
- isHovered = false;
2096
- outline.classList.remove('impeccable-hover');
2097
- outline.style.outlineColor = '';
2098
- label.style.background = LABEL_BG;
2099
- if (cycleMode) {
2100
- updateCycleText();
2101
- } else {
2102
- textSpan.textContent = allText;
2103
- }
2104
- });
2105
-
2106
- document.body.appendChild(outline);
2107
- overlays.push(outline);
2108
- };
2109
-
2110
- const showPageBanner = function(findings) {
2111
- if (!findings.length) return;
2112
- const banner = document.createElement('div');
2113
- banner.className = 'impeccable-overlay impeccable-banner';
2114
- Object.assign(banner.style, {
2115
- position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
2116
- background: LABEL_BG, color: 'white',
2117
- fontFamily: 'system-ui, sans-serif', fontSize: '13px',
2118
- display: 'flex', alignItems: 'center', pointerEvents: 'auto',
2119
- height: '36px', overflow: 'hidden', maxWidth: '100vw',
2120
- transform: 'translateY(-100%)',
2121
- transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
2122
- });
2123
- requestAnimationFrame(() => requestAnimationFrame(() => {
2124
- banner.style.transform = 'translateY(0)';
2125
- }));
2126
-
2127
- // Scrollable findings area
2128
- const scrollArea = document.createElement('div');
2129
- Object.assign(scrollArea.style, {
2130
- flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
2131
- display: 'flex', gap: '8px', alignItems: 'center',
2132
- padding: '0 12px', scrollSnapType: 'x mandatory',
2133
- scrollbarWidth: 'none',
2134
- });
2135
- for (const f of findings) {
2136
- const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
2137
- const tag = document.createElement('span');
2138
- tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
2139
- Object.assign(tag.style, {
2140
- background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
2141
- borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
2142
- whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
2143
- });
2144
- scrollArea.appendChild(tag);
2145
- }
2146
- banner.appendChild(scrollArea);
2147
-
2148
- // Controls area (only in standalone mode, not extension)
2149
- if (!EXTENSION_MODE) {
2150
- const controls = document.createElement('div');
2151
- Object.assign(controls.style, {
2152
- display: 'flex', alignItems: 'center', gap: '2px',
2153
- padding: '0 8px', flexShrink: '0',
2154
- });
2155
-
2156
- // Toggle visibility button
2157
- const toggle = document.createElement('button');
2158
- toggle.textContent = '\u25C9'; // circle with dot (visible state)
2159
- toggle.title = 'Toggle overlay visibility';
2160
- Object.assign(toggle.style, {
2161
- background: 'none', border: 'none',
2162
- color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
2163
- opacity: '0.85', transition: 'opacity 0.15s',
2164
- });
2165
- let overlaysVisible = true;
2166
- toggle.addEventListener('click', () => {
2167
- overlaysVisible = !overlaysVisible;
2168
- document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
2169
- toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
2170
- toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
2171
- });
2172
- controls.appendChild(toggle);
2173
-
2174
- // Close button
2175
- const close = document.createElement('button');
2176
- close.textContent = '\u00d7';
2177
- close.title = 'Dismiss banner';
2178
- Object.assign(close.style, {
2179
- background: 'none', border: 'none',
2180
- color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
2181
- });
2182
- close.addEventListener('click', () => banner.remove());
2183
- controls.appendChild(close);
2184
-
2185
- banner.appendChild(controls);
2186
- }
2187
- document.body.appendChild(banner);
2188
- overlays.push(banner);
2189
- };
2190
-
2191
- // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
2192
- // These change between builds and produce brittle, ugly selectors.
2193
- function isLikelyHashedClass(c) {
2194
- if (!c) return true;
2195
- if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
2196
- if (/^_[\w-]{5,}$/.test(c)) return true;
2197
- if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
2198
- return false;
2199
- }
2200
-
2201
- function buildSelectorSegment(el) {
2202
- const tag = el.tagName.toLowerCase();
2203
- let sel = tag;
2204
-
2205
- if (el.classList && el.classList.length > 0) {
2206
- const classes = [...el.classList]
2207
- .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
2208
- .slice(0, 2);
2209
- if (classes.length > 0) {
2210
- sel += '.' + classes.map(c => CSS.escape(c)).join('.');
2211
- }
2212
- }
2213
-
2214
- // Disambiguate among siblings only if the parent has multiple matches
2215
- const parent = el.parentElement;
2216
- if (parent) {
2217
- try {
2218
- const matching = parent.querySelectorAll(':scope > ' + sel);
2219
- if (matching.length > 1) {
2220
- const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
2221
- const idx = sameType.indexOf(el) + 1;
2222
- sel += `:nth-of-type(${idx})`;
2223
- }
2224
- } catch {
2225
- const idx = [...parent.children].indexOf(el) + 1;
2226
- sel = `${tag}:nth-child(${idx})`;
2227
- }
2228
- }
2229
- return sel;
2230
- }
2231
-
2232
- function generateSelector(el) {
2233
- if (el === document.body) return 'body';
2234
- if (el === document.documentElement) return 'html';
2235
- if (el.id) return '#' + CSS.escape(el.id);
2236
-
2237
- const parts = [];
2238
- let current = el;
2239
- let depth = 0;
2240
- const MAX_DEPTH = 10;
2241
-
2242
- while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
2243
- parts.unshift(buildSelectorSegment(current));
2244
-
2245
- // Anchor on an ancestor's ID and stop walking up
2246
- if (current.id) {
2247
- parts[0] = '#' + CSS.escape(current.id);
2248
- break;
2249
- }
2250
-
2251
- // Stop as soon as the partial selector uniquely identifies the target
2252
- const trySelector = parts.join(' > ');
2253
- try {
2254
- const matches = document.querySelectorAll(trySelector);
2255
- if (matches.length === 1 && matches[0] === el) {
2256
- return trySelector;
2257
- }
2258
- } catch { /* invalid selector — keep walking */ }
2259
-
2260
- current = current.parentElement;
2261
- depth++;
2262
- }
2263
-
2264
- return parts.join(' > ');
2265
- }
2266
-
2267
- function isElementHidden(el) {
2268
- if (!el || el === document.body || el === document.documentElement) return false;
2269
- if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
2270
- // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
2271
- return el.offsetWidth === 0 && el.offsetHeight === 0;
2272
- }
2273
-
2274
- function serializeFindings(allFindings) {
2275
- return allFindings.map(({ el, findings }) => ({
2276
- selector: generateSelector(el),
2277
- tagName: el.tagName?.toLowerCase() || 'unknown',
2278
- rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
2279
- ? el.getBoundingClientRect().toJSON() : null,
2280
- isPageLevel: el === document.body || el === document.documentElement,
2281
- isHidden: isElementHidden(el),
2282
- findings: findings.map(f => {
2283
- const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
2284
- return {
2285
- type: f.type || f.id,
2286
- category: ap ? ap.category : 'quality',
2287
- detail: f.detail || f.snippet,
2288
- name: ap ? ap.name : (f.type || f.id),
2289
- description: ap ? ap.description : '',
2290
- };
2291
- }),
2292
- }));
2293
- }
2294
-
2295
- const printSummary = function(allFindings) {
2296
- if (allFindings.length === 0) {
2297
- console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
2298
- return;
2299
- }
2300
- console.group(
2301
- `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
2302
- 'color: oklch(60% 0.25 350); font-weight: bold'
2303
- );
2304
- for (const { el, findings } of allFindings) {
2305
- for (const f of findings) {
2306
- console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
2307
- 'color: oklch(55% 0.25 350); font-weight: bold', 'color: inherit', el);
2308
- }
2309
- }
2310
- console.groupEnd();
2311
- };
2312
-
2313
- let firstScanDone = false;
2314
- const scan = function() {
2315
- for (const o of overlays) o.remove();
2316
- overlays.length = 0;
2317
- visibilityObserver.disconnect();
2318
- overlayIndex = 0;
2319
- const allFindings = [];
2320
- const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
2321
- const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
2322
-
2323
- for (const el of document.querySelectorAll('*')) {
2324
- // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
2325
- if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
2326
- // Skip browser extension elements (Claude, etc.)
2327
- const elId = el.id || '';
2328
- if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
2329
- // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
2330
- // These are inspector chrome, not part of the user's design.
2331
- if (el.closest('[id^="impeccable-live-"]')) continue;
2332
- // Skip html/body -- page-level findings go in the banner, not a full-page overlay
2333
- if (el === document.body || el === document.documentElement) continue;
2334
-
2335
- const findings = [
2336
- ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2337
- ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2338
- ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2339
- ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2340
- ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2341
- ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2342
- ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
2343
- ].filter(f => _ruleOk(f.type));
2344
-
2345
- if (findings.length > 0) {
2346
- highlight(el, findings);
2347
- allFindings.push({ el, findings });
2348
- }
2349
- }
2350
-
2351
- const pageLevelFindings = [];
2352
-
2353
- const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
2354
- if (typoFindings.length > 0) {
2355
- pageLevelFindings.push(...typoFindings);
2356
- allFindings.push({ el: document.body, findings: typoFindings });
2357
- }
2358
-
2359
- const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
2360
- for (const f of layoutFindings) {
2361
- const el = f.el || document.body;
2362
- delete f.el;
2363
- // Merge into existing overlay if this element already has one
2364
- const existing = el._impeccableOverlay;
2365
- if (existing) {
2366
- const nameRow = existing.querySelector('.impeccable-label-name');
2367
- const detailRow = existing.querySelector('.impeccable-label-detail');
2368
- const newType = TYPE_LABELS[f.type] || f.type;
2369
- if (nameRow) nameRow.textContent += ', ' + newType;
2370
- if (detailRow) detailRow.textContent += ' | ' + (f.detail || '');
2371
- } else {
2372
- highlight(el, [f]);
2373
- }
2374
- allFindings.push({ el, findings: [f] });
2375
- }
2376
-
2377
- // Page-level quality checks (headings, etc.)
2378
- const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
2379
- if (qualityFindings.length > 0) {
2380
- pageLevelFindings.push(...qualityFindings);
2381
- allFindings.push({ el: document.body, findings: qualityFindings });
2382
- }
2383
-
2384
- // Regex-on-HTML checks (shared with Node)
2385
- // Clone the document and strip impeccable-live overlay nodes before the
2386
- // regex scan, so the inspector's own inline styles (transitions on top/
2387
- // left/width/height, etc.) don't register as page anti-patterns.
2388
- const docClone = document.documentElement.cloneNode(true);
2389
- for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
2390
- node.remove();
2391
- }
2392
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
2393
- if (htmlPatternFindings.length > 0) {
2394
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
2395
- pageLevelFindings.push(...mapped);
2396
- allFindings.push({ el: document.body, findings: mapped });
2397
- }
2398
-
2399
- if (pageLevelFindings.length > 0) {
2400
- showPageBanner(pageLevelFindings);
2401
- }
2402
-
2403
- if (!EXTENSION_MODE) printSummary(allFindings);
2404
-
2405
- // In extension mode, post serialized results for the DevTools panel
2406
- if (EXTENSION_MODE) {
2407
- window.postMessage({
2408
- source: 'impeccable-results',
2409
- findings: serializeFindings(allFindings),
2410
- count: allFindings.length,
2411
- }, '*');
2412
- }
2413
-
2414
- // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
2415
- setTimeout(() => { firstScanDone = true; }, 1000);
2416
-
2417
- return allFindings;
2418
- };
2419
-
2420
- if (EXTENSION_MODE) {
2421
- // Extension mode: listen for commands, don't auto-scan
2422
- window.addEventListener('message', (e) => {
2423
- if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
2424
- if (e.data.action === 'scan') {
2425
- if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
2426
- scan();
2427
- }
2428
- if (e.data.action === 'toggle-overlays') {
2429
- const visible = !document.body.classList.contains('impeccable-hidden');
2430
- document.body.classList.toggle('impeccable-hidden', visible);
2431
- window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
2432
- }
2433
- if (e.data.action === 'remove') {
2434
- for (const o of overlays) o.remove();
2435
- overlays.length = 0;
2436
- visibilityObserver.disconnect();
2437
- styleEl.remove();
2438
- if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
2439
- document.body.classList.remove('impeccable-hidden');
2440
- }
2441
- if (e.data.action === 'highlight') {
2442
- if (spotlightTimer) { clearTimeout(spotlightTimer); spotlightTimer = null; }
2443
- try {
2444
- const target = e.data.selector ? document.querySelector(e.data.selector) : null;
2445
- if (target) {
2446
- // Scroll first so positionOverlay reads the post-scroll rect
2447
- if (!isInViewport(target) && target.scrollIntoView) {
2448
- target.scrollIntoView({ behavior: 'instant', block: 'center' });
2449
- }
2450
- for (const o of overlays) {
2451
- if (o.classList.contains('impeccable-banner')) continue;
2452
- const isMatch = o._targetEl === target;
2453
- o.classList.toggle('impeccable-spotlight', isMatch);
2454
- o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
2455
- if (isMatch) {
2456
- // Force the matching overlay visible immediately, don't wait for IntersectionObserver
2457
- o.style.display = '';
2458
- o.style.animation = 'none';
2459
- o.classList.add('impeccable-visible');
2460
- o._revealed = true;
2461
- positionOverlay(o);
2462
- }
2463
- }
2464
- showSpotlight(target);
2465
- }
2466
- } catch { /* invalid selector */ }
2467
- }
2468
- if (e.data.action === 'unhighlight') {
2469
- hideSpotlight();
2470
- for (const o of overlays) {
2471
- o.classList.remove('impeccable-spotlight');
2472
- o.classList.remove('impeccable-spotlight-dimmed');
2473
- }
2474
- }
2475
- });
2476
- window.postMessage({ source: 'impeccable-ready' }, '*');
2477
- } else {
2478
- if (document.readyState === 'loading') {
2479
- document.addEventListener('DOMContentLoaded', () => setTimeout(scan, 100));
2480
- } else {
2481
- setTimeout(scan, 100);
2482
- }
2483
- }
2484
-
2485
- window.impeccableScan = scan;
2486
- }
2487
-
2488
- // ─── Section 8: Node Engine ─────────────────────────────────────────────────
2489
- // @browser-strip-start
2490
-
2491
- function getAP(id) {
2492
- return ANTIPATTERNS.find(a => a.id === id);
2493
- }
2494
-
2495
- function finding(id, filePath, snippet, line = 0) {
2496
- const ap = getAP(id);
2497
- return { antipattern: id, name: ap.name, description: ap.description, file: filePath, line, snippet };
2498
- }
2499
-
2500
- /** Check if content looks like a full page (not a component/partial) */
2501
- function isFullPage(content) {
2502
- const stripped = content.replace(/<!--[\s\S]*?-->/g, '');
2503
- return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(stripped);
2504
- }
2505
-
2506
- // ---------------------------------------------------------------------------
2507
- // jsdom CSS-variable border override map
2508
- // ---------------------------------------------------------------------------
2509
- //
2510
- // jsdom's CSSOM silently drops any border shorthand that contains a var()
2511
- // reference — the computed style for the element then shows empty width,
2512
- // empty style, and a default black color. That's enough to hide the most
2513
- // common real-world side-tab pattern in AI-generated pages:
2514
- //
2515
- // :root { --brand: #87a8ff; }
2516
- // .card { border-left: 5px solid var(--brand); border-radius: 4px; }
2517
- //
2518
- // Real browsers (and therefore the browser detector path) resolve var()
2519
- // natively, so this only affects the Node jsdom path.
2520
- //
2521
- // This pre-pass walks the stylesheets, finds any rule whose per-side or
2522
- // all-sides border property contains var(), resolves the var() against
2523
- // :root-level custom properties (read from the documentElement's computed
2524
- // style, which jsdom DOES handle correctly), and attaches the resolved
2525
- // width+color to every element that matches the rule's selector. The
2526
- // Node-side `checkElementBorders` adapter consumes that map as a fallback
2527
- // whenever jsdom's computed style came back empty.
2528
- //
2529
- // Limitations (intentional, to keep the pass simple):
2530
- // * Only :root-level custom properties are resolved. Scoped overrides on
2531
- // descendants are not tracked — uncommon in practice and would require
2532
- // a per-element cascade walk.
2533
- // * @media / @supports wrapped rules are ignored (jsdom often mishandles
2534
- // these anyway).
2535
- // * The fallback only fills sides that jsdom left empty, so any rule
2536
- // whose border parses normally still wins via the computed style.
2537
-
2538
- const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
2539
-
2540
- // isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
2541
- // CSS variables typically hold hex or named colors, so normalize those to
2542
- // rgb() before handing the value off to the shared check. Anything we don't
2543
- // recognise is passed through unchanged — isNeutralColor then treats it as
2544
- // non-neutral, which is the safer default (matches the oklch-era bugfix).
2545
- const NAMED_COLORS = {
2546
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
2547
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
2548
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
2549
- };
2550
-
2551
- function normalizeColorForCheck(value) {
2552
- if (!value) return value;
2553
- const v = value.trim();
2554
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
2555
- if (hex6) {
2556
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
2557
- return `rgb(${r}, ${g}, ${b})`;
2558
- }
2559
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
2560
- if (hex3) {
2561
- const [r, g, b] = [
2562
- parseInt(hex3[1] + hex3[1], 16),
2563
- parseInt(hex3[2] + hex3[2], 16),
2564
- parseInt(hex3[3] + hex3[3], 16),
2565
- ];
2566
- return `rgb(${r}, ${g}, ${b})`;
2567
- }
2568
- const named = NAMED_COLORS[v.toLowerCase()];
2569
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
2570
- return v;
2571
- }
2572
-
2573
- function buildBorderOverrideMap(document, window) {
2574
- const map = new Map();
2575
- const rootStyle = window.getComputedStyle(document.documentElement);
2576
-
2577
- function resolveVar(value, depth = 0) {
2578
- if (!value || depth > 10 || !value.includes('var(')) return value;
2579
- return value.replace(
2580
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
2581
- (_, name, fallback) => {
2582
- const v = rootStyle.getPropertyValue(name).trim();
2583
- if (v) return resolveVar(v, depth + 1);
2584
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
2585
- return '';
2586
- }
2587
- );
2588
- }
2589
-
2590
- function parseShorthand(text) {
2591
- const m = text.trim().match(BORDER_SHORTHAND_RE);
2592
- if (!m) return null;
2593
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
2594
- }
2595
-
2596
- // Read from the per-property accessors on rule.style. jsdom preserves
2597
- // each border-* shorthand it parsed, even when the overall cssText has
2598
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
2599
- // `border-left: ...` loses the first declaration but keeps the second).
2600
- const SIDE_PROPS = [
2601
- ['borderLeft', 'Left'],
2602
- ['borderRight', 'Right'],
2603
- ['borderTop', 'Top'],
2604
- ['borderBottom', 'Bottom'],
2605
- ['borderInlineStart', 'Left'],
2606
- ['borderInlineEnd', 'Right'],
2607
- ];
2608
-
2609
- for (const sheet of document.styleSheets) {
2610
- let rules;
2611
- try { rules = sheet.cssRules || []; } catch { continue; }
2612
- for (const rule of rules) {
2613
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
2614
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
2615
-
2616
- const perSide = {};
2617
-
2618
- for (const [prop, side] of SIDE_PROPS) {
2619
- const val = rule.style[prop];
2620
- if (!val || !val.includes('var(')) continue;
2621
- const parsed = parseShorthand(resolveVar(val));
2622
- if (parsed && parsed.color) perSide[side] = parsed;
2623
- }
2624
-
2625
- // Uniform `border: <w> <style> var(...)` applies to every side the
2626
- // per-side map didn't already claim.
2627
- const borderAll = rule.style.border;
2628
- if (borderAll && borderAll.includes('var(')) {
2629
- const parsed = parseShorthand(resolveVar(borderAll));
2630
- if (parsed && parsed.color) {
2631
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
2632
- if (!perSide[s]) perSide[s] = parsed;
2633
- }
2634
- }
2635
- }
2636
-
2637
- // Longhand `border-*-color: var(...)` with width/style in separate
2638
- // declarations. Rare in AI-generated pages, but cheap to cover.
2639
- for (const [prop, side] of [
2640
- ['borderLeftColor', 'Left'],
2641
- ['borderRightColor', 'Right'],
2642
- ['borderTopColor', 'Top'],
2643
- ['borderBottomColor', 'Bottom'],
2644
- ]) {
2645
- const val = rule.style[prop];
2646
- if (!val || !val.includes('var(')) continue;
2647
- const resolved = resolveVar(val).trim();
2648
- if (!resolved) continue;
2649
- // Width may or may not come from this rule — that's fine; the
2650
- // adapter only substitutes the color when jsdom left it as a
2651
- // literal var() string.
2652
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
2653
- }
2654
-
2655
- if (Object.keys(perSide).length === 0) continue;
2656
-
2657
- let matched;
2658
- try { matched = document.querySelectorAll(rule.selectorText); }
2659
- catch { continue; }
2660
-
2661
- for (const el of matched) {
2662
- const existing = map.get(el);
2663
- if (existing) {
2664
- // Later rules overwrite earlier ones — approximates source-order
2665
- // cascade for equal-specificity rules and is good enough for the
2666
- // uncontested var()-dropped sides we're trying to recover.
2667
- Object.assign(existing, perSide);
2668
- } else {
2669
- map.set(el, { ...perSide });
2670
- }
2671
- }
2672
- }
2673
- }
2674
-
2675
- return map;
2676
- }
2677
-
2678
- // ---------------------------------------------------------------------------
2679
- // jsdom detection (default for HTML files)
2680
- // ---------------------------------------------------------------------------
2681
-
2682
- async function detectHtml(filePath) {
2683
- let JSDOM;
2684
- try {
2685
- ({ JSDOM } = await import('jsdom'));
2686
- } catch {
2687
- const content = fs.readFileSync(filePath, 'utf-8');
2688
- return detectText(content, filePath);
2689
- }
2690
-
2691
- const html = fs.readFileSync(filePath, 'utf-8');
2692
- const resolvedPath = path.resolve(filePath);
2693
- const fileDir = path.dirname(resolvedPath);
2694
-
2695
- // Inline linked local stylesheets so jsdom can see them
2696
- let processedHtml = html;
2697
- const linkRes = [
2698
- /<link[^>]+rel=["']stylesheet["'][^>]*href=["']([^"']+)["'][^>]*>/gi,
2699
- /<link[^>]+href=["']([^"']+)["'][^>]*rel=["']stylesheet["'][^>]*>/gi,
2700
- ];
2701
- for (const re of linkRes) {
2702
- let m;
2703
- while ((m = re.exec(html)) !== null) {
2704
- const href = m[1];
2705
- if (/^(https?:)?\/\//.test(href)) continue;
2706
- const cssPath = path.resolve(fileDir, href);
2707
- try {
2708
- const css = fs.readFileSync(cssPath, 'utf-8');
2709
- processedHtml = processedHtml.replace(m[0], `<style>/* ${href} */\n${css}\n</style>`);
2710
- } catch { /* skip unreadable */ }
2711
- }
2712
- }
2713
-
2714
- const dom = new JSDOM(processedHtml, {
2715
- url: `file://${resolvedPath}`,
2716
- });
2717
- const { window } = dom;
2718
- const { document } = window;
2719
-
2720
- const findings = [];
2721
-
2722
- // Pre-pass: recover border declarations that jsdom dropped because they
2723
- // contained a var() reference. The map is keyed by element and consulted
2724
- // by the border check adapter as a fallback.
2725
- const borderOverrides = buildBorderOverrideMap(document, window);
2726
-
2727
- // Element-level checks (borders + colors + motion)
2728
- for (const el of document.querySelectorAll('*')) {
2729
- const tag = el.tagName.toLowerCase();
2730
- const style = window.getComputedStyle(el);
2731
- const resolvedRadius = resolveBorderRadiusPx(el, style, parseFloat(style.width) || 0, window);
2732
- for (const f of checkElementBorders(tag, style, borderOverrides.get(el), resolvedRadius)) {
2733
- findings.push(finding(f.id, filePath, f.snippet));
2734
- }
2735
- for (const f of checkElementColors(el, style, tag, window)) {
2736
- findings.push(finding(f.id, filePath, f.snippet));
2737
- }
2738
- for (const f of checkElementGlow(tag, style, resolveBackground(el.parentElement || el, window))) {
2739
- findings.push(finding(f.id, filePath, f.snippet));
2740
- }
2741
- for (const f of checkElementMotion(tag, style)) {
2742
- findings.push(finding(f.id, filePath, f.snippet));
2743
- }
2744
- for (const f of checkElementIconTile(el, tag, window)) {
2745
- findings.push(finding(f.id, filePath, f.snippet));
2746
- }
2747
- for (const f of checkElementQuality(el, style, tag, window)) {
2748
- findings.push(finding(f.id, filePath, f.snippet));
2749
- }
2750
- }
2751
-
2752
- // Page-level checks (only for full pages, not partials)
2753
- if (isFullPage(html)) {
2754
- for (const f of checkPageTypography(document, window)) {
2755
- findings.push(finding(f.id, filePath, f.snippet));
2756
- }
2757
- for (const f of checkPageLayout(document, window)) {
2758
- findings.push(finding(f.id, filePath, f.snippet));
2759
- }
2760
- for (const f of checkPageQualityFromDoc(document)) {
2761
- findings.push(finding(f.id, filePath, f.snippet));
2762
- }
2763
- for (const f of checkHtmlPatterns(html)) {
2764
- findings.push(finding(f.id, filePath, f.snippet));
2765
- }
2766
- }
2767
-
2768
- window.close();
2769
- return findings;
2770
- }
2771
-
2772
- // ---------------------------------------------------------------------------
2773
- // Puppeteer detection (for URLs)
2774
- // ---------------------------------------------------------------------------
2775
-
2776
- async function detectUrl(url) {
2777
- let puppeteer;
2778
- try {
2779
- puppeteer = await import('puppeteer');
2780
- } catch {
2781
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
2782
- }
2783
-
2784
- // Read the browser detection script — reuse it instead of reimplementing
2785
- const browserScriptPath = path.resolve(
2786
- path.dirname(fileURLToPath(import.meta.url)),
2787
- 'detect-antipatterns-browser.js'
2788
- );
2789
- let browserScript;
2790
- try {
2791
- browserScript = fs.readFileSync(browserScriptPath, 'utf-8');
2792
- } catch {
2793
- throw new Error(`Browser script not found at ${browserScriptPath}`);
2794
- }
2795
-
2796
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
2797
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
2798
- // running in CI; local users keep the default hardened launch.
2799
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
2800
- const browser = await puppeteer.default.launch({ headless: true, args: launchArgs });
2801
- const page = await browser.newPage();
2802
- await page.setViewport({ width: 1280, height: 800 });
2803
- await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
2804
-
2805
- // Inject the browser detection script and collect results
2806
- await page.evaluate(browserScript);
2807
- const results = await page.evaluate(() => {
2808
- if (!window.impeccableScan) return [];
2809
- const allFindings = window.impeccableScan();
2810
- return allFindings.flatMap(({ findings }) =>
2811
- findings.map(f => ({ id: f.type, snippet: f.detail }))
2812
- );
2813
- });
2814
-
2815
- await browser.close();
2816
- return results.map(f => finding(f.id, url, f.snippet));
2817
- }
2818
-
2819
- // ---------------------------------------------------------------------------
2820
- // Regex fallback (non-HTML files: CSS, JSX, TSX, etc.)
2821
- // ---------------------------------------------------------------------------
2822
-
2823
- const hasRounded = (line) => /\brounded(?:-\w+)?\b/.test(line);
2824
- const hasBorderRadius = (line) => /border-radius/i.test(line);
2825
- const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(line);
2826
-
2827
- function isNeutralBorderColor(str) {
2828
- const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
2829
- if (!m) return false;
2830
- const c = m[1].toLowerCase();
2831
- if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
2832
- const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
2833
- if (hex) {
2834
- const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
2835
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
2836
- }
2837
- const shex = c.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/);
2838
- if (shex) {
2839
- const [r, g, b] = [parseInt(shex[1] + shex[1], 16), parseInt(shex[2] + shex[2], 16), parseInt(shex[3] + shex[3], 16)];
2840
- return (Math.max(r, g, b) - Math.min(r, g, b)) < 30;
2841
- }
2842
- return false;
2843
- }
2844
-
2845
- const REGEX_MATCHERS = [
2846
- // --- Side-tab ---
2847
- { id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
2848
- test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
2849
- fmt: (m) => m[0] },
2850
- { id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
2851
- 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; },
2852
- fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
2853
- { id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
2854
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
2855
- fmt: (m) => m[0] },
2856
- { id: 'side-tab', regex: /border-inline-(?:start|end)\s*:\s*(\d+)px\s+solid/gi,
2857
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
2858
- fmt: (m) => m[0] },
2859
- { id: 'side-tab', regex: /border-inline-(?:start|end)-width\s*:\s*(\d+)px/gi,
2860
- test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
2861
- fmt: (m) => m[0] },
2862
- { id: 'side-tab', regex: /border(?:Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,
2863
- test: (m) => +m[1] >= 3,
2864
- fmt: (m) => m[0] },
2865
- // --- Border accent on rounded ---
2866
- { id: 'border-accent-on-rounded', regex: /\bborder-[tb]-(\d+)\b/g,
2867
- test: (m, line) => hasRounded(line) && +m[1] >= 1,
2868
- fmt: (m) => m[0] },
2869
- { id: 'border-accent-on-rounded', regex: /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi,
2870
- test: (m, line) => +m[1] >= 3 && hasBorderRadius(line),
2871
- fmt: (m) => m[0] },
2872
- // --- Overused font ---
2873
- { id: 'overused-font', regex: /font-family\s*:\s*['"]?(Inter|Roboto|Open Sans|Lato|Montserrat|Arial|Helvetica)\b/gi,
2874
- test: () => true,
2875
- fmt: (m) => m[0] },
2876
- { id: 'overused-font', regex: /fonts\.googleapis\.com\/css2?\?family=(Inter|Roboto|Open\+Sans|Lato|Montserrat)\b/gi,
2877
- test: () => true,
2878
- fmt: (m) => `Google Fonts: ${m[1].replace(/\+/g, ' ')}` },
2879
- // --- Pure black background ---
2880
- { id: 'pure-black-white', regex: /background(?:-color)?\s*:\s*(#000000|#000|rgb\(0,\s*0,\s*0\))\b/gi,
2881
- test: () => true,
2882
- fmt: (m) => m[0] },
2883
- // --- Gradient text ---
2884
- { id: 'gradient-text', regex: /background-clip\s*:\s*text|-webkit-background-clip\s*:\s*text/gi,
2885
- test: (m, line) => /gradient/i.test(line),
2886
- fmt: () => 'background-clip: text + gradient' },
2887
- // --- Gradient text (Tailwind) ---
2888
- { id: 'gradient-text', regex: /\bbg-clip-text\b/g,
2889
- test: (m, line) => /\bbg-gradient-to-/i.test(line),
2890
- fmt: () => 'bg-clip-text + bg-gradient' },
2891
- // --- Tailwind pure black background ---
2892
- { id: 'pure-black-white', regex: /\bbg-black\b/g,
2893
- test: () => true,
2894
- fmt: (m) => m[0] },
2895
- // --- Tailwind gray on colored bg ---
2896
- { id: 'gray-on-color', regex: /\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g,
2897
- 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),
2898
- 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] || '?'}`; } },
2899
- // --- Tailwind AI palette ---
2900
- { id: 'ai-color-palette', regex: /\btext-(?:purple|violet|indigo)-(\d+)\b/g,
2901
- test: (m, line) => /\btext-(?:[2-9]xl|[3-9]xl)\b|<h[1-3]/i.test(line),
2902
- fmt: (m) => `${m[0]} on heading` },
2903
- { id: 'ai-color-palette', regex: /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g,
2904
- test: (m, line) => /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(line),
2905
- fmt: (m) => `${m[0]} gradient` },
2906
- // --- Bounce/elastic easing ---
2907
- { id: 'bounce-easing', regex: /\banimate-bounce\b/g,
2908
- test: () => true,
2909
- fmt: () => 'animate-bounce (Tailwind)' },
2910
- { id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
2911
- test: () => true,
2912
- fmt: (m) => m[0] },
2913
- { id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
2914
- test: (m) => {
2915
- const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
2916
- return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1;
2917
- },
2918
- fmt: (m) => `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` },
2919
- // --- Layout property transition ---
2920
- { id: 'layout-transition', regex: /transition\s*:\s*([^;{}]+)/gi,
2921
- test: (m) => {
2922
- const val = m[1].toLowerCase();
2923
- if (/\ball\b/.test(val)) return false;
2924
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
2925
- },
2926
- fmt: (m) => {
2927
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
2928
- return `transition: ${found ? found.join(', ') : m[1].trim()}`;
2929
- } },
2930
- { id: 'layout-transition', regex: /transition-property\s*:\s*([^;{}]+)/gi,
2931
- test: (m) => {
2932
- const val = m[1].toLowerCase();
2933
- if (/\ball\b/.test(val)) return false;
2934
- return /\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding\b|\bmargin\b/.test(val);
2935
- },
2936
- fmt: (m) => {
2937
- const found = m[1].match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
2938
- return `transition-property: ${found ? found.join(', ') : m[1].trim()}`;
2939
- } },
2940
- ];
2941
-
2942
- const REGEX_ANALYZERS = [
2943
- // Single font
2944
- (content, filePath) => {
2945
- const fontFamilyRe = /font-family\s*:\s*([^;}]+)/gi;
2946
- const fonts = new Set();
2947
- let m;
2948
- while ((m = fontFamilyRe.exec(content)) !== null) {
2949
- for (const f of m[1].split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase())) {
2950
- if (f && !GENERIC_FONTS.has(f)) fonts.add(f);
2951
- }
2952
- }
2953
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
2954
- while ((m = gfRe.exec(content)) !== null) {
2955
- for (const f of m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase())) fonts.add(f);
2956
- }
2957
- if (fonts.size !== 1 || content.split('\n').length < 20) return [];
2958
- const name = [...fonts][0];
2959
- const lines = content.split('\n');
2960
- let line = 1;
2961
- for (let i = 0; i < lines.length; i++) { if (lines[i].toLowerCase().includes(name)) { line = i + 1; break; } }
2962
- return [finding('single-font', filePath, `only font used is ${name}`, line)];
2963
- },
2964
- // Flat type hierarchy
2965
- (content, filePath) => {
2966
- const sizes = new Set();
2967
- const REM = 16;
2968
- let m;
2969
- const sizeRe = /font-size\s*:\s*([\d.]+)(px|rem|em)\b/gi;
2970
- while ((m = sizeRe.exec(content)) !== null) {
2971
- const px = m[2] === 'px' ? +m[1] : +m[1] * REM;
2972
- if (px > 0 && px < 200) sizes.add(Math.round(px * 10) / 10);
2973
- }
2974
- const clampRe = /font-size\s*:\s*clamp\(\s*([\d.]+)(px|rem|em)\s*,\s*[^,]+,\s*([\d.]+)(px|rem|em)\s*\)/gi;
2975
- while ((m = clampRe.exec(content)) !== null) {
2976
- sizes.add(Math.round((m[2] === 'px' ? +m[1] : +m[1] * REM) * 10) / 10);
2977
- sizes.add(Math.round((m[4] === 'px' ? +m[3] : +m[3] * REM) * 10) / 10);
2978
- }
2979
- 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 };
2980
- for (const [cls, px] of Object.entries(TW)) { if (new RegExp(`\\b${cls}\\b`).test(content)) sizes.add(px); }
2981
- if (sizes.size < 3) return [];
2982
- const sorted = [...sizes].sort((a, b) => a - b);
2983
- const ratio = sorted[sorted.length - 1] / sorted[0];
2984
- if (ratio >= 2.0) return [];
2985
- const lines = content.split('\n');
2986
- let line = 1;
2987
- 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; } }
2988
- return [finding('flat-type-hierarchy', filePath, `Sizes: ${sorted.map(s => s + 'px').join(', ')} (ratio ${ratio.toFixed(1)}:1)`, line)];
2989
- },
2990
- // Monotonous spacing (regex)
2991
- (content, filePath) => {
2992
- const vals = [];
2993
- let m;
2994
- const pxRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
2995
- while ((m = pxRe.exec(content)) !== null) { const v = +m[1]; if (v > 0 && v < 200) vals.push(v); }
2996
- const remRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
2997
- while ((m = remRe.exec(content)) !== null) { const v = Math.round(parseFloat(m[1]) * 16); if (v > 0 && v < 200) vals.push(v); }
2998
- const gapRe = /gap\s*:\s*(\d+)px/gi;
2999
- while ((m = gapRe.exec(content)) !== null) vals.push(+m[1]);
3000
- const twRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
3001
- while ((m = twRe.exec(content)) !== null) vals.push(+m[1] * 4);
3002
- const rounded = vals.map(v => Math.round(v / 4) * 4);
3003
- if (rounded.length < 10) return [];
3004
- const counts = {};
3005
- for (const v of rounded) counts[v] = (counts[v] || 0) + 1;
3006
- const maxCount = Math.max(...Object.values(counts));
3007
- const pct = maxCount / rounded.length;
3008
- const unique = [...new Set(rounded)].filter(v => v > 0);
3009
- if (pct <= 0.6 || unique.length > 3) return [];
3010
- const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
3011
- return [finding('monotonous-spacing', filePath, `~${dominant}px used ${maxCount}/${rounded.length} times (${Math.round(pct * 100)}%)`)];
3012
- },
3013
- // Everything centered (regex)
3014
- (content, filePath) => {
3015
- const lines = content.split('\n');
3016
- let centered = 0, total = 0;
3017
- for (const line of lines) {
3018
- if (/<(?:h[1-6]|p|div|li|button)\b[^>]*>/i.test(line) && line.trim().length > 20) {
3019
- total++;
3020
- if (/text-align\s*:\s*center/i.test(line) || /\btext-center\b/.test(line)) centered++;
3021
- }
3022
- }
3023
- if (total < 5 || centered / total <= 0.7) return [];
3024
- return [finding('everything-centered', filePath, `${centered}/${total} text elements centered (${Math.round(centered / total * 100)}%)`)];
3025
- },
3026
- // Dark glow (page-level: dark bg + colored box-shadow with blur)
3027
- (content, filePath) => {
3028
- // Check if page has a dark background
3029
- 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;
3030
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
3031
- const hasDarkBg = darkBgRe.test(content) || twDarkBg.test(content);
3032
- if (!hasDarkBg) return [];
3033
-
3034
- // Check for colored box-shadow with blur > 4px
3035
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
3036
- let m;
3037
- while ((m = shadowRe.exec(content)) !== null) {
3038
- const val = m[1];
3039
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
3040
- if (!colorMatch) continue;
3041
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
3042
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue; // skip gray
3043
- // Check blur: look for pattern like "0 0 20px" (third number > 4)
3044
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
3045
- if (pxVals.length >= 3 && pxVals[2] > 4) {
3046
- const lines = content.substring(0, m.index).split('\n');
3047
- return [finding('dark-glow', filePath, `Colored glow (rgb(${r},${g},${b})) on dark page`, lines.length)];
3048
- }
3049
- }
3050
- return [];
3051
- },
3052
- ];
3053
-
3054
- // ---------------------------------------------------------------------------
3055
- // Style block extraction (Vue/Svelte <style> blocks)
3056
- // ---------------------------------------------------------------------------
3057
-
3058
- function extractStyleBlocks(content, ext) {
3059
- ext = ext.toLowerCase();
3060
- if (ext !== '.vue' && ext !== '.svelte') return [];
3061
- const blocks = [];
3062
- const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
3063
- let m;
3064
- while ((m = re.exec(content)) !== null) {
3065
- const before = content.substring(0, m.index);
3066
- const startLine = before.split('\n').length + 1;
3067
- blocks.push({ content: m[1], startLine });
3068
- }
3069
- return blocks;
3070
- }
3071
-
3072
- // ---------------------------------------------------------------------------
3073
- // CSS-in-JS extraction (styled-components, emotion)
3074
- // ---------------------------------------------------------------------------
3075
-
3076
- const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
3077
-
3078
- function extractCSSinJS(content, ext) {
3079
- ext = ext.toLowerCase();
3080
- if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
3081
- const blocks = [];
3082
- const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
3083
- let m;
3084
- while ((m = re.exec(content)) !== null) {
3085
- const before = content.substring(0, m.index);
3086
- const startLine = before.split('\n').length;
3087
- blocks.push({ content: m[1], startLine });
3088
- }
3089
- return blocks;
3090
- }
3091
-
3092
- function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null) {
3093
- const findings = [];
3094
- for (const matcher of REGEX_MATCHERS) {
3095
- for (let i = 0; i < lines.length; i++) {
3096
- const line = lines[i];
3097
- matcher.regex.lastIndex = 0;
3098
- let m;
3099
- while ((m = matcher.regex.exec(line)) !== null) {
3100
- // For extracted blocks, use nearby lines as context for multi-line CSS patterns
3101
- const context = blockContext
3102
- ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
3103
- : line;
3104
- if (matcher.test(m, context)) {
3105
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
3106
- }
3107
- }
3108
- }
3109
- }
3110
- return findings;
3111
- }
3112
-
3113
- function detectText(content, filePath) {
3114
- const findings = [];
3115
- const lines = content.split('\n');
3116
- const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
3117
-
3118
- // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
3119
- // Enable block context for CSS files where related properties span multiple lines
3120
- const cssLike = new Set(['.css', '.scss', '.less']);
3121
- findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null));
3122
-
3123
- // Extract and scan <style> blocks from Vue/Svelte SFCs
3124
- const styleBlocks = extractStyleBlocks(content, ext);
3125
- for (const block of styleBlocks) {
3126
- const blockLines = block.content.split('\n');
3127
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true));
3128
- }
3129
-
3130
- // Extract and scan CSS-in-JS template literals
3131
- const cssJsBlocks = extractCSSinJS(content, ext);
3132
- for (const block of cssJsBlocks) {
3133
- const blockLines = block.content.split('\n');
3134
- findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true));
3135
- }
3136
-
3137
- // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
3138
- const deduped = [];
3139
- for (const f of findings) {
3140
- const isDupe = deduped.some(d =>
3141
- d.antipattern === f.antipattern &&
3142
- d.snippet === f.snippet &&
3143
- Math.abs(d.line - f.line) <= 2
3144
- );
3145
- if (!isDupe) deduped.push(f);
3146
- }
3147
-
3148
- // Page-level analyzers only run on full pages
3149
- if (isFullPage(content)) {
3150
- for (const analyzer of REGEX_ANALYZERS) {
3151
- deduped.push(...analyzer(content, filePath));
3152
- }
3153
- }
3154
-
3155
- return deduped;
3156
- }
3157
-
3158
- // ---------------------------------------------------------------------------
3159
- // File walker
3160
- // ---------------------------------------------------------------------------
3161
-
3162
- const SKIP_DIRS = new Set([
3163
- 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.output',
3164
- '.svelte-kit', '__pycache__', '.turbo', '.vercel',
3165
- ]);
3166
-
3167
- const SCANNABLE_EXTENSIONS = new Set([
3168
- '.html', '.htm', '.css', '.scss', '.less',
3169
- '.jsx', '.tsx', '.js', '.ts',
3170
- '.vue', '.svelte', '.astro',
3171
- ]);
3172
-
3173
- const HTML_EXTENSIONS = new Set(['.html', '.htm']);
3174
-
3175
- function walkDir(dir) {
3176
- const files = [];
3177
- let entries;
3178
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
3179
- for (const entry of entries) {
3180
- if (SKIP_DIRS.has(entry.name)) continue;
3181
- const full = path.join(dir, entry.name);
3182
- if (entry.isDirectory()) files.push(...walkDir(full));
3183
- else if (SCANNABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) files.push(full);
3184
- }
3185
- return files;
3186
- }
3187
-
3188
- // ---------------------------------------------------------------------------
3189
- // Output formatting
3190
- // ---------------------------------------------------------------------------
3191
-
3192
- function formatFindings(findings, jsonMode) {
3193
- if (jsonMode) return JSON.stringify(findings, null, 2);
3194
-
3195
- const grouped = {};
3196
- for (const f of findings) {
3197
- if (!grouped[f.file]) grouped[f.file] = [];
3198
- grouped[f.file].push(f);
3199
- }
3200
- const out = [];
3201
- for (const [file, items] of Object.entries(grouped)) {
3202
- const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
3203
- out.push(`\n${file}${importNote}`);
3204
- for (const item of items) {
3205
- out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
3206
- out.push(` → ${item.description}`);
3207
- }
3208
- }
3209
- out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
3210
- return out.join('\n');
3211
- }
3212
-
3213
- // ---------------------------------------------------------------------------
3214
- // Stdin handling
3215
- // ---------------------------------------------------------------------------
3216
-
3217
- async function handleStdin() {
3218
- const chunks = [];
3219
- for await (const chunk of process.stdin) chunks.push(chunk);
3220
- const input = Buffer.concat(chunks).toString('utf-8');
3221
- try {
3222
- const parsed = JSON.parse(input);
3223
- const fp = parsed?.tool_input?.file_path;
3224
- if (fp && fs.existsSync(fp)) {
3225
- return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
3226
- ? detectHtml(fp) : detectText(fs.readFileSync(fp, 'utf-8'), fp);
3227
- }
3228
- } catch { /* not JSON */ }
3229
- return detectText(input, '<stdin>');
3230
- }
3231
-
3232
- // ---------------------------------------------------------------------------
3233
- // Import graph (multi-file awareness)
3234
- // ---------------------------------------------------------------------------
3235
-
3236
- function resolveImport(specifier, fromDir, fileSet) {
3237
- if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
3238
- const base = path.resolve(fromDir, specifier);
3239
- if (fileSet.has(base)) return base;
3240
- for (const ext of SCANNABLE_EXTENSIONS) {
3241
- const withExt = base + ext;
3242
- if (fileSet.has(withExt)) return withExt;
3243
- }
3244
- // index file convention
3245
- for (const ext of SCANNABLE_EXTENSIONS) {
3246
- const indexFile = path.join(base, 'index' + ext);
3247
- if (fileSet.has(indexFile)) return indexFile;
3248
- }
3249
- return null;
3250
- }
3251
-
3252
- function buildImportGraph(files) {
3253
- const fileSet = new Set(files);
3254
- const graph = new Map();
3255
-
3256
- for (const file of files) {
3257
- const content = fs.readFileSync(file, 'utf-8');
3258
- const dir = path.dirname(file);
3259
- const imports = new Set();
3260
-
3261
- // ES imports: import ... from '...' and import '...'
3262
- const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
3263
- let m;
3264
- while ((m = esRe.exec(content)) !== null) {
3265
- const resolved = resolveImport(m[1], dir, fileSet);
3266
- if (resolved) imports.add(resolved);
3267
- }
3268
-
3269
- // CSS @import
3270
- const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
3271
- while ((m = cssRe.exec(content)) !== null) {
3272
- const resolved = resolveImport(m[1], dir, fileSet);
3273
- if (resolved) imports.add(resolved);
3274
- }
3275
-
3276
- // SCSS @use / @forward
3277
- const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
3278
- while ((m = scssRe.exec(content)) !== null) {
3279
- const resolved = resolveImport(m[1], dir, fileSet);
3280
- if (resolved) imports.add(resolved);
3281
- }
3282
-
3283
- graph.set(file, imports);
3284
- }
3285
- return graph;
3286
- }
3287
-
3288
- // ---------------------------------------------------------------------------
3289
- // Framework dev server detection
3290
- // ---------------------------------------------------------------------------
3291
-
3292
- const FRAMEWORK_CONFIGS = [
3293
- { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
3294
- portRe: /port\s*[:=]\s*(\d+)/,
3295
- fingerprint: { header: 'x-powered-by', value: /next/i } },
3296
- { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
3297
- portRe: /port\s*[:=]\s*(\d+)/,
3298
- fingerprint: { header: 'x-sveltekit-page', value: null } },
3299
- { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
3300
- portRe: /port\s*[:=]\s*(\d+)/,
3301
- fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
3302
- { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
3303
- portRe: /port\s*[:=]\s*(\d+)/,
3304
- fingerprint: { body: /@vite\/client/ } },
3305
- { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
3306
- portRe: /port\s*[:=]\s*(\d+)/,
3307
- fingerprint: { body: /astro/i } },
3308
- { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
3309
- portRe: /"port"\s*:\s*(\d+)/,
3310
- fingerprint: { body: /ng-version/i } },
3311
- { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
3312
- portRe: /port\s*[:=]\s*(\d+)/,
3313
- fingerprint: { header: 'x-powered-by', value: /remix/i } },
3314
- ];
3315
-
3316
- function detectFrameworkConfig(dir) {
3317
- let entries;
3318
- try { entries = fs.readdirSync(dir); } catch { return null; }
3319
- const entrySet = new Set(entries);
3320
-
3321
- for (const cfg of FRAMEWORK_CONFIGS) {
3322
- const match = cfg.files.find(f => entrySet.has(f));
3323
- if (!match) continue;
3324
-
3325
- const configPath = path.join(dir, match);
3326
- let port = cfg.defaultPort;
3327
- try {
3328
- const content = fs.readFileSync(configPath, 'utf-8');
3329
- const portMatch = content.match(cfg.portRe);
3330
- if (portMatch) port = parseInt(portMatch[1], 10);
3331
- } catch { /* use default */ }
3332
-
3333
- return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
3334
- }
3335
- return null;
3336
- }
3337
-
3338
- /**
3339
- * Check if a port is listening and optionally verify it matches the expected framework.
3340
- * Returns { listening: true, matched: true/false } or { listening: false }.
3341
- */
3342
- async function isPortListening(port, fingerprint = null) {
3343
- if (!fingerprint) {
3344
- // Simple TCP probe fallback
3345
- const net = await import('node:net');
3346
- return new Promise((resolve) => {
3347
- const sock = net.default.createConnection({ port, host: '127.0.0.1' });
3348
- sock.setTimeout(500);
3349
- sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
3350
- sock.on('error', () => resolve({ listening: false }));
3351
- sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
3352
- });
3353
- }
3354
-
3355
- // HTTP probe with fingerprint matching
3356
- try {
3357
- const controller = new AbortController();
3358
- const timeout = setTimeout(() => controller.abort(), 2000);
3359
- const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
3360
- clearTimeout(timeout);
3361
-
3362
- // Check header fingerprint
3363
- if (fingerprint.header) {
3364
- const val = res.headers.get(fingerprint.header);
3365
- if (val && (!fingerprint.value || fingerprint.value.test(val))) {
3366
- return { listening: true, matched: true };
3367
- }
3368
- }
3369
-
3370
- // Check body fingerprint
3371
- if (fingerprint.body) {
3372
- const body = await res.text();
3373
- if (fingerprint.body.test(body)) {
3374
- return { listening: true, matched: true };
3375
- }
3376
- }
3377
-
3378
- // Port is listening but doesn't match the expected framework
3379
- return { listening: true, matched: false };
3380
- } catch {
3381
- return { listening: false };
3382
- }
3383
- }
3384
-
3385
- // ---------------------------------------------------------------------------
3386
- // CLI
3387
- // ---------------------------------------------------------------------------
3388
-
3389
- async function confirm(question) {
3390
- const rl = (await import('node:readline')).default.createInterface({
3391
- input: process.stdin, output: process.stderr,
3392
- });
3393
- return new Promise((resolve) => {
3394
- rl.question(`${question} [Y/n] `, (answer) => {
3395
- rl.close();
3396
- resolve(!answer || /^y(es)?$/i.test(answer.trim()));
3397
- });
3398
- });
3399
- }
3400
-
3401
- function printUsage() {
3402
- console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
3403
-
3404
- Scan files or URLs for UI anti-patterns and design quality issues.
3405
-
3406
- Options:
3407
- --fast Regex-only mode (skip jsdom, faster but misses linked stylesheets)
3408
- --json Output results as JSON
3409
- --help Show this help message
3410
-
3411
- Detection modes:
3412
- HTML files jsdom with computed styles (default, catches linked CSS)
3413
- Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
3414
- URLs Puppeteer full browser rendering (auto-detected)
3415
- --fast Forces regex for all files
3416
-
3417
- Examples:
3418
- impeccable detect src/
3419
- impeccable detect index.html
3420
- impeccable detect https://example.com
3421
- impeccable detect --fast --json .`);
3422
- }
3423
-
3424
- async function main() {
3425
- const args = process.argv.slice(2);
3426
- const jsonMode = args.includes('--json');
3427
- const helpMode = args.includes('--help');
3428
- const fastMode = args.includes('--fast');
3429
- const targets = args.filter(a => !a.startsWith('--'));
3430
-
3431
- if (helpMode) { printUsage(); process.exit(0); }
3432
-
3433
- let allFindings = [];
3434
-
3435
- if (!process.stdin.isTTY && targets.length === 0) {
3436
- allFindings = await handleStdin();
3437
- } else {
3438
- const paths = targets.length > 0 ? targets : [process.cwd()];
3439
-
3440
- for (const target of paths) {
3441
- if (/^https?:\/\//i.test(target)) {
3442
- try { allFindings.push(...await detectUrl(target)); }
3443
- catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
3444
- continue;
3445
- }
3446
-
3447
- const resolved = path.resolve(target);
3448
- let stat;
3449
- try { stat = fs.statSync(resolved); }
3450
- catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
3451
-
3452
- if (stat.isDirectory()) {
3453
- // Check for framework dev server config (skip in JSON mode to avoid polluting output)
3454
- if (!jsonMode) {
3455
- const fwConfig = detectFrameworkConfig(resolved);
3456
- if (fwConfig) {
3457
- const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
3458
- if (probe.listening && probe.matched) {
3459
- process.stderr.write(
3460
- `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
3461
- `For more accurate results, scan the running site:\n` +
3462
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
3463
- );
3464
- } else if (probe.listening && !probe.matched) {
3465
- process.stderr.write(
3466
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
3467
- `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
3468
- );
3469
- } else {
3470
- process.stderr.write(
3471
- `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
3472
- `Start the dev server and scan via URL for best results:\n` +
3473
- ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
3474
- );
3475
- }
3476
- }
3477
- }
3478
-
3479
- const files = walkDir(resolved);
3480
- const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
3481
-
3482
- // Warn and confirm if scanning many files (jsdom is slow per HTML file)
3483
- if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
3484
- process.stderr.write(
3485
- `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
3486
- `Scanning may take a while${htmlCount > 10 ? ' (jsdom processes each HTML file individually)' : ''}.\n` +
3487
- `Use --fast to skip jsdom, or target a specific subdirectory.\n`
3488
- );
3489
- const ok = await confirm('Continue?');
3490
- if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
3491
- }
3492
-
3493
- // Build import graph for multi-file awareness
3494
- const graph = buildImportGraph(files);
3495
- // Build reverse map: file -> set of files that import it
3496
- const importedByMap = new Map();
3497
- for (const [importer, imports] of graph) {
3498
- for (const imported of imports) {
3499
- if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
3500
- importedByMap.get(imported).add(importer);
3501
- }
3502
- }
3503
-
3504
- for (const file of files) {
3505
- const ext = path.extname(file).toLowerCase();
3506
- let fileFindings;
3507
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
3508
- fileFindings = await detectHtml(file);
3509
- } else {
3510
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
3511
- }
3512
- // Annotate findings with import context
3513
- const importers = importedByMap.get(file);
3514
- if (importers && importers.size > 0) {
3515
- const importerNames = [...importers].map(f => path.basename(f));
3516
- for (const f of fileFindings) {
3517
- f.importedBy = importerNames;
3518
- }
3519
- }
3520
- allFindings.push(...fileFindings);
3521
- }
3522
- } else if (stat.isFile()) {
3523
- const ext = path.extname(resolved).toLowerCase();
3524
- if (!fastMode && HTML_EXTENSIONS.has(ext)) {
3525
- allFindings.push(...await detectHtml(resolved));
3526
- } else {
3527
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved));
3528
- }
3529
- }
3530
- }
3531
- }
3532
-
3533
- if (allFindings.length > 0) {
3534
- process.stderr.write(formatFindings(allFindings, jsonMode) + '\n');
3535
- process.exit(2);
3536
- }
3537
- if (jsonMode) process.stdout.write('[]\n');
3538
- process.exit(0);
3539
- }
3540
-
3541
- // ---------------------------------------------------------------------------
3542
- // Entry point
3543
- // ---------------------------------------------------------------------------
3544
-
3545
- if (!IS_BROWSER) {
3546
- const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
3547
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
3548
- if (isMainModule) main();
3549
- }
3550
-
3551
- // @browser-strip-end
3552
-
3553
- // ─── Section 9: Exports ─────────────────────────────────────────────────────
3554
- // @browser-strip-start
3555
-
3556
- export {
3557
- ANTIPATTERNS, SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS,
3558
- checkElementBorders, checkElementMotion, checkElementGlow, checkPageTypography, checkPageLayout, isNeutralColor, isFullPage,
3559
- detectHtml, detectUrl, detectText,
3560
- walkDir, formatFindings, SCANNABLE_EXTENSIONS, SKIP_DIRS,
3561
- extractStyleBlocks, extractCSSinJS,
3562
- buildImportGraph, resolveImport,
3563
- detectFrameworkConfig, isPortListening, FRAMEWORK_CONFIGS,
3564
- main as detectCli,
3565
- };
3566
-
3567
- // @browser-strip-end