All files / packages/sds-customization-compliance/src/audit extract.ts

94.63% Statements 194/205
81.02% Branches 111/137
91.3% Functions 21/23
95.2% Lines 159/167

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360                                  7x                     7x     7x     7x     7x                 115x 115x               77x     77x         3417x               162x 162x 162x 162x 1580x 1580x 1579x 1578x 10x 10x     162x 162x               149x 149x                           27x 27x 27x 27x 27x 27x   27x 5x 5x 5x 5x 41x 41x 41x   5x     27x         27x 60x 60x 4x 9x 4x 56x 29x 173x 29x 27x 9x 1x 1x 26x 7x 7x 6x 7x 28x 7x 7x 5x 5x   3x 3x 3x 6x 6x         6x     3x 3x 3x                     2x 1x   19x 4x 9x 4x 4x   15x       27x         14x 11x 3x         7x 7x 7x 8x 8x   7x                           3163x 3163x 1213x 1213x 1213x 58252x 58252x 56839x 55426x   1213x 302x 302x 302x 167x   2117x               3155x 3155x 3155x 1206x 1206x 1206x 1206x 1206x 1206x 49712x 49712x 48473x 47531x 297x 297x     1206x 297x 297x 297x   3155x         3151x 3151x 3151x 3151x                 96x 96x 1713x 1713x 1713x 1675x 1675x   1713x 3151x 3151x                     96x                     134x 134x 2235x 2235x 5168x 2982x           2235x 1548x 1548x 1548x   134x                 118x       118x 76x 5x   118x 2222x   118x    
/**
 * Shared CSS extraction helpers for the theme-regression audit.
 *
 * Everything here operates on a flattened PostCSS root (after `@import` +
 * nesting resolution), so selectors are fully expanded and decls are grouped
 * exactly as they would render. Kept dependency-light and side-effect-free
 * so it can run in either Node or the browser.
 */
 
import postcss, { type Root, type AcceptedPlugin } from 'postcss';
import postcssAtImport from 'postcss-import';
import postcssNested from 'postcss-nested';
import postcssRemoveComments from 'postcss-discard-comments';
 
import type { DeclModel, MotionSignals, Specificity, ThemeAssignmentsBlock } from './types.js';
 
/** PostCSS plugin chain that flattens a CSS file to a single-level AST (with `@import` resolution). */
export const flattenPlugins: AcceptedPlugin[] = [
  postcssAtImport({ cache: false }),
  postcssRemoveComments(),
  postcssNested(),
];
 
/**
 * Plugin chain that flattens in-memory CSS strings without touching the
 * filesystem — used by {@link loadModelsFromStrings} in `models.ts` and by
 * any browser-side audit path.
 */
export const stringFlattenPlugins: AcceptedPlugin[] = [postcssRemoveComments(), postcssNested()];
 
/** Matches every `--slds-c-*` token reference in a declaration value. */
export const HOOK_TOKEN_RE = /--slds-c-[a-z0-9-]+/gi;
 
/** Matches a custom property whose name is a component hook. */
export const HOOK_PROP_RE = /^--slds-c-[a-z0-9-]+$/i;
 
/** Matches any `--slds-*` token reference (component, shared, global, raw). */
export const ANY_TOKEN_RE = /--slds-[a-z]-[a-z0-9-]+/gi;
 
/**
 * Run the filesystem-aware flatten pipeline on raw CSS text.
 *
 * @param css Raw CSS source.
 * @param fromPath Absolute path used for `@import` resolution.
 */
export async function flattenCss(css: string, fromPath: string): Promise<Root> {
  const result = await postcss(flattenPlugins).process(css, { from: fromPath });
  return result.root;
}
 
/**
 * Flatten a raw CSS string without resolving `@import`s. Suitable for
 * already-flattened input (e.g. theme build output, browser fixtures).
 */
export async function flattenCssString(css: string): Promise<Root> {
  const result = await postcss(stringFlattenPlugins).process(css, {
    from: undefined,
  });
  return result.root;
}
 
/** Collapse runs of whitespace in a selector to single spaces and trim. */
export function normalizeSelector(sel: string): string {
  return String(sel).replace(/\s+/g, ' ').trim();
}
 
/**
 * Split a comma-separated selector list into trimmed members, respecting
 * parentheses so things like `:is(a, b)` stay intact.
 */
export function splitSelectorList(selector: string): string[] {
  const out: string[] = [];
  let depth = 0;
  let start = 0;
  for (let i = 0; i < selector.length; i++) {
    const c = selector[i];
    if (c === '(' || c === '[') depth += 1;
    else if (c === ')' || c === ']') depth -= 1;
    else if (c === ',' && depth === 0) {
      out.push(selector.slice(start, i).trim());
      start = i + 1;
    }
  }
  out.push(selector.slice(start).trim());
  return out.filter(Boolean);
}
 
/**
 * Normalized, sortable key for a selector list — lets us match the "same"
 * rule on both sides even when the author re-ordered commas.
 */
