All files / packages/sds-stylelint-config/src/validators/shared helpers.ts

100% Statements 15/15
100% Branches 16/16
100% Functions 4/4
100% Lines 13/13

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        62x                                               62x 62x     62x 21x 21x       55x     16x 16x 5x     11x         92x         81x    
import type { ValidationError } from '../../types.js';
 
/** Create a validation error. */
export function err(segment: string, expected: string[] | string, received: string): ValidationError {
  return { segment, expected: Array.isArray(expected) ? expected : [expected], received };
}
 
/** Result of matching a token against an allowlist. */
export interface TokenMatch {
  match: string | null;
  consumed: number;
  isLegacy?: boolean;
  received?: string;
}
 
/**
 * Match a token against a valid-value list, supporting compound
 * (hyphenated) values and legacy squash-case aliases.
 *
 * Compound matches are tried first (e.g. 'block' + 'start' -> 'block-start').
 * Single matches are tried next. Legacy aliases are tried last.
 */
export function matchToken(
  tokens: string[],
  idx: number,
  validList: string[],
  aliases: Record<string, string> = {},
): TokenMatch {
  const current = tokens[idx];
  const next = tokens[idx + 1];
 
  // Compound match (two tokens joined by hyphen)
  if (next) {
    const compound = `${current}-${next}`;
    if (validList.includes(compound)) return { match: compound, consumed: 2 };
  }
 
  // Direct single-token match
  if (validList.includes(current)) return { match: current, consumed: 1 };
 
  // Legacy alias match (squash-case -> canonical)
  const canonical = aliases[current];
  if (canonical && validList.includes(canonical)) {
    return { match: canonical, consumed: 1, isLegacy: true, received: current };
  }
 
  return { match: null, consumed: 1 };
}
 
/** Tokenize a CSS custom property name. */
export function tokenize(prop: string): string[] {
  return prop.replace(/^--/, '').split('-').filter(Boolean);
}
 
/** Check whether a custom property should be validated. */
export function shouldValidate(value: unknown, privatePrefix: string): value is string {
  return typeof value === 'string' && value.startsWith('--') && !value.includes(privatePrefix);
}