All files / packages/design-tokens/src/validators temp-test-brand-refs-resolution.js

0% Statements 0/75
0% Branches 0/51
0% Functions 0/5
0% Lines 0/75

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                                                                                                                                                                                                                                                                                                                                                             
#!/usr/bin/env node
 
/**
 * TEMPORARY Brand Reference Resolution Test (TO BE REMOVED AFTER MIGRATION)
 *
 * Validate that all brand reference tokens (--slds-r-color-brand-*) resolve correctly
 * and display their values across themes.
 *
 * Similar to temp-test-alias-resolution.js but specifically for brand reference tokens.
 *
 * NOTE: This is a temporary migration tool that should be deleted once the
 * design token migration from legacy (Theo) to modern (Style Dictionary + W3C)
 * is complete and verified.
 *
 * Usage:
 *   yarn temp:test:brand-refs-resolution           # Summary only
 *   yarn temp:test:brand-refs-resolution --verbose # Show detailed issue tables
 *   yarn temp:test:brand-refs-resolution --report  # Show full table of all brand reference tokens
 */
 
import fs from 'fs';
import path from 'node:path';
import { fileURLToPath } from 'url';
import chalk from 'chalk';
import Table from 'cli-table3';
import { parseValidatorArgs, colorSwatch } from './validator-utils.js';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const { isVerbose, isReport } = parseValidatorArgs();
 
console.log(chalk.bold.blue('\nšŸ” Testing brand reference token resolution\n'));
 
const themes = ['slds', 'cosmos'];
const allBrandRefs = [];
let hasErrors = false;
 
// Load source JSON to get alias references
const sourceJsonPath = path.resolve(__dirname, '../tokens/cosmos/reference-palettes.json');
let sourceTokens = {};
if (fs.existsSync(sourceJsonPath)) {
  const sourceJson = JSON.parse(fs.readFileSync(sourceJsonPath, 'utf-8'));
  sourceTokens = sourceJson.slds?.r?.color?.brand || {};
}
 
themes.forEach((theme) => {
  console.log(chalk.bold(`šŸ“ Testing ${theme.toUpperCase()} theme:`));
 
  const refPath = path.resolve(
    __dirname,
    `../../dist/themes/${theme}/${theme}.reference.hooks.custom-props.css`,
  );
 
  if (!fs.existsSync(refPath)) {
    console.log(chalk.red(`  āŒ Reference file not found`));
    hasErrors = true;
    console.log('');
    return;
  }
 
  const refCSS = fs.readFileSync(refPath, 'utf-8');
 
  // Extract all brand reference tokens
  const brandRefRegex = /^\s*(--slds-r-color-brand-\d+)\s*:\s*([^;]+);/gm;
  let match;
  let count = 0;
 
  while ((match = brandRefRegex.exec(refCSS)) !== null) {
    const property = match[1];
    const value = match[2].trim();
 
    // Extract the number from the property (e.g., "10" from "--slds-r-color-brand-10")
    const brandNumber = property.match(/brand-(\d+)/)?.[1];
    const sourceRef =
      brandNumber && sourceTokens[brandNumber]?.$value ? sourceTokens[brandNumber].$value : '';
 
    count++;
    allBrandRefs.push({ theme, property, value, sourceRef });
 
    // Check for issues
    if (!value || value === '') {
      console.log(chalk.red(`  āŒ ${property}: Empty value`));
      hasErrors = true;
    } else if (!value.includes('#')) {
      console.log(chalk.yellow(`  āš ļø  ${property}: No hex color found (${value})`));
    }
  }
 
  console.log(chalk.green(`  āœ… Found ${count} brand reference tokens`));
  console.log('');
});
 
// Summary
if (hasErrors) {
  console.log(chalk.red('āŒ Brand reference resolution has errors\n'));
} else {
  console.log(chalk.green('āœ… All brand reference tokens resolved correctly\n'));
 
  if (!isVerbose && !isReport && allBrandRefs.length > 0) {
    console.log(chalk.gray('Run with --report to see all brand reference tokens\n'));
  }
}
 
// Show all brand references in report mode
if (isReport && allBrandRefs.length > 0) {
  // Group by property for side-by-side comparison
  const byProperty = {};
 
  allBrandRefs.forEach((ref) => {
    if (!byProperty[ref.property]) {
      byProperty[ref.property] = { sourceRef: ref.sourceRef, slds: null, cosmos: null };
    }
 
    // Add color swatches for hex values (including light-dark)
    let valueWithSwatch = ref.value;
 
    // Check if it's a light-dark() function
    const lightDarkMatch = ref.value.match(/light-dark\(([^,]+),\s*([^)]+)\)/);
    if (lightDarkMatch) {
      const lightValue = lightDarkMatch[1].trim();
      const darkValue = lightDarkMatch[2].trim();
 
      const lightHex = lightValue.match(/#[0-9a-fA-F]{3,6}/);
      const darkHex = darkValue.match(/#[0-9a-fA-F]{3,6}/);
 
      if (lightHex && darkHex) {
        valueWithSwatch = `${colorSwatch(lightHex[0])} ${lightHex[0]} / ${colorSwatch(darkHex[0])} ${darkHex[0]}`;
      }
    } else if (ref.value.includes('#')) {
      // Simple hex color
      const hexColors = ref.value.match(/#[0-9a-fA-F]{3,6}/g);
      if (hexColors) {
        hexColors.forEach((hex) => {
          valueWithSwatch = valueWithSwatch.replace(hex, `${colorSwatch(hex)} ${hex}`);
        });
      }
    }
 
    byProperty[ref.property][ref.theme] = valueWithSwatch;
  });
 
  const uniqueProperties = Object.keys(byProperty).length;
  console.log(chalk.bold.blue(`šŸ“‹ Brand Reference Tokens (${uniqueProperties} unique properties):\n`));
 
  const table = new Table({
    head: ['#', 'Property', 'Source Reference', 'SLDS Value', 'Cosmos Value'],
    colWidths: [5, 35, 35, 30, 30],
    style: { head: ['cyan'] },
    wordWrap: true,
  });
 
  // Sort by property name (numerically by brand number)
  const sortedKeys = Object.keys(byProperty).sort((a, b) => {
    const numA = parseInt(a.match(/brand-(\d+)/)?.[1] || '0', 10);
    const numB = parseInt(b.match(/brand-(\d+)/)?.[1] || '0', 10);
    return numA - numB;
  });
  sortedKeys.forEach((property, index) => {
    const { sourceRef, slds, cosmos } = byProperty[property];
    table.push([
      index + 1,
      property,
      sourceRef || chalk.gray('—'),
      slds || chalk.gray('—'),
      cosmos || chalk.gray('—'),
    ]);
  });
 
  console.log(table.toString());
  console.log('');
}
 
process.exit(hasErrors ? 1 : 0);