impeccable 3.5.0 → 3.6.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.
@@ -741,11 +741,43 @@ function contrastRatio(c1, c2) {
741
741
  return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
742
742
  }
743
743
 
744
+ // The CSS color functions worth pulling out of a longer declaration. The set
745
+ // is deliberately closed: `linear-gradient(` and `url(` also look like
746
+ // `name(` and must not be read as colors.
747
+ const COLOR_FUNCTION_NAMES = new Set([
748
+ 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'oklch', 'oklab', 'lch', 'lab', 'color', 'color-mix',
749
+ ]);
750
+
751
+ // Pull every color-function token out of a value, with balanced-paren capture
752
+ // so nested forms (`color-mix(in oklab, oklch(...) 20%, transparent)`) survive
753
+ // whole. Returns the raw substrings in source order.
754
+ function extractColorFunctionTokens(value) {
755
+ const str = String(value || '');
756
+ const tokens = [];
757
+ const re = /([a-z][a-z-]*)\(/gi;
758
+ let m;
759
+ while ((m = re.exec(str)) !== null) {
760
+ if (!COLOR_FUNCTION_NAMES.has(m[1].toLowerCase())) continue;
761
+ let depth = 0, end = -1;
762
+ for (let i = m.index + m[0].length - 1; i < str.length; i++) {
763
+ if (str[i] === '(') depth++;
764
+ else if (str[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
765
+ }
766
+ if (end < 0) break;
767
+ tokens.push(str.slice(m.index, end + 1));
768
+ re.lastIndex = end + 1;
769
+ }
770
+ return tokens;
771
+ }
772
+
744
773
  function parseGradientColors(bgImage) {
745
774
  if (!bgImage || !bgImage.includes('gradient')) return [];
746
775
  const colors = [];
747
- for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
748
- const c = parseRgb(m[0]);
776
+ // Stops arrive in whatever syntax the author wrote and the browser kept.
777
+ // A dark ground painted as `linear-gradient(oklch(...), oklch(...))` used
778
+ // to read as a gradient with no stops at all.
779
+ for (const token of extractColorFunctionTokens(bgImage)) {
780
+ const c = parseAnyColor(token);
749
781
  if (c) colors.push(c);
750
782
  }
751
783
  for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
@@ -782,102 +814,548 @@ function colorToHex(c) {
782
814
  return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
783
815
  }
784
816
 
785
- // --- cli/engine/shared/fonts.mjs ---
786
- const GOOGLE_FONTS_URL_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
817
+ // ─── Color-space conversions ────────────────────────────────────────────────
818
+ //
819
+ // Every function here lands on 8-bit sRGB, clamped to gamut. Chrome, Safari,
820
+ // and Firefox all keep the authored color space in getComputedStyle output
821
+ // (`oklch(0.84 0.19 80.46)`, `lch(20 5 60)`, `color(srgb 1.04 0.72 -0.21)`),
822
+ // so a detector that only reads rgb() is blind on any modern palette. The
823
+ // expected outputs are pinned in tests/detect-antipatterns.test.js against
824
+ // what Chrome itself paints for the same strings.
787
825
 
788
- function normalizeGoogleFontFamilyParam(value) {
789
- return String(value || '')
790
- .split('|')
791
- .map(part => part.split(':')[0].trim().toLowerCase())
792
- .filter(Boolean);
826
+ function clamp01(x) {
827
+ return Number.isFinite(x) ? Math.max(0, Math.min(1, x)) : 0;
793
828
  }
794
829
 
795
- function extractGoogleFontFamilies(text) {
796
- const families = [];
797
- if (!text) return families;
830
+ // Linear-light sRGB channel to the encoded 0-255 value.
831
+ function encodeSrgbChannel(x) {
832
+ const c = clamp01(x);
833
+ return Math.round((c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055) * 255);
834
+ }
798
835
 
799
- GOOGLE_FONTS_URL_RE.lastIndex = 0;
800
- let urlMatch;
801
- while ((urlMatch = GOOGLE_FONTS_URL_RE.exec(text)) !== null) {
802
- const url = urlMatch[0];
803
- const queryStart = url.indexOf('?');
804
- if (queryStart === -1) continue;
836
+ function decodeSrgbChannel(x) {
837
+ const c = Number.isFinite(x) ? x : 0;
838
+ const sign = c < 0 ? -1 : 1;
839
+ const abs = Math.abs(c);
840
+ return sign * (abs <= 0.04045 ? abs / 12.92 : Math.pow((abs + 0.055) / 1.055, 2.4));
841
+ }
805
842
 
806
- const params = new URLSearchParams(url.slice(queryStart + 1).replace(/&amp;/g, '&'));
807
- for (const value of params.getAll('family')) {
808
- families.push(...normalizeGoogleFontFamilyParam(value));
809
- }
810
- }
843
+ function linearSrgbToColor(r, g, b, a = 1) {
844
+ return { r: encodeSrgbChannel(r), g: encodeSrgbChannel(g), b: encodeSrgbChannel(b), a };
845
+ }
811
846
 
812
- return families;
847
+ // OKLab to sRGB (Björn Ottosson's matrices). L in 0..1, a/b are signed axes.
848
+ function oklabToRgb(L, a, b) {
849
+ const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
850
+ const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
851
+ const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
852
+ const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
853
+ return linearSrgbToColor(
854
+ 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc,
855
+ -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc,
856
+ -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc,
857
+ );
813
858
  }
814
859
 
815
- // --- cli/engine/rules/checks.mjs ---
816
- const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
860
+ // OKLCH to sRGB. L in 0..1, C in 0..~0.4 typical, H in degrees. Chroma past
861
+ // the sRGB gamut clamps per channel rather than producing NaN.
862
+ function oklchToRgb(L, C, H) {
863
+ const hRad = (H * Math.PI) / 180;
864
+ return oklabToRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
865
+ }
817
866
 
818
- // ─── Section 3: Pure Detection ──────────────────────────────────────────────
867
+ // CIE Lab to sRGB. CSS lab()/lch() use the D50 white point; the matrix below
868
+ // is the Bradford-adapted XYZ-D50 to linear-sRGB transform from CSS Color 4.
869
+ function labToRgb(L, a, b) {
870
+ const kappa = 24389 / 27, epsilon = 216 / 24389;
871
+ const fy = (L + 16) / 116, fx = fy + a / 500, fz = fy - b / 200;
872
+ const invert = (t) => (t * t * t > epsilon ? t * t * t : (116 * t - 16) / kappa);
873
+ const yr = L > kappa * epsilon ? Math.pow((L + 16) / 116, 3) : L / kappa;
874
+ const Xn = 0.3457 / 0.3585, Zn = (1 - 0.3457 - 0.3585) / 0.3585;
875
+ const x = invert(fx) * Xn, y = yr, z = invert(fz) * Zn;
876
+ return linearSrgbToColor(
877
+ 3.1341359569958707 * x - 1.6173863321612538 * y - 0.4906619460083532 * z,
878
+ -0.9787955029120890 * x + 1.9162545672595240 * y + 0.0334427311613195 * z,
879
+ 0.0719553798841168 * x - 0.2289768264158322 * y + 1.4053860583241250 * z,
880
+ );
881
+ }
819
882
 
820
- function checkBorders(tag, widths, colors, radius, opts = {}) {
821
- // Badge-shaped <span>s (own visible background) are a real stripe target
822
- // for the top/bottom variant — the inline-tag exemption exists to quiet
823
- // text-level borders, not chips. They skip the left/right arms below.
824
- const spanBadge = tag === 'span' && !!opts.badgeLike;
825
- if (BORDER_SAFE_TAGS.has(tag) && !spanBadge) return [];
826
- // A live status/alert region wears a colored single-edge border as a
827
- // severity accent (toast, snackbar, callout), not as the side-tab tell.
828
- if (opts.statusContext) return [];
829
- const findings = [];
830
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
883
+ function lchToRgb(L, C, H) {
884
+ const hRad = (H * Math.PI) / 180;
885
+ return labToRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
886
+ }
887
+
888
+ // color(<space> c1 c2 c3) for the spaces that turn up in real stylesheets.
889
+ // `srgb` is what Chrome serializes most color-mix() results into, routinely
890
+ // with channels outside 0..1. Spaces we do not model return null so callers
891
+ // abstain instead of measuring against a color we invented.
892
+ function colorFunctionToRgb(space, c1, c2, c3) {
893
+ switch (space) {
894
+ case 'srgb':
895
+ return { r: Math.round(clamp01(c1) * 255), g: Math.round(clamp01(c2) * 255), b: Math.round(clamp01(c3) * 255), a: 1 };
896
+ case 'srgb-linear':
897
+ return linearSrgbToColor(c1, c2, c3);
898
+ case 'display-p3': {
899
+ const [R, G, B] = [decodeSrgbChannel(c1), decodeSrgbChannel(c2), decodeSrgbChannel(c3)];
900
+ return linearSrgbToColor(
901
+ 1.2249401762805587 * R - 0.2249404646817506 * G + 0.0000002884022551 * B,
902
+ -0.0420569547096138 * R + 1.0420571661298634 * G - 0.0000002113202247 * B,
903
+ -0.0196375587040044 * R - 0.0786360772174755 * G + 1.0982736359214800 * B,
904
+ );
905
+ }
906
+ default:
907
+ return null;
908
+ }
909
+ }
831
910
 
832
- for (const side of sides) {
833
- const w = widths[side];
834
- if (w < 1 || isNeutralColor(colors[side])) continue;
911
+ function hslToRgb(h, s, l) {
912
+ h = ((h % 360) + 360) % 360;
913
+ const c = (1 - Math.abs(2 * l - 1)) * s;
914
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
915
+ const m0 = l - c / 2;
916
+ const [r, g, b] =
917
+ h < 60 ? [c, x, 0] :
918
+ h < 120 ? [x, c, 0] :
919
+ h < 180 ? [0, c, x] :
920
+ h < 240 ? [0, x, c] :
921
+ h < 300 ? [x, 0, c] : [c, 0, x];
922
+ return {
923
+ r: Math.round((r + m0) * 255),
924
+ g: Math.round((g + m0) * 255),
925
+ b: Math.round((b + m0) * 255),
926
+ a: 1,
927
+ };
928
+ }
835
929
 
836
- const otherSides = sides.filter(s => s !== side);
837
- const maxOther = Math.max(...otherSides.map(s => widths[s]));
838
- if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
930
+ function hwbToRgb(h, w, bl) {
931
+ if (w + bl >= 1) {
932
+ const g = Math.round((w / (w + bl)) * 255);
933
+ return { r: g, g, b: g, a: 1 };
934
+ }
935
+ const base = hslToRgb(h, 1, 0.5);
936
+ const mix = (c) => Math.round(((c / 255) * (1 - w - bl) + w) * 255);
937
+ return { r: mix(base.r), g: mix(base.g), b: mix(base.b), a: 1 };
938
+ }
839
939
 
840
- const sn = side.toLowerCase();
841
- const isSide = side === 'Left' || side === 'Right';
940
+ // Common CSS named colors — the handful that actually show up in generated
941
+ // UIs, not the full 148-name spec list. Includes the achromatic names so a
942
+ // named gray parses (and correctly reads as no-chroma) instead of being
943
+ // treated as an unknown color.
944
+ const CSS_NAMED_COLORS = {
945
+ black: { r: 0, g: 0, b: 0 },
946
+ white: { r: 255, g: 255, b: 255 },
947
+ gray: { r: 128, g: 128, b: 128 },
948
+ grey: { r: 128, g: 128, b: 128 },
949
+ silver: { r: 192, g: 192, b: 192 },
950
+ dimgray: { r: 105, g: 105, b: 105 },
951
+ darkgray: { r: 169, g: 169, b: 169 },
952
+ lightgray: { r: 211, g: 211, b: 211 },
953
+ gainsboro: { r: 220, g: 220, b: 220 },
954
+ whitesmoke: { r: 245, g: 245, b: 245 },
955
+ red: { r: 255, g: 0, b: 0 },
956
+ crimson: { r: 220, g: 20, b: 60 },
957
+ tomato: { r: 255, g: 99, b: 71 },
958
+ coral: { r: 255, g: 127, b: 80 },
959
+ salmon: { r: 250, g: 128, b: 114 },
960
+ orange: { r: 255, g: 165, b: 0 },
961
+ gold: { r: 255, g: 215, b: 0 },
962
+ yellow: { r: 255, g: 255, b: 0 },
963
+ olive: { r: 128, g: 128, b: 0 },
964
+ lime: { r: 0, g: 255, b: 0 },
965
+ green: { r: 0, g: 128, b: 0 },
966
+ teal: { r: 0, g: 128, b: 128 },
967
+ turquoise: { r: 64, g: 224, b: 208 },
968
+ cyan: { r: 0, g: 255, b: 255 },
969
+ aqua: { r: 0, g: 255, b: 255 },
970
+ skyblue: { r: 135, g: 206, b: 235 },
971
+ dodgerblue: { r: 30, g: 144, b: 255 },
972
+ blue: { r: 0, g: 0, b: 255 },
973
+ navy: { r: 0, g: 0, b: 128 },
974
+ indigo: { r: 75, g: 0, b: 130 },
975
+ rebeccapurple: { r: 102, g: 51, b: 153 },
976
+ purple: { r: 128, g: 0, b: 128 },
977
+ violet: { r: 238, g: 130, b: 238 },
978
+ orchid: { r: 218, g: 112, b: 214 },
979
+ magenta: { r: 255, g: 0, b: 255 },
980
+ fuchsia: { r: 255, g: 0, b: 255 },
981
+ hotpink: { r: 255, g: 105, b: 180 },
982
+ pink: { r: 255, g: 192, b: 203 },
983
+ maroon: { r: 128, g: 0, b: 0 },
984
+ };
842
985
 
843
- if (isSide) {
844
- if (spanBadge) continue;
845
- if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
846
- else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
847
- } else {
848
- if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
849
- // Horizontal variant of the side-tab stripe: a thick chromatic accent
850
- // riding the top or bottom edge of a card/badge/container. Same
851
- // dominant-edge + chroma gates as left/right, 3-12px band. Selected-
852
- // tab underlines are exempt via opts.tabContext (adapters look for
853
- // tablist/nav/tab ancestors and aria-selected); links, buttons,
854
- // table cells, and <hr> never reach here (BORDER_SAFE_TAGS).
855
- else if (!opts.tabContext && w >= 3 && w <= 12) {
856
- findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
857
- }
986
+ // Split a string on top-level commas (ignoring commas nested in parens).
987
+ function splitTopLevelCommas(str) {
988
+ const parts = [];
989
+ let depth = 0, start = 0;
990
+ for (let i = 0; i < str.length; i++) {
991
+ const ch = str[i];
992
+ if (ch === '(') depth++;
993
+ else if (ch === ')') depth = Math.max(0, depth - 1);
994
+ else if (ch === ',' && depth === 0) {
995
+ parts.push(str.slice(start, i).trim());
996
+ start = i + 1;
858
997
  }
859
998
  }
999
+ const tail = str.slice(start).trim();
1000
+ if (tail) parts.push(tail);
1001
+ return parts;
1002
+ }
860
1003
 
861
- return findings;
1004
+ // Evaluate a CSS color-mix() expression to {r,g,b,a}. Returns null when
1005
+ // the expression can't be resolved (unresolved var(), unknown colors).
1006
+ //
1007
+ // Mixing is done with premultiplied alpha in sRGB regardless of the
1008
+ // declared interpolation space. That is exact for the dominant generated-UI
1009
+ // pattern — `color-mix(in oklab, <color> N%, transparent)` — where the
1010
+ // result is simply <color> at alpha N% in ANY rectangular space, and a
1011
+ // close-enough approximation for opaque-opaque mixes (the detector only
1012
+ // consumes these values for contrast/chroma thresholds, not for display).
1013
+ function parseColorMix(str) {
1014
+ const m = String(str).trim().match(/^color-mix\(/i);
1015
+ if (!m) return null;
1016
+ // Balanced-paren capture of the arguments.
1017
+ let depth = 0, end = -1;
1018
+ const open = str.indexOf('(');
1019
+ for (let i = open; i < str.length; i++) {
1020
+ if (str[i] === '(') depth++;
1021
+ else if (str[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
1022
+ }
1023
+ if (end < 0) return null;
1024
+ const args = splitTopLevelCommas(str.slice(open + 1, end));
1025
+ if (args.length !== 3 || !/^in\s/i.test(args[0])) return null;
1026
+
1027
+ const parseComponent = (component) => {
1028
+ // Percentage may lead or trail the color per spec.
1029
+ let pct = null;
1030
+ let colorStr = component;
1031
+ const trail = component.match(/\s+([\d.]+)%$/);
1032
+ const lead = component.match(/^([\d.]+)%\s+/);
1033
+ if (trail) { pct = parseFloat(trail[1]); colorStr = component.slice(0, trail.index).trim(); }
1034
+ else if (lead) { pct = parseFloat(lead[1]); colorStr = component.slice(lead[0].length).trim(); }
1035
+ let color;
1036
+ if (/^transparent$/i.test(colorStr)) color = { r: 0, g: 0, b: 0, a: 0 };
1037
+ else color = parseAnyColor(colorStr);
1038
+ if (!color) return null;
1039
+ return { color, pct };
1040
+ };
1041
+
1042
+ const c1 = parseComponent(args[1]);
1043
+ const c2 = parseComponent(args[2]);
1044
+ if (!c1 || !c2) return null;
1045
+ let p1 = c1.pct, p2 = c2.pct;
1046
+ if (p1 == null && p2 == null) { p1 = 50; p2 = 50; }
1047
+ else if (p1 == null) p1 = 100 - p2;
1048
+ else if (p2 == null) p2 = 100 - p1;
1049
+ const sum = p1 + p2;
1050
+ if (sum <= 0) return null;
1051
+ // Per spec: weights normalize to sum; when sum < 100 the result alpha is
1052
+ // additionally scaled by sum/100.
1053
+ const w1 = p1 / sum, w2 = p2 / sum;
1054
+ const alphaScale = sum < 100 ? sum / 100 : 1;
1055
+ const a1 = c1.color.a ?? 1, a2 = c2.color.a ?? 1;
1056
+ const a = (a1 * w1 + a2 * w2) * alphaScale;
1057
+ if (a <= 0) return { r: 0, g: 0, b: 0, a: 0 };
1058
+ const mix = (ch) => Math.round((c1.color[ch] * a1 * w1 + c2.color[ch] * a2 * w2) / (a1 * w1 + a2 * w2));
1059
+ return { r: mix('r'), g: mix('g'), b: mix('b'), a: Math.min(1, a) };
862
1060
  }
863
1061
 
864
- // Returns true if the given text is composed entirely of emoji characters
865
- // (plus whitespace / variation selectors). Emojis render as multicolor glyphs
866
- // regardless of CSS `color`, so contrast checks against the element's text
867
- // color are meaningless for these nodes.
868
- 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;
869
- 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;
870
- function isEmojiOnlyText(text) {
871
- if (!text) return false;
872
- if (!EMOJI_CHAR_RE.test(text)) return false;
873
- return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
1062
+ // Composite a translucent color over an opaque(ish) base (simple
1063
+ // source-over in sRGB). Returns an opaque {r,g,b,a:1}.
1064
+ function compositeColorOver(top, base) {
1065
+ const a = top.a ?? 1;
1066
+ return {
1067
+ r: Math.round(top.r * a + base.r * (1 - a)),
1068
+ g: Math.round(top.g * a + base.g * (1 - a)),
1069
+ b: Math.round(top.b * a + base.b * (1 - a)),
1070
+ a: 1,
1071
+ };
874
1072
  }
875
1073
 
876
- function checkColors(opts) {
877
- const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
878
- if (SAFE_TAGS.has(tag)) {
879
- // Exception for elements styled as controls or chips. SAFE_TAGS exists to
880
- // suppress contrast noise on inline links and unstyled spans, where the
1074
+ // A color() / lab() / lch() component: a bare number, a percentage against
1075
+ // `scale`, or the `none` keyword (which resolves to zero for our purposes).
1076
+ function parseColorComponent(token, scale = 1) {
1077
+ if (token == null) return null;
1078
+ const t = String(token).trim();
1079
+ if (/^none$/i.test(t)) return 0;
1080
+ const num = parseFloat(t);
1081
+ if (!Number.isFinite(num)) return null;
1082
+ return t.endsWith('%') ? (num / 100) * scale : num;
1083
+ }
1084
+
1085
+ function parseAlphaToken(token) {
1086
+ if (token == null) return 1;
1087
+ const t = String(token).trim();
1088
+ if (/^none$/i.test(t)) return 1;
1089
+ const num = parseFloat(t);
1090
+ if (!Number.isFinite(num)) return 1;
1091
+ return t.endsWith('%') ? num / 100 : num;
1092
+ }
1093
+
1094
+ // Extended color parser: rgb/rgba/hex/oklch/oklab/lch/lab/hsl/hwb/color()/
1095
+ // color-mix/common named colors. Returns null on no match. Use this when the
1096
+ // input might be any CSS color form; use plain parseRgb when you only expect
1097
+ // computed rgb() values from real browsers.
1098
+ function parseAnyColor(s) {
1099
+ if (!s || typeof s !== 'string') return null;
1100
+ const str = s.trim();
1101
+ if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
1102
+ if (/^color-mix\(/i.test(str)) return parseColorMix(str);
1103
+ let m;
1104
+ m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+)(%)?)?\s*\)/);
1105
+ if (m) {
1106
+ const c = { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: 1 };
1107
+ if (m[4] !== undefined) c.a = m[5] === '%' ? parseFloat(m[4]) / 100 : +m[4];
1108
+ return c;
1109
+ }
1110
+ m = str.match(/^#([0-9a-f]{3,8})$/i);
1111
+ if (m) {
1112
+ const h = m[1];
1113
+ if (h.length === 3 || h.length === 4) {
1114
+ return {
1115
+ r: parseInt(h[0] + h[0], 16),
1116
+ g: parseInt(h[1] + h[1], 16),
1117
+ b: parseInt(h[2] + h[2], 16),
1118
+ a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
1119
+ };
1120
+ }
1121
+ if (h.length === 6 || h.length === 8) {
1122
+ return {
1123
+ r: parseInt(h.slice(0, 2), 16),
1124
+ g: parseInt(h.slice(2, 4), 16),
1125
+ b: parseInt(h.slice(4, 6), 16),
1126
+ a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
1127
+ };
1128
+ }
1129
+ }
1130
+ // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
1131
+ // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
1132
+ // Match L (with optional %), then C and H separated permissively.
1133
+ m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
1134
+ if (m) {
1135
+ const Lnum = parseFloat(m[1]);
1136
+ const L = m[2] === '%' ? Lnum / 100 : Lnum;
1137
+ const rgb = oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
1138
+ if (m[5] !== undefined) {
1139
+ const alpha = parseFloat(m[5]);
1140
+ rgb.a = m[6] === '%' ? alpha / 100 : alpha;
1141
+ }
1142
+ return rgb;
1143
+ }
1144
+ // OKLAB — a/b are signed axes; percentages map 100% → 0.4.
1145
+ m = str.match(/oklab\(\s*([\d.]+)(%?)\s+(-?[\d.]+)(%?)\s+(-?[\d.]+)(%?)(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
1146
+ if (m) {
1147
+ const L = m[2] === '%' ? parseFloat(m[1]) / 100 : parseFloat(m[1]);
1148
+ const a = m[4] === '%' ? parseFloat(m[3]) * 0.004 : parseFloat(m[3]);
1149
+ const b = m[6] === '%' ? parseFloat(m[5]) * 0.004 : parseFloat(m[5]);
1150
+ const rgb = oklabToRgb(L, a, b);
1151
+ if (m[7] !== undefined) {
1152
+ const alpha = parseFloat(m[7]);
1153
+ rgb.a = m[8] === '%' ? alpha / 100 : alpha;
1154
+ }
1155
+ return rgb;
1156
+ }
1157
+ // LCH / LAB — CIE, D50 white point. Chrome serializes lch(20% 5 60) as
1158
+ // `lch(20 5 60)`, so L arrives with or without its percent sign. In both
1159
+ // spaces L runs 0..100 and 100% means 100.
1160
+ m = str.match(/^lch\(\s*([\d.]+%?|none)\s+([\d.]+%?|none)\s+(-?[\d.]+)(?:deg)?(?:\s*\/\s*([\d.]+%?|none))?\s*\)$/i);
1161
+ if (m) {
1162
+ const L = parseColorComponent(m[1], 100);
1163
+ const C = parseColorComponent(m[2], 150);
1164
+ const H = parseFloat(m[3]);
1165
+ if (L == null || C == null || !Number.isFinite(H)) return null;
1166
+ const rgb = lchToRgb(L, C, H);
1167
+ rgb.a = parseAlphaToken(m[4]);
1168
+ return rgb;
1169
+ }
1170
+ m = str.match(/^lab\(\s*([\d.]+%?|none)\s+(-?[\d.]+%?|none)\s+(-?[\d.]+%?|none)(?:\s*\/\s*([\d.]+%?|none))?\s*\)$/i);
1171
+ if (m) {
1172
+ const L = parseColorComponent(m[1], 100);
1173
+ const a = parseColorComponent(m[2], 125);
1174
+ const b = parseColorComponent(m[3], 125);
1175
+ if (L == null || a == null || b == null) return null;
1176
+ const rgb = labToRgb(L, a, b);
1177
+ rgb.a = parseAlphaToken(m[4]);
1178
+ return rgb;
1179
+ }
1180
+ // color(<space> c1 c2 c3 [/ alpha]) — what Chrome hands back for most
1181
+ // color-mix() results and for any wide-gamut color an author wrote.
1182
+ m = str.match(/^color\(\s*([a-z0-9-]+)\s+(-?[\d.eE+-]+%?|none)\s+(-?[\d.eE+-]+%?|none)\s+(-?[\d.eE+-]+%?|none)(?:\s*\/\s*([\d.]+%?|none))?\s*\)$/i);
1183
+ if (m) {
1184
+ const c1 = parseColorComponent(m[2]);
1185
+ const c2 = parseColorComponent(m[3]);
1186
+ const c3 = parseColorComponent(m[4]);
1187
+ if (c1 == null || c2 == null || c3 == null) return null;
1188
+ const rgb = colorFunctionToRgb(m[1].toLowerCase(), c1, c2, c3);
1189
+ if (!rgb) return null;
1190
+ rgb.a = parseAlphaToken(m[5]);
1191
+ return rgb;
1192
+ }
1193
+ // HSL/HSLA — comma or space syntax, optional deg on hue.
1194
+ m = str.match(/hsla?\(\s*(-?[\d.]+)(?:deg)?\s*[,\s]\s*([\d.]+)%\s*[,\s]\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+)(%)?)?\s*\)/i);
1195
+ if (m) {
1196
+ const rgb = hslToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
1197
+ if (m[4] !== undefined) {
1198
+ const alpha = parseFloat(m[4]);
1199
+ rgb.a = m[5] === '%' ? alpha / 100 : alpha;
1200
+ }
1201
+ return rgb;
1202
+ }
1203
+ // HWB — hue whiteness% blackness%.
1204
+ m = str.match(/hwb\(\s*(-?[\d.]+)(?:deg)?\s+([\d.]+)%\s+([\d.]+)%(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
1205
+ if (m) {
1206
+ const rgb = hwbToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
1207
+ if (m[4] !== undefined) {
1208
+ const alpha = parseFloat(m[4]);
1209
+ rgb.a = m[5] === '%' ? alpha / 100 : alpha;
1210
+ }
1211
+ return rgb;
1212
+ }
1213
+ const named = CSS_NAMED_COLORS[str.toLowerCase()];
1214
+ if (named) return { ...named, a: 1 };
1215
+ return null;
1216
+ }
1217
+
1218
+ // True when a computed background-color string names no paint at all. Used to
1219
+ // tell "this layer is see-through" (walk on to the ancestor) apart from "this
1220
+ // layer has a color we could not read" (stop and abstain).
1221
+ //
1222
+ // `inherit` belongs here even though it is not literally see-through: it means
1223
+ // "paint with the parent's background-color", and walking on to the parent IS
1224
+ // that resolution. Real browsers resolve the keyword before getComputedStyle
1225
+ // output; only jsdom's partial cascade hands it through verbatim, and treating
1226
+ // it as unreadable would make the walk abstain on a surface it can know.
1227
+ // (`currentcolor` is NOT here — it is real paint in the element's own text
1228
+ // color; resolveBackgroundInfo substitutes the computed color for it.)
1229
+ function isNoPaintColorValue(value) {
1230
+ const v = String(value || '').trim().toLowerCase();
1231
+ if (!v) return true;
1232
+ return v === 'transparent' || v === 'none' || v === 'initial' || v === 'inherit' || v === 'unset' || v === 'revert' || v === 'revert-layer';
1233
+ }
1234
+
1235
+ // --- cli/engine/shared/fonts.mjs ---
1236
+ const GOOGLE_FONTS_URL_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
1237
+
1238
+ function normalizeGoogleFontFamilyParam(value) {
1239
+ return String(value || '')
1240
+ .split('|')
1241
+ .map(part => part.split(':')[0].trim().toLowerCase())
1242
+ .filter(Boolean);
1243
+ }
1244
+
1245
+ function extractGoogleFontFamilies(text) {
1246
+ const families = [];
1247
+ if (!text) return families;
1248
+
1249
+ GOOGLE_FONTS_URL_RE.lastIndex = 0;
1250
+ let urlMatch;
1251
+ while ((urlMatch = GOOGLE_FONTS_URL_RE.exec(text)) !== null) {
1252
+ const url = urlMatch[0];
1253
+ const queryStart = url.indexOf('?');
1254
+ if (queryStart === -1) continue;
1255
+
1256
+ const params = new URLSearchParams(url.slice(queryStart + 1).replace(/&amp;/g, '&'));
1257
+ for (const value of params.getAll('family')) {
1258
+ families.push(...normalizeGoogleFontFamilyParam(value));
1259
+ }
1260
+ }
1261
+
1262
+ return families;
1263
+ }
1264
+
1265
+ // --- cli/engine/rules/checks.mjs ---
1266
+ const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
1267
+
1268
+ // ─── Section 3: Pure Detection ──────────────────────────────────────────────
1269
+
1270
+ function checkBorders(tag, widths, colors, radius, opts = {}) {
1271
+ // Badge-shaped <span>s (own visible background) are a real stripe target
1272
+ // for the top/bottom variant — the inline-tag exemption exists to quiet
1273
+ // text-level borders, not chips. They skip the left/right arms below.
1274
+ const spanBadge = tag === 'span' && !!opts.badgeLike;
1275
+ if (BORDER_SAFE_TAGS.has(tag) && !spanBadge) return [];
1276
+ // A live status/alert region wears a colored single-edge border as a
1277
+ // severity accent (toast, snackbar, callout), not as the side-tab tell.
1278
+ if (opts.statusContext) return [];
1279
+ const findings = [];
1280
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
1281
+
1282
+ for (const side of sides) {
1283
+ const w = widths[side];
1284
+ if (w < 1 || isNeutralColor(colors[side])) continue;
1285
+
1286
+ const otherSides = sides.filter(s => s !== side);
1287
+ const maxOther = Math.max(...otherSides.map(s => widths[s]));
1288
+ if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
1289
+
1290
+ const sn = side.toLowerCase();
1291
+ const isSide = side === 'Left' || side === 'Right';
1292
+
1293
+ if (isSide) {
1294
+ if (spanBadge) continue;
1295
+ if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
1296
+ else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
1297
+ } else {
1298
+ if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
1299
+ // Horizontal variant of the side-tab stripe: a thick chromatic accent
1300
+ // riding the top or bottom edge of a card/badge/container. Same
1301
+ // dominant-edge + chroma gates as left/right, 3-12px band. Selected-
1302
+ // tab underlines are exempt via opts.tabContext (adapters look for
1303
+ // tablist/nav/tab ancestors and aria-selected); links, buttons,
1304
+ // table cells, and <hr> never reach here (BORDER_SAFE_TAGS).
1305
+ else if (!opts.tabContext && w >= 3 && w <= 12) {
1306
+ findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
1307
+ }
1308
+ }
1309
+ }
1310
+
1311
+ return findings;
1312
+ }
1313
+
1314
+ // ─── Scoped ignores: data-impeccable-ignore ─────────────────────────────────
1315
+ //
1316
+ // An element-scoped waiver that travels with the markup: any element carrying
1317
+ // `data-impeccable-ignore="rule-a rule-b"` (or `*`, or an empty value, for
1318
+ // every rule) suppresses matching findings from itself and its entire subtree,
1319
+ // in every engine that walks elements — the browser overlay, the extension,
1320
+ // and the static scan. This is the DOM twin of the line-based
1321
+ // `impeccable-disable` comment directives, which the browser cannot apply (a
1322
+ // live DOM has no line numbers), and the generalization of the one-off
1323
+ // `data-impeccable-allow-kickers` opt-out.
1324
+ //
1325
+ // The intended use is curated exhibits: a page that documents anti-patterns by
1326
+ // example, or renders a deliberate "before" specimen, marks the container once
1327
+ // and every engine skips it while still scanning the page around it.
1328
+ function scopedIgnoreActive(el, ruleId) {
1329
+ const rule = String(ruleId || '').toLowerCase();
1330
+ let cur = el;
1331
+ while (cur && cur.nodeType === 1) {
1332
+ const attr = typeof cur.getAttribute === 'function' ? cur.getAttribute('data-impeccable-ignore') : null;
1333
+ if (attr != null) {
1334
+ const rules = String(attr).trim().toLowerCase().split(/[\s,]+/).filter(Boolean);
1335
+ if (rules.length === 0 || rules.includes('*') || rules.includes(rule)) return true;
1336
+ }
1337
+ cur = cur.parentElement;
1338
+ }
1339
+ return false;
1340
+ }
1341
+
1342
+ // Returns true if the given text is composed entirely of emoji characters
1343
+ // (plus whitespace / variation selectors). Emojis render as multicolor glyphs
1344
+ // regardless of CSS `color`, so contrast checks against the element's text
1345
+ // color are meaningless for these nodes.
1346
+ 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;
1347
+ 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;
1348
+ function isEmojiOnlyText(text) {
1349
+ if (!text) return false;
1350
+ if (!EMOJI_CHAR_RE.test(text)) return false;
1351
+ return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
1352
+ }
1353
+
1354
+ function checkColors(opts) {
1355
+ const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
1356
+ if (SAFE_TAGS.has(tag)) {
1357
+ // Exception for elements styled as controls or chips. SAFE_TAGS exists to
1358
+ // suppress contrast noise on inline links and unstyled spans, where the
881
1359
  // element has no own background and the contrast against the ancestor
882
1360
  // surface is already the intended visual. When the element paints its own
883
1361
  // opaque background under direct text, it is a styled button, chip, or
@@ -1428,6 +1906,26 @@ function cssTextHasDarkRootBg(content, customProps) {
1428
1906
  return false;
1429
1907
  }
1430
1908
 
1909
+ // Best-effort extraction of the CSS selector whose declaration block contains
1910
+ // the given index in raw CSS text. Lets CSS-text findings carry a live-DOM
1911
+ // anchor, so the browser pass can resolve scoped ignores against the actual
1912
+ // element and drop patterns that render nowhere on the page. Returns null for
1913
+ // @-rule preludes, keyframe steps, nested blocks, and anything that does not
1914
+ // read as a selector; those findings stay page-level.
1915
+ function enclosingCssSelector(cssText, index) {
1916
+ if (!cssText || !Number.isFinite(index)) return null;
1917
+ const open = cssText.lastIndexOf('{', index);
1918
+ if (open === -1) return null;
1919
+ const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
1920
+ const raw = cssText.slice(prevClose + 1, open).trim().replace(/\s+/g, ' ');
1921
+ if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
1922
+ // Keyframe steps: percentage steps fail the digit test above, but `from`
1923
+ // and `to` would read as (never-matching) type selectors and get a valid
1924
+ // finding wrongly dropped by the zero-match rule downstream.
1925
+ if (/^(?:from|to)(?:\s*,\s*(?:from|to))*$/i.test(raw)) return null;
1926
+ return raw;
1927
+ }
1928
+
1431
1929
  function scanCssTextForGlow(content) {
1432
1930
  const customProps = collectCssCustomProps(content);
1433
1931
  const hasDarkBg = cssTextHasDarkRootBg(content, customProps);
@@ -1739,6 +2237,7 @@ function scanCssTextForPseudoStripe(rawContent) {
1739
2237
  id: 'side-tab',
1740
2238
  snippet: `${selector} — absolute ${thicknessPx}px pseudo-element stripe (${edge}: 0)`,
1741
2239
  index: selectorStart,
2240
+ selector,
1742
2241
  });
1743
2242
  }
1744
2243
  return findings;
@@ -1801,6 +2300,7 @@ function scanCssTextForInsetStripe(content) {
1801
2300
  findings.push({
1802
2301
  id: 'side-tab',
1803
2302
  snippet: `${selector} — inset box-shadow ${ay === 0 ? ax : ay}px stripe (${edge})`,
2303
+ selector,
1804
2304
  });
1805
2305
  break;
1806
2306
  }
@@ -1858,7 +2358,7 @@ function collectMarqueeKeyframes(content) {
1858
2358
  function scanCssTextForMarquee(content, markup = content) {
1859
2359
  const findings = [];
1860
2360
  if (/<marquee\b/i.test(markup)) {
1861
- findings.push({ id: 'marquee', snippet: '<marquee> element' });
2361
+ findings.push({ id: 'marquee', snippet: '<marquee> element', selector: 'marquee' });
1862
2362
  }
1863
2363
  const marqueeKeyframes = collectMarqueeKeyframes(content);
1864
2364
  if (marqueeKeyframes.size === 0) return findings;
@@ -1873,7 +2373,7 @@ function scanCssTextForMarquee(content, markup = content) {
1873
2373
  const key = `${selector} ${name}`;
1874
2374
  if (seen.has(key)) continue;
1875
2375
  seen.add(key);
1876
- findings.push({ id: 'marquee', snippet: `${selector} — infinite horizontal loop animation "${name}"` });
2376
+ findings.push({ id: 'marquee', snippet: `${selector} — infinite horizontal loop animation "${name}"`, selector });
1877
2377
  }
1878
2378
  }
1879
2379
  return findings;
@@ -2244,8 +2744,10 @@ function checkHtmlPatterns(html, corpora) {
2244
2744
  const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
2245
2745
  if (purpleHexRe.test(styleText)) {
2246
2746
  const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
2247
- if (purpleTextRe.test(styleText)) {
2248
- findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
2747
+ purpleTextRe.lastIndex = 0;
2748
+ const purpleMatch = purpleTextRe.exec(styleText);
2749
+ if (purpleMatch) {
2750
+ findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected', selector: enclosingCssSelector(styleText, purpleMatch.index + 1) || undefined });
2249
2751
  }
2250
2752
  }
2251
2753
 
@@ -2256,7 +2758,7 @@ function checkHtmlPatterns(html, corpora) {
2256
2758
  const start = Math.max(0, gm.index - 200);
2257
2759
  const context = styleText.substring(start, gm.index + gm[0].length + 200);
2258
2760
  if (/gradient/i.test(context)) {
2259
- findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
2761
+ findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient', selector: enclosingCssSelector(styleText, gm.index) || undefined });
2260
2762
  break;
2261
2763
  }
2262
2764
  }
@@ -2322,7 +2824,7 @@ function checkHtmlPatterns(html, corpora) {
2322
2824
  const animationToken = bounceMatch[1]
2323
2825
  .split(/[,\s]+/)
2324
2826
  .find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
2325
- findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
2827
+ findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}`, selector: enclosingCssSelector(styleText, bounceMatch.index) || undefined });
2326
2828
  }
2327
2829
 
2328
2830
  // Overshoot cubic-bezier
@@ -2331,7 +2833,7 @@ function checkHtmlPatterns(html, corpora) {
2331
2833
  while ((bm = bezierRe.exec(styleText)) !== null) {
2332
2834
  const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
2333
2835
  if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
2334
- findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
2836
+ findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})`, selector: enclosingCssSelector(styleText, bm.index) || undefined });
2335
2837
  break;
2336
2838
  }
2337
2839
  }
@@ -2364,18 +2866,21 @@ function checkHtmlPatterns(html, corpora) {
2364
2866
 
2365
2867
  const glowHits = scanCssTextForGlow(styleText);
2366
2868
  if (glowHits.length > 0) {
2367
- findings.push({ id: 'dark-glow', snippet: glowHits[0].snippet });
2869
+ findings.push({ id: 'dark-glow', snippet: glowHits[0].snippet, selector: enclosingCssSelector(styleText, glowHits[0].index) || undefined });
2368
2870
  }
2369
2871
 
2370
2872
  // Radial-gradient background halo (gradient-drawn sibling of dark-glow)
2371
2873
  const haloHits = scanCssTextForRadialHalo(styleText);
2372
2874
  if (haloHits.length > 0) {
2373
- findings.push({ id: 'radial-halo', snippet: haloHits[0].snippet });
2875
+ findings.push({ id: 'radial-halo', snippet: haloHits[0].snippet, selector: enclosingCssSelector(styleText, haloHits[0].index) || undefined });
2374
2876
  }
2375
2877
 
2376
2878
  // --- Generated-UI tells: repeating-gradient stripes ---
2377
- if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(styleText)) {
2378
- findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
2879
+ {
2880
+ const stripesMatch = /repeating-(?:linear|radial|conic)-gradient\s*\(/i.exec(styleText);
2881
+ if (stripesMatch) {
2882
+ findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes', selector: enclosingCssSelector(styleText, stripesMatch.index) || undefined });
2883
+ }
2379
2884
  }
2380
2885
 
2381
2886
  // --- Generated-UI tells: two-axis grid-line background ---
@@ -2393,7 +2898,7 @@ function checkHtmlPatterns(html, corpora) {
2393
2898
  // whole gradient layers.
2394
2899
  const gridHits = scanCssTextForGridBackground(styleText);
2395
2900
  if (gridHits.length > 0) {
2396
- findings.push({ id: 'codex-grid-background', snippet: gridHits[0].snippet });
2901
+ findings.push({ id: 'codex-grid-background', snippet: gridHits[0].snippet, selector: enclosingCssSelector(styleText, gridHits[0].index) || undefined });
2397
2902
  }
2398
2903
 
2399
2904
  // --- Generated-copy tells: "X theater" framing copy ---
@@ -2413,8 +2918,11 @@ function checkHtmlPatterns(html, corpora) {
2413
2918
  // hover:rotate / hover:translate utility on an <img>. Each distinct
2414
2919
  // mechanism is its own finding.
2415
2920
  const imgHoverCss = /\bimg\b[^,{}]*:hover\b[^{}]*\{[^}]*\btransform\s*:\s*(?:scale|rotate|translate|matrix|skew)/i;
2416
- if (imgHoverCss.test(styleText)) {
2417
- findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule' });
2921
+ {
2922
+ const imgHoverMatch = imgHoverCss.exec(styleText);
2923
+ if (imgHoverMatch) {
2924
+ findings.push({ id: 'image-hover-transform', snippet: 'img:hover { transform } rule', selector: enclosingCssSelector(styleText, imgHoverMatch.index + imgHoverMatch[0].indexOf('{') + 1) || undefined });
2925
+ }
2418
2926
  }
2419
2927
  const imgTagRe = /<img\b[^>]*\bclass\s*=\s*"([^"]*)"/gi;
2420
2928
  let im;
@@ -2461,7 +2969,46 @@ function readOwnBackgroundColor(el, computedStyle) {
2461
2969
  return bg;
2462
2970
  }
2463
2971
 
2464
- function resolveBackground(el, win, customPropMap) {
2972
+ // One element's background-color as the cascade walk sees it: computed style
2973
+ // first (with the modern-color fallback), then, in static mode only,
2974
+ // custom-prop resolution and the inline-shorthand peek. Shared by
2975
+ // resolveBackgroundInfo and resolveGradientStops so both walks read the same
2976
+ // surfaces.
2977
+ function readCascadeBackgroundColor(current, style, customPropMap) {
2978
+ let bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
2979
+ if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
2980
+ // The static engine can return literal "var(--X)" / "oklch(...)" strings.
2981
+ // Resolve through customPropMap so Tailwind v4 color tokens become RGB.
2982
+ if (customPropMap) {
2983
+ bg = parseColorResolved(style.backgroundColor, customPropMap);
2984
+ }
2985
+ if (!bg || bg.a < 0.1) {
2986
+ // Inline-style fallback for colors the static cascade did not surface
2987
+ // on backgroundColor.
2988
+ const rawStyle = current.getAttribute?.('style') || '';
2989
+ const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
2990
+ const inlineBg = bgMatch ? bgMatch[1].trim() : '';
2991
+ if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
2992
+ bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
2993
+ }
2994
+ }
2995
+ }
2996
+ return bg;
2997
+ }
2998
+
2999
+ // Walk up for the surface the element's text is painted on.
3000
+ //
3001
+ // Returns { color, unresolved }:
3002
+ // • color set — the effective surface, overlays composited in.
3003
+ // • unresolved: true — a layer on the way up paints a color this parser
3004
+ // cannot read, so the surface is unknown. Callers
3005
+ // must SKIP their contrast checks. Guessing white
3006
+ // here is what flooded dark themes with false
3007
+ // "on #ffffff" findings: one abstention costs a
3008
+ // single finding, one wrong guess costs a hundred.
3009
+ // • both null/false — no solid color, but a gradient or image is in
3010
+ // play; callers fall back to its color stops.
3011
+ function resolveBackgroundInfo(el, win, customPropMap) {
2465
3012
  let current = el;
2466
3013
  // Translucent layers (0.1 < a < 1) found on the way down to an opaque
2467
3014
  // base. A browser composites these over the base; the old behavior
@@ -2489,67 +3036,114 @@ function resolveBackground(el, win, customPropMap) {
2489
3036
  // body backgrounds.
2490
3037
  // Real browsers serialize wide-gamut computed values as oklab()/oklch()
2491
3038
  // (e.g. any color-mix() result), which plain parseRgb misses.
2492
- let bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
2493
- if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
2494
- // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
2495
- // through customPropMap so Tailwind v4 color tokens become RGB.
2496
- if (customPropMap) {
2497
- bg = parseColorResolved(style.backgroundColor, customPropMap);
2498
- }
2499
- if (!bg || bg.a < 0.1) {
2500
- // Inline-style fallback. jsdom doesn't decompose background
2501
- // shorthand, so colors set via inline style are otherwise invisible.
2502
- const rawStyle = current.getAttribute?.('style') || '';
2503
- const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
2504
- const inlineBg = bgMatch ? bgMatch[1].trim() : '';
2505
- if (inlineBg && !/gradient/i.test(inlineBg) && !/url\s*\(/i.test(inlineBg)) {
2506
- bg = parseColorResolved(inlineBg, customPropMap) || parseAnyColor(inlineBg);
2507
- }
2508
- }
3039
+ let bg = readCascadeBackgroundColor(current, style, customPropMap);
3040
+
3041
+ // `background-color: currentcolor` paints with the element's own text
3042
+ // color — real paint whose value we know. Real browsers resolve the
3043
+ // keyword before getComputedStyle output; jsdom hands it through
3044
+ // verbatim, and without this substitution the layer would read as
3045
+ // unparseable and force a needless abstention.
3046
+ if ((!bg || bg.a < 0.1) && /^currentcolor$/i.test(String(style.backgroundColor || '').trim())) {
3047
+ // The static cascade resolves var() text tokens before checks run, so
3048
+ // style.color is normally already an rgb string here; parseColorResolved
3049
+ // is defense in depth for any future caller that passes a live
3050
+ // customPropMap (it matches the text-color path in checkElementColors
3051
+ // and reduces to parseAnyColor when the map is null or absent).
3052
+ bg = parseRgb(style.color) || parseColorResolved(style.color, customPropMap);
2509
3053
  }
2510
3054
 
2511
3055
  if (bg && bg.a > 0.1) {
2512
- if (bg.a >= 0.99) return flatten(bg);
3056
+ if (bg.a >= 0.99) return { color: flatten(bg), unresolved: false };
2513
3057
  overlays.push(bg);
2514
- }
2515
- // No solid bg-color at this level. If THIS level has a gradient/url
2516
- // with no underlying solid color we can read:
2517
- // • on body/html: assume white. Body-level gradients are almost
2518
- // always decorative texture (paper grain, noise) on top of a
2519
- // solid bg-color the page set via `background: var(--paper)`
2520
- // shorthand — which jsdom can't decompose into bg-color. The
2521
- // downstream gradient-stops fallback path produces catastrophic
2522
- // false positives in this case (gradient noise stops have
2523
- // accidental browns/blacks that look like card backgrounds).
2524
- // • on other elements: bail to null and let the caller fall back
2525
- // to gradient stops (gradient buttons / hero sections are real
2526
- // bgs worth checking against).
3058
+ } else if (!bg && !isNoPaintColorValue(style.backgroundColor)) {
3059
+ // This layer names a color we could not parse (a color space we do not
3060
+ // model, an unresolved var(), a syntax newer than the parser). It may
3061
+ // well be opaque, which would make every ancestor below it invisible —
3062
+ // so the surface is unknown and the walk stops here rather than
3063
+ // reporting an ancestor the visitor never sees.
3064
+ return { color: null, unresolved: true };
3065
+ }
3066
+ // No solid bg-color at this level, but this level paints an image. CSS
3067
+ // stacks background-image layers first-on-top, so which layer leads
3068
+ // decides what the visitor sees:
3069
+ // • gradient on top — the gradient is the surface. Hand the caller a
3070
+ // null color so it falls back to the gradient's own stops (body
3071
+ // grounds, gradient buttons, hero sections).
3072
+ // • url() on top — the surface is an image whose pixels this engine
3073
+ // cannot read, and it may fully cover every layer and ancestor
3074
+ // beneath it. Same contract as an unparseable color: abstain, so
3075
+ // the gradient-stop fallback never measures a gradient the image
3076
+ // hides (the shipped miss: `url(photo), linear-gradient(...)`
3077
+ // reported low-contrast against the invisible gradient's stops).
2527
3078
  if (hasGradientOrUrl) {
2528
- if (current.tagName === 'BODY' || current.tagName === 'HTML') {
2529
- return flatten({ r: 255, g: 255, b: 255, a: 1 });
3079
+ const layers = splitTopLevelCommas(bgImage);
3080
+ const topPaintLayer = layers.find(
3081
+ (layer) => /gradient\s*\(/i.test(layer) || /url\s*\(/i.test(layer),
3082
+ );
3083
+ const gradientOnTop = !!topPaintLayer
3084
+ && /gradient\s*\(/i.test(topPaintLayer)
3085
+ && !/^\s*url\s*\(/i.test(topPaintLayer);
3086
+ if (!gradientOnTop) return { color: null, unresolved: true };
3087
+ // Gradient on top of a url() layer: the image shows through wherever
3088
+ // the gradient is not fully opaque, so a translucent wash like
3089
+ // `linear-gradient(rgba(0,0,0,.2), rgba(0,0,0,.2)), url(photo)` paints
3090
+ // a blend with pixels this engine cannot read. Only a gradient whose
3091
+ // every readable stop is opaque provably covers the image; otherwise
3092
+ // the surface is unknown — abstain rather than hand callers gradient
3093
+ // stops (or a stop average) the visitor never sees unmixed.
3094
+ const urlBeneath = layers.some(
3095
+ (layer) => layer !== topPaintLayer && /url\s*\(/i.test(layer),
3096
+ );
3097
+ if (urlBeneath) {
3098
+ const topStops = parseGradientColors(topPaintLayer);
3099
+ const provablyOpaque = topStops.length > 0 && topStops.every((s) => (s.a ?? 1) >= 0.99);
3100
+ if (!provablyOpaque) return { color: null, unresolved: true };
2530
3101
  }
2531
- return null;
3102
+ return { color: null, unresolved: false };
2532
3103
  }
2533
3104
  current = current.parentElement;
2534
3105
  }
2535
- return flatten({ r: 255, g: 255, b: 255, a: 1 });
3106
+ // Every layer up to the document root was genuinely see-through, so the
3107
+ // browser paints its default canvas. This is the ONLY case that earns the
3108
+ // white assumption.
3109
+ return { color: flatten({ r: 255, g: 255, b: 255, a: 1 }), unresolved: false };
3110
+ }
3111
+
3112
+ function resolveBackground(el, win, customPropMap) {
3113
+ return resolveBackgroundInfo(el, win, customPropMap).color;
2536
3114
  }
2537
3115
 
2538
3116
  // Walk parents looking for a gradient background and return its color stops.
2539
3117
  // Used as a fallback when resolveBackground() returns null because the
2540
3118
  // effective background is a gradient (no single solid color to compare against).
3119
+ // Translucent solid layers found between the element and the gradient (frosted
3120
+ // panels, glass washes) are composited over every stop, the same way
3121
+ // resolveBackground flattens them over a solid base — raw stops alone would
3122
+ // false-flag dark text on a light frosted wash over a dark gradient, and miss
3123
+ // the inverse.
2541
3124
  function resolveGradientStops(el, win, customPropMap) {
2542
3125
  let current = el;
3126
+ const overlays = [];
2543
3127
  while (current && current.nodeType === 1) {
2544
3128
  const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
2545
3129
  const bgImage = style.backgroundImage || '';
3130
+ // A url() layer anywhere in the stack — alone, or alongside a gradient in
3131
+ // the same declaration (a translucent wash over a texture photo) — paints
3132
+ // pixels the analytic walk cannot know. Measuring the gradient stops over
3133
+ // the wrong base flagged dark ink sitting on a bright gold-leaf image at
3134
+ // 2.6:1; skipping beats a wrong ratio, and the screenshot subsystem owns
3135
+ // image-backed text.
3136
+ if (bgImage && bgImage !== 'none' && /url\s*\(/i.test(bgImage)) return null;
2546
3137
  let stops = null;
2547
3138
  if (bgImage && bgImage !== 'none' && /gradient/i.test(bgImage)) {
3139
+ // parseGradientColors (shared) reads modern-space stops too — oklch,
3140
+ // color-mix and friends via balanced-paren token capture — so browser
3141
+ // computed values that keep the authored syntax stay measurable.
2548
3142
  const parsed = parseGradientColors(bgImage);
2549
3143
  if (parsed.length > 0) stops = parsed;
2550
3144
  }
2551
3145
  if (!stops && !DETECTOR_IS_BROWSER) {
2552
- // jsdom doesn't decompose `background:` shorthand — peek at the raw inline style
3146
+ // Static mode: peek at the raw inline style for gradients the cascade did not surface
2553
3147
  const rawStyle = current.getAttribute?.('style') || '';
2554
3148
  const bgMatch = rawStyle.match(/background(?:-image)?\s*:\s*([^;]+)/i);
2555
3149
  if (bgMatch && /gradient/i.test(bgMatch[1])) {
@@ -2557,7 +3151,23 @@ function resolveGradientStops(el, win, customPropMap) {
2557
3151
  if (parsed.length > 0) stops = parsed;
2558
3152
  }
2559
3153
  }
2560
- if (stops) return compositeGradientStops(stops, current, win, customPropMap);
3154
+ if (stops) {
3155
+ const composited = compositeGradientStops(stops, current, win, customPropMap);
3156
+ if (!composited || overlays.length === 0) return composited;
3157
+ return composited.map(stop => {
3158
+ let acc = stop;
3159
+ for (let i = overlays.length - 1; i >= 0; i--) acc = compositeColorOver(overlays[i], acc);
3160
+ return acc;
3161
+ });
3162
+ }
3163
+ const bg = readCascadeBackgroundColor(current, style, customPropMap);
3164
+ if (bg && bg.a > 0.1) {
3165
+ // An opaque surface above the gradient means the gradient never shows
3166
+ // through here; resolveBackground would have returned it, so reaching
3167
+ // this is defensive — bail rather than measure the wrong layer.
3168
+ if (bg.a >= 0.99) return null;
3169
+ overlays.push(bg);
3170
+ }
2561
3171
  current = current.parentElement;
2562
3172
  }
2563
3173
  return null;
@@ -2777,15 +3387,25 @@ function checkElementColorsDOM(el) {
2777
3387
  const rect = el.getBoundingClientRect();
2778
3388
  if (rect.width < 10 || rect.height < 10) return [];
2779
3389
  const style = getComputedStyle(el);
3390
+ // Invisible at rest: hidden scene variants (opacity-0 carousels, swap
3391
+ // decks) are not user-visible, and measuring their inherited colors against
3392
+ // whatever surface happens to sit behind the stack is noise, not audit.
3393
+ if (style.visibility === 'hidden' || effectiveOpacityDOM(el) <= 0.02) return [];
2780
3394
  const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
2781
3395
  const hasDirectText = directText.trim().length > 0;
2782
- let effectiveBg = resolveBackground(el);
3396
+ const bgInfo = resolveBackgroundInfo(el);
3397
+ let effectiveBg = bgInfo.color;
3398
+ // An unreadable surface anywhere up the chain: skip the gradient-stop
3399
+ // fallback too, so nothing downstream measures against a ground we never
3400
+ // resolved.
3401
+ let surfaceUnresolved = bgInfo.unresolved;
2783
3402
  let ownBg = readOwnBackgroundColor(el, style);
2784
3403
  if (!ownBg || (ownBg.a ?? 1) <= 0.5) {
2785
3404
  const pseudoSurface = readPseudoSurfaceDOM(el, rect);
2786
3405
  if (pseudoSurface) {
2787
3406
  ownBg = pseudoSurface;
2788
3407
  effectiveBg = pseudoSurface;
3408
+ surfaceUnresolved = false;
2789
3409
  }
2790
3410
  }
2791
3411
  return checkColors({
@@ -2797,8 +3417,8 @@ function checkElementColorsDOM(el) {
2797
3417
  // an oklch token near its own oklch background).
2798
3418
  textColor: parseRgb(style.color) || parseAnyColor(style.color),
2799
3419
  bgColor: ownBg,
2800
- effectiveBg,
2801
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
3420
+ effectiveBg: surfaceUnresolved ? null : effectiveBg,
3421
+ effectiveBgStops: surfaceUnresolved || effectiveBg ? null : resolveGradientStops(el),
2802
3422
  fontSize: parseFloat(style.fontSize) || 16,
2803
3423
  fontWeight: parseInt(style.fontWeight) || 400,
2804
3424
  hasDirectText,
@@ -2807,425 +3427,148 @@ function checkElementColorsDOM(el) {
2807
3427
  bgImage: style.backgroundImage || '',
2808
3428
  classList: el.getAttribute('class') || '',
2809
3429
  });
2810
- }
2811
-
2812
- function checkElementIconTileDOM(el) {
2813
- const tag = el.tagName.toLowerCase();
2814
- if (!HEADING_TAGS.has(tag)) return [];
2815
- const sibling = el.previousElementSibling;
2816
- if (!sibling) return [];
2817
-
2818
- const sibRect = sibling.getBoundingClientRect();
2819
- const headRect = el.getBoundingClientRect();
2820
- const sibStyle = getComputedStyle(sibling);
2821
-
2822
- // The tile may either contain an <svg>/<i> icon child, OR the tile itself
2823
- // may contain an emoji/symbol character directly as its only text content
2824
- // (the "card-icon" pattern from many AI-generated demos).
2825
- const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
2826
- const iconRect = iconChild?.getBoundingClientRect();
2827
- const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
2828
- const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
2829
-
2830
- return checkIconTile({
2831
- headingTag: tag,
2832
- headingText: el.textContent || '',
2833
- headingTop: headRect.top,
2834
- siblingTag: sibling.tagName.toLowerCase(),
2835
- siblingWidth: sibRect.width,
2836
- siblingHeight: sibRect.height,
2837
- siblingBottom: sibRect.bottom,
2838
- siblingBgColor: parseRgb(sibStyle.backgroundColor),
2839
- siblingBgImage: sibStyle.backgroundImage || '',
2840
- siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
2841
- siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
2842
- hasIconChild: !!iconChild || hasInlineEmojiIcon,
2843
- iconChildWidth: iconRect?.width || 0,
2844
- });
2845
- }
2846
-
2847
- function checkElementItalicSerifDOM(el) {
2848
- const tag = el.tagName.toLowerCase();
2849
- if (tag !== 'h1' && tag !== 'h2') return [];
2850
- const style = getComputedStyle(el);
2851
- return checkItalicSerif({
2852
- tag,
2853
- fontStyle: style.fontStyle || '',
2854
- fontFamily: style.fontFamily || '',
2855
- fontSize: parseFloat(style.fontSize) || 0,
2856
- headingText: el.textContent || '',
2857
- });
2858
- }
2859
-
2860
- function domAccentDashPseudo(el) {
2861
- for (const which of ['::before', '::after']) {
2862
- let ps;
2863
- try { ps = getComputedStyle(el, which); } catch { continue; }
2864
- if (!ps || ps.content === 'none' || ps.content === '') continue;
2865
- const w = parseFloat(ps.width) || 0;
2866
- const h = parseFloat(ps.height) || 0;
2867
- if (!(w >= 8 && w <= 80 && h >= 1 && h <= 6)) continue;
2868
- const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2869
- if (!bg || (bg.a ?? 1) < 0.1) continue;
2870
- if (Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) >= 30) return true;
2871
- }
2872
- return false;
2873
- }
2874
-
2875
- function checkElementHeroEyebrowDOM(el) {
2876
- const tag = el.tagName.toLowerCase();
2877
- if (tag !== 'h1') return [];
2878
- const sibling = el.previousElementSibling;
2879
- if (!sibling) return [];
2880
- const headStyle = getComputedStyle(el);
2881
- const sibStyle = getComputedStyle(sibling);
2882
- return checkHeroEyebrow({
2883
- headingTag: tag,
2884
- headingText: el.textContent || '',
2885
- headingFontSize: parseFloat(headStyle.fontSize) || 0,
2886
- headingInApplicationContext: !!el.closest('[role="tabpanel"], [role="dialog"], [role="application"], dialog'),
2887
- siblingTag: sibling.tagName.toLowerCase(),
2888
- siblingText: sibling.textContent || '',
2889
- siblingTextTransform: sibStyle.textTransform || '',
2890
- siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
2891
- siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
2892
- siblingFontWeight: sibStyle.fontWeight || '',
2893
- siblingColor: sibStyle.color || '',
2894
- siblingHasAccentDashPseudo: domAccentDashPseudo(sibling),
2895
- });
2896
- }
2897
-
2898
- // Build a map of CSS custom properties declared on :root / :host / html.
2899
- // Used to resolve var(--X) refs that jsdom returns verbatim in
2900
- // getComputedStyle. Tailwind v4 routes every utility class through
2901
- // CSS vars (font-weight: var(--font-weight-bold), font-size:
2902
- // var(--text-xs), letter-spacing: var(--tracking-widest)), so without
2903
- // resolution every style-based check silently fails on Tailwind v4
2904
- // builds — the values come back as literal "var(--font-weight-bold)"
2905
- // strings and parseFloat returns NaN.
2906
- function buildCustomPropMap(document) {
2907
- const map = new Map();
2908
- let sheets;
2909
- try { sheets = Array.from(document.styleSheets || []); }
2910
- catch { return map; }
2911
- for (const sheet of sheets) {
2912
- let rules;
2913
- try { rules = Array.from(sheet.cssRules || []); }
2914
- catch { continue; }
2915
- for (const rule of rules) {
2916
- // Style rules only (type 1). Walk @media / @supports if present.
2917
- if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
2918
- try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
2919
- continue;
2920
- }
2921
- if (rule.type !== 1 /* STYLE_RULE */) continue;
2922
- const sel = rule.selectorText || '';
2923
- if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
2924
- const style = rule.style;
2925
- if (!style) continue;
2926
- for (let i = 0; i < style.length; i++) {
2927
- const prop = style[i];
2928
- if (!prop || !prop.startsWith('--')) continue;
2929
- const val = style.getPropertyValue(prop).trim();
2930
- if (val) map.set(prop, val);
2931
- }
2932
- }
2933
- }
2934
- return map;
2935
- }
2936
-
2937
- // Resolve var(--X[, fallback]) refs in a computed-style value string.
2938
- // Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
2939
- // the original string when no refs are present or the chain doesn't
2940
- // resolve. Safe to call on already-resolved values.
2941
- function resolveVarRefs(raw, customPropMap, depth = 0) {
2942
- if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
2943
- if (depth > 8) return raw;
2944
- return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
2945
- const v = customPropMap.get(name);
2946
- if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
2947
- return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
2948
- });
2949
- }
2950
-
2951
- // OKLCH → sRGB conversion (Björn Ottosson's matrices). L in 0..1 (or %),
2952
- // C in 0..~0.4 typical, H in degrees. Returns clamped {r,g,b,a:1} in 0..255.
2953
- // Needed because jsdom doesn't compute oklch() values — getComputedStyle
2954
- // returns the literal "oklch(...)" string. Without this, the entire
2955
- // Tailwind v4 color palette (which is OKLCH-based) is invisible to the
2956
- // detector's contrast / color checks.
2957
- function oklchToRgb(L, C, H) {
2958
- const hRad = (H * Math.PI) / 180;
2959
- return oklabToRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
2960
- }
2961
-
2962
- function oklabToRgb(L, a, b) {
2963
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
2964
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
2965
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
2966
- const lc = l_ * l_ * l_, mc = m_ * m_ * m_, sc = s_ * s_ * s_;
2967
- const rLin = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;
2968
- const gLin = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;
2969
- const bLin = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;
2970
- const enc = (x) => {
2971
- const c = Math.max(0, Math.min(1, x));
2972
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
2973
- };
2974
- return {
2975
- r: Math.round(enc(rLin) * 255),
2976
- g: Math.round(enc(gLin) * 255),
2977
- b: Math.round(enc(bLin) * 255),
2978
- a: 1,
2979
- };
2980
- }
2981
-
2982
- function hslToRgb(h, s, l) {
2983
- h = ((h % 360) + 360) % 360;
2984
- const c = (1 - Math.abs(2 * l - 1)) * s;
2985
- const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
2986
- const m0 = l - c / 2;
2987
- const [r, g, b] =
2988
- h < 60 ? [c, x, 0] :
2989
- h < 120 ? [x, c, 0] :
2990
- h < 180 ? [0, c, x] :
2991
- h < 240 ? [0, x, c] :
2992
- h < 300 ? [x, 0, c] : [c, 0, x];
2993
- return {
2994
- r: Math.round((r + m0) * 255),
2995
- g: Math.round((g + m0) * 255),
2996
- b: Math.round((b + m0) * 255),
2997
- a: 1,
2998
- };
2999
- }
3000
-
3001
- function hwbToRgb(h, w, bl) {
3002
- if (w + bl >= 1) {
3003
- const g = Math.round((w / (w + bl)) * 255);
3004
- return { r: g, g, b: g, a: 1 };
3005
- }
3006
- const base = hslToRgb(h, 1, 0.5);
3007
- const mix = (c) => Math.round(((c / 255) * (1 - w - bl) + w) * 255);
3008
- return { r: mix(base.r), g: mix(base.g), b: mix(base.b), a: 1 };
3009
- }
3010
-
3011
- // Common CSS named colors — the handful that actually show up in generated
3012
- // UIs, not the full 148-name spec list. Includes the achromatic names so a
3013
- // named gray parses (and correctly reads as no-chroma) instead of being
3014
- // treated as an unknown color.
3015
- const CSS_NAMED_COLORS = {
3016
- black: { r: 0, g: 0, b: 0 },
3017
- white: { r: 255, g: 255, b: 255 },
3018
- gray: { r: 128, g: 128, b: 128 },
3019
- grey: { r: 128, g: 128, b: 128 },
3020
- silver: { r: 192, g: 192, b: 192 },
3021
- dimgray: { r: 105, g: 105, b: 105 },
3022
- darkgray: { r: 169, g: 169, b: 169 },
3023
- lightgray: { r: 211, g: 211, b: 211 },
3024
- gainsboro: { r: 220, g: 220, b: 220 },
3025
- whitesmoke: { r: 245, g: 245, b: 245 },
3026
- red: { r: 255, g: 0, b: 0 },
3027
- crimson: { r: 220, g: 20, b: 60 },
3028
- tomato: { r: 255, g: 99, b: 71 },
3029
- coral: { r: 255, g: 127, b: 80 },
3030
- salmon: { r: 250, g: 128, b: 114 },
3031
- orange: { r: 255, g: 165, b: 0 },
3032
- gold: { r: 255, g: 215, b: 0 },
3033
- yellow: { r: 255, g: 255, b: 0 },
3034
- olive: { r: 128, g: 128, b: 0 },
3035
- lime: { r: 0, g: 255, b: 0 },
3036
- green: { r: 0, g: 128, b: 0 },
3037
- teal: { r: 0, g: 128, b: 128 },
3038
- turquoise: { r: 64, g: 224, b: 208 },
3039
- cyan: { r: 0, g: 255, b: 255 },
3040
- aqua: { r: 0, g: 255, b: 255 },
3041
- skyblue: { r: 135, g: 206, b: 235 },
3042
- dodgerblue: { r: 30, g: 144, b: 255 },
3043
- blue: { r: 0, g: 0, b: 255 },
3044
- navy: { r: 0, g: 0, b: 128 },
3045
- indigo: { r: 75, g: 0, b: 130 },
3046
- rebeccapurple: { r: 102, g: 51, b: 153 },
3047
- purple: { r: 128, g: 0, b: 128 },
3048
- violet: { r: 238, g: 130, b: 238 },
3049
- orchid: { r: 218, g: 112, b: 214 },
3050
- magenta: { r: 255, g: 0, b: 255 },
3051
- fuchsia: { r: 255, g: 0, b: 255 },
3052
- hotpink: { r: 255, g: 105, b: 180 },
3053
- pink: { r: 255, g: 192, b: 203 },
3054
- maroon: { r: 128, g: 0, b: 0 },
3055
- };
3056
-
3057
- // Split a string on top-level commas (ignoring commas nested in parens).
3058
- function splitTopLevelCommas(str) {
3059
- const parts = [];
3060
- let depth = 0, start = 0;
3061
- for (let i = 0; i < str.length; i++) {
3062
- const ch = str[i];
3063
- if (ch === '(') depth++;
3064
- else if (ch === ')') depth = Math.max(0, depth - 1);
3065
- else if (ch === ',' && depth === 0) {
3066
- parts.push(str.slice(start, i).trim());
3067
- start = i + 1;
3068
- }
3069
- }
3070
- const tail = str.slice(start).trim();
3071
- if (tail) parts.push(tail);
3072
- return parts;
3073
- }
3074
-
3075
- // Evaluate a CSS color-mix() expression to {r,g,b,a}. Returns null when
3076
- // the expression can't be resolved (unresolved var(), unknown colors).
3077
- //
3078
- // Mixing is done with premultiplied alpha in sRGB regardless of the
3079
- // declared interpolation space. That is exact for the dominant generated-UI
3080
- // pattern — `color-mix(in oklab, <color> N%, transparent)` — where the
3081
- // result is simply <color> at alpha N% in ANY rectangular space, and a
3082
- // close-enough approximation for opaque-opaque mixes (the detector only
3083
- // consumes these values for contrast/chroma thresholds, not for display).
3084
- function parseColorMix(str) {
3085
- const m = String(str).trim().match(/^color-mix\(/i);
3086
- if (!m) return null;
3087
- // Balanced-paren capture of the arguments.
3088
- let depth = 0, end = -1;
3089
- const open = str.indexOf('(');
3090
- for (let i = open; i < str.length; i++) {
3091
- if (str[i] === '(') depth++;
3092
- else if (str[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
3093
- }
3094
- if (end < 0) return null;
3095
- const args = splitTopLevelCommas(str.slice(open + 1, end));
3096
- if (args.length !== 3 || !/^in\s/i.test(args[0])) return null;
3430
+ }
3097
3431
 
3098
- const parseComponent = (component) => {
3099
- // Percentage may lead or trail the color per spec.
3100
- let pct = null;
3101
- let colorStr = component;
3102
- const trail = component.match(/\s+([\d.]+)%$/);
3103
- const lead = component.match(/^([\d.]+)%\s+/);
3104
- if (trail) { pct = parseFloat(trail[1]); colorStr = component.slice(0, trail.index).trim(); }
3105
- else if (lead) { pct = parseFloat(lead[1]); colorStr = component.slice(lead[0].length).trim(); }
3106
- let color;
3107
- if (/^transparent$/i.test(colorStr)) color = { r: 0, g: 0, b: 0, a: 0 };
3108
- else color = parseAnyColor(colorStr);
3109
- if (!color) return null;
3110
- return { color, pct };
3111
- };
3432
+ function checkElementIconTileDOM(el) {
3433
+ const tag = el.tagName.toLowerCase();
3434
+ if (!HEADING_TAGS.has(tag)) return [];
3435
+ const sibling = el.previousElementSibling;
3436
+ if (!sibling) return [];
3112
3437
 
3113
- const c1 = parseComponent(args[1]);
3114
- const c2 = parseComponent(args[2]);
3115
- if (!c1 || !c2) return null;
3116
- let p1 = c1.pct, p2 = c2.pct;
3117
- if (p1 == null && p2 == null) { p1 = 50; p2 = 50; }
3118
- else if (p1 == null) p1 = 100 - p2;
3119
- else if (p2 == null) p2 = 100 - p1;
3120
- const sum = p1 + p2;
3121
- if (sum <= 0) return null;
3122
- // Per spec: weights normalize to sum; when sum < 100 the result alpha is
3123
- // additionally scaled by sum/100.
3124
- const w1 = p1 / sum, w2 = p2 / sum;
3125
- const alphaScale = sum < 100 ? sum / 100 : 1;
3126
- const a1 = c1.color.a ?? 1, a2 = c2.color.a ?? 1;
3127
- const a = (a1 * w1 + a2 * w2) * alphaScale;
3128
- if (a <= 0) return { r: 0, g: 0, b: 0, a: 0 };
3129
- const mix = (ch) => Math.round((c1.color[ch] * a1 * w1 + c2.color[ch] * a2 * w2) / (a1 * w1 + a2 * w2));
3130
- return { r: mix('r'), g: mix('g'), b: mix('b'), a: Math.min(1, a) };
3438
+ const sibRect = sibling.getBoundingClientRect();
3439
+ const headRect = el.getBoundingClientRect();
3440
+ const sibStyle = getComputedStyle(sibling);
3441
+
3442
+ // The tile may either contain an <svg>/<i> icon child, OR the tile itself
3443
+ // may contain an emoji/symbol character directly as its only text content
3444
+ // (the "card-icon" pattern from many AI-generated demos).
3445
+ const iconChild = sibling.querySelector('svg, i[data-lucide], i[class*="fa-"], i[class*="icon"]');
3446
+ const iconRect = iconChild?.getBoundingClientRect();
3447
+ const sibDirectText = [...sibling.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
3448
+ const hasInlineEmojiIcon = sibling.children.length === 0 && isEmojiOnlyText(sibDirectText);
3449
+
3450
+ return checkIconTile({
3451
+ headingTag: tag,
3452
+ headingText: el.textContent || '',
3453
+ headingTop: headRect.top,
3454
+ siblingTag: sibling.tagName.toLowerCase(),
3455
+ siblingWidth: sibRect.width,
3456
+ siblingHeight: sibRect.height,
3457
+ siblingBottom: sibRect.bottom,
3458
+ siblingBgColor: parseRgb(sibStyle.backgroundColor),
3459
+ siblingBgImage: sibStyle.backgroundImage || '',
3460
+ siblingBorderWidth: parseFloat(sibStyle.borderTopWidth) || 0,
3461
+ siblingBorderRadius: parseFloat(sibStyle.borderRadius) || 0,
3462
+ hasIconChild: !!iconChild || hasInlineEmojiIcon,
3463
+ iconChildWidth: iconRect?.width || 0,
3464
+ });
3131
3465
  }
3132
3466
 
3133
- // Composite a translucent color over an opaque(ish) base (simple
3134
- // source-over in sRGB). Returns an opaque {r,g,b,a:1}.
3135
- function compositeColorOver(top, base) {
3136
- const a = top.a ?? 1;
3137
- return {
3138
- r: Math.round(top.r * a + base.r * (1 - a)),
3139
- g: Math.round(top.g * a + base.g * (1 - a)),
3140
- b: Math.round(top.b * a + base.b * (1 - a)),
3141
- a: 1,
3142
- };
3467
+ function checkElementItalicSerifDOM(el) {
3468
+ const tag = el.tagName.toLowerCase();
3469
+ if (tag !== 'h1' && tag !== 'h2') return [];
3470
+ const style = getComputedStyle(el);
3471
+ return checkItalicSerif({
3472
+ tag,
3473
+ fontStyle: style.fontStyle || '',
3474
+ fontFamily: style.fontFamily || '',
3475
+ fontSize: parseFloat(style.fontSize) || 0,
3476
+ headingText: el.textContent || '',
3477
+ });
3143
3478
  }
3144
3479
 
3145
- // Extended color parser: rgb/rgba/hex/oklch/oklab/hsl/hwb/color-mix/common
3146
- // named colors. Returns null on no match. Use this when the input might be
3147
- // any CSS color form; use plain parseRgb when you only expect computed rgb()
3148
- // values from real browsers.
3149
- function parseAnyColor(s) {
3150
- if (!s || typeof s !== 'string') return null;
3151
- const str = s.trim();
3152
- if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
3153
- if (/^color-mix\(/i.test(str)) return parseColorMix(str);
3154
- let m;
3155
- m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
3156
- if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
3157
- m = str.match(/^#([0-9a-f]{3,8})$/i);
3158
- if (m) {
3159
- const h = m[1];
3160
- if (h.length === 3 || h.length === 4) {
3161
- return {
3162
- r: parseInt(h[0] + h[0], 16),
3163
- g: parseInt(h[1] + h[1], 16),
3164
- b: parseInt(h[2] + h[2], 16),
3165
- a: h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1,
3166
- };
3167
- }
3168
- if (h.length === 6 || h.length === 8) {
3169
- return {
3170
- r: parseInt(h.slice(0, 2), 16),
3171
- g: parseInt(h.slice(2, 4), 16),
3172
- b: parseInt(h.slice(4, 6), 16),
3173
- a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
3174
- };
3175
- }
3176
- }
3177
- // OKLCH parser. Tailwind v4's CSS minifier squishes the space after
3178
- // `%` ("21.5%.02 50"), so the separator between L and C may be absent.
3179
- // Match L (with optional %), then C and H separated permissively.
3180
- m = str.match(/oklch\(\s*([\d.]+)(%?)\s*[\s,]*\s*([\d.]+)\s*[\s,]+\s*([-\d.]+)(?:deg)?(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3181
- if (m) {
3182
- const Lnum = parseFloat(m[1]);
3183
- const L = m[2] === '%' ? Lnum / 100 : Lnum;
3184
- const rgb = oklchToRgb(L, parseFloat(m[3]), parseFloat(m[4]));
3185
- if (m[5] !== undefined) {
3186
- const alpha = parseFloat(m[5]);
3187
- rgb.a = m[6] === '%' ? alpha / 100 : alpha;
3188
- }
3189
- return rgb;
3190
- }
3191
- // OKLAB — a/b are signed axes; percentages map 100% → 0.4.
3192
- m = str.match(/oklab\(\s*([\d.]+)(%?)\s+(-?[\d.]+)(%?)\s+(-?[\d.]+)(%?)(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3193
- if (m) {
3194
- const L = m[2] === '%' ? parseFloat(m[1]) / 100 : parseFloat(m[1]);
3195
- const a = m[4] === '%' ? parseFloat(m[3]) * 0.004 : parseFloat(m[3]);
3196
- const b = m[6] === '%' ? parseFloat(m[5]) * 0.004 : parseFloat(m[5]);
3197
- const rgb = oklabToRgb(L, a, b);
3198
- if (m[7] !== undefined) {
3199
- const alpha = parseFloat(m[7]);
3200
- rgb.a = m[8] === '%' ? alpha / 100 : alpha;
3201
- }
3202
- return rgb;
3203
- }
3204
- // HSL/HSLA — comma or space syntax, optional deg on hue.
3205
- m = str.match(/hsla?\(\s*(-?[\d.]+)(?:deg)?\s*[,\s]\s*([\d.]+)%\s*[,\s]\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+)(%)?)?\s*\)/i);
3206
- if (m) {
3207
- const rgb = hslToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
3208
- if (m[4] !== undefined) {
3209
- const alpha = parseFloat(m[4]);
3210
- rgb.a = m[5] === '%' ? alpha / 100 : alpha;
3211
- }
3212
- return rgb;
3480
+ function domAccentDashPseudo(el) {
3481
+ for (const which of ['::before', '::after']) {
3482
+ let ps;
3483
+ try { ps = getComputedStyle(el, which); } catch { continue; }
3484
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
3485
+ const w = parseFloat(ps.width) || 0;
3486
+ const h = parseFloat(ps.height) || 0;
3487
+ if (!(w >= 8 && w <= 80 && h >= 1 && h <= 6)) continue;
3488
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
3489
+ if (!bg || (bg.a ?? 1) < 0.1) continue;
3490
+ if (Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) >= 30) return true;
3213
3491
  }
3214
- // HWB — hue whiteness% blackness%.
3215
- m = str.match(/hwb\(\s*(-?[\d.]+)(?:deg)?\s+([\d.]+)%\s+([\d.]+)%(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3216
- if (m) {
3217
- const rgb = hwbToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
3218
- if (m[4] !== undefined) {
3219
- const alpha = parseFloat(m[4]);
3220
- rgb.a = m[5] === '%' ? alpha / 100 : alpha;
3492
+ return false;
3493
+ }
3494
+
3495
+ function checkElementHeroEyebrowDOM(el) {
3496
+ const tag = el.tagName.toLowerCase();
3497
+ if (tag !== 'h1') return [];
3498
+ const sibling = el.previousElementSibling;
3499
+ if (!sibling) return [];
3500
+ const headStyle = getComputedStyle(el);
3501
+ const sibStyle = getComputedStyle(sibling);
3502
+ return checkHeroEyebrow({
3503
+ headingTag: tag,
3504
+ headingText: el.textContent || '',
3505
+ headingFontSize: parseFloat(headStyle.fontSize) || 0,
3506
+ headingInApplicationContext: !!el.closest('[role="tabpanel"], [role="dialog"], [role="application"], dialog'),
3507
+ siblingTag: sibling.tagName.toLowerCase(),
3508
+ siblingText: sibling.textContent || '',
3509
+ siblingTextTransform: sibStyle.textTransform || '',
3510
+ siblingFontSize: parseFloat(sibStyle.fontSize) || 0,
3511
+ siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
3512
+ siblingFontWeight: sibStyle.fontWeight || '',
3513
+ siblingColor: sibStyle.color || '',
3514
+ siblingHasAccentDashPseudo: domAccentDashPseudo(sibling),
3515
+ });
3516
+ }
3517
+
3518
+ // Build a map of CSS custom properties declared on :root / :host / html.
3519
+ // Used to resolve var(--X) refs that jsdom returns verbatim in
3520
+ // getComputedStyle. Tailwind v4 routes every utility class through
3521
+ // CSS vars (font-weight: var(--font-weight-bold), font-size:
3522
+ // var(--text-xs), letter-spacing: var(--tracking-widest)), so without
3523
+ // resolution every style-based check silently fails on Tailwind v4
3524
+ // builds — the values come back as literal "var(--font-weight-bold)"
3525
+ // strings and parseFloat returns NaN.
3526
+ function buildCustomPropMap(document) {
3527
+ const map = new Map();
3528
+ let sheets;
3529
+ try { sheets = Array.from(document.styleSheets || []); }
3530
+ catch { return map; }
3531
+ for (const sheet of sheets) {
3532
+ let rules;
3533
+ try { rules = Array.from(sheet.cssRules || []); }
3534
+ catch { continue; }
3535
+ for (const rule of rules) {
3536
+ // Style rules only (type 1). Walk @media / @supports if present.
3537
+ if (rule.type === 4 /* MEDIA_RULE */ || rule.type === 12 /* SUPPORTS_RULE */) {
3538
+ try { rules.push(...Array.from(rule.cssRules || [])); } catch { /* ignore */ }
3539
+ continue;
3540
+ }
3541
+ if (rule.type !== 1 /* STYLE_RULE */) continue;
3542
+ const sel = rule.selectorText || '';
3543
+ if (!/(^|,\s*)(:root|html|:host)\b/i.test(sel)) continue;
3544
+ const style = rule.style;
3545
+ if (!style) continue;
3546
+ for (let i = 0; i < style.length; i++) {
3547
+ const prop = style[i];
3548
+ if (!prop || !prop.startsWith('--')) continue;
3549
+ const val = style.getPropertyValue(prop).trim();
3550
+ if (val) map.set(prop, val);
3551
+ }
3221
3552
  }
3222
- return rgb;
3223
3553
  }
3224
- const named = CSS_NAMED_COLORS[str.toLowerCase()];
3225
- if (named) return { ...named, a: 1 };
3226
- return null;
3554
+ return map;
3555
+ }
3556
+
3557
+ // Resolve var(--X[, fallback]) refs in a computed-style value string.
3558
+ // Recurses up to 8 levels for chained refs (--a: var(--b)). Returns
3559
+ // the original string when no refs are present or the chain doesn't
3560
+ // resolve. Safe to call on already-resolved values.
3561
+ function resolveVarRefs(raw, customPropMap, depth = 0) {
3562
+ if (typeof raw !== 'string' || !raw.includes('var(')) return raw;
3563
+ if (depth > 8) return raw;
3564
+ return raw.replace(/var\(\s*(--[a-zA-Z0-9_-]+)\s*(?:,\s*([^)]+))?\)/g, (_m, name, fallback) => {
3565
+ const v = customPropMap.get(name);
3566
+ if (v != null) return resolveVarRefs(v, customPropMap, depth + 1);
3567
+ return fallback ? resolveVarRefs(fallback.trim(), customPropMap, depth + 1) : _m;
3568
+ });
3227
3569
  }
3228
3570
 
3571
+
3229
3572
  // Resolve var() refs in a color string (via customPropMap), then parse.
3230
3573
  // Returns null on any failure. Used in jsdom-mode paths where
3231
3574
  // getComputedStyle returns literal "var(--X)" or "oklch(...)" strings.
@@ -3587,9 +3930,20 @@ function checkElementGlowDOM(el) {
3587
3930
  if (!boxShadow && !textShadow) return [];
3588
3931
  // Use parent's background — glow radiates outward, so the surrounding context matters
3589
3932
  // If resolveBackground returns null (gradient), try to infer from the gradient colors
3590
- let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
3591
- if (!parentBg) {
3592
- // Gradient background — sample its colors to determine if it's dark
3933
+ const parentBgInfo = resolveBackgroundInfo(el.parentElement || el);
3934
+ // Unknown surface (an unreadable layer on the way up): skip only the
3935
+ // gradient hunt below, which would walk PAST that layer and score the
3936
+ // glow against a background the visitor never sees. checkGlow still runs
3937
+ // with a null surface: the zero-offset chromatic halo tell holds on ANY
3938
+ // background, and the static loop already passes the unresolved walk's
3939
+ // null color straight through (detect-html.mjs uses resolveBackground).
3940
+ let parentBg = parentBgInfo.color;
3941
+ if (!parentBg && !parentBgInfo.unresolved) {
3942
+ // Gradient background — sample its colors to determine if it's dark.
3943
+ // Modern-syntax parsing matters here: body-level gradients now reach this
3944
+ // fallback in browser mode, and their stops usually serialize as oklch —
3945
+ // which the shared parseGradientColors reads via its color-function
3946
+ // token capture.
3593
3947
  let cur = el.parentElement;
3594
3948
  while (cur && cur.nodeType === 1) {
3595
3949
  const bgImage = getComputedStyle(cur).backgroundImage || '';
@@ -3637,10 +3991,13 @@ function checkElementAIPaletteDOM(el) {
3637
3991
  const hue = getHue(textColor);
3638
3992
  const isAIPalette = (hue >= 160 && hue <= 200) || (hue >= 260 && hue <= 310);
3639
3993
  if (isAIPalette) {
3640
- const parentBg = el.parentElement ? resolveBackground(el.parentElement) : null;
3641
- // Also check gradient parents
3642
- let effectiveBg = parentBg;
3643
- if (!effectiveBg) {
3994
+ const parentBgInfo = el.parentElement
3995
+ ? resolveBackgroundInfo(el.parentElement)
3996
+ : { color: null, unresolved: false };
3997
+ // Unknown surface: leave effectiveBg null (no finding) rather than
3998
+ // hunting gradient ancestors past a layer we could not read.
3999
+ let effectiveBg = parentBgInfo.color;
4000
+ if (!effectiveBg && !parentBgInfo.unresolved) {
3644
4001
  let cur = el.parentElement;
3645
4002
  while (cur && cur.nodeType === 1) {
3646
4003
  const gi = getComputedStyle(cur).backgroundImage || '';
@@ -4435,10 +4792,19 @@ function checkElementBorders(tag, style, overrides, resolvedRadius, el = null) {
4435
4792
  }
4436
4793
 
4437
4794
  function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
4795
+ // Invisible at rest, static twin of the browser walk's skip: opacity does
4796
+ // not inherit, so walk ancestors multiplying declared opacity down.
4797
+ if (style.visibility === 'hidden') return [];
4798
+ let effOpacity = 1;
4799
+ for (let cur = el; cur && cur.nodeType === 1 && effOpacity > 0.02; cur = cur.parentElement) {
4800
+ effOpacity *= parseFloat(window.getComputedStyle(cur).opacity || '1');
4801
+ }
4802
+ if (effOpacity <= 0.02) return [];
4438
4803
  const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
4439
4804
  const hasDirectText = directText.trim().length > 0;
4440
4805
 
4441
- const effectiveBg = resolveBackground(el, window, customPropMap);
4806
+ const bgInfo = resolveBackgroundInfo(el, window, customPropMap);
4807
+ const effectiveBg = bgInfo.color;
4442
4808
  // jsdom returns literal "var(--X)" / "oklch(...)" for color, so plain
4443
4809
  // parseRgb misses Tailwind-tokenized text colors. Resolve through the
4444
4810
  // customPropMap first; fall back to parseRgb for vanilla rgb() pages.
@@ -4484,11 +4850,13 @@ function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInhe
4484
4850
  // element itself has no usable own background, that pseudo is the real
4485
4851
  // surface for contrast purposes.
4486
4852
  let finalEffectiveBg = effectiveBg;
4853
+ let surfaceUnresolved = bgInfo.unresolved;
4487
4854
  if ((!ownBg || (ownBg.a ?? 1) <= 0.5) && typeof window.getPseudoSurface === 'function') {
4488
4855
  const pseudoSurface = window.getPseudoSurface(el);
4489
4856
  if (pseudoSurface) {
4490
4857
  ownBg = pseudoSurface;
4491
4858
  finalEffectiveBg = pseudoSurface;
4859
+ surfaceUnresolved = false;
4492
4860
  }
4493
4861
  }
4494
4862
 
@@ -4496,8 +4864,9 @@ function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInhe
4496
4864
  tag,
4497
4865
  textColor,
4498
4866
  bgColor: ownBg,
4499
- effectiveBg: finalEffectiveBg,
4500
- effectiveBgStops: finalEffectiveBg ? null : resolveGradientStops(el, window, customPropMap),
4867
+ // Unknown surface: hand the checks nothing rather than a guess.
4868
+ effectiveBg: surfaceUnresolved ? null : finalEffectiveBg,
4869
+ effectiveBgStops: surfaceUnresolved || finalEffectiveBg ? null : resolveGradientStops(el, window, customPropMap),
4501
4870
  fontSize: parseFloat(style.fontSize) || 16,
4502
4871
  fontWeight: parseInt(style.fontWeight) || 400,
4503
4872
  hasDirectText,
@@ -5593,6 +5962,11 @@ function isRenderedForBrowserRule(el) {
5593
5962
  function checkElementTextOverflowDOM(el) {
5594
5963
  const tag = el.tagName.toLowerCase();
5595
5964
  if (TEXT_OVERFLOW_SKIP_TAGS.has(tag)) return [];
5965
+ // scrollWidth/clientWidth are CSS box-model metrics; on SVG content Chrome
5966
+ // returns arbitrary non-zero values for both (a <text> reported 78/48 while
5967
+ // its rendered length sat comfortably inside its box), so the delta is
5968
+ // noise, not overflow. SVG clips to its own viewport anyway.
5969
+ if (el.namespaceURI === 'http://www.w3.org/2000/svg') return [];
5596
5970
  if (!isRenderedForBrowserRule(el)) return [];
5597
5971
  // Only the element that actually owns overflowing text — not its ancestors,
5598
5972
  // which inherit a wider scrollWidth from the spilling descendant.
@@ -5977,6 +6351,22 @@ function isPaintedForOcclusion(el) {
5977
6351
  // path is pure geometry and runs anywhere on the page.
5978
6352
  const OCCLUSION_TEXT_SKIP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'title']);
5979
6353
 
6354
+ // An element whose effective opacity multiplies out to ~0 paints nothing at
6355
+ // rest: it is not user-visible, so visual findings on it (contrast, occlusion)
6356
+ // measure a state nobody sees. Browser-only — the walk needs live computed
6357
+ // styles. Cycling scenes that fade such elements in later are the screenshot
6358
+ // subsystem's territory, not the analytic walk's.
6359
+ function effectiveOpacityDOM(el) {
6360
+ let o = 1;
6361
+ // Walk all the way through body and html: `body { opacity: 0 }` page-fade
6362
+ // wrappers hide every descendant just as thoroughly as a local wrapper.
6363
+ for (let cur = el; cur && cur.nodeType === 1; cur = cur.parentElement) {
6364
+ o *= parseFloat(getComputedStyle(cur).opacity || '1');
6365
+ if (o <= 0.02) return 0;
6366
+ }
6367
+ return o;
6368
+ }
6369
+
5980
6370
  function checkTextOcclusionDOM() {
5981
6371
  const findings = [];
5982
6372
  const seenVictims = new Set();
@@ -6004,6 +6394,11 @@ function checkTextOcclusionDOM() {
6004
6394
  }
6005
6395
  return false;
6006
6396
  };
6397
+ // The classic occluder shape this rules out is an opacity-0 interaction
6398
+ // layer — a range scrubber stretched over a before/after comparison — which
6399
+ // elementFromPoint still returns and whose UA background-color otherwise
6400
+ // reads as an opaque box.
6401
+ const effectiveOpacity = effectiveOpacityDOM;
6007
6402
 
6008
6403
  // Collect renderable text owners in / near the first viewport for the
6009
6404
  // elementFromPoint probe. SVG <text> counts too.
@@ -6016,6 +6411,7 @@ function checkTextOcclusionDOM() {
6016
6411
  const text = inSvg ? (el.textContent || '').trim() : elementDirectText(el);
6017
6412
  if (text.length < 2) continue;
6018
6413
  if (!isPaintedForOcclusion(el)) continue;
6414
+ if (effectiveOpacity(el) <= 0.02) continue;
6019
6415
  let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
6020
6416
  if (rect.width < 6 || rect.height < 6) continue;
6021
6417
  // Viewport-bound probe: keep text whose box overlaps the live viewport.
@@ -6049,6 +6445,7 @@ function checkTextOcclusionDOM() {
6049
6445
  if (top === el || el.contains(top) || top.contains(el)) continue;
6050
6446
  const topCs = getComputedStyle(top);
6051
6447
  if (isFloated(topCs) || isMarqueeish(top, topCs) || isPinnedOverlay(top)) continue;
6448
+ if (effectiveOpacity(top) <= 0.02) continue;
6052
6449
  const topTag = top.tagName.toLowerCase();
6053
6450
  // Text sitting under a raw image/video is contrast territory (deduped
6054
6451
  // against the pixel low-contrast rule); leave those alone here.
@@ -6941,6 +7338,10 @@ if (IS_BROWSER) {
6941
7338
 
6942
7339
  const reasons = collectVisualContrastReasons(el, style);
6943
7340
  if (reasons.length === 0) continue;
7341
+ // Image-only mode filters here, inside the cap: gradient/opacity/filter
7342
+ // candidates earlier in DOM order must not consume the budget and
7343
+ // starve the url()-backed texts this mode exists to sample.
7344
+ if (options.imageOnly && !reasons.includes('image background')) continue;
6944
7345
 
6945
7346
  const textColor = parseRgb(style.color);
6946
7347
  const fontSize = parseFloat(style.fontSize) || 16;
@@ -7433,6 +7834,7 @@ if (IS_BROWSER) {
7433
7834
  }
7434
7835
 
7435
7836
  async function analyzeVisualContrast(options = {}) {
7837
+ // imageOnly is enforced inside the collector, before the candidate cap.
7436
7838
  const candidates = collectVisualContrastCandidates(options);
7437
7839
  const results = [];
7438
7840
  const shouldScrollOffscreen = options.scrollOffscreen === true;
@@ -7518,9 +7920,16 @@ if (IS_BROWSER) {
7518
7920
 
7519
7921
  function addBrowserFindings(groupMap, el, findings) {
7520
7922
  if (!findings || findings.length === 0) return;
7923
+ // Element-scoped waivers: a data-impeccable-ignore ancestor suppresses
7924
+ // matching findings for its whole subtree. Applied at this choke point so
7925
+ // every per-element attribution (checks, layout, occlusion, rhythm)
7926
+ // honors it; page-level findings attributed to <body> pass through
7927
+ // untouched, since body has no ignoring ancestor.
7928
+ const kept = findings.filter(f => !scopedIgnoreActive(el, f.type));
7929
+ if (kept.length === 0) return;
7521
7930
  const existing = groupMap.get(el);
7522
- if (existing) existing.push(...findings);
7523
- else groupMap.set(el, [...findings]);
7931
+ if (existing) existing.push(...kept);
7932
+ else groupMap.set(el, [...kept]);
7524
7933
  }
7525
7934
 
7526
7935
  function browserFindingsFromMap(groupMap) {
@@ -7878,9 +8287,27 @@ if (IS_BROWSER) {
7878
8287
  for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
7879
8288
  node.remove();
7880
8289
  }
7881
- const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
7882
- if (htmlPatternFindings.length > 0) {
7883
- const mapped = htmlPatternFindings.map(f => {
8290
+ // Regex findings that name a live selector resolve against the real DOM:
8291
+ // pseudo-element/class segments are stripped (the host element is the
8292
+ // anchor), a selector that matches nothing on this page drops the finding
8293
+ // (the CSS ships here, but the pattern never renders — the live DOM is
8294
+ // ground truth in the browser), and a match under a data-impeccable-ignore
8295
+ // ancestor is waived. Selector-less findings stay page-level.
8296
+ const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
8297
+ if (!f.selector) return true;
8298
+ const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
8299
+ if (!query || /^[,\s]*$/.test(query)) return true;
8300
+ let matches;
8301
+ try {
8302
+ matches = document.querySelectorAll(query);
8303
+ } catch {
8304
+ return true;
8305
+ }
8306
+ if (matches.length === 0) return false;
8307
+ return [...matches].some(el => !scopedIgnoreActive(el, f.id));
8308
+ });
8309
+ if (scopedHtmlFindings.length > 0) {
8310
+ const mapped = scopedHtmlFindings.map(f => {
7884
8311
  const item = { type: f.id, detail: f.snippet };
7885
8312
  if (f.severity) {
7886
8313
  item.severity = f.severity;
@@ -7910,8 +8337,27 @@ if (IS_BROWSER) {
7910
8337
  };
7911
8338
  }
7912
8339
 
8340
+ // Visual contrast has three modes. Explicit true runs the full sampled
8341
+ // pass; explicit false disables it entirely (the deterministic-only mode
8342
+ // the test suites use). Unset — the default overlay run — samples ONLY
8343
+ // image-backed text: the one class the analytic walk deliberately skips,
8344
+ // because a url() layer's pixels are unknowable without looking. In-page
8345
+ // sampling draws the source image alone to a canvas (glyph ink never
8346
+ // pollutes it), and a cross-origin image without CORS reports unresolved
8347
+ // instead of guessing.
8348
+ function visualContrastMode(options = {}) {
8349
+ const explicit = typeof options.visualContrast === 'boolean'
8350
+ ? options.visualContrast
8351
+ : typeof window.__IMPECCABLE_CONFIG__?.visualContrast === 'boolean'
8352
+ ? window.__IMPECCABLE_CONFIG__.visualContrast
8353
+ : null;
8354
+ if (explicit === true) return 'full';
8355
+ if (explicit === false) return false;
8356
+ return 'image-only';
8357
+ }
8358
+
7913
8359
  function shouldRunVisualContrast(options = {}) {
7914
- return options.visualContrast === true || window.__IMPECCABLE_CONFIG__?.visualContrast === true;
8360
+ return visualContrastMode(options) !== false;
7915
8361
  }
7916
8362
 
7917
8363
  function visualContrastOptions(options = {}) {
@@ -8088,6 +8534,7 @@ if (IS_BROWSER) {
8088
8534
  return [];
8089
8535
  }
8090
8536
  const resolvedOptions = visualContrastOptions(options);
8537
+ if (visualContrastMode(options) === 'image-only') resolvedOptions.imageOnly = true;
8091
8538
  const analyses = await analyzeVisualContrast(resolvedOptions);
8092
8539
  if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
8093
8540
  lastVisualContrastAnalyses = analyses;