All files / packages/design-tokens/src/style-dictionary/formats ios-tokens-split.js

97.5% Statements 352/361
87.11% Branches 196/225
97.7% Functions 85/87
97.96% Lines 337/344

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 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278                                                                                                                  157x                                     2x 2x 2x 2x 2x     17x 17x 2x     15x 15x 15x 15x   15x               2071x 2071x 5x     2066x 2066x 2066x   2066x   2066x   2066x       2435x 2435x 2435x 2435x       2072x   2070x 7x     2063x 2063x 2063x 2052x       11x       2067x   2066x 1x 1x 1x         2065x                         3262x     2x       177x   146x 146x     6x     2x       40x   1x                 2x           10x             8x             7x             6x                 5x                     3x                     3x                 3x                   2x                 2x                       2x                               157x 1x         154x               4x 1x                       10x 51x 8x     2x               7x 7x                                         154x     152x 1x       151x 3x 3x 1x         150x 1x 1x 1x       149x                       1400x     1400x 3104x     3105x 1x           1400x 7x   7x 5x   2x       1393x 445x 445x   280x   280x 280x     165x   591x 591x 426x           948x 31x   91x 91x 60x           917x 874x 874x   2334x 2334x 1460x           43x   88x 88x 45x                   694x 692x   2x                                                             19x     28x 9x         19x   4x     19x                     62x 62x     62x   62x     62x   62x     111x     120x 9x         111x 62x   49x                         262x   2x         260x 260x 260x 260x   260x 260x   260x     649x 213x     436x       4x 2x         436x 178x                         25x 25x   25x                     25x     25x 7x   7x     11x           7x 7x       25x 10x   10x       39x     10x 10x       25x 6x     6x 5x 5x     6x 6x   1x   5x 5x           6x 6x       25x 5x     5x 201x 201x     5x     49x   76x 76x           5x 5x       25x 8x     8x     42x     42x   42x     8x     32x   5x     8x 8x       25x 7x   7x   7x   7x     7x 7x       25x 1x 1x 1x 1x 1x   1x   1x     3x 3x 2x     1x     1x     25x                                                             45x   45x     45x     650x     1058x 1058x           45x 45x 642x   45x     45x 45x 642x   45x   45x                                               15x   15x   3114x         650x 114x 114x 114x   536x                                                     13x   13x   3112x         466x 50x 50x 50x   416x 60x 60x 60x   356x           356x                                                   13x   13x   3112x         138x                                                 18x   18x   3120x           18x     18x   18x 691x   691x 691x   691x 65x     691x   691x   691x     691x     691x 691x 691x               691x 691x 691x                 18x   18x 65x 65x     65x 65x 691x   65x     65x 65x 65x 691x   65x       18x                         67x 67x   67x 553x   50x 50x       67x     2x 7x 7x   7x                     7x                       7x 63x 63x 63x     7x       2x                               2x 146x 146x   146x       146x   20x                     13x                     14x                     15x                     25x     15x     13x     13x     18x             2x     2x                                                              
/**
 * iOS Split Tokens Format for iOS/SwiftUI
 *
 * Generates multiple Swift files with structured token output:
 * - ${themePrefix}SystemColors.swift - System color classes (Light/Dark)
 * - ${themePrefix}ReferenceColors.swift - Reference color classes (Light/Dark)
 * - ${themePrefix}SemanticColors.swift - Semantic color classes (Light/Dark)
 * - ${themePrefix}PaletteColors.swift - Palette color enums (per color family, Light/Dark)
 * - ${themePrefix}Fonts.swift - Font size/weight/family enums
 * - ${themePrefix}Shapes.swift - Border radius class
 * - ${themePrefix}Spacing.swift - Spacing class
 * - ${themePrefix}Sizing.swift - Sizing class
 * - ${themePrefix}MotionDuration.swift - Duration class
 
 * Note: Deprecated tokens are excluded from this output.
 */
 
import Color from 'colorjs.io';
import {
  convertDurationToSeconds,
  extractNumber,
  getRawValueUnitValue,
  resolveTokenReference,
  isTokenReference,
  parseOklch,
  expandHexColor,
  getTokensForCategory,
  shouldSkipToken,
  isSystemColorToken,
  isReferenceColorToken,
  isSemanticColorToken,
  generateDimensionOutput,
  generateDurationOutput,
  groupFontTokens,
  generateFontFamilyOutput,
  generateFontWeightOutput,
  generateFontDimensionOutput,
  generateLineHeightOutput,
  generateTruncationOutput,
  getTokenDescription,
  PATH_INDEX,
  CATEGORY,
  COLOR_SUBCATEGORY,
  COLOR_MODIFIER,
  FONT_SUBCATEGORY,
  FONT_MODIFIER,
  NAMESPACE,
  SCOPE,
} from '../utils/mobile-helpers.js';
import { MODE_EXTENSION_KEY } from '../utils/constants.js';
import { processColorTokens } from '../utils/mobile-color-helpers.js';
 
// ============================================================================
// FILE HEADER GENERATOR
// ============================================================================
 
function generateFileHeader(purpose) {
  return `/*
 * AUTO-GENERATED FILE. DO NOT EDIT.
 *
 * ${purpose}
 * Requires: import SwiftUI, import Foundation
 *
 * Note: Deprecated tokens are excluded from this output.
 */
 
import SwiftUI
import Foundation
 
`;
}
 
// ============================================================================
// COLOR UTILITIES (shared with ios-tokens.js)
// ============================================================================
 
const RGB_MAX_VALUE = 255.0;
const RGB_MIN_COMPONENT = 0;
const RGB_MAX_COMPONENT = 1;
const HEX_COLOR_LENGTH = 6;
const RGB_DECIMAL_PLACES = 3;
 
