All files / packages/sds-stylelint-config/src/plugins design-token-reference-pattern.ts

96.29% Statements 26/27
92.85% Branches 13/14
100% Functions 5/5
100% Lines 23/23

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                          1x 1x               26x 13x   12x 12x   7x 7x   7x 1x     7x 7x   7x 6x           1x   1x 11x 11x 11x   11x   11x 13x 26x                
import stylelint from 'stylelint';
import valueParser from 'postcss-value-parser';
import type { Declaration } from 'postcss';
import metadata from '../metadata/metadata.js';
import {
  validateNamespace,
  validateReferenceTokens,
  tokenize,
  shouldValidate,
  formatErrors,
} from '../utils/index.js';
import type { RuleOptions } from '../types.js';
 
const { report, validateOptions } = stylelint.utils;
const ruleName = 'sds-stylelint-plugin/design-token-reference-pattern';
 
function processNode(
  node: any,
  decl: Declaration,
  result: stylelint.PostcssResult,
  privatePrefix: string,
): void {
  if (node.type !== 'word') return;
  if (!shouldValidate(node.value, privatePrefix)) return;
 
  const tokens = tokenize(node.value);
  if (tokens[1] !== 'r') return;
 
  const nsResult = validateNamespace(tokens[0], privatePrefix);
  const allErrors = [];
 
  if (!nsResult.valid) {
    allErrors.push({ segment: 'namespace', expected: nsResult.names, received: tokens[0] });
  }
 
  const { errors } = validateReferenceTokens(tokens, metadata);
  allErrors.push(...errors);
 
  if (allErrors.length > 0) {
    report({ ruleName, result, message: formatErrors(node.value, allErrors), node: decl });
  }
}
 
type Rule = Parameters<typeof stylelint.createPlugin>[1];
 
const messages = stylelint.utils.ruleMessages(ruleName, {});
 
const referenceTokens = Object.assign(
  (primary: boolean, options?: RuleOptions) => (root: any, result: stylelint.PostcssResult) => {
    const valid = validateOptions(result, ruleName, { actual: primary, possible: [true] });
    Iif (!valid) return;
 
    const privatePrefix = options?.privateSyntax || metadata.privateSyntax[0];
 
    root.walkDecls((decl: Declaration) => {
      valueParser(decl.value).walk((node: any) => {
        processNode(node, decl, result, privatePrefix);
      });
    });
  },
  { ruleName, messages },
) satisfies Rule;
 
export default stylelint.createPlugin(ruleName, referenceTokens);