All files / packages/design-tokens/src/validators temp-compare-aliases.js

0% Statements 0/119
0% Branches 0/69
0% Functions 0/7
0% Lines 0/113

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
#!/usr/bin/env node
 
/**
 * TEMPORARY Alias Comparison Tool (TO BE REMOVED AFTER MIGRATION)
 *
 * Compare aliases between @sds-styling-aliases and @design-tokens
 *
 * This script validates that all OKLCH values in design tokens
 * produce the exact hex values expected by the styling aliases.
 *
 * 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:compare:aliases           # Summary only
 *   yarn temp:compare:aliases --verbose # Show detailed list of issues
 *   yarn temp:compare:aliases --report  # Show full table of all aliases
 */
 
import Color from 'colorjs.io';
import fs from 'fs';
import path from 'node:path';
import chalk from 'chalk';
import Table from 'cli-table3';
import {
  parseValidatorArgs,
  loadKnownIssues,
  filterKnownIssues,
  exitWithStatus,
  colorSwatch,
} from './validator-utils.js';
 
const { isVerbose, isReport } = parseValidatorArgs();
const knownIssues = loadKnownIssues();
 
console.log(chalk.bold.blue('\nπŸ” Validating color aliases\n'));
console.log(chalk.gray('Comparing sds-styling-aliases (hex) vs design-tokens (OKLCH→hex conversion)'));
console.log(chalk.gray('Source of truth: @sds-styling-aliases\n'));
 
// Read the styling aliases (source of truth) from sds-styling-aliases package
let aliases;
try {
  const aliasesPath = path.join(process.cwd(), '../../packages/sds-styling-aliases/src/color-palettes.json');
  const aliasesData = JSON.parse(fs.readFileSync(aliasesPath, 'utf8'));
  aliases = aliasesData.aliases;
  if (!aliases) throw new Error('No aliases found in file');
} catch (error) {
  console.error(chalk.red(`❌ Failed to read sds-styling-aliases: ${error.message}`));
  process.exit(1);
}
 
// Read the design tokens (both themes use same alias palettes)
let designTokensData;
try {
  const designTokensPath = path.join(process.cwd(), './src/tokens/common/alias-palettes.json');
  designTokensData = JSON.parse(fs.readFileSync(designTokensPath, 'utf8'));
  if (!designTokensData?.alias?.palette) throw new Error('Invalid design tokens structure');
} catch (error) {
  console.error(chalk.red(`❌ Failed to read design tokens: ${error.message}`));
  process.exit(1);
}
 
// Function to convert OKLCH to hex
function oklchToHex(oklchValue) {
  try {
    if (typeof oklchValue === 'object' && oklchValue.colorSpace === 'oklch') {
      const [L, C, H] = oklchValue.components;
      const color = new Color('oklch', [L, C, H]);
      return color.to('srgb').toString({ format: 'hex' });
    }
    return null;
  } catch (error) {
    return null;
  }
}
 
// Function to normalize hex values for comparison
function normalizeHex(hex) {
  return hex.toLowerCase();
}
 
// Map alias names to design token palette names
const paletteMapping = {
  CLOUD_BLUE: 'cloudBlue',
  ELECTRIC_BLUE: 'electricBlue',
  HOT_ORANGE: 'hotOrange',
};
 
// Collect all alias data
const allAliases = [];
let totalTests = 0;
let passedTests = 0;
const failedTests = [];
 
for (const [aliasName, expectedHex] of Object.entries(aliases)) {
  if (!aliasName.startsWith('PALETTE_')) continue;
 
  const match = aliasName.match(/PALETTE_(\w+)_(\d+)/);
  if (!match) continue;
 
  const [, paletteName, number] = match;
  const paletteKey = paletteMapping[paletteName] || paletteName.toLowerCase();
 
  totalTests++;
 
  // Get the OKLCH value from design tokens
  const oklchValue = designTokensData.alias?.palette?.[paletteKey]?.[number]?.$value;
 
  if (!oklchValue) {
    failedTests.push({
      alias: aliasName,
      issue: 'Missing in design tokens',
      palette: paletteKey,
      number,
    });
    allAliases.push({
      alias: aliasName,
      aliasesExpected: expectedHex,
      tokensActual: null,
      hasMismatch: true,
    });
    continue;
  }
 
  const actualHex = oklchToHex(oklchValue);
 
  if (!actualHex) {
    failedTests.push({
      alias: aliasName,
      issue: 'OKLCH conversion failed',
      oklch: oklchValue,
    });
    allAliases.push({
      alias: aliasName,
      aliasesExpected: expectedHex,
      tokensActual: null,
      hasMismatch: true,
    });
    continue;
  }
 
  const normalizedExpected = normalizeHex(expectedHex);
  const normalizedActual = normalizeHex(actualHex);
  const hasMismatch = normalizedExpected !== normalizedActual;
 
  if (!hasMismatch) {
    passedTests++;
  } else {
    failedTests.push({
      alias: aliasName,
      expected: expectedHex,
      actual: actualHex,
      oklch: oklchValue,
    });
  }
 
  allAliases.push({
    alias: aliasName,
    aliasesExpected: expectedHex,
    tokensActual: actualHex,
    hasMismatch,
  });
}
 