function oklchToRGB(oklch) {
  const components = parseOklch(oklch);
  if (!components) {
    throw new Error(`[iOS-Split] Could not parse OKLCH color: ${JSON.stringify(oklch)}`);
  }
 
  const [L, C, H] = components;
  const color = new Color('oklch', [L, C, H]);
  const srgb = color.to('srgb');
  const coords = srgb.coords;
 
  return {
    r: Math.max(RGB_MIN_COMPONENT, Math.min(RGB_MAX_COMPONENT, coords[0])),
    g: Math.max(RGB_MIN_COMPONENT, Math.min(RGB_MAX_COMPONENT, coords[1])),
    b: Math.max(RGB_MIN_COMPONENT, Math.min(RGB_MAX_COMPONENT, coords[2])),
  };
}
 
function hexToRGB(hex) {
  const cleanHex = expandHexColor(hex);
  if (cleanHex.length !== HEX_COLOR_LENGTH) {
    throw new Error(`[iOS-Split] Invalid hex color: "${hex}" (expected 3 or 6 character hex)`);
  }
 
  const HEX_BASE = 16;
  const HEX_COMPONENT_LENGTH = 2;
  const r = parseInt(cleanHex.substring(0, HEX_COMPONENT_LENGTH), HEX_BASE) / RGB_MAX_VALUE;
  const g =
    parseInt(cleanHex.substring(HEX_COMPONENT_LENGTH, HEX_COMPONENT_LENGTH * 2), HEX_BASE) / RGB_MAX_VALUE;
  const b =
    parseInt(cleanHex.substring(HEX_COMPONENT_LENGTH * 2, HEX_COMPONENT_LENGTH * 3), HEX_BASE) /
    RGB_MAX_VALUE;
  return { r, g, b };
}
 
function toSwiftUIColor(rgb) {
  const r = rgb.r.toFixed(RGB_DECIMAL_PLACES);
  const g = rgb.g.toFixed(RGB_DECIMAL_PLACES);
  const b = rgb.b.toFixed(RGB_DECIMAL_PLACES);
  return `Color(red: ${r}, green: ${g}, blue: ${b})`;
}
 
function colorToRGB(colorValue) {
  if (!colorValue) return null;
 
  if (parseOklch(colorValue)) {
    return oklchToRGB(colorValue);
  }
 
  Eif (typeof colorValue === 'string') {
    const cleanHex = expandHexColor(colorValue);
    if (cleanHex.length === HEX_COLOR_LENGTH && /^[0-9a-f]{6}$/i.test(cleanHex)) {
      return hexToRGB(colorValue);
    }
  }
 
  return null;
}
 
function resolveColorToRGB(colorValue, allTokens, visited = new Set()) {
  if (!colorValue) return null;
 
  if (isTokenReference(colorValue)) {
    const refValue = resolveTokenReference(colorValue, allTokens, visited);
    Eif (refValue !== null) {
      return resolveColorToRGB(refValue, allTokens, visited);
    }
    return null;
  }
 
  return colorToRGB(colorValue);
}
 
// ============================================================================
// iOS PLATFORM CONFIG
// ============================================================================
 
/**
 * Format an inline comment for descriptions
 * @param {string|null} description - Description text
 * @returns {string} - Formatted inline comment or empty string
 */
function formatInlineComment(description) {
  return description ? ` // ${description}` : '';
}
 
const IOS_DIMENSION_CONFIG = {
  objectDeclaration: 'public class {{name}} {',
  objectClose: '}',
  valueProperty: (propName, value, description) =>
    `    public static var ${propName}: CGFloat { ${value} }${formatInlineComment(description)}\n`,
  referenceProperty: (propName, refPropName, unit, description) => {
    const suffix = unit === '%' ? 'Percent' : '';
    return `    public static var ${propName}${suffix}: CGFloat { Self.${refPropName}${suffix} }${formatInlineComment(description)}\n`;
  },
  percentProperty: (propName, value, description) =>
    `    public static var ${propName}Percent: CGFloat { ${value} }${formatInlineComment(description)}\n`,
};
 
const IOS_DURATION_CONFIG = {
  objectDeclaration: 'public class {{name}} {',
  objectClose: '}',
  valueProperty: (propName, seconds, description) =>
    `    public static var ${propName}: TimeInterval { ${seconds} }${formatInlineComment(description)}\n`,
  referenceProperty: (propName, refPropName, description) =>
    `    public static var ${propName}: TimeInterval { Self.${refPropName} }${formatInlineComment(description)}\n`,
};
 
// ============================================================================
// CONSTANTS (iOS-specific)
// ============================================================================
// Note: Shared constants (PATH_INDEX, CATEGORY, etc.) are imported from mobile-helpers.js
 
