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

0% Statements 0/231
0% Branches 0/127
0% Functions 0/22
0% Lines 0/227

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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * TEMPORARY CSS Comparison Tool (TO BE REMOVED AFTER MIGRATION)
 *
 * Compare CSS custom properties coverage: sds-styling-hooks (source of truth) vs design-tokens
 * Focus on ensuring design-tokens generates all the same CSS custom properties across shared & component scopes
 *
 * COMPARES: Scoped files vs scoped files (shared vs shared, component vs component)
 * NOT: .json files - use temp-compare-json.js for JSON comparison
 *
 * Usage:
 *   yarn temp:compare:css           # Summary only
 *   yarn temp:compare:css --verbose # Show detailed issue tables
 *   yarn temp:compare:css --report  # Show full table of all properties
 *
 * 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.
 */
 
import fs from 'fs';
import path from 'node:path';
import chalk from 'chalk';
import Table from 'cli-table3';
import { parseValidatorArgs, colorSwatch, loadKnownIssues, exitWithStatus } from './validator-utils.js';
 
const { isVerbose, isReport } = parseValidatorArgs();
const knownIssues = loadKnownIssues();
 
console.log(
  chalk.bold.blue(
    '\nšŸ”„ TEMPORARY CSS Comparison (TO BE REMOVED): sds-styling-hooks (source of truth) vs design-tokens',
  ),
);
console.log(chalk.gray('(SHARED & COMPONENT SCOPES ONLY)\n'));
 
const themes = ['slds', 'cosmos'];
 
// Compare scoped tokens: design-tokens scoped files vs sds-styling-hooks scoped files
const scopeFiles = [
  { name: 'shared', prefix: 'slds-s-', file: 'shared.hooks.custom-props.css' },
  { name: 'component', prefix: 'slds-c-', file: 'component.hooks.custom-props.css' },
];
 
let grandTotalMatching = 0;
let grandTotalNewMissing = 0;
let grandTotalNewExtra = 0;
let grandTotalNewMismatches = 0;
let grandTotalKnownMissing = 0;
let grandTotalKnownExtra = 0;
let grandTotalKnownMismatches = 0;
const allNewIssues = [];
const allKnownIssues = [];
 
const extractProperties = (css) => {
  const properties = new Map();
  const regex = /--([a-zA-Z][\w-]*)\s*:\s*([^;]+);/g;
  let match;
 
  while ((match = regex.exec(css)) !== null) {
    const name = match[1];
    const value = match[2].trim();
    properties.set(name, value);
  }
 
  return properties;
};
 
