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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 | #!/usr/bin/env node
import fs from 'fs';
import path from 'node:path';
import chalk from 'chalk';
import Table from 'cli-table3';
import { fileURLToPath } from 'url';
import { parseValidatorArgs, exitWithStatus, loadKnownIssues, colorSwatch } from './validator-utils.js';
import { MODE_EXTENSION_KEY } from '../style-dictionary/utils/constants.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const knownIssues = loadKnownIssues();
/**
* TEMPORARY GLOBAL JSON Comparison Tool (TO BE REMOVED AFTER MIGRATION)
*
* Compare global JSON hook files between sds-styling-hooks and design-tokens packages
* This script helps verify that both packages generate identical global JSON output
*
* COMPARES: Global scope in .raw.json files
* NOT: Shared/component scopes - use temp-compare-json.js for those
*
* 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:global-json # Summary only
* yarn temp:compare:global-json --verbose # Show detailed issue tables
* yarn temp:compare:global-json --report # Show full table of all properties
*/
// Paths to the two packages
const SDS_STYLING_HOOKS_PATH = path.resolve(__dirname, '../../../sds-styling-hooks/dist/themes');
const DESIGN_TOKENS_PATH = path.resolve(__dirname, '../../dist/themes');
// Themes to compare
const THEMES = ['slds', 'cosmos'];
// Parse command line arguments
const { themeFilter, isVerbose, isReport } = parseValidatorArgs();
/**
* Add color swatches to hex colors and light-dark() values
*/
function addColorSwatches(value) {
if (!value || typeof value !== 'string') return value;
// Handle simple hex colors
if (value.match(/^#[0-9a-fA-F]{3,8}$/)) {
return `${colorSwatch(value)} ${value}`;
}
// Handle light-dark() function
const lightDarkMatch = value.match(/^light-dark\(([^,]+),\s*([^)]+)\)$/);
if (lightDarkMatch) {
const lightValue = lightDarkMatch[1].trim();
const darkValue = lightDarkMatch[2].trim();
// Add swatches to both light and dark values if they're hex colors
let formattedLight = lightValue;
let formattedDark = darkValue;
if (lightValue.match(/^#[0-9a-fA-F]{3,8}$/)) {
formattedLight = `${colorSwatch(lightValue)} ${lightValue}`;
}
if (darkValue.match(/^#[0-9a-fA-F]{3,8}$/)) {
formattedDark = `${colorSwatch(darkValue)} ${darkValue}`;
}
return `light-dark(${formattedLight}, ${formattedDark})`;
}
return value;
}
/**
* Convert token reference from {slds.g.color.brand.base.95} to var(--slds-g-color-brand-base-95)
*/
function convertTokenReference(value) {
if (typeof value !== 'string') return value;
// Match {slds.g.something} or {alias.palette.something}
const refMatch = value.match(/^\{([^}]+)\}$/);
if (refMatch) {
const ref = refMatch[1]; // e.g., "slds.g.color.brand.base.95" or "alias.palette.neutral.10"
// Convert dots to hyphens and add var() wrapper
if (ref.startsWith('slds.')) {
// slds.g.color.brand.base.95 -> var(--slds-g-color-brand-base-95)
const hookName = ref.replace(/\./g, '-');
return `var(--${hookName})`;
} else if (ref.startsWith('alias.')) {
// alias.palette.neutral.10 -> var(--slds-g-palette-neutral-10)
const path = ref.replace('alias.', '').replace(/\./g, '-');
return `var(--slds-g-${path})`;
}
}
return value;
}
/**
* Normalize $value from design-tokens format to string
* NOTE: This does NOT resolve token references - that's done separately
*/
function normalizeDesignTokenValue(value) {
// If it's an object with value and unit, convert to string
if (value && typeof value === 'object' && 'value' in value && 'unit' in value) {
return `${value.value}${value.unit}`;
}
// Otherwise return as-is (including token references like {slds.g.spacing.1})
return value;
}
/**
* Normalize token values for comparison
*/
function normalizeTokenValue(value) {
// Convert numbers to strings for consistent comparison
if (typeof value === 'number') {
return String(value);
}
if (typeof value !== 'string') return value;
// Handle specific palette cases FIRST (before general var(--slds-g-) rule)
if (value.startsWith('var(--slds-g-color-palette-')) {
return value.replace('var(--slds-g-color-palette-', 'alias.palette.').replace(')', '').replace(/-/g, '.');
}
// Handle special transparent case
if (value === 'var(--slds-g-transparent)') {
return 'transparent';
}
// Convert var(--cosmos-g-spacing-1) -> slds.g.spacing.1 (cosmos uses slds tokens)
if (value.startsWith('var(--cosmos-g-')) {
return value.replace('var(--cosmos-g-', 'slds.g.').replace(')', '').replace(/-/g, '.');
}
// Convert var(--slds-g-color-accent-container-3) -> slds.g.color.accent.container.3
if (value.startsWith('var(--slds-g-')) {
return value.replace('var(--slds-g-', 'slds.g.').replace(')', '').replace(/-/g, '.');
}
// Convert {slds.g.color.accent.container.3} -> slds.g.color.accent.container.3
if (value.startsWith('{slds.g.') && value.endsWith('}')) {
return value.slice(1, -1);
}
// Convert {alias.palette.yellow.90} -> alias.palette.yellow.90
if (value.startsWith('{alias.') && value.endsWith('}')) {
return value.slice(1, -1);
}
// Handle trailing semicolons
if (value.endsWith(';')) {
value = value.slice(0, -1);
}
return value;
}
/**
* Compare CSS custom properties between two packages
*/
function compareCustomProperties(sdsProps, designTokensProps) {
const differences = [];
// Get all property names
const sdsKeys = new Set(Object.keys(sdsProps));
const designTokensKeys = new Set(Object.keys(designTokensProps));
// Check for missing properties
for (const key of sdsKeys) {
if (!designTokensKeys.has(key)) {
differences.push({
path: key,
issue: 'MISSING_IN_DESIGN_TOKENS',
sdsStyleHooks: sdsProps[key].value,
designTokens: undefined,
});
}
}
for (const key of designTokensKeys) {
if (!sdsKeys.has(key)) {
differences.push({
path: key,
issue: 'MISSING_IN_SDS_STYLING_HOOKS',
sdsStyleHooks: undefined,
designTokens: designTokensProps[key].value,
});
}
}
// Compare values for common properties using normalized values
for (const key of sdsKeys) {
if (designTokensKeys.has(key)) {
const sdsValue = sdsProps[key].value;
const designTokensValue = designTokensProps[key].value;
// Normalize both values for comparison
const normalizedSdsValue = normalizeTokenValue(sdsValue);
const normalizedDesignTokensValue = normalizeTokenValue(designTokensValue);
if (normalizedSdsValue !== normalizedDesignTokensValue) {
differences.push({
path: key,
issue: 'VALUE_MISMATCH',
sdsStyleHooks: sdsValue,
designTokens: designTokensValue,
normalizedSds: normalizedSdsValue,
normalizedDesignTokens: normalizedDesignTokensValue,
});
}
}
}
return differences;
}
/**
* Normalize var() references in sds-styling-hooks
* Only normalizes cosmos to slds, does NOT resolve var() to values
*/
function resolveStylingHooksVar(value, allProps) {
if (typeof value !== 'string') return value;
// Just normalize cosmos to slds in var() references
return value.replace(/var\(--cosmos-g-/g, 'var(--slds-g-');
}
/**
* Extract global properties from sds-styling-hooks format
*/
function extractFromStylingHooks(data) {
const properties = {};
if (data.props) {
// First pass: collect all properties
for (const [key, value] of Object.entries(data.props)) {
if (value.scope === 'global') {
const hookName = `--slds-g-${key.replace(/_/g, '-')}`;
properties[hookName] = {
value: value.value,
description: value.comment || '',
scope: value.scope,
type: value.type,
};
}
}
// Second pass: resolve var() references
for (const [hookName, prop] of Object.entries(properties)) {
prop.value = resolveStylingHooksVar(prop.value, properties);
}
}
return properties;
}
/**
* Resolve token references like {slds.g.spacing.1} to their actual values
*/
function resolveTokenReference(value, allTokens, visited = new Set()) {
// Prevent infinite loops
if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
const reference = value.slice(1, -1); // Remove { and }
// Check for circular references
if (visited.has(reference)) {
return value; // Return unresolved to avoid infinite loop
}
visited.add(reference);
// Convert dot notation to path: slds.g.spacing.1 -> ['slds', 'g', 'spacing', '1']
const path = reference.split('.');
// Navigate through the token structure
let current = allTokens;
for (const segment of path) {
if (current && typeof current === 'object' && segment in current) {
current = current[segment];
} else {
// Reference not found, return as-is
return value;
}
}
// If we found a token with $value, resolve it recursively
if (current && typeof current === 'object' && '$value' in current) {
const resolvedValue = normalizeDesignTokenValue(current.$value);
// Recursively resolve if the value is also a reference
return resolveTokenReference(resolvedValue, allTokens, visited);
}
// If we found a direct value, return it
if (current !== undefined && typeof current !== 'object') {
return current;
}
// Couldn't resolve, return original
return value;
}
return value;
}
/**
* Extract global properties from design-tokens format
*/
function extractFromDesignTokens(obj, prefix = '', scope = '', rootObj = null) {
const properties = {};
// Store reference to root object for resolution
if (rootObj === null) {
rootObj = obj;
}
for (const [key, value] of Object.entries(obj)) {
// Skip the top-level "slds" wrapper
if (key === 'slds' && !scope && !prefix) {
Object.assign(properties, extractFromDesignTokens(value, '', '', rootObj));
continue;
}
if (key === 'g' && !scope) {
// Global scope - this is what we want
Object.assign(properties, extractFromDesignTokens(value, '', 'global', rootObj));
} else if (key === 's' || key === 'c') {
// Skip shared and component scopes
continue;
} else if (value && typeof value === 'object' && scope === 'global') {
const currentPath = prefix ? `${prefix}-${key}` : key;
if (value.$value !== undefined) {
// This is a token with a value
const rawValue = normalizeDesignTokenValue(value.$value);
// Check if there's a dark mode extension and convert to light-dark() format
let tokenValue = rawValue;
if (value.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value) {
const darkValue = normalizeDesignTokenValue(value.$extensions[MODE_EXTENSION_KEY].dark.$value);
tokenValue = `light-dark(${rawValue}, ${darkValue})`;
}
// Convert camelCase to kebab-case and underscores to hyphens
const kebabPath = currentPath
.replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase to kebab-case
.toLowerCase()
.replace(/_/g, '-'); // underscores to hyphens
const hookName = `--slds-g-${kebabPath}`;
properties[hookName] = {
value: tokenValue,
description: value.$description || '',
dynamic: value.dynamic || false,
scope: scope,
rawObj: value, // Store raw object for later resolution
};
} else {
// Recurse deeper
Object.assign(properties, extractFromDesignTokens(value, currentPath, scope, rootObj));
}
}
}
return properties;
}
/**
* Resolve token references in design-tokens raw JSON
* Converts {slds.g.spacing.1} to the actual value by looking it up in the raw object
* Falls back to flat JSON for alias.palette references
* Preserves {slds.r.*} references as var(--slds-r-*) without resolving them
* Also handles references embedded in strings like "0px 0px {slds.g.color.brand.base.15}"
*/
function resolveDesignTokensReference(value, rawObj, flatObj, currentHookName) {
if (typeof value !== 'string') return value;
// First, handle references embedded in strings (like shadow values)
if (value.includes('{') && !value.match(/^\{[^}]+\}$/)) {
// Replace all {ref} occurrences in the string
return value.replace(/\{([^}]+)\}/g, (match, ref) => {
// Recursively resolve this single reference
const resolved = resolveDesignTokensReference(`{${ref}}`, rawObj, flatObj, currentHookName);
// If it's still a reference, return the match as-is
return resolved.startsWith('{') ? match : resolved;
});
}
// Match {slds.g.something} or {alias.palette.something} or {slds.r.something}
const refMatch = value.match(/^\{([^}]+)\}$/);
if (!refMatch) return value;
const ref = refMatch[1]; // e.g., "slds.g.spacing.1" or "alias.palette.neutral.10" or "slds.r.color.brand.10"
// For slds.r (reference tokens), convert to var() and DON'T resolve
if (ref.startsWith('slds.r.')) {
// slds.r.color.brand.10 -> var(--slds-r-color-brand-10)
const hookName = ref.replace(/\./g, '-');
return `var(--${hookName})`;
}
// For slds.g (global tokens), convert to var() and DON'T resolve
// This keeps the comparison fair with sds-styling-hooks which uses var() references
if (ref.startsWith('slds.g.')) {
// slds.g.color.neutral.base.100 -> var(--slds-g-color-neutral-base-100)
const hookName = ref.replace(/\./g, '-');
return `var(--${hookName})`;
}
// For alias.palette references, use the flat JSON
if (ref.startsWith('alias.palette.')) {
// Convert alias.palette.blue.10 -> slds-g-color-palette-blue-10
// or alias.palette.electricBlue.50 -> slds-g-color-palette-electric-blue-50
// or alias.palette.cloudBlue.10 -> slds-g-color-palette-cloud-blue-10
let palettePath = ref.replace('alias.palette.', '');
// Split by dots to separate color name from number
const parts = palettePath.split('.');
if (parts.length >= 2) {
// Convert camelCase to kebab-case for the color name (electricBlue -> electric-blue)
const colorName = parts[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
const number = parts.slice(1).join('-'); // Join remaining parts with hyphens
palettePath = `${colorName}-${number}`;
} else {
// Fallback: just convert camelCase and replace dots
palettePath = palettePath
.replace(/([a-z])([A-Z])/g, '$1-$2')
.toLowerCase()
.replace(/\./g, '-');
}
const flatKey = `slds-g-color-palette-${palettePath}`;
if (flatObj[flatKey]) {
// Check if this token has a dark mode extension
if (flatObj[flatKey].$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value) {
// Don't return the light value here, we need to handle light-dark separately
// Just return the light value for now
return normalizeDesignTokenValue(flatObj[flatKey].$value);
}
return normalizeDesignTokenValue(flatObj[flatKey].$value);
}
// If not found in flat JSON, try to look it up in the raw JSON
// Navigate through alias.palette.cloudBlue.85
// Note: raw JSON uses camelCase, not kebab-case
const rawParts = ref.split('.');
let current = rawObj;
for (const part of rawParts) {
if (current && typeof current === 'object' && part in current) {
current = current[part];
} else {
// Not found, return original
return value;
}
}
// If we found a token, resolve it
if (current && typeof current === 'object' && current.$value !== undefined) {
const resolvedValue = normalizeDesignTokenValue(current.$value);
// Recursively resolve
return resolveDesignTokensReference(resolvedValue, rawObj, flatObj, currentHookName);
}
// If not found, return original
return value;
}
// For slds.g references, navigate through the raw object
const parts = ref.split('.');
let current = rawObj;
for (const part of parts) {
if (current && typeof current === 'object' && part in current) {
current = current[part];
} else {
// Reference not found, return original
return value;
}
}
// If we found a token object with $value, extract and recursively resolve it
if (current && typeof current === 'object' && current.$value !== undefined) {
const resolvedValue = normalizeDesignTokenValue(current.$value);
// Recursively resolve in case the value is also a reference
return resolveDesignTokensReference(resolvedValue, rawObj, flatObj, currentHookName);
}
return value;
}
/**
* Resolve var() references in design-tokens flat JSON
* BUT preserve var(--slds-r-*) references (reference tokens)
*/
function resolveDesignTokensVar(value, allTokens) {
if (typeof value !== 'string') return value;
// Match var(--slds-g-spacing-1) or var(--slds-r-color-brand-10)
const varMatch = value.match(/^var\((--slds-[gr]-[^)]+)\)$/);
if (varMatch) {
const refName = varMatch[1]; // e.g., --slds-g-spacing-1 or --slds-r-color-brand-10
// DON'T resolve reference tokens (--slds-r-*)
if (refName.startsWith('--slds-r-')) {
return value; // Keep as var(--slds-r-...)
}
// Look up the referenced token
if (refName in allTokens) {
// Recursively resolve in case the referenced value is also a var()
return resolveDesignTokensVar(allTokens[refName].value, allTokens);
}
}
return value;
}
/**
* Extract global properties from design-tokens flat format (fully resolved)
*/
function extractFromDesignTokensFlat(data) {
const properties = {};
// First pass: collect all properties
for (const [key, value] of Object.entries(data)) {
// Only include global scope tokens (slds-g-*)
if (key.startsWith('slds-g-')) {
const hookName = `--${key}`;
// Handle tokens with light/dark modes
if (value.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value !== undefined) {
// This is a light-dark token
const lightValue = normalizeDesignTokenValue(value.$value);
const darkValue = normalizeDesignTokenValue(value.$extensions[MODE_EXTENSION_KEY].dark.$value);
properties[hookName] = {
value: `light-dark(${lightValue}, ${darkValue})`,
description: value.$description || '',
scope: 'global',
};
} else {
// Regular token
properties[hookName] = {
value: normalizeDesignTokenValue(value.$value),
description: value.$description || '',
scope: 'global',
};
}
}
}
// Second pass: resolve var() references
for (const [hookName, prop] of Object.entries(properties)) {
prop.value = resolveDesignTokensVar(prop.value, properties);
}
return properties;
}
/**
* Compare global hook files between packages
*/
function compareGlobalHookFiles(theme) {
const sdsStyleHooksFile = path.join(SDS_STYLING_HOOKS_PATH, theme, `${theme}.hooks.raw.json`);
const designTokensRawFile = path.join(DESIGN_TOKENS_PATH, theme, `${theme}.hooks.raw.json`);
const designTokensFlatFile = path.join(DESIGN_TOKENS_PATH, theme, `${theme}.hooks.flat.json`);
// Check if files exist
if (!fs.existsSync(sdsStyleHooksFile)) {
console.log(chalk.red(` ❌ Missing sds-styling-hooks file: ${sdsStyleHooksFile}`));
return { differences: [], missing: 'sds-styling-hooks' };
}
if (!fs.existsSync(designTokensRawFile)) {
console.log(chalk.red(` ❌ Missing design-tokens raw file: ${designTokensRawFile}`));
return { differences: [], missing: 'design-tokens' };
}
if (!fs.existsSync(designTokensFlatFile)) {
console.log(chalk.red(` ❌ Missing design-tokens flat file: ${designTokensFlatFile}`));
return { differences: [], missing: 'design-tokens' };
}
try {
// Read and parse JSON files
const sdsStyleHooksData = JSON.parse(fs.readFileSync(sdsStyleHooksFile, 'utf8'));
const designTokensRawData = JSON.parse(fs.readFileSync(designTokensRawFile, 'utf8'));
const designTokensFlatData = JSON.parse(fs.readFileSync(designTokensFlatFile, 'utf8'));
// Extract global properties
const sdsStyleHooksProps = extractFromStylingHooks(sdsStyleHooksData);
const designTokensPropsRaw = extractFromDesignTokens(designTokensRawData);
// Resolve all token references in design-tokens using both raw and flat data
const designTokensProps = {};
for (const [hookName, tokenData] of Object.entries(designTokensPropsRaw)) {
const resolvedValue = resolveDesignTokensReference(
tokenData.value,
designTokensRawData,
designTokensFlatData,
hookName,
);
// If it's a light-dark() value, resolve both parts
const lightDarkMatch = resolvedValue.match(/^light-dark\((.+),\s*(.+)\)$/);
if (lightDarkMatch) {
const lightPart = resolveDesignTokensReference(
lightDarkMatch[1].trim(),
designTokensRawData,
designTokensFlatData,
hookName,
);
const darkPart = resolveDesignTokensReference(
lightDarkMatch[2].trim(),
designTokensRawData,
designTokensFlatData,
hookName,
);
// Check if BOTH light and dark parts are still unresolved references
// If so, try to resolve them using the flat JSON
let finalLightPart = lightPart;
let finalDarkPart = darkPart;
if (lightPart.match(/^\{[^}]+\}$/)) {
// Check if it's a {slds.r.*} reference - convert to var() format
const refMatch = lightPart.match(/^\{(slds\.r\.[^}]+)\}$/);
if (refMatch) {
// slds.r.color.brand.40 -> var(--slds-r-color-brand-40)
const hookRef = refMatch[1].replace(/\./g, '-');
finalLightPart = `var(--${hookRef})`;
} else {
// Still unresolved, use flat JSON
const flatKey = hookName.replace('--', '');
const flatToken = designTokensFlatData[flatKey];
if (flatToken?.$value) {
finalLightPart = normalizeDesignTokenValue(flatToken.$value);
}
}
}
if (darkPart.match(/^\{[^}]+\}$/)) {
// Check if it's a {slds.r.*} reference - convert to var() format
const refMatch = darkPart.match(/^\{(slds\.r\.[^}]+)\}$/);
if (refMatch) {
// slds.r.color.brand.40 -> var(--slds-r-color-brand-40)
const hookRef = refMatch[1].replace(/\./g, '-');
finalDarkPart = `var(--${hookRef})`;
} else {
// Still unresolved, use flat JSON
const flatKey = hookName.replace('--', '');
const flatToken = designTokensFlatData[flatKey];
if (flatToken?.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value) {
finalDarkPart = normalizeDesignTokenValue(
flatToken.$extensions[MODE_EXTENSION_KEY].dark.$value,
);
}
}
}
designTokensProps[hookName] = {
...tokenData,
value: `light-dark(${finalLightPart}, ${finalDarkPart})`,
};
} else {
// Check if the flat JSON has a dark mode extension for this token
// (handles tokens that reference other tokens with dark mode)
const flatKey = hookName.replace('--', '');
const flatToken = designTokensFlatData[flatKey];
if (flatToken?.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value) {
const lightValue = resolvedValue;
let darkValue = normalizeDesignTokenValue(flatToken.$extensions[MODE_EXTENSION_KEY].dark.$value);
// If flat dark value is hex, check raw JSON for {slds.r.*} reference
if (darkValue.startsWith('#')) {
// Look up the raw object to see if original was a reference
const rawDarkValue = tokenData.rawObj?.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value;
if (rawDarkValue && rawDarkValue.startsWith('{slds.r.')) {
// Convert {slds.r.color.brand.40} -> var(--slds-r-color-brand-40)
const refHookName = rawDarkValue.slice(1, -1).replace(/\./g, '-');
darkValue = `var(--${refHookName})`;
}
}
designTokensProps[hookName] = {
...tokenData,
value: `light-dark(${lightValue}, ${darkValue})`,
};
} else {
// Token doesn't have its own dark mode extension
// Keep the resolved value as-is (don't expand var() references to light-dark())
designTokensProps[hookName] = {
...tokenData,
value: resolvedValue,
};
}
}
}
console.log(` sds-styling-hooks: ${Object.keys(sdsStyleHooksProps).length} properties`);
console.log(` design-tokens: ${Object.keys(designTokensProps).length} properties`);
// Compare the CSS custom properties
const allDifferences = compareCustomProperties(sdsStyleHooksProps, designTokensProps);
// Separate into new vs known issues
const themeKnownIssuesConfig = knownIssues.json_global?.[theme] || {};
const newMissing = allDifferences.filter(
(d) => d.issue === 'MISSING_IN_DESIGN_TOKENS' && !themeKnownIssuesConfig.missing?.includes(d.path),
);
const newExtra = allDifferences.filter(
(d) => d.issue === 'MISSING_IN_SDS_STYLING_HOOKS' && !themeKnownIssuesConfig.extra?.includes(d.path),
);
const newMismatches = allDifferences.filter(
(d) => d.issue === 'VALUE_MISMATCH' && !themeKnownIssuesConfig.value_mismatches?.includes(d.path),
);
const knownMissing = allDifferences.filter(
(d) => d.issue === 'MISSING_IN_DESIGN_TOKENS' && themeKnownIssuesConfig.missing?.includes(d.path),
);
const knownExtra = allDifferences.filter(
(d) => d.issue === 'MISSING_IN_SDS_STYLING_HOOKS' && themeKnownIssuesConfig.extra?.includes(d.path),
);
const knownMismatches = allDifferences.filter(
(d) => d.issue === 'VALUE_MISMATCH' && themeKnownIssuesConfig.value_mismatches?.includes(d.path),
);
const newIssues = [...newMissing, ...newExtra, ...newMismatches];
const knownIssuesArr = [...knownMissing, ...knownExtra, ...knownMismatches];
// Calculate coverage
const totalProps = Object.keys(sdsStyleHooksProps).length;
const matching =
totalProps - allDifferences.filter((d) => d.issue !== 'MISSING_IN_SDS_STYLING_HOOKS').length;
const coverage = totalProps > 0 ? ((matching / totalProps) * 100).toFixed(1) : '0.0';
console.log(` ${chalk.green('✅ Covered:')} ${matching} (${coverage}%)`);
if (newIssues.length > 0) {
console.log(` ${chalk.red('❌')} New issues: ${newIssues.length}`);
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}`);
}
}
if (knownIssuesArr.length > 0) {
console.log(` ${chalk.yellow('⚠️')} Known issues: ${knownIssuesArr.length}`);
if (knownMismatches.length > 0) {
console.log(` ${chalk.yellow('⚠️')} Mismatches: ${knownMismatches.length}`);
}
if (knownMissing.length > 0) {
console.log(` ${chalk.yellow('⚠️')} Missing: ${knownMissing.length}`);
}
if (knownExtra.length > 0) {
console.log(` ${chalk.yellow('⚠️')} Extra: ${knownExtra.length}`);
}
}
return {
differences: allDifferences,
newIssues,
knownIssues: knownIssuesArr,
sdsStyleHooksProps,
designTokensProps,
sdsStyleHooksCount: Object.keys(sdsStyleHooksProps).length,
designTokensCount: Object.keys(designTokensProps).length,
matching,
};
} catch (error) {
console.log(chalk.red(` ❌ Error parsing JSON files: ${error.message}`));
return { differences: [], error: error.message };
}
}
/**
* Print verbose tables for new and known issues
*/
function printVerboseTables(newIssues, knownIssues) {
console.log(chalk.bold('\n📋 Detailed Issues:'));
console.log('='.repeat(50));
const printIssuesTable = (issues, title, headerColor) => {
if (issues.length === 0) return;
// Group by theme
const grouped = {};
issues.forEach((issue) => {
const key = issue.theme;
if (!grouped[key]) grouped[key] = [];
grouped[key].push(issue);
});
console.log(chalk.bold(`\n${title}`));
Object.keys(grouped).forEach((theme) => {
const themeIssues = grouped[theme];
console.log(chalk.bold(`\n${theme.toUpperCase()} - GLOBAL:`));
const table = new Table({
head: ['#', 'Property', 'sds-styling-hooks', 'design-tokens', 'Type'],
colWidths: [5, 40, 40, 40, 15],
style: { head: [headerColor] },
wordWrap: true,
});
themeIssues.forEach((issue, index) => {
let sdsValue = issue.sdsStyleHooks || '-';
let dtValue = issue.designTokens || '-';
// Don't truncate - let wordWrap handle long values
// Add color swatches for hex colors and light-dark() values
if (typeof sdsValue === 'string') {
sdsValue = addColorSwatches(sdsValue);
}
if (typeof dtValue === 'string') {
dtValue = addColorSwatches(dtValue);
}
// Determine type display
let typeDisplay = '';
const isKnown = title.includes('KNOWN');
if (issue.issue === 'MISSING_IN_DESIGN_TOKENS') {
typeDisplay = isKnown ? `${chalk.yellow('⚠️ Missing')}` : `${chalk.red('❌ Missing')}`;
} else if (issue.issue === 'MISSING_IN_SDS_STYLING_HOOKS') {
typeDisplay = isKnown ? `${chalk.yellow('⚠️ Extra')}` : `${chalk.green('➕ Extra')}`;
} else if (issue.issue === 'VALUE_MISMATCH') {
typeDisplay = isKnown ? `${chalk.yellow('⚠️ Mismatch')}` : `${chalk.red('❌ Mismatch')}`;
}
table.push([index + 1, issue.path, sdsValue, dtValue, typeDisplay]);
});
console.log(table.toString());
});
};
if (newIssues.length > 0) {
printIssuesTable(newIssues, '🔴 NEW ISSUES', 'red');
}
if (knownIssues.length > 0) {
printIssuesTable(knownIssues, '⚠️ KNOWN ISSUES', 'yellow');
}
}
/**
* Main comparison function
*/
function main() {
console.log(
chalk.bold.blue(
'\n🔄 TEMPORARY GLOBAL JSON Comparison (TO BE REMOVED): sds-styling-hooks (source of truth) vs design-tokens',
),
);
console.log(chalk.gray('(GLOBAL SCOPE ONLY)\n'));
const results = {
themes: {},
allNewIssues: [],
allKnownIssues: [],
summary: {
totalMatching: 0,
totalNewMissing: 0,
totalNewExtra: 0,
totalNewMismatches: 0,
totalKnownMissing: 0,
totalKnownExtra: 0,
totalKnownMismatches: 0,
},
};
const themesToCompare = themeFilter ? [themeFilter] : THEMES;
for (const theme of themesToCompare) {
if (!THEMES.includes(theme)) {
console.log(chalk.red(`❌ Unknown theme: ${theme}. Available themes: ${THEMES.join(', ')}`));
continue;
}
console.log(chalk.bold(`\nTheme: ${theme.toUpperCase()}`));
console.log('='.repeat(50));
console.log(chalk.bold('\nGLOBAL SCOPE:'));
const result = compareGlobalHookFiles(theme);
results.themes[theme] = result;
if (!result.error && !result.missing) {
results.summary.totalMatching += result.matching || 0;
// Collect issues for verbose mode
if (isVerbose && result.newIssues) {
result.newIssues.forEach((issue) => {
results.allNewIssues.push({
theme,
...issue,
});
});
}
if (isVerbose && result.knownIssues) {
result.knownIssues.forEach((issue) => {
results.allKnownIssues.push({
theme,
...issue,
});
});
}
// Count new issues
const newMissing = result.newIssues?.filter((d) => d.issue === 'MISSING_IN_DESIGN_TOKENS').length || 0;
const newExtra =
result.newIssues?.filter((d) => d.issue === 'MISSING_IN_SDS_STYLING_HOOKS').length || 0;
const newMismatches = result.newIssues?.filter((d) => d.issue === 'VALUE_MISMATCH').length || 0;
results.summary.totalNewMissing += newMissing;
results.summary.totalNewExtra += newExtra;
results.summary.totalNewMismatches += newMismatches;
// Count known issues
const knownMissing =
result.knownIssues?.filter((d) => d.issue === 'MISSING_IN_DESIGN_TOKENS').length || 0;
const knownExtra =
result.knownIssues?.filter((d) => d.issue === 'MISSING_IN_SDS_STYLING_HOOKS').length || 0;
const knownMismatches = result.knownIssues?.filter((d) => d.issue === 'VALUE_MISMATCH').length || 0;
results.summary.totalKnownMissing += knownMissing;
results.summary.totalKnownExtra += knownExtra;
results.summary.totalKnownMismatches += knownMismatches;
}
}
// Report mode: show full table of all properties
if (isReport) {
console.log(chalk.bold.blue('\n📋 All Global JSON Properties:'));
console.log('='.repeat(50));
for (const theme of themesToCompare) {
const result = results.themes[theme];
if (!result || result.error || result.missing) continue;
const allProps = new Map();
// Collect all properties
for (const [prop, data] of Object.entries(result.sdsStyleHooksProps || {})) {
allProps.set(prop, { sds: data.value, design: result.designTokensProps?.[prop]?.value });
}
for (const [prop, data] of Object.entries(result.designTokensProps || {})) {
if (!allProps.has(prop)) {
allProps.set(prop, { sds: null, design: data.value });
}
}
console.log(chalk.bold(`\n${theme.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 { sds, design } = allProps.get(prop);
let sdsValue = sds ? addColorSwatches(sds) : chalk.gray('—');
let designValue = design ? addColorSwatches(design) : chalk.gray('—');
let status = '';
// Determine status
if (!sds) {
status = chalk.green('➕ Extra');
} else if (!design) {
status = chalk.red('❌ Missing');
} else if (normalizeTokenValue(sds) !== normalizeTokenValue(design)) {
status = chalk.red('❌ Mismatch');
} else {
status = chalk.green('✓');
}
table.push([index + 1, prop, sdsValue, designValue, status]);
});
console.log(table.toString());
}
console.log('');
}
// Print verbose tables if requested
if (isVerbose && (results.allNewIssues.length > 0 || results.allKnownIssues.length > 0)) {
printVerboseTables(results.allNewIssues, results.allKnownIssues);
}
// Print summary
console.log(chalk.bold.blue('\n📊 Summary:'));
const totalNewIssues =
results.summary.totalNewMissing + results.summary.totalNewExtra + results.summary.totalNewMismatches;
const totalKnownIssues =
results.summary.totalKnownMissing +
results.summary.totalKnownExtra +
results.summary.totalKnownMismatches;
const totalTests = results.summary.totalMatching + totalNewIssues + totalKnownIssues;
console.log(`${results.summary.totalMatching}/${totalTests} tests passed`);
console.log(`${chalk.green('✅')} Matching: ${results.summary.totalMatching}`);
if (totalNewIssues > 0) {
console.log(`${chalk.red('❌')} New failures: ${totalNewIssues}`);
if (results.summary.totalNewMismatches > 0) {
console.log(` ${chalk.red('❌')} Mismatches: ${results.summary.totalNewMismatches}`);
}
if (results.summary.totalNewMissing > 0) {
console.log(` ${chalk.red('❌')} Missing: ${results.summary.totalNewMissing}`);
}
if (results.summary.totalNewExtra > 0) {
console.log(` ${chalk.green('➕')} Extra: ${results.summary.totalNewExtra}`);
}
}
if (totalKnownIssues > 0) {
console.log(`${chalk.yellow('⚠️')} Known issues: ${totalKnownIssues}`);
if (results.summary.totalKnownMismatches > 0) {
console.log(` ${chalk.yellow('⚠️')} Mismatches: ${results.summary.totalKnownMismatches}`);
}
if (results.summary.totalKnownMissing > 0) {
console.log(` ${chalk.yellow('⚠️')} Missing: ${results.summary.totalKnownMissing}`);
}
if (results.summary.totalKnownExtra > 0) {
console.log(` ${chalk.yellow('⚠️')} Extra: ${results.summary.totalKnownExtra}`);
}
}
if (!isVerbose && !isReport && (totalNewIssues > 0 || totalKnownIssues > 0)) {
console.log(chalk.gray('\nRun with --verbose to see detailed issues or --report to see all properties'));
}
// Overall status - exitWithStatus handles the messaging and exit codes
exitWithStatus(totalNewIssues, totalKnownIssues);
}
// Run the comparison
if (
import.meta.url.startsWith('file:') &&
process.argv[1] &&
import.meta.url === new URL(process.argv[1], 'file:').href
) {
main();
}
|