// Token type descriptors for maintainability and validation
const TOKEN_TYPE_DESCRIPTORS = {
  SPACING: {
    category: CATEGORY.SPACING,
    minPathLength: 4, // slds.g.spacing.{name}
    preserveReferences: true,
    propertyNameOffset: PATH_INDEX.CATEGORY, // Start from 'spacing'
    checkMatch: (token) => token.path[PATH_INDEX.CATEGORY] === CATEGORY.SPACING,
  },
  SIZING: {
    category: CATEGORY.SIZING,
    minPathLength: 4, // slds.g.sizing.{name}
    preserveReferences: true,
    propertyNameOffset: PATH_INDEX.CATEGORY,
    checkMatch: (token) => token.path[PATH_INDEX.CATEGORY] === CATEGORY.SIZING,
  },
  RADIUS: {
    category: CATEGORY.RADIUS,
    minPathLength: 4, // slds.g.radius.{name}
    preserveReferences: true,
    propertyNameOffset: PATH_INDEX.CATEGORY,
    checkMatch: (token) => token.path[PATH_INDEX.CATEGORY] === CATEGORY.RADIUS,
  },
  DURATION: {
    category: CATEGORY.DURATION,
    minPathLength: 4, // slds.g.duration.{name}
    preserveReferences: true,
    propertyNameOffset: PATH_INDEX.CATEGORY,
    checkMatch: (token) => token.path[PATH_INDEX.CATEGORY] === CATEGORY.DURATION,
  },
  FONT_SCALE: {
    category: CATEGORY.FONT,
    subcategory: FONT_SUBCATEGORY.SCALE,
    minPathLength: 4, // slds.g.font.scale or slds.g.font.scale.{name}
    preserveReferences: true,
    propertyNameOffset: 4, // Start after 'scale'
    checkMatch: (token) =>
      token.path[PATH_INDEX.CATEGORY] === CATEGORY.FONT &&
      token.path[PATH_INDEX.SUBCATEGORY] === FONT_SUBCATEGORY.SCALE,
  },
  FONT_LINE_HEIGHT: {
    category: CATEGORY.FONT,
    subcategory: FONT_SUBCATEGORY.LINE,
    modifier: FONT_MODIFIER.HEIGHT,
    minPathLength: 5, // slds.g.font.line.height or slds.g.font.line.height.{name}
    preserveReferences: true,
    propertyNameOffset: 5, // Start after 'height'
    checkMatch: (token) =>
      token.path[PATH_INDEX.CATEGORY] === CATEGORY.FONT &&
      token.path[PATH_INDEX.SUBCATEGORY] === FONT_SUBCATEGORY.LINE &&
      token.path[PATH_INDEX.MODIFIER] === FONT_MODIFIER.HEIGHT,
  },
  FONT_SIZE: {
    category: CATEGORY.FONT,
    subcategory: FONT_SUBCATEGORY.SIZE,
    minPathLength: 4, // slds.g.font.size.{name}
    preserveReferences: true,
    propertyNameOffset: 4,
    checkMatch: (token) =>
      token.path[PATH_INDEX.CATEGORY] === CATEGORY.FONT &&
      token.path[PATH_INDEX.SUBCATEGORY] === FONT_SUBCATEGORY.SIZE,
  },
  SYSTEM_COLOR: {
    category: CATEGORY.COLOR,
    modifier: COLOR_MODIFIER.BASE,
    minPathLength: 6, // slds.g.color.{family}.base.{scale}
    preserveReferences: true,
    checkMatch: (token) =>
      token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.SLDS &&
      token.path[PATH_INDEX.SCOPE] === SCOPE.GLOBAL &&
      token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR &&
      token.path[PATH_INDEX.MODIFIER] === COLOR_MODIFIER.BASE,
  },
  REFERENCE_COLOR: {
    category: CATEGORY.COLOR,
    minPathLength: 5, // slds.r.color.{name}.{scale}
    preserveReferences: false, // Always resolve to RGB
    checkMatch: (token) =>
      token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.SLDS &&
      token.path[PATH_INDEX.SCOPE] === SCOPE.REFERENCE &&
      token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR,
  },
  SEMANTIC_COLOR: {
    category: CATEGORY.COLOR,
    minPathLength: 4, // slds.g.color.{semantic-category}.{name}
    preserveReferences: true,
    checkMatch: (token) =>
      token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.SLDS &&
      token.path[PATH_INDEX.SCOPE] === SCOPE.GLOBAL &&
      token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR &&
      token.path[PATH_INDEX.SUBCATEGORY] !== COLOR_SUBCATEGORY.PALETTE &&
      token.path[PATH_INDEX.MODIFIER] !== COLOR_MODIFIER.BASE,
  },
  PALETTE_COLOR: {
    category: CATEGORY.COLOR,
    subcategory: COLOR_SUBCATEGORY.PALETTE,
    minPathLength: 5, // slds.g.color.palette.{family}.{scale}
    preserveReferences: false, // Always resolve to RGB
    checkMatch: (token) =>
      (token.path[PATH_INDEX.CATEGORY] === CATEGORY.COLOR &&
        token.path[PATH_INDEX.SUBCATEGORY] === COLOR_SUBCATEGORY.PALETTE) ||
      (token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.ALIAS &&
        token.path[PATH_INDEX.SCOPE] === COLOR_SUBCATEGORY.PALETTE),
  },
};
 
// ============================================================================
// HELPER UTILITIES
// ============================================================================
 
/**
 * Get a path segment safely with validation
 * Throws descriptive error if index is out of bounds
 */
function getPathSegment(token, index, segmentName = 'segment') {
  if (index >= token.path.length) {
    throw new Error(
      `Token path too short: ${token.path.join('.')} ` +
        `(expected ${segmentName} at index ${index}, but path has only ${token.path.length} segments)`,
    );
  }
  return token.path[index];
}
 
/**
 * Validate token path against expected minimum length
 * Throws descriptive error if validation fails
 */
function validateTokenPath(token, minLength, tokenTypeName) {
  if (token.path.length < minLength) {
    throw new Error(
      `Invalid ${tokenTypeName} token path: ${token.path.join('.')} ` +
        `(expected at least ${minLength} segments, got ${token.path.length})`,
    );
  }
}
 
/**
 * Get token type descriptor for a given token
 * Returns the matching descriptor or null if no match
 */
function getTokenTypeDescriptor(token) {
  for (const [typeName, descriptor] of Object.entries(TOKEN_TYPE_DESCRIPTORS)) {
    if (descriptor.checkMatch(token)) {
      return { ...descriptor, typeName };
    }
  }
  return null;
}
 
/**
 * Check if a token should preserve references based on its type
 * Returns true if references should be preserved, false otherwise
 */
function shouldPreserveReferences(token) {
  const descriptor = getTokenTypeDescriptor(token);
  return descriptor ? descriptor.preserveReferences : false;
}
 
/**
 * Check if a reference should be preserved between two tokens
 * Returns true if the reference token matches the expected type for preservation
 *
 * @param {object} sourceToken - The token that contains the reference
 * @param {object} refToken - The token being referenced
 * @param {string} expectedCategory - Expected category for same-class references (e.g., 'spacing')
 * @param {string} [expectedSubcategory] - Optional expected subcategory (e.g., 'scale')
 * @param {string} [expectedModifier] - Optional expected modifier (e.g., 'height')
 * @returns {boolean}
 */
function shouldPreserveReference(
  sourceToken,
  refToken,
  expectedCategory,
  expectedSubcategory = null,
  expectedModifier = null,
) {
  if (!refToken) return false;
 
  // Check category match
  if (getPathSegment(refToken, PATH_INDEX.CATEGORY, 'category') !== expectedCategory) {
    return false;
  }
 
  // Check subcategory if specified
  if (expectedSubcategory !== null) {
    const refSubcategory = refToken.path[PATH_INDEX.SUBCATEGORY];
    if (refSubcategory !== expectedSubcategory) {
      return false;
    }
  }
 
  // Check modifier if specified
  if (expectedModifier !== null) {
    const refModifier = refToken.path[PATH_INDEX.MODIFIER];
    Eif (refModifier !== expectedModifier) {
      return false;
    }
  }
 
  return true;
}
 