export function selectorKey(selector: string): string {
  const members = splitSelectorList(normalizeSelector(selector));
  return [...members].sort().join(', ');
}
 
/**
 * Compute CSS specificity for a single selector ([ids, classes, types]).
 *
 * Handles what shows up in SLDS2 component CSS: ids (`#`), classes (`.`),
 * attributes (`[...]`), pseudo-classes (`:hover`), pseudo-elements
 * (`::before`), type selectors, combinators, and the universal selector.
 *
 * `:is(...)` / `:where(...)` / `:not(...)` arguments are walked so the
 * highest-specificity child contributes (`:where()` contributes zero).
 */
export function computeSpecificity(selector: string): Specificity {
  let ids = 0;
  let classes = 0;
  let types = 0;
  const s = String(selector).trim();
  let i = 0;
  const len = s.length;
 
  const skipParens = (): string => {
    let depth = 1;
    const start = i;
    i += 1;
    while (i < len && depth > 0) {
      Iif (s[i] === '(') depth += 1;
      else if (s[i] === ')') depth -= 1;
      i += 1;
    }
    return s.slice(start + 1, i - 1);
  };
 
  const walk = (sub: string, addFn: (a: number, b: number, c: number) => void): void => {
    const [a, b, c] = computeSpecificity(sub);
    addFn(a, b, c);
  };
 
  while (i < len) {
    const c = s[i];
    if (c === '#') {
      i += 1;
      while (i < len && /[\w-]/.test(s[i])) i += 1;
      ids += 1;
    } else if (c === '.') {
      i += 1;
      while (i < len && /[\w-]/.test(s[i])) i += 1;
      classes += 1;
    } else if (c === '[') {
      while (i < len && s[i] !== ']') i += 1;
      Eif (i < len) i += 1;
      classes += 1;
    } else if (c === ':') {
      const isPseudoElement = s[i + 1] === ':';
      if (isPseudoElement) i += 2;
      else i += 1;
      const nameStart = i;
      while (i < len && /[\w-]/.test(s[i])) i += 1;
      const name = s.slice(nameStart, i).toLowerCase();
      if (i < len && s[i] === '(') {
        const inner = skipParens();
        if (name === 'where') {
          // :where() contributes zero.
        } else if (name === 'is' || name === 'not' || name === 'has') {
          let best: Specificity = [0, 0, 0];
          for (const arg of splitSelectorList(inner)) {
            const [a, b, c2] = computeSpecificity(arg);
            Eif (
              a > best[0] ||
              (a === best[0] && b > best[1]) ||
              (a === best[0] && b === best[1] && c2 > best[2])
            ) {
              best = [a, b, c2];
            }
          }
          ids += best[0];
          classes += best[1];
          types += best[2];
        } else E{
          if (isPseudoElement) types += 1;
          else classes += 1;
          walk(inner, (a, b, c2) => {
            ids += a;
            classes += b;
            types += c2;
          });
        }
      } else {
        if (isPseudoElement) types += 1;
        else classes += 1;
      }
    } else if (/[a-zA-Z-]/.test(c)) {
      const nameStart = i;
      while (i < len && /[\w-]/.test(s[i])) i += 1;
      const name = s.slice(nameStart, i);
      Eif (name !== '*') types += 1;
    } else {
      i += 1;
    }
  }
 
  return [ids, classes, types];
}
 
/** Compare two specificity triples. `< 0`, `0`, `> 0` mirror `Array.sort`. */
export function compareSpecificity(a: Specificity, b: Specificity): number {
  if (a[0] !== b[0]) return a[0] - b[0];
  if (a[1] !== b[1]) return a[1] - b[1];
  return a[2] - b[2];
}
 
/** Highest-specificity member of a comma-separated selector list. */
export function maxSpecificity(selector: string): Specificity {
  const members = splitSelectorList(normalizeSelector(selector));
  let best: Specificity = [0, 0, 0];
  for (const m of members) {
    const s = computeSpecificity(m);
    Eif (compareSpecificity(s, best) > 0) best = s;
  }
  return best;
}
 
/**
 * Recursively peel `var(--x, …)` until a non-`var()` token remains.
 * Returns `null` when the outer value isn't a `var()` expression or the
 * chain bottoms out with no terminal.
 *
 *   var(--a, var(--b, transparent))  -> 'transparent'
 *   var(--a, var(--b))               -> null
 *   var(--a, 0)                      -> '0'
 *   #fff                             -> null (not a var chain)
 */