themes.forEach((theme) => {
  console.log(chalk.bold(`\nTheme: ${theme.toUpperCase()}`));
  console.log('='.repeat(50));
 
  scopeFiles.forEach(({ name, prefix, file }) => {
    const designTokensPath = path.resolve(process.cwd(), `dist/themes/${theme}/${theme}.${file}`);
    const legacyPath = path.resolve(
      process.cwd(),
      `../sds-styling-hooks/dist/themes/${theme}/${theme}.${file}`,
    );
 
    if (!fs.existsSync(designTokensPath)) {
      console.log(chalk.yellow(`  āš ļø  Design-tokens file not found: ${designTokensPath}`));
      return;
    }
 
    if (!fs.existsSync(legacyPath)) {
      console.log(chalk.yellow(`  āš ļø  Legacy file not found: ${legacyPath}`));
      return;
    }
 
    console.log(chalk.bold(`\n${name.toUpperCase()} SCOPE:`));
 
    const designTokensCss = fs.readFileSync(designTokensPath, 'utf-8');
    const legacyCss = fs.readFileSync(legacyPath, 'utf-8');
 
    const designTokensPropsAll = extractProperties(designTokensCss);
    const allLegacyPropsAll = extractProperties(legacyCss);
 
    // Filter design-tokens CSS to only include the scoped properties
    const designTokensProps = new Map();
    for (const [prop, value] of designTokensPropsAll) {
      if (prop.startsWith(prefix)) {
        designTokensProps.set(prop, value);
      }
    }
 
    // Filter out deprecated sds namespace properties
    const legacyProps = new Map();
    for (const [prop, value] of allLegacyPropsAll) {
      if (!prop.startsWith('sds-')) {
        legacyProps.set(prop, value);
      }
    }
 
    console.log(`  sds-styling-hooks: ${legacyProps.size} properties`);
    console.log(`  design-tokens: ${designTokensProps.size} properties`);
 
    // Calculate coverage
    const matching = [];
    const missing = [];
    const valueMismatches = [];
 
    for (const [prop, legacyValue] of legacyProps) {
      if (designTokensProps.has(prop)) {
        const designValue = designTokensProps.get(prop);
        if (designValue === legacyValue) {
          matching.push({ property: `--${prop}`, value: legacyValue });
        } else {
          valueMismatches.push({
            property: `--${prop}`,
            legacy: legacyValue,
            design: designValue,
          });
        }
      } else {
        missing.push({ property: `--${prop}`, value: legacyValue });
      }
    }
 
    const extra = [];
    for (const [prop, designValue] of designTokensProps) {
      if (!legacyProps.has(prop)) {
        extra.push({ property: `--${prop}`, value: designValue });
      }
    }
 
    // Separate issues into new vs known for this theme/scope
    const scopeKey = `${name}`; // shared or component
    const themeKnownIssuesConfig = knownIssues.css?.[theme]?.[scopeKey] || {};
 
    const newMissing = missing.filter((issue) => !themeKnownIssuesConfig.missing?.includes(issue.property));
    const newExtra = extra.filter((issue) => !themeKnownIssuesConfig.extra?.includes(issue.property));
    const newMismatches = valueMismatches.filter(
      (v) => !themeKnownIssuesConfig.value_mismatches?.includes(v.property),
    );
 
    const knownMissing = missing.length - newMissing.length;
    const knownExtra = extra.length - newExtra.length;
    const knownMismatches = valueMismatches.length - newMismatches.length;
 
    // Track totals
    grandTotalMatching += matching.length;
    grandTotalNewMissing += newMissing.length;
    grandTotalNewExtra += newExtra.length;
    grandTotalNewMismatches += newMismatches.length;
    grandTotalKnownMissing += knownMissing;
    grandTotalKnownExtra += knownExtra;
    grandTotalKnownMismatches += knownMismatches;
 
    // Collect issues for verbose mode
    if (isVerbose) {
      newMissing.forEach((issue) =>
        allNewIssues.push({ theme, scope: name, type: 'missing', icon: 'āŒ', ...issue }),
      );
      newExtra.forEach((issue) =>
        allNewIssues.push({ theme, scope: name, type: 'extra', icon: 'āž•', ...issue }),
      );
      newMismatches.forEach((issue) =>
        allNewIssues.push({ theme, scope: name, type: 'mismatch', icon: 'āŒ', ...issue }),
      );
 
      // Known issues
      missing
        .filter((issue) => themeKnownIssuesConfig.missing?.includes(issue.property))
        .forEach((issue) =>
          allKnownIssues.push({ theme, scope: name, type: 'missing', icon: 'āš ļø', ...issue }),
        );
      extra
        .filter((issue) => themeKnownIssuesConfig.extra?.includes(issue.property))
        .forEach((issue) => allKnownIssues.push({ theme, scope: name, type: 'extra', icon: 'āš ļø', ...issue }));
      valueMismatches
        .filter((v) => themeKnownIssuesConfig.value_mismatches?.includes(v.property))
        .forEach((issue) =>
          allKnownIssues.push({ theme, scope: name, type: 'mismatch', icon: 'āš ļø', ...issue }),
        );
    }
 
    // Print summary for this scope
    console.log(
      `  ${chalk.green('āœ… Covered:')} ${matching.length} (${((matching.length / legacyProps.size) * 100).toFixed(1)}%)`,
    );
 
    const totalNewIssues = newMissing.length + newExtra.length + newMismatches.length;
    if (totalNewIssues > 0) {
      console.log(`  ${chalk.red('āŒ')} New issues: ${totalNewIssues}`);
      if (newMismatches.length > 0) {
        console.log(`     ${chalk.red('āŒ')} Mismatches: ${newMismatches.length}`);
      }
      if (newMissing.length > 0) {
        console.log(`     ${chalk.red('āŒ')} Missing: ${newMissing.length}`);
      }
      if (newExtra.length > 0) {
        console.log(`     ${chalk.red('āž•')} Extra: ${newExtra.length}`);
      }
    }
 
    const totalKnownIssues = knownMissing + knownExtra + knownMismatches;
    if (totalKnownIssues > 0) {
      console.log(`  ${chalk.yellow('āš ļø')}  Known issues: ${totalKnownIssues}`);
      if (knownMismatches > 0) {
        console.log(`     ${chalk.yellow('āš ļø')}  Mismatches: ${knownMismatches}`);
      }
      if (knownMissing > 0) {
        console.log(`     ${chalk.yellow('āš ļø')}  Missing: ${knownMissing}`);
      }
      if (knownExtra > 0) {
        console.log(`     ${chalk.yellow('āš ļø')}  Extra: ${knownExtra}`);
      }
    }
  });
});
 