// ============================================================================
// NAMING UTILITIES FOR SPLIT FORMAT
// ============================================================================
 
/**
 * Convert token path to a short property name for split format
 */
function pathToShortPropertyName(path, category) {
  // Remove namespace and scope prefix (slds.g or slds.r)
  const relevantPath = path.slice(PATH_INDEX.CATEGORY);
 
  // Helper to convert segment to camelCase (handling hyphens)
  const toCamelCase = (segment) => {
    return segment
      .split('-')
      .map((word, index) => {
        if (index === 0) return word;
        return word.charAt(0).toUpperCase() + word.slice(1);
      })
      .join('');
  };
 
  // Special handling for font sizes -> size naming
  if (category === CATEGORY.FONT && relevantPath[1] === FONT_SUBCATEGORY.SIZE) {
    const sizeNum = relevantPath[2];
    // Capitalize 'Base' for consistency: sizeBase not sizebase
    if (sizeNum.toLowerCase() === 'base') {
      return 'sizeBase';
    }
    return `size${sizeNum}`;
  }
 
  // For spacing/sizing: include category prefix (spacing1, sizing1, sizingBorder1)
  if ((category === CATEGORY.SPACING || category === CATEGORY.SIZING) && relevantPath[0] === category) {
    const remaining = relevantPath.slice(1);
    if (remaining.length === 1) {
      // spacing.1 -> spacing1, sizing.base -> sizingBase
      const segment = remaining[0];
      // Capitalize if it's a word (not a number)
      const suffix = /^\d/.test(segment) ? segment : segment.charAt(0).toUpperCase() + segment.slice(1);
      return `${category}${suffix}`;
    }
    // spacing.var.1 -> spacingVar1, sizing.border.1 -> sizingBorder1
    return relevantPath
      .map((segment, index) => {
        const camelSegment = toCamelCase(segment);
        if (index === 0) return camelSegment;
        return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
      })
      .join('');
  }
 
  // For radius tokens: radius.border.1 -> radiusBorder1
  if (relevantPath[0] === CATEGORY.RADIUS) {
    return relevantPath
      .map((segment, index) => {
        const camelSegment = toCamelCase(segment);
        if (index === 0) return camelSegment;
        return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
      })
      .join('');
  }
 
  // For color tokens, we need the full path after category
  if (category === CATEGORY.COLOR) {
    const colorPath = relevantPath.slice(1); // Remove 'color' prefix
    return colorPath
      .map((segment, index) => {
        const camelSegment = toCamelCase(segment);
        if (index === 0) return camelSegment;
        return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
      })
      .join('');
  }
 
  // Default: join remaining in camelCase
  return relevantPath
    .map((segment, index) => {
      const camelSegment = toCamelCase(segment);
      if (index === 0) return camelSegment;
      return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
    })
    .join('');
}
 
/**
 * Get the palette family from a color token path
 * Example: ['slds', 'g', 'color', 'palette', 'blue', '50'] -> 'blue'
 */
function getPaletteFamily(path) {
  if (path[PATH_INDEX.SUBCATEGORY] === COLOR_SUBCATEGORY.PALETTE && path[PATH_INDEX.MODIFIER]) {
    return path[PATH_INDEX.MODIFIER];
  }
  return null;
}
 
/**
 * Check if a token is an alias palette token
 */
function isAliasPaletteToken(token) {
  return (
    token.path[PATH_INDEX.NAMESPACE] === NAMESPACE.ALIAS &&
    token.path[PATH_INDEX.SCOPE] === COLOR_SUBCATEGORY.PALETTE
  );
}
 
// ============================================================================
// FONTS OUTPUT HELPER
// ============================================================================
//
// Font tokens define typography-related values (sizes, weights, families, etc.)
// - Organized into separate enums: FontFamily, FontWeight, FontSize, FontScale, FontLineHeight
// - Preserves references between font tokens (e.g., fontSize.base → fontScale.base)
// - Uses static let for constant values, static var for computed references
// - Path structure: slds.g.font.{subcategory}.{name}
//
// ============================================================================
 
/**
 * Convert a token path segment to a valid Swift property name
 * Handles hyphens, leading numbers, etc.
 */
function toValidSwiftName(segment) {
  // Convert hyphens to camelCase
  let name = segment
    .split('-')
    .map((word, index) => {
      if (index === 0) return word;
      return word.charAt(0).toUpperCase() + word.slice(1);
    })
    .join('');
 
  // If starts with a number, prefix with underscore or descriptive word
  if (/^\d/.test(name)) {
    // For font scales, use 'scale' prefix
    name = `scale${name}`;
  }
 
  return name;
}
 
/**
 * Convert token path to property name for scoped font enums
 * Skips category and subcategory since they're already in the enum name
 * Example: ['slds', 'g', 'font', 'scale', '1'] -> 'scale1'
 */
function pathToScopedFontPropertyName(path) {
  // For font tokens, include subcategory + name for better clarity
  // Path structure: [slds, g, font, subcategory, name, ...]
  const subcategory = path[PATH_INDEX.SUBCATEGORY]; // e.g., 'scale', 'weight', 'line-clamp'
  const nameParts = path.slice(4); // Everything after subcategory
 
  // Check if this is a semantic name (non-numeric) - if so, don't prefix with subcategory
  const firstNamePart = nameParts[0];
  const isSemanticName =
    firstNamePart && !/^\d/.test(firstNamePart) && !['base', 'var', 'ratio'].includes(firstNamePart);
 
  // For semantic names, use just the name parts. For numeric/structured names, include subcategory
  const allParts = isSemanticName ? nameParts : [subcategory, ...nameParts];
 
  return allParts
    .map((segment, index) => {
      // Convert hyphens to camelCase without adding 'scale' prefix
      let name = segment
        .split('-')
        .map((word, wordIndex) => {
          if (wordIndex === 0) return word;
          return word.charAt(0).toUpperCase() + word.slice(1);
        })
        .join('');
 
      // First segment lowercase for Swift property naming
      if (index === 0) {
        return name.charAt(0).toLowerCase() + name.slice(1);
      }
      return name.charAt(0).toUpperCase() + name.slice(1);
    })
    .join('');
}
 
