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

0% Statements 0/85
0% Branches 0/43
0% Functions 0/9
0% Lines 0/81

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                                                                                                                                                                                                                                                                                                                                                                                                                               
#!/usr/bin/env node
 
/**
 * TEMPORARY Alias Resolution Test Tool (TO BE REMOVED AFTER MIGRATION)
 *
 * Test script to verify alias resolution in CSS output
 *
 * This script checks that:
 * 1. No --alias-* references remain in the CSS files
 * 2. All alias references are properly resolved to theme-specific tokens
 * 3. Both SLDS and Cosmos themes are working correctly
 *
 * 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:alias-resolution           # Summary only
 *   yarn temp:test:alias-resolution --verbose # Show detailed issue tables
 *   yarn temp:test:alias-resolution --report  # Show full table of all resolved palette references
 */
 
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();
 
const themes = ['slds', 'cosmos'];
const cssFiles = [
  'hooks.custom-props.css',
  'reference.hooks.custom-props.css',
  'shared.hooks.custom-props.css',
  'component.hooks.custom-props.css',
];
 
const allIssues = [];
const resolvedPaletteRefs = [];
 
console.log(chalk.bold.blue('\nšŸ” Testing alias resolution in CSS output\n'));
 
themes.forEach((theme) => {
  console.log(chalk.bold(`šŸ“ Testing ${theme.toUpperCase()} theme:`));
 
  cssFiles.forEach((cssFile) => {
    const filePath = path.join(__dirname, '..', '..', 'dist', 'themes', theme, `${theme}.${cssFile}`);
    const displayName = `${theme}.${cssFile}`;
 
    if (!fs.existsSync(filePath)) {
      if (isVerbose) {
        console.log(chalk.gray(`  āš ļø  ${displayName}: File not found`));
      }
      return;
    }
 
    const content = fs.readFileSync(filePath, 'utf8');
 
    // Check for unresolved alias references
    const aliasMatches = content.match(/--alias-[^:]+/g);
    const hasUnresolved = aliasMatches && aliasMatches.length > 0;
 
    if (hasUnresolved) {
      // Remove duplicates
      const uniqueAliases = [...new Set(aliasMatches)];
      uniqueAliases.forEach((alias) => {
        allIssues.push({
          theme,
          file: cssFile,
          alias,
        });
      });
    }
 
    // Check for properly resolved theme-specific references
    // Note: Both themes use --slds-g-color-palette-* properties
    // Match only properties that START with --slds-g-color-palette-
    const paletteRegex = new RegExp(`^\\s*(--slds-g-color-palette-[^:]+):\\s*([^;]+);`, 'gm');
    let match;
    const fileRefsStart = resolvedPaletteRefs.length;
    while ((match = paletteRegex.exec(content)) !== null) {
      const [, property, value] = match;
      resolvedPaletteRefs.push({
        theme,
        file: cssFile,
        property,
        value: value.trim(),
      });
    }
    const fileRefsCount = resolvedPaletteRefs.length - fileRefsStart;
 
    // Display combined status
    if (hasUnresolved) {
      const uniqueAliases = [...new Set(aliasMatches)];
      console.log(
        chalk.red(`  āŒ ${displayName}: Found ${uniqueAliases.length} unresolved alias references`),
      );
    } else {
      const resolvedMsg =
        fileRefsCount > 0 ? chalk.gray(` (Found ${fileRefsCount} resolved palette references)`) : '';
      console.log(chalk.green(`  āœ… ${displayName}: No unresolved alias references`) + resolvedMsg);
    }
  });
 
  console.log('');
});
 
// Display results
if (allIssues.length > 0) {
  if (isVerbose) {
    console.log(chalk.bold.red(`\nšŸ“‹ Unresolved Alias References (${allIssues.length}):\n`));
 
    const table = new Table({
      head: ['Theme', 'File', 'Alias Reference'],
      colWidths: [10, 35, 50],
      style: { head: ['red'] },
      wordWrap: true,
    });
 
    allIssues.forEach((issue) => {
      table.push([issue.theme, issue.file, chalk.red(issue.alias)]);
    });
 
    console.log(table.toString());
  } else {
    // Minimal output
    console.log(chalk.bold.red(`\nāŒ Found ${allIssues.length} unresolved alias references:\n`));
    allIssues.forEach((issue) => {
      console.log(chalk.red(`  - ${issue.theme}/${issue.file}: ${issue.alias}`));
    });
  }
 
  console.log(chalk.red('\nāŒ Test failed: Some alias references were not properly resolved\n'));
  process.exit(1);
} else {
  console.log(chalk.green('\nāœ… All tests passed: No unresolved alias references found'));
  console.log(chalk.green('šŸŽ‰ Alias resolution is working correctly for all themes!\n'));
 
  if (!isVerbose && !isReport && resolvedPaletteRefs.length > 0) {
    console.log(chalk.gray('Run with --report to see all resolved palette references\n'));
  }
 
  // Show resolved palette references in report mode
  if (isReport && resolvedPaletteRefs.length > 0) {
    // Group by property and scope for side-by-side comparison
    const byProperty = {};
 
    resolvedPaletteRefs.forEach((ref) => {
      // Extract scope from filename
      let scope = 'global';
      if (ref.file.includes('reference')) scope = 'reference';
      else if (ref.file.includes('shared')) scope = 'shared';
      else if (ref.file.includes('component')) scope = 'component';
 
      const key = `${scope}:${ref.property}`;
      if (!byProperty[key]) {
        byProperty[key] = { scope, property: ref.property, slds: null, cosmos: null };
      }
 
      // Add color swatches for hex values
      let valueWithSwatch = ref.value;
      if (ref.value.includes('#')) {
        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[key][ref.theme] = valueWithSwatch;
    });
 
    // Count unique properties
    const uniqueProperties = Object.keys(byProperty).length;
    console.log(chalk.bold.blue(`šŸ“‹ Resolved Palette References (${uniqueProperties} unique properties):\n`));
 
    const table = new Table({
      head: ['#', 'Scope', 'Property', 'SLDS Value', 'Cosmos Value'],
      colWidths: [5, 12, 40, 30, 40],
      style: { head: ['cyan'] },
      wordWrap: true,
    });
 
    // Sort by scope then property
    const sortedKeys = Object.keys(byProperty).sort();
    sortedKeys.forEach((key, index) => {
      const { scope, property, slds, cosmos } = byProperty[key];
 
      // Check if this property has any unresolved aliases
      const hasUnresolved = allIssues.some((issue) => issue.alias === property);
      const propertyDisplay = hasUnresolved ? chalk.red(`āŒ ${property}`) : property;
 
      table.push([index + 1, scope, propertyDisplay, slds || chalk.gray('—'), cosmos || chalk.gray('—')]);
    });
 
    console.log(table.toString());
    console.log('');
  }
 
  process.exit(0);
}