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 | #!/usr/bin/env node
/**
* TEMPORARY Light-Dark Function Validation Tool (TO BE REMOVED AFTER MIGRATION)
*
* Validate light-dark() function usage in Cosmos theme
*
* 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:light-dark # Summary only
* yarn temp:compare:light-dark --verbose # Show detailed issue tables
* yarn temp:compare:light-dark --report # Show full table of all light-dark() properties
*/
import fs from 'fs';
import path from 'node:path';
import chalk from 'chalk';
import Table from 'cli-table3';
import { parseValidatorArgs, colorSwatch } from './validator-utils.js';
import { MODE_EXTENSION_KEY } from '../style-dictionary/utils/constants.js';
const { isVerbose, isReport } = parseValidatorArgs();
console.log(chalk.bold.blue('\nš Validating light-dark() function usage\n'));
console.log(chalk.gray('Checking Cosmos theme for proper light-dark() syntax\n'));
const theme = 'cosmos';
const cssPath = path.resolve(process.cwd(), `dist/themes/${theme}/${theme}.hooks.custom-props.css`);
if (!fs.existsSync(cssPath)) {
console.error(chalk.red(`ā CSS file not found: ${cssPath}`));
process.exit(1);
}
const css = fs.readFileSync(cssPath, 'utf-8');
// Also read the reference CSS file for resolving brand references
const referenceCssPath = path.resolve(
process.cwd(),
`dist/themes/${theme}/${theme}.reference.hooks.custom-props.css`,
);
const referenceCss = fs.existsSync(referenceCssPath) ? fs.readFileSync(referenceCssPath, 'utf-8') : '';
// Read source JSON files to get original token references
const rawPalettesPath = path.resolve(process.cwd(), 'src/tokens/cosmos/raw-palettes.json');
const semanticColorsPath = path.resolve(process.cwd(), 'src/tokens/cosmos/semantic-colors.json');
const systemColorsPath = path.resolve(process.cwd(), 'src/tokens/cosmos/system-colors.json');
const rawPalettes = JSON.parse(fs.readFileSync(rawPalettesPath, 'utf-8'));
const semanticColors = JSON.parse(fs.readFileSync(semanticColorsPath, 'utf-8'));
const systemColors = JSON.parse(fs.readFileSync(systemColorsPath, 'utf-8'));
// Deep merge function
function deepMerge(target, source) {
for (const key in source) {
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
target[key] = target[key] || {};
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
// Merge all source JSONs for lookup
const sourceJson = JSON.parse(JSON.stringify(rawPalettes)); // Deep clone
deepMerge(sourceJson, semanticColors);
deepMerge(sourceJson, systemColors);
// Function to convert kebab-case to camelCase
function kebabToCamel(str) {
return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
}
// Function to get source token reference from JSON
function getSourceReference(property) {
// Parse property name like --slds-g-color-palette-neutral-0 or --slds-g-color-palette-cloud-blue-10
const parts = property.replace('--', '').split('-');
if (parts.length < 5) return null;
// Navigate the JSON structure: slds.g.color.palette.neutral.0
// Handle multi-word palette names like cloud-blue -> cloudBlue
let current = sourceJson;
let i = 0;
while (i < parts.length && current && typeof current === 'object') {
const part = parts[i];
// Check if this part exists as-is
if (part in current) {
current = current[part];
i++;
} else if (i < parts.length - 1 && !/^\d+$/.test(parts[i + 1])) {
// Try combining with next part as camelCase (e.g., cloud + blue -> cloudBlue)
// But only if the next part is NOT a number
const combined = kebabToCamel(`${part}-${parts[i + 1]}`);
if (combined in current) {
current = current[combined];
i += 2;
} else {
return null;
}
} else {
return null;
}
}
if (current && typeof current === 'object') {
const lightRef = current.$value || null;
const darkRef = current.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value || null;
return { light: lightRef, dark: darkRef };
}
return null;
}
// Build a map of all CSS custom properties for resolving var() references
const allProperties = new Map();
const propRegex = /--([\w-]+)\s*:\s*([^;]+);/g;
let propMatch;
// Read properties from main CSS file
while ((propMatch = propRegex.exec(css)) !== null) {
allProperties.set(propMatch[1], propMatch[2].trim());
}
// Read properties from reference CSS file
const refPropRegex = /--([\w-]+)\s*:\s*([^;]+);/g;
let refPropMatch;
while ((refPropMatch = refPropRegex.exec(referenceCss)) !== null) {
allProperties.set(refPropMatch[1], refPropMatch[2].trim());
}
// Function to resolve var() references recursively
function resolveVar(value, properties, mode = 'light', depth = 0) {
// Prevent infinite recursion
if (depth > 10) return value;
const varRegex = /var\((--[\w-]+)\)/g;
let resolved = value;
let match;
while ((match = varRegex.exec(value)) !== null) {
const varName = match[1].replace('--', '');
const varValue = properties.get(varName);
if (varValue) {
// Check if the resolved value is a light-dark() function
if (varValue.includes('light-dark(')) {
// Extract the appropriate value based on mode
const lightDarkMatch = varValue.match(/light-dark\(([^,]+),\s*([^)]+)\)/);
if (lightDarkMatch) {
const lightVal = lightDarkMatch[1].trim();
const darkVal = lightDarkMatch[2].trim();
const modeValue = mode === 'light' ? lightVal : darkVal;
// Recursively resolve if it contains more var() references
const finalValue = resolveVar(modeValue, properties, mode, depth + 1);
resolved = resolved.replace(match[0], finalValue);
}
} else {
// Simple value, recursively resolve if it contains more var() references
const finalValue = resolveVar(varValue, properties, mode, depth + 1);
resolved = resolved.replace(match[0], finalValue);
}
}
}
return resolved;
}
const allLightDarkProps = [];
// More robust regex to handle nested parentheses in light-dark()
const regex = /--([\w-]+)\s*:\s*light-dark\(/g;
let match;
while ((match = regex.exec(css)) !== null) {
const property = `--${match[1]}`;
const startPos = match.index + match[0].length;
// Find the matching closing parenthesis
let depth = 1;
let endPos = startPos;
while (depth > 0 && endPos < css.length) {
if (css[endPos] === '(') depth++;
if (css[endPos] === ')') depth--;
endPos++;
}
const innerContent = css.substring(startPos, endPos - 1);
const value = `light-dark(${innerContent})`;
// Split by comma, but respect nested parentheses
let commaPos = -1;
depth = 0;
for (let i = 0; i < innerContent.length; i++) {
if (innerContent[i] === '(') depth++;
if (innerContent[i] === ')') depth--;
if (innerContent[i] === ',' && depth === 0) {
commaPos = i;
break;
}
}
const isValid = commaPos > 0;
let lightValue = '';
let darkValue = '';
if (isValid) {
lightValue = innerContent.substring(0, commaPos).trim();
darkValue = innerContent.substring(commaPos + 1).trim();
}
// Get source token references
const sourceRefs = getSourceReference(property);
// Resolve var() references to get actual hex values
const lightResolved = resolveVar(lightValue, allProperties, 'light');
const darkResolved = resolveVar(darkValue, allProperties, 'dark');
allLightDarkProps.push({
property,
value,
lightValue,
darkValue,
lightSource: sourceRefs?.light || lightValue,
darkSource: sourceRefs?.dark || darkValue,
lightResolved,
darkResolved,
isValid,
});
}
const validProps = allLightDarkProps.filter((p) => p.isValid);
const invalidProps = allLightDarkProps.filter((p) => !p.isValid);
// Summary
console.log(chalk.bold(`š Summary: ${validProps.length}/${allLightDarkProps.length} properties valid\n`));
console.log(`ā
Valid: ${validProps.length}`);
if (invalidProps.length > 0) {
console.log(chalk.red(`ā Invalid: ${invalidProps.length}`));
} else {
console.log(`ā Invalid: 0`);
}
if (!isVerbose && !isReport && allLightDarkProps.length > 0) {
console.log(chalk.gray('\nRun with --verbose to see detailed issues or --report to see all properties'));
}
console.log('');
// Verbose mode: show detailed issues
if (isVerbose && invalidProps.length > 0) {
console.log(chalk.bold.red(`\nš Invalid Properties (${invalidProps.length}):\n`));
const table = new Table({
head: ['#', 'Property', 'Value', 'Issue'],
colWidths: [5, 40, 50, 30],
style: { head: ['red'] },
wordWrap: true,
});
invalidProps.forEach((prop, index) => {
table.push([index + 1, prop.property, prop.value, 'Invalid light-dark() syntax']);
});
console.log(table.toString());
console.log('');
}
// Report mode: show full table
if (isReport) {
console.log(chalk.bold.blue(`š All Properties Using light-dark() (${allLightDarkProps.length}):\n`));
const table = new Table({
head: ['#', 'Property', 'Light Source', 'Light Resolved', 'Dark Source', 'Dark Resolved'],
colWidths: [5, 40, 30, 20, 30, 20],
style: { head: ['cyan'] },
wordWrap: true,
});
allLightDarkProps.forEach((prop, index) => {
let propertyDisplay = prop.property;
if (!prop.isValid) {
propertyDisplay = `${chalk.red('ā')} ${prop.property}`;
}
// Display source token references
let lightSourceDisplay = prop.lightSource;
let darkSourceDisplay = prop.darkSource;
// Display resolved values with color swatches
let lightResolvedDisplay = '';
let darkResolvedDisplay = '';
// Extract hex colors from resolved values and add swatches
const lightHex = prop.lightResolved.match(/#[0-9a-fA-F]{3,6}/);
const darkHex = prop.darkResolved.match(/#[0-9a-fA-F]{3,6}/);
if (lightHex) {
lightResolvedDisplay = `${colorSwatch(lightHex[0])} ${lightHex[0]}`;
} else {
lightResolvedDisplay = prop.lightResolved;
}
if (darkHex) {
darkResolvedDisplay = `${colorSwatch(darkHex[0])} ${darkHex[0]}`;
} else {
darkResolvedDisplay = prop.darkResolved;
}
table.push([
index + 1,
propertyDisplay,
lightSourceDisplay || chalk.gray('ā'),
lightResolvedDisplay || chalk.gray('ā'),
darkSourceDisplay || chalk.gray('ā'),
darkResolvedDisplay || chalk.gray('ā'),
]);
});
console.log(table.toString());
console.log('');
}
if (invalidProps.length > 0) {
console.log(chalk.red('ā Validation failed: Some light-dark() functions are invalid\n'));
process.exit(1);
} else {
console.log(chalk.green('ā
All light-dark() functions are valid\n'));
process.exit(0);
}
|