/**
 * Extract property name from font-related token path parts
 * Handles font.scale.*, font.line.height.*, etc.
 * Note: This is used within specific font subcategory contexts (scale, line.height)
 * where the subcategory is already known. For structural tokens (base, ratio, var),
 * we add the subcategory prefix for consistency.
 */
function getFontPropertyName(pathParts, subcategory = null) {
  if (pathParts.length === 0) {
    // If we know the subcategory context, prefix 'base' with it
    return subcategory ? `${subcategory}Base` : 'base';
  }
 
  // Check if this is a semantic name - if so, don't prefix with subcategory
  // Semantic names are non-numeric names that aren't structural tokens
  const structuralTokens = ['base', 'ratio', 'var', 'neg'];
  const isNumeric = /^\d/.test(pathParts[0]);
  const isStructural = structuralTokens.includes(pathParts[0]);
  const isSemanticName = !isNumeric && !isStructural;
 
  const shouldPrependSubcategory = subcategory && !isSemanticName;
  const allParts = shouldPrependSubcategory ? [subcategory, ...pathParts] : pathParts;
 
  return allParts
    .map((part, index) => {
      // For numeric parts, just use them as-is (subcategory already provides context)
      if (/^\d/.test(part)) {
        return part;
      }
      // For other parts, handle hyphens and capitalization
      const camelPart = part.includes('-')
        ? part
            .split('-')
            .map((word, i) => {
              if (i === 0) return word;
              return word.charAt(0).toUpperCase() + word.slice(1);
            })
            .join('')
        : part;
 
      if (index === 0) return camelPart;
      return camelPart.charAt(0).toUpperCase() + camelPart.slice(1);
    })
    .join('');
}
 
/**
 * Generate font tokens output for iOS
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Swift code
 */
function generateFontsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
  const fontTokens = getTokensForCategory(tokens, CATEGORY.FONT);
 
  let output = generateFileHeader('Font design tokens for SwiftUI.');
 
  // Group font tokens by sub-category using shared helper
  const {
    sizes: fontSizes,
    weights: fontWeights,
    families: fontFamilies,
    lineHeights: fontLineHeights,
    scales: fontScales,
    truncation: fontTruncation,
    other: fontOther,
  } = groupFontTokens(fontTokens);
 
  // Font Families - enum with static let
  if (fontFamilies.length > 0) {
    output += `public enum ${themePrefix}FontFamily {\n`;
 
    const familyOutputs = generateFontFamilyOutput(fontFamilies, tokens, {
      pathToPropertyName: pathToScopedFontPropertyName,
      formatValue: (propName, fontStack, description) =>
        `    public static let ${propName} = "${fontStack}"${formatInlineComment(description)}\n`,
      formatReference: (propName, refPropName, objectName, description) =>
        `    public static var ${propName} { Self.${refPropName} }${formatInlineComment(description)}\n`,
      objectName: 'FontFamily',
    });
 
    output += familyOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Weights - enum with static let
  if (fontWeights.length > 0) {
    output += `public enum ${themePrefix}FontWeight {\n`;
 
    const weightOutputs = generateFontWeightOutput(
      fontWeights,
      pathToScopedFontPropertyName,
      (propName, value, description) =>
        `    public static let ${propName}: Int = ${value}${formatInlineComment(description)}\n`,
    );
 
    output += weightOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Sizes - enum with static let/var
  if (fontSizes.length > 0) {
    output += `public enum ${themePrefix}FontSize {\n`;
 
    // Helper to extract property name from scale tokens (used for references)
    const getScalePropertyName = (path) => {
      const scaleParts = path.slice(4); // Everything after 'scale'
      return getFontPropertyName(scaleParts, 'scale');
    };
 
    const sizeOutputs = generateFontDimensionOutput(fontSizes, tokens, {
      pathToPropertyName: (path) => pathToShortPropertyName(path, CATEGORY.FONT),
      formatValue: (propName, value, token, description) =>
        `    public static let ${propName}: CGFloat = ${value}${formatInlineComment(description)}\n`,
      formatReference: (propName, refToken, allTokens, description) => {
        const refPropName = getScalePropertyName(refToken.path);
        return `    public static var ${propName}: CGFloat { ${themePrefix}FontScale.${refPropName} }${formatInlineComment(description)}\n`;
      },
      useDimensionConversion: true,
      expectedSubcategory: FONT_SUBCATEGORY.SCALE,
    });
 
    output += sizeOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Scales - enum with static let/var
  if (fontScales.length > 0) {
    output += `public enum ${themePrefix}FontScale {\n`;
 
    // Helper to extract property name from scale tokens
    const getScalePropertyName = (path) => {
      const scaleParts = path.slice(4); // Everything after 'scale'
      return getFontPropertyName(scaleParts, 'scale');
    };
 
    const scaleOutputs = generateFontDimensionOutput(fontScales, tokens, {
      pathToPropertyName: getScalePropertyName,
      formatValue: (propName, value, token, description) =>
        `    public static let ${propName}: CGFloat = ${value}${formatInlineComment(description)}\n`,
      formatReference: (propName, refToken, allTokens, description) => {
        const refPropName = getScalePropertyName(refToken.path);
        return `    public static var ${propName}: CGFloat { Self.${refPropName} }${formatInlineComment(description)}\n`;
      },
      useDimensionConversion: true, // Changed from false - iOS scales need dimension conversion for rem units
      expectedSubcategory: FONT_SUBCATEGORY.SCALE,
    });
 
    output += scaleOutputs.join('');
    output += '}\n\n';
  }
 
  // Line Heights - enum with static let/var
  if (fontLineHeights.length > 0) {
    output += `public enum ${themePrefix}FontLineHeight {\n`;
 
    // Helper to extract property name from line-height tokens
    const getLineHeightPropertyName = (path) => {
      // Path: ['slds', 'g', 'font', 'line', 'height', '1']
      // Everything after 'height' (index 5)
      const heightParts = path.slice(5);
 
      // Build subcategory from path[3] + path[4]: 'line' + 'height' -> 'lineHeight'
      const subcategory = path[3] + path[4].charAt(0).toUpperCase() + path[4].slice(1);
 
      return getFontPropertyName(heightParts, subcategory);
    };
 
    const lineHeightOutputs = generateLineHeightOutput(fontLineHeights, tokens, {
      pathToPropertyName: getLineHeightPropertyName,
      formatValue: (propName, value, description) =>
        `    public static let ${propName}: CGFloat = ${value}${formatInlineComment(description)}\n`,
      formatReference: (propName, refPropName, description) =>
        `    public static var ${propName}: CGFloat { Self.${refPropName} }${formatInlineComment(description)}\n`,
    });
 
    output += lineHeightOutputs.join('');
    output += '}\n\n';
  }
 
  // Line Clamp - enum with static let
  if (fontTruncation.length > 0) {
    output += `public enum ${themePrefix}FontLineClamp {\n`;
 
    const truncationOutputs = generateTruncationOutput(
      fontTruncation,
      () => 'lineClamp',
      (propName, value, description) =>
        `    public static let ${propName}: CGFloat = ${value}${formatInlineComment(description)}\n`,
    );
 
    output += truncationOutputs.join('');
    output += '}\n\n';
  }
 
  // Other font tokens (line-clamp, etc.)
  if (fontOther.length > 0) {
    output += `public enum ${themePrefix}FontMisc {\n`;
    fontOther.forEach((token) => {
      const rawValue = getRawValueUnitValue(token);
      const numValue = extractNumber(rawValue);
      const description = getTokenDescription(token);
 
      Eif (numValue !== null) {
        // Convert path segments to valid Swift camelCase
        const propName = token.path
          .slice(3)
          .map((part, index) => {
            const validPart = toValidSwiftName(part);
            if (index === 0) return validPart;
            return validPart.charAt(0).toUpperCase() + validPart.slice(1);
          })
          .join('');
        output += `    public static let ${propName}: CGFloat = ${numValue}${formatInlineComment(description)}\n`;
      }
    });
    output += '}\n';
  }
 
  return output.trimEnd() + '\n';
}
 
// ============================================================================
// COLOR OUTPUT HELPERS
// ============================================================================
//
// Generic function to generate color format with light/dark classes
// Used by System, Semantic, and Reference color formats
//
// ============================================================================
 
/**
 * Generate iOS color format with light/dark mode support
 * @param {object} config - Configuration object
 * @param {Array} config.tokens - All tokens from dictionary
 * @param {Function} config.filterFn - Function to filter tokens for this format
 * @param {string} config.fileHeader - Header comment for the file
 * @param {string} config.classNameLight - Class name for light mode (e.g., 'SystemColorsLight')
 * @param {string} config.classNameDark - Class name for dark mode (e.g., 'SystemColorsDark')
 * @param {Function} config.getRefProperty - Function to get reference property string for a token (refToken, isDark) => string | null
 * @returns {string} - Generated Swift code
 */
function generateColorFormatWithModes({
  tokens,
  filterFn,
  fileHeader,
  classNameLight,
  classNameDark,
  getRefProperty,
}) {
  const colorTokens = tokens.filter(filterFn);
 
  let output = generateFileHeader(fileHeader);
 
  // Use shared helper to process color tokens
  const { lightColors, darkColors } = processColorTokens({
    tokens: colorTokens,
    allTokens: tokens,
    getPropName: (path) => pathToShortPropertyName(path, 'color'),
    getRefProperty,
    resolveColor: (colorValue, allTokens) => {
      const rgb = resolveColorToRGB(colorValue, allTokens);
      return rgb ? toSwiftUIColor(rgb) : null;
    },
    useDarkFallback: true,
  });
 
  // Light Colors Class
  output += `public class ${classNameLight} {\n`;
  lightColors.forEach(({ name, color, description }) => {
    output += `    public static var ${name}: Color { ${color} }${formatInlineComment(description)}\n`;
  });
  output += '}\n\n';
 
  // Dark Colors Class
  output += `public class ${classNameDark} {\n`;
  darkColors.forEach(({ name, color, description }) => {
    output += `    public static var ${name}: Color { ${color} }${formatInlineComment(description)}\n`;
  });
  output += '}\n';
 
  return output;
}
 
// ============================================================================
// SYSTEM COLORS OUTPUT HELPER (Base layer: neutral.base.*, brand.base.*, etc.)
// ============================================================================
//
// System colors are foundational color tokens that semantic colors reference
// - Includes: neutral.base.*, brand.base.*, error.base.*, success.base.*, etc.
// - Preserves references to Reference Colors (slds.r.*)
// - Resolves alias.palette.* tokens to RGB values
// - Separate Light/Dark classes for mode-specific values
// - Path structure: slds.g.color.{family}.base.{scale}
//
// ============================================================================
 
/**
 * Generate system color tokens output for iOS
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Swift code with Light and Dark color classes
 */
function generateSystemColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
 
  return generateColorFormatWithModes({
    tokens,
    filterFn: (token) => !shouldSkipToken(token) && isSystemColorToken(token),
    fileHeader: 'System color design tokens for SwiftUI.',
    classNameLight: `${themePrefix}SystemColorsLight`,
    classNameDark: `${themePrefix}SystemColorsDark`,
    getRefProperty: (refToken, isDark) => {
      if (isReferenceColorToken(refToken)) {
        const refPropName = pathToShortPropertyName(refToken.path, 'color');
        const className = isDark ? `${themePrefix}ReferenceColorsDark` : `${themePrefix}ReferenceColorsLight`;
        return `${className}.${refPropName}`;
      }
      return null;
    },
  });
}
 
// ============================================================================
// SEMANTIC COLORS OUTPUT HELPER (High-level: surface, border, on, etc.)
// ============================================================================
//
// Semantic colors are high-level color tokens for UI elements
// - Includes: surface.*, border.*, on.*, text.*, icon.*, background.*, shadow.*
// - Preserves references to System Colors and Reference Colors
// - Resolves alias.palette.* and slds.g.color.palette.* tokens to RGB
// - Resolves semantic-to-semantic references to RGB (can't use Self with static var)
// - Separate Light/Dark classes for mode-specific values
// - Path structure: slds.g.color.{semantic-category}.{name}
//
// ============================================================================
 
/**
 * Generate semantic color tokens output for iOS
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Swift code with Light and Dark color classes
 */
function generateSemanticColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
 
  return generateColorFormatWithModes({
    tokens,
    filterFn: (token) => !shouldSkipToken(token) && isSemanticColorToken(token),
    fileHeader: 'Semantic color design tokens for SwiftUI.',
    classNameLight: `${themePrefix}SemanticColorsLight`,
    classNameDark: `${themePrefix}SemanticColorsDark`,
    getRefProperty: (refToken, isDark) => {
      if (isSystemColorToken(refToken)) {
        const refPropName = pathToShortPropertyName(refToken.path, 'color');
        const className = isDark ? `${themePrefix}SystemColorsDark` : `${themePrefix}SystemColorsLight`;
        return `${className}.${refPropName}`;
      }
      if (isReferenceColorToken(refToken)) {
        const refPropName = pathToShortPropertyName(refToken.path, 'color');
        const className = isDark ? `${themePrefix}ReferenceColorsDark` : `${themePrefix}ReferenceColorsLight`;
        return `${className}.${refPropName}`;
      }
      Iif (isSemanticColorToken(refToken)) {
        // Reference to another semantic color in the same class (static)
        const refPropName = pathToShortPropertyName(refToken.path, 'color');
        return `Self.${refPropName}`;
      }
      // Everything else resolves to RGB
      return null;
    },
  });
}
 