// Report mode: show full table of all properties
if (isReport) {
  console.log(chalk.bold.blue('\nšŸ“‹ All Shared & Component Properties:'));
  console.log('='.repeat(50));
 
  themes.forEach((theme) => {
    scopeFiles.forEach(({ name, prefix, file }) => {
      const designTokensPath = path.resolve(process.cwd(), `dist/themes/${theme}/${theme}.${file}`);
      const legacyPath = path.resolve(
        process.cwd(),
        `../sds-styling-hooks/dist/themes/${theme}/${theme}.${file}`,
      );
 
      if (!fs.existsSync(designTokensPath) || !fs.existsSync(legacyPath)) {
        return;
      }
 
      const designTokensCss = fs.readFileSync(designTokensPath, 'utf-8');
      const legacyCss = fs.readFileSync(legacyPath, 'utf-8');
 
      const designTokensPropsAll = extractProperties(designTokensCss);
      const allLegacyPropsAll = extractProperties(legacyCss);
 
      // Filter properties
      const designTokensProps = new Map();
      for (const [prop, value] of designTokensPropsAll) {
        if (prop.startsWith(prefix)) {
          designTokensProps.set(prop, value);
        }
      }
 
      const legacyProps = new Map();
      for (const [prop, value] of allLegacyPropsAll) {
        if (!prop.startsWith('sds-')) {
          legacyProps.set(prop, value);
        }
      }
 
      // Collect all properties
      const allProps = new Map();
      for (const [prop, value] of legacyProps) {
        allProps.set(prop, { legacy: value, design: designTokensProps.get(prop) });
      }
      for (const [prop, value] of designTokensProps) {
        if (!allProps.has(prop)) {
          allProps.set(prop, { legacy: null, design: value });
        }
      }
 
      if (allProps.size === 0) return;
 
      console.log(
        chalk.bold(`\n${theme.toUpperCase()} - ${name.toUpperCase()} (${allProps.size} properties):\n`),
      );
 
      const table = new Table({
        head: ['#', 'Property', 'sds-styling-hooks', 'design-tokens', 'Status'],
        colWidths: [5, 40, 35, 35, 12],
        style: { head: ['cyan'] },
        wordWrap: true,
      });
 
      const sortedProps = Array.from(allProps.keys()).sort();
      sortedProps.forEach((prop, index) => {
        const { legacy, design } = allProps.get(prop);
 
        let legacyValue = legacy || chalk.gray('—');
        let designValue = design || chalk.gray('—');
        let status = '';
 
        // Add color swatches
        if (typeof legacyValue === 'string' && legacyValue.match(/^#[0-9a-fA-F]{3,8}$/)) {
          legacyValue = `${colorSwatch(legacyValue)} ${legacyValue}`;
        }
        if (typeof designValue === 'string' && designValue.match(/^#[0-9a-fA-F]{3,8}$/)) {
          designValue = `${colorSwatch(designValue)} ${designValue}`;
        }
 
        // Determine status
        if (!legacy) {
          status = chalk.green('āž• Extra');
        } else if (!design) {
          status = chalk.red('āŒ Missing');
        } else if (legacy !== design) {
          status = chalk.red('āŒ Mismatch');
        } else {
          status = chalk.green('āœ“');
        }
 
        table.push([index + 1, `--${prop}`, legacyValue, designValue, status]);
      });
 
      console.log(table.toString());
    });
  });
  console.log('');
}
 
// Print verbose tables grouped by theme and scope
if (isVerbose && (allNewIssues.length > 0 || allKnownIssues.length > 0)) {
  console.log(chalk.bold('\nšŸ“‹ Detailed Issues:'));
  console.log('='.repeat(50));
 
  // Helper function to print issues table
  const printIssuesTable = (issues, title, headerColor) => {
    if (issues.length === 0) return;
 
    // Group issues by theme and scope
    const groupedIssues = {};
    issues.forEach((issue) => {
      const key = `${issue.theme}|${issue.scope}`;
      if (!groupedIssues[key]) {
        groupedIssues[key] = [];
      }
      groupedIssues[key].push(issue);
    });
 
    console.log(chalk.bold(`\n${title}`));
 
    // Print a table for each theme/scope combination
    Object.keys(groupedIssues).forEach((key) => {
      const [theme, scope] = key.split('|');
      const scopeIssues = groupedIssues[key];
 
      console.log(chalk.bold(`\n${theme.toUpperCase()} - ${scope.toUpperCase()}:`));
 
      const table = new Table({
        head: ['#', 'Property', 'sds-styling-hooks', 'design-tokens', 'Type'],
        colWidths: [5, 35, 45, 45, 15],
        style: { head: [headerColor] },
        wordWrap: true,
      });
 
      scopeIssues.forEach((issue, index) => {
        let legacyValue = issue.legacy || issue.value || '-';
        let designValue = issue.design || issue.value || '-';
 
        // Add color swatches for hex colors
        if (typeof legacyValue === 'string' && legacyValue.match(/^#[0-9a-fA-F]{3,8}$/)) {
          legacyValue = `${colorSwatch(legacyValue)} ${legacyValue}`;
        }
        if (typeof designValue === 'string' && designValue.match(/^#[0-9a-fA-F]{3,8}$/)) {
          designValue = `${colorSwatch(designValue)} ${designValue}`;
        }
 
        // Determine type display
        let typeDisplay = '';
        if (issue.type === 'missing') {
          typeDisplay = issue.icon === 'āŒ' ? `${chalk.red('āŒ Missing')}` : `${chalk.yellow('āš ļø  Missing')}`;
        } else if (issue.type === 'extra') {
          typeDisplay = issue.icon === 'āž•' ? `${chalk.green('āž• Extra')}` : `${chalk.yellow('āš ļø  Extra')}`;
        } else if (issue.type === 'mismatch') {
          typeDisplay =
            issue.icon === 'āŒ' ? `${chalk.red('āŒ Mismatch')}` : `${chalk.yellow('āš ļø  Mismatch')}`;
        }
 
        table.push([index + 1, issue.property, legacyValue, designValue, typeDisplay]);
      });
 
      console.log(table.toString());
    });
  };
 
  // Print new issues first
  if (allNewIssues.length > 0) {
    printIssuesTable(allNewIssues, 'šŸ”“ NEW ISSUES', 'red');
  }
 
  // Then print known issues
  if (allKnownIssues.length > 0) {
    printIssuesTable(allKnownIssues, 'āš ļø  KNOWN ISSUES', 'yellow');
  }
}
 
// Print final summary
console.log(chalk.bold.blue('\nšŸ“Š Summary:'));
const totalNewIssues = grandTotalNewMissing + grandTotalNewExtra + grandTotalNewMismatches;
const totalKnownIssues = grandTotalKnownMissing + grandTotalKnownExtra + grandTotalKnownMismatches;
const totalTests = grandTotalMatching + totalNewIssues + totalKnownIssues;
 
console.log(`${grandTotalMatching}/${totalTests} tests passed`);
console.log(`${chalk.green('āœ…')} Matching: ${grandTotalMatching}`);
 
if (totalNewIssues > 0) {
  console.log(`${chalk.red('āŒ')} New failures: ${totalNewIssues}`);
  if (grandTotalNewMismatches > 0) {
    console.log(`   ${chalk.red('āŒ')} Mismatches: ${grandTotalNewMismatches}`);
  }
  if (grandTotalNewMissing > 0) {
    console.log(`   ${chalk.red('āŒ')} Missing: ${grandTotalNewMissing}`);
  }
  if (grandTotalNewExtra > 0) {
    console.log(`   ${chalk.green('āž•')} Extra: ${grandTotalNewExtra}`);
  }
}
 
if (totalKnownIssues > 0) {
  console.log(`${chalk.yellow('āš ļø')}  Known issues: ${totalKnownIssues}`);
  if (grandTotalKnownMismatches > 0) {
    console.log(`   ${chalk.yellow('āš ļø')}  Mismatches: ${grandTotalKnownMismatches}`);
  }
  if (grandTotalKnownMissing > 0) {
    console.log(`   ${chalk.yellow('āš ļø')}  Missing: ${grandTotalKnownMissing}`);
  }
  if (grandTotalKnownExtra > 0) {
    console.log(`   ${chalk.yellow('āš ļø')}  Extra: ${grandTotalKnownExtra}`);
  }
}
 
if (!isVerbose && !isReport && (totalNewIssues > 0 || totalKnownIssues > 0)) {
  console.log(chalk.gray('\nRun with --verbose to see detailed issues or --report to see all properties'));
}
 
exitWithStatus(totalNewIssues, totalKnownIssues);