// Filter known issues
const { newIssues: newFailures, knownIssues: knownFailures } = filterKnownIssues(
  failedTests,
  knownIssues.aliases.value_mismatches || [],
  'alias',
);
 
// Minimal output
console.log(chalk.bold(`πŸ“Š Summary: ${passedTests}/${totalTests} tests passed\n`));
console.log(`βœ… Passing: ${passedTests}`);
 
if (newFailures.length > 0) {
  console.log(chalk.red(`❌ New failures: ${newFailures.length}`));
} else {
  console.log(`❌ New failures: 0`);
}
 
if (knownFailures.length > 0) {
  console.log(chalk.yellow(`⚠️  Known issues: ${knownFailures.length}`));
}
 
if (!isVerbose && !isReport && (newFailures.length > 0 || knownFailures.length > 0)) {
  console.log(chalk.gray('\nRun with --verbose to see detailed issues or --report to see all aliases'));
}
 
console.log('');
 
// Verbose mode: show detailed lists
if (isVerbose && (newFailures.length > 0 || knownFailures.length > 0)) {
  console.log(chalk.bold.blue('\nπŸ“‹ Detailed Issues:\n'));
 
  if (newFailures.length > 0) {
    console.log(chalk.red(`NEW FAILURES (${newFailures.length}):\n`));
 
    const table = new Table({
      head: ['#', 'Alias', 'Expected', 'Actual', 'Issue'],
      colWidths: [5, 40, 20, 20, 30],
      style: { head: ['red'] },
      wordWrap: true,
    });
 
    newFailures.forEach((test, index) => {
      const expected = test.expected ? `${colorSwatch(test.expected)} ${test.expected}` : '-';
      const actual = test.actual ? `${colorSwatch(test.actual)} ${test.actual}` : '-';
      const issue = test.issue || 'Value mismatch';
 
      table.push([index + 1, test.alias, expected, actual, issue]);
    });
 
    console.log(table.toString());
    console.log('');
  }
 
  if (knownFailures.length > 0) {
    console.log(chalk.yellow(`KNOWN ISSUES (${knownFailures.length}):\n`));
 
    const table = new Table({
      head: ['#', 'Alias', 'Expected', 'Actual', 'Issue'],
      colWidths: [5, 40, 20, 20, 30],
      style: { head: ['yellow'] },
      wordWrap: true,
    });
 
    knownFailures.forEach((test, index) => {
      const expected = test.expected ? `${colorSwatch(test.expected)} ${test.expected}` : '-';
      const actual = test.actual ? `${colorSwatch(test.actual)} ${test.actual}` : '-';
      const issue = test.issue || 'Value mismatch';
 
      table.push([index + 1, test.alias, expected, actual, issue]);
    });
 
    console.log(table.toString());
    console.log('');
  }
}
 
// Report mode: show full table
if (isReport) {
  console.log(chalk.bold.blue(`πŸ“‹ All Color Aliases (${allAliases.length}):\n`));
 
  const table = new Table({
    head: ['#', 'Alias', 'sds-styling-aliases', 'design-tokens (OKLCH)'],
    colWidths: [5, 40, 25, 25],
    style: { head: ['cyan'] },
    wordWrap: true,
  });
 
  // Sort aliases by name
  allAliases.sort((a, b) => {
    // Extract palette name and number for proper sorting
    const matchA = a.alias.match(/PALETTE_(\w+)_(\d+)/);
    const matchB = b.alias.match(/PALETTE_(\w+)_(\d+)/);
 
    if (!matchA || !matchB) return a.alias.localeCompare(b.alias);
 
    const [, paletteA, numA] = matchA;
    const [, paletteB, numB] = matchB;
 
    // Sort by palette name first, then by number
    if (paletteA !== paletteB) {
      return paletteA.localeCompare(paletteB);
    }
    return parseInt(numA, 10) - parseInt(numB, 10);
  });
 
  allAliases.forEach((item, index) => {
    let aliasDisplay = item.alias;
 
    if (item.hasMismatch) {
      // Check if it's a known issue
      const isKnown = knownFailures.some((f) => f.alias === item.alias);
      if (isKnown) {
        aliasDisplay = `${chalk.yellow('⚠️')}  ${item.alias}`;
      } else {
        aliasDisplay = `${chalk.red('❌')} ${item.alias}`;
      }
    }
 
    const aliasesValue = item.aliasesExpected
      ? `${colorSwatch(item.aliasesExpected)} ${item.aliasesExpected}`
      : chalk.gray('β€”');
    const tokensValue = item.tokensActual
      ? `${colorSwatch(item.tokensActual)} ${item.tokensActual}`
      : chalk.gray('β€”');
 
    table.push([index + 1, aliasDisplay, aliasesValue, tokensValue]);
  });
 
  console.log(table.toString());
  console.log('');
}
 
exitWithStatus(newFailures.length, knownFailures.length);