// ============================================================================
// REFERENCE COLORS OUTPUT HELPER (Theming layer: slds.r.* tokens)
// ============================================================================
//
// Reference colors (slds.r.*) are theming tokens that map to palette colors.
// Unlike System and Semantic colors, these ALWAYS resolve to RGB values rather
// than preserving references. This is intentional because:
// 1. They represent the final themeable color values
// 2. They reference alias.palette.* tokens which aren't output in iOS
// 3. They serve as the boundary between the design system and consumer themes
//
// ============================================================================
 
/**
 * Generate reference color tokens output for iOS
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Swift code with Light and Dark color classes
 */
function generateReferenceColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
 
  return generateColorFormatWithModes({
    tokens,
    filterFn: (token) => !shouldSkipToken(token) && isReferenceColorToken(token),
    fileHeader: 'Reference color design tokens for SwiftUI theming.',
    classNameLight: `${themePrefix}ReferenceColorsLight`,
    classNameDark: `${themePrefix}ReferenceColorsDark`,
    // Always return null to resolve all references to RGB
    getRefProperty: () => null,
  });
}
 
// ============================================================================
// PALETTE COLORS OUTPUT HELPER (Light/Dark enums per color family)
// ============================================================================
//
// Palette colors are raw color values organized by color family
// - Includes: blue, red, neutral, green, etc. palette families
// - Always resolves to RGB values (no references preserved)
// - Separate Light/Dark enums for each color family
// - Uses static let for constant values
// - Path structure: slds.g.color.palette.{family}.{scale}
//
// ============================================================================
 
/**
 * Generate palette color tokens output for iOS
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Swift code with Light and Dark color enums per palette family
 */
function generatePaletteColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
  // Filter for slds.g.color.palette.* tokens, not alias.palette.*
  const paletteTokens = tokens.filter(
    (token) =>
      token.path[0] === 'slds' &&
      token.path[1] === 'g' &&
      token.path[2] === 'color' &&
      token.path[3] === 'palette',
  );
 
  let output = generateFileHeader('Palette color design tokens for SwiftUI.');
 
  // Group by palette family (blue, red, neutral, etc.)
  const paletteFamilies = new Map();
 
  paletteTokens.forEach((token) => {
    Iif (shouldSkipToken(token)) return;
 
    const family = getPaletteFamily(token.path);
    Iif (!family) return;
 
    if (!paletteFamilies.has(family)) {
      paletteFamilies.set(family, { light: [], dark: [] });
    }
 
    const tokenValue = getRawValueUnitValue(token);
    const darkValue =
      token.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value ||
      token.original?.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value;
    const description = getTokenDescription(token);
 
    // Get the scale number (e.g., '50' from palette.blue.50)
    const scale = token.path[5];
 
    // Get light color
    const lightRGB = resolveColorToRGB(tokenValue, tokens);
    Eif (lightRGB) {
      paletteFamilies.get(family).light.push({
        name: `${family}${scale}`,
        color: toSwiftUIColor(lightRGB),
        description,
      });
    }
 
    // Get dark color
    const darkRGB = darkValue ? resolveColorToRGB(darkValue, tokens) : lightRGB;
    Eif (darkRGB) {
      paletteFamilies.get(family).dark.push({
        name: `${family}${scale}`,
        color: toSwiftUIColor(darkRGB),
        description,
      });
    }
  });
 
  // Generate enums for each palette family
  const sortedFamilies = [...paletteFamilies.keys()].sort();
 
  sortedFamilies.forEach((family) => {
    const familyName = family.charAt(0).toUpperCase() + family.slice(1);
    const { light, dark } = paletteFamilies.get(family);
 
    // Light palette enum
    output += `public enum ${themePrefix}${familyName}PaletteLight {\n`;
    light.forEach(({ name, color, description }) => {
      output += `    public static let ${name} = ${color}${formatInlineComment(description)}\n`;
    });
    output += '}\n\n';
 
    // Dark palette enum - only create if there are dark colors
    Eif (dark.length > 0) {
      output += `public enum ${themePrefix}${familyName}PaletteDark {\n`;
      dark.forEach(({ name, color, description }) => {
        output += `    public static let ${name} = ${color}${formatInlineComment(description)}\n`;
      });
      output += '}\n\n';
    }
  });
 
  return output.trimEnd() + '\n';
}
 