export function terminalFallback(rawValue: string | null | undefined): string | null {
  let raw = String(rawValue ?? '').trim();
  while (raw.startsWith('var(')) {
    let depth = 0;
    let lastCommaAtDepth1 = -1;
    for (let i = 0; i < raw.length; i++) {
      const c = raw[i];
      if (c === '(') depth += 1;
      else if (c === ')') depth -= 1;
      else if (c === ',' && depth === 1) lastCommaAtDepth1 = i;
    }
    if (lastCommaAtDepth1 === -1) return null;
    let tail = raw.slice(lastCommaAtDepth1 + 1).trim();
    Eif (tail.endsWith(')')) tail = tail.slice(0, -1).trim();
    if (!tail.startsWith('var(')) return tail || null;
    raw = tail;
  }
  return null;
}
 
/**
 * Ordered list of `var()` token refs in a declaration value, outermost
 * first. Returns every `--slds-*` token, not just component hooks.
 */
export function extractVarChain(rawValue: string | null | undefined): string[] {
  const chain: string[] = [];
  let raw = String(rawValue ?? '').trim();
  while (raw.startsWith('var(')) {
    const m = raw.match(/^var\(\s*(--[a-z0-9-]+)/i);
    Iif (!m) break;
    chain.push(m[1]);
    let depth = 0;
    let firstCommaAtDepth1 = -1;
    for (let i = 0; i < raw.length; i++) {
      const c = raw[i];
      if (c === '(') depth += 1;
      else if (c === ')') depth -= 1;
      else if (c === ',' && depth === 1) {
        firstCommaAtDepth1 = i;
        break;
      }
    }
    if (firstCommaAtDepth1 === -1) break;
    let tail = raw.slice(firstCommaAtDepth1 + 1).trim();
    Eif (tail.endsWith(')')) tail = tail.slice(0, -1).trim();
    raw = tail;
  }
  return chain;
}
 
/** Collect all component hooks referenced in a declaration value. */
export function extractHooksFromValue(value: string | null | undefined): Set<string> {
  const hooks = new Set<string>();
  const matches = String(value ?? '').match(HOOK_TOKEN_RE);
  if (matches) for (const m of matches) hooks.add(m);
  return hooks;
}
 
/**
 * Walk a flattened PostCSS root and produce a declaration model keyed by
 * normalized selector. Comma-separated selector lists are kept verbatim so
 * customer-visible selector shape is preserved in reporting.
 */
export function extractDeclModel(rootNode: Root): Map<string, DeclModel[]> {
  const bySelector = new Map<string, DeclModel[]>();
  rootNode.walkRules((rule) => {
    const rawSelector = normalizeSelector(rule.selector);
    let bucket = bySelector.get(rawSelector);
    if (!bucket) {
      bucket = [];
      bySelector.set(rawSelector, bucket);
    }
    rule.walkDecls((decl) => {
      const rawValue = String(decl.value ?? '').trim();
      bucket!.push({
        prop: decl.prop,
        rawValue,
        hooksRead: [...extractHooksFromValue(rawValue)],
        terminalFallback: terminalFallback(rawValue),
        varChain: extractVarChain(rawValue),
        line: decl.source?.start?.line ?? null,
        source: decl.source?.input?.from ?? null,
      });
    });
  });
  return bySelector;
}
 
/**
 * Walk a flattened theme-file root and produce
 * `{selector: {hookProp: HookAssignment}}`. Only declarations whose prop
 * matches `HOOK_PROP_RE` are captured. Later assignments win within the
 * same selector, matching CSS cascade within a single file. Each
 * assignment carries the `value` plus its source `path` + `line`.
 */
export function extractHookAssignments(rootNode: Root): ThemeAssignmentsBlock['assignmentsBySelector'] {
  const selectors: ThemeAssignmentsBlock['assignmentsBySelector'] = {};
  rootNode.walkRules((rule) => {
    const hooks: Record<string, ThemeAssignmentsBlock['assignmentsBySelector'][string][string]> = {};
    rule.walkDecls((decl) => {
      if (!HOOK_PROP_RE.test(decl.prop)) return;
      hooks[decl.prop] = {
        value: String(decl.value ?? '').trim(),
        source: decl.source?.input?.from ?? null,
        line: decl.source?.start?.line ?? null,
      };
    });
    if (Object.keys(hooks).length === 0) return;
    const selector = normalizeSelector(rule.selector);
    const existing = selectors[selector];
    selectors[selector] = existing ? { ...existing, ...hooks } : hooks;
  });
  return selectors;
}
 
/**
 * Collect every at-rule of interest — currently
 * `@media (prefers-reduced-motion: reduce)` blocks and `[kx-*]` rules — so
 * the diff engine can spot motion/kinetics blocks that vanished.
 */
export function extractMotionSignals(rootNode: Root): MotionSignals {
  const signals: MotionSignals = {
    reducedMotionBlocks: 0,
    kxRules: 0,
  };
  rootNode.walkAtRules((atRule) => {
    if (atRule.name !== 'media') return;
    if (/prefers-reduced-motion/i.test(atRule.params)) signals.reducedMotionBlocks += 1;
  });
  rootNode.walkRules((rule) => {
    if (/\[kx-/i.test(rule.selector)) signals.kxRules += 1;
  });
  return signals;
}