// ============================================================================
// COMBINED FORMAT (all tokens in one file for comparison)
// ============================================================================
 
/**
 * Helper to extract the content after the file header from a format output
 * Removes everything up to and including the first blank line after imports
 */
function stripFileHeader(content) {
  // Find the end of imports (Foundation import line) and skip to content
  const lines = content.split('\n');
  let startIndex = 0;
 
  for (let i = 0; i < lines.length; i++) {
    if (lines[i].startsWith('import Foundation')) {
      // Skip the blank line after imports
      startIndex = i + 2;
      break;
    }
  }
 
  return lines.slice(startIndex).join('\n');
}
 
export const iosTokensAllFormat = ({ dictionary, options }) => {
  const { themePrefix = 'SalesforceCosmos' } = options || {};
  let output = generateFileHeader('All design tokens combined for comparison.');
 
  const tokenTypes = [
    'spacing',
    'sizing',
    'shapes',
    'motion-duration',
    'fonts',
    'system-colors',
    'reference-colors',
    'semantic-colors',
    'palette-colors',
  ];
  const sectionLabels = [
    'Spacing',
    'Sizing',
    'Shapes',
    'Motion Duration',
    'Fonts',
    'System Colors',
    'Reference Colors',
    'Semantic Colors',
    'Palette Colors',
  ];
 
  tokenTypes.forEach((tokenType, index) => {
    if (index > 0) output += '\n';
    output += `// MARK: - ${sectionLabels[index]}\n\n`;
    output += stripFileHeader(iosFormat({ dictionary, options: { tokenType, themePrefix } }));
  });
 
  return output;
};
 
// Mark formats as nested to avoid collision warnings
iosTokensAllFormat.nested = true;
 
// ============================================================================
// UNIFIED MOBILE FORMAT
// ============================================================================
 
/**
 * Unified iOS format that routes to appropriate rendering based on tokenType option.
 * Uses pre-filtered tokens from Style Dictionary file-level filters.
 *
 * @param {object} params - Format parameters
 * @param {object} params.dictionary - Style Dictionary dictionary object
 * @param {object} params.options - Options object containing tokenType
 * @param {string} params.options.tokenType - Type of tokens to format (spacing, sizing, shapes, etc.)
 * @returns {string} - Formatted output for the specified token type
 */
export const iosFormat = ({ dictionary, options }) => {
  const tokens = dictionary.allTokens;
  const { tokenType, themePrefix = 'SalesforceCosmos' } = options || {};
 
  Iif (!tokenType) {
    throw new Error('[iosFormat] options.tokenType is required');
  }
 
  switch (tokenType) {
    case 'spacing':
      return generateDimensionOutput({
        tokens,
        category: CATEGORY.SPACING,
        fileHeader: generateFileHeader('Spacing design tokens for SwiftUI.'),
        objectName: `${themePrefix}Spacing`,
        config: IOS_DIMENSION_CONFIG,
        pathToPropertyName: pathToShortPropertyName,
        shouldPreserveRef: shouldPreserveReference,
      });
 
    case 'sizing':
      return generateDimensionOutput({
        tokens,
        category: CATEGORY.SIZING,
        fileHeader: generateFileHeader('Sizing design tokens for SwiftUI.'),
        objectName: `${themePrefix}Sizing`,
        config: IOS_DIMENSION_CONFIG,
        pathToPropertyName: pathToShortPropertyName,
        shouldPreserveRef: shouldPreserveReference,
      });
 
    case 'shapes':
      return generateDimensionOutput({
        tokens,
        category: CATEGORY.RADIUS,
        fileHeader: generateFileHeader('Shape/radius design tokens for SwiftUI.'),
        objectName: `${themePrefix}Shapes`,
        config: IOS_DIMENSION_CONFIG,
        pathToPropertyName: pathToShortPropertyName,
        shouldPreserveRef: shouldPreserveReference,
      });
 
    case 'motion-duration':
      return generateDurationOutput({
        tokens,
        fileHeader: generateFileHeader('Motion/duration design tokens for SwiftUI.'),
        objectName: `${themePrefix}MotionDuration`,
        config: IOS_DURATION_CONFIG,
        pathToPropertyName: pathToShortPropertyName,
        convertDuration: convertDurationToSeconds,
        shouldPreserveRef: shouldPreserveReference,
      });
 
    case 'fonts':
      return generateFontsOutput({ dictionary, themePrefix });
 
    case 'system-colors':
      return generateSystemColorsOutput({ dictionary, themePrefix });
 
    case 'semantic-colors':
      return generateSemanticColorsOutput({ dictionary, themePrefix });
 
    case 'reference-colors':
      return generateReferenceColorsOutput({ dictionary, themePrefix });
 
    case 'palette-colors':
      return generatePaletteColorsOutput({ dictionary, themePrefix });
 
    default:
      throw new Error(`[iosFormat] Unknown tokenType: ${tokenType}`);
  }
};
 
iosFormat.nested = true;
 
// Export for testing
export const _testExports = {
  // Constants
  PATH_INDEX,
  CATEGORY,
  COLOR_SUBCATEGORY,
  COLOR_MODIFIER,
  FONT_SUBCATEGORY,
  FONT_MODIFIER,
  NAMESPACE,
  SCOPE,
  TOKEN_TYPE_DESCRIPTORS,
  // Helper functions
  getPathSegment,
  validateTokenPath,
  getTokenTypeDescriptor,
  shouldPreserveReferences,
  shouldPreserveReference,
  pathToShortPropertyName,
  getFontPropertyName,
  getPaletteFamily,
  isAliasPaletteToken,
  oklchToRGB,
  hexToRGB,
  toSwiftUIColor,
  resolveColorToRGB,
  colorToRGB,
  toValidSwiftName,
  pathToScopedFontPropertyName,
  stripFileHeader,
  generateColorFormatWithModes,
};