Bin
2025-12-16 7423b0c6e1959f30a7e8e453e953310f32ce13c6
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
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
 
const camelCase = (str) => {
  return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
};
 
// Get current file directory for resolving paths
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const RAW_COLOR_VALUE_TOKENS = ["primary", "shadow", "outline", "surface", "accent", "background"];
 
const shouldGenerateRawColorValue = (name) => {
  return RAW_COLOR_VALUE_TOKENS.some((token) => name.includes(token));
};
 
// Determine correct paths for the workspace
const findWorkspaceRoot = () => {
  // We'll start with this file's directory and go up until we find the web directory
  let currentDir = __dirname;
  while (!currentDir.endsWith("web") && currentDir !== "/") {
    currentDir = path.dirname(currentDir);
  }
 
  if (!currentDir.endsWith("web")) {
    throw new Error("Could not find workspace root directory");
  }
 
  return currentDir;
};
 
const workspaceRoot = findWorkspaceRoot();
 
// Paths
const designVariablesPath = path.join(workspaceRoot, "design-tokens.json");
const cssOutputPath = path.join(workspaceRoot, "libs/ui/src/tokens/tokens.scss");
const jsOutputPath = path.join(workspaceRoot, "libs/ui/src/tokens/tokens.js");
 
/**
 * Convert a value to rem units rounded to 4 decimal places no trailing zeros
 * @param {string} value - The value to convert
 * @returns {string} - The converted value in rem units
 */
function convertToRem(value) {
  const remValue = (Number(value) / 16).toFixed(4).replace(/\.?0+$/, "");
  // Ensure 0 is returned as a unitless value
  if (remValue === "0") {
    return remValue;
  }
  return `${remValue}rem`;
}
 
/**
 * Process design variables and extract tokens
 * @param {Object} variables - The design variables object
 * @returns {Object} - Object containing tokens for CSS and JavaScript
 */
function processDesignVariables(variables) {
  const result = {
    cssVariables: {
      light: [],
      dark: [],
    },
    jsTokens: {
      colors: {},
      spacing: {},
      typography: {},
      cornerRadius: {},
    },
  };
 
  // Process colors
  if (variables["@color"] && variables["@color"].$color) {
    processColorTokens(variables["@color"].$color, "", result, variables);
  }
  // Process primitives
  if (variables["@primitives"] && variables["@primitives"].$color) {
    processPrimitiveColors(variables["@primitives"].$color, result, variables);
  }
 
  // Process primitive spacing
  if (variables["@primitives"] && variables["@primitives"].$spacing) {
    processPrimitiveSpacing(variables["@primitives"].$spacing, result);
  }
 
  // Process primitive typography
  if (variables["@primitives"] && variables["@primitives"].$typography) {
    processPrimitiveTypography(variables["@primitives"].$typography, result);
  }
 
  // Process primitive corner-radius
  if (variables["@primitives"] && variables["@primitives"]["$corner-radius"]) {
    processPrimitiveCornerRadius(variables["@primitives"]["$corner-radius"], result);
  }
 
  // Process sizing tokens
  if (variables["@sizing"]) {
    processSizingTokens(variables["@sizing"], result, variables);
  }
 
  // Process typography
  if (variables["@typography"]) {
    processTypographyTokens(variables["@typography"], result, variables);
  }
 
  // Post-process for Tailwind compatibility
  result.jsTokens.colors = transformColorObjectForTailwind(result.jsTokens.colors);
 
  return result;
}
 
/**
 * Process primitive spacing tokens
 * @param {Object} spacingObj - The spacing object from primitives
 * @param {Object} result - The result object to populate
 */
function processPrimitiveSpacing(spacingObj, result) {
  for (const key in spacingObj) {
    if (spacingObj[key].$type === "number" && spacingObj[key].$value !== undefined) {
      const name = key.replace("$", "");
      const value = spacingObj[key].$value;
      const cssVarName = `--spacing-${name}`;
 
      // Add to CSS variables
      result.cssVariables.light.push(`${cssVarName}: ${convertToRem(value)};`);
 
      // Add to JavaScript tokens
      if (!result.jsTokens.spacing.primitive) {
        result.jsTokens.spacing.primitive = {};
      }
 
      result.jsTokens.spacing.primitive[name] = `var(${cssVarName})`;
    }
  }
}
 
/**
 * Process primitive typography tokens
 * @param {Object} typographyObj - The typography object from primitives
 * @param {Object} result - The result object to populate
 */
function processPrimitiveTypography(typographyObj, result) {
  // Process font sizes
  if (typographyObj["$font-size"]) {
    for (const key in typographyObj["$font-size"]) {
      if (
        typographyObj["$font-size"][key].$type === "number" &&
        typographyObj["$font-size"][key].$value !== undefined
      ) {
        const name = key.replace("$", "");
        const value = typographyObj["$font-size"][key].$value;
        const cssVarName = `--font-size-${name}`;
 
        // Add to CSS variables
        result.cssVariables.light.push(`${cssVarName}: ${convertToRem(value)};`);
 
        // Add to JavaScript tokens
        if (!result.jsTokens.typography.fontSize) {
          result.jsTokens.typography.fontSize = {};
        }
        if (!result.jsTokens.typography.fontSize.primitive) {
          result.jsTokens.typography.fontSize.primitive = {};
        }
        result.jsTokens.typography.fontSize.primitive[name] = `var(${cssVarName})`;
      }
    }
  }
 
  // Process font weights
  if (typographyObj["$font-weight"]) {
    for (const key in typographyObj["$font-weight"]) {
      if (
        typographyObj["$font-weight"][key].$type === "number" &&
        typographyObj["$font-weight"][key].$value !== undefined
      ) {
        const name = key.replace("$", "");
        const value = typographyObj["$font-weight"][key].$value;
        const cssVarName = `--font-weight-${name}`;
 
        // Add to CSS variables
        result.cssVariables.light.push(`${cssVarName}: ${value};`);
 
        // Add to JavaScript tokens
        if (!result.jsTokens.typography.fontWeight) {
          result.jsTokens.typography.fontWeight = {};
        }
        if (!result.jsTokens.typography.fontWeight.primitive) {
          result.jsTokens.typography.fontWeight.primitive = {};
        }
        result.jsTokens.typography.fontWeight.primitive[name] = `var(${cssVarName})`;
      }
    }
  }
 
  // Process line heights
  if (typographyObj["$line-height"]) {
    for (const key in typographyObj["$line-height"]) {
      if (
        typographyObj["$line-height"][key].$type === "number" &&
        typographyObj["$line-height"][key].$value !== undefined
      ) {
        const name = key.replace("$", "");
        const value = typographyObj["$line-height"][key].$value;
        const cssVarName = `--line-height-${name}`;
 
        // Add to CSS variables
        result.cssVariables.light.push(`${cssVarName}: ${convertToRem(value)};`);
 
        // Add to JavaScript tokens
        if (!result.jsTokens.typography.lineHeight) {
          result.jsTokens.typography.lineHeight = {};
        }
        if (!result.jsTokens.typography.lineHeight.primitive) {
          result.jsTokens.typography.lineHeight.primitive = {};
        }
        result.jsTokens.typography.lineHeight.primitive[name] = `var(${cssVarName})`;
      }
    }
  }
 
  // Process letter spacing
  if (typographyObj["$letter-spacing"]) {
    for (const key in typographyObj["$letter-spacing"]) {
      if (
        typographyObj["$letter-spacing"][key].$type === "number" &&
        typographyObj["$letter-spacing"][key].$value !== undefined
      ) {
        const name = key.replace("$", "");
        const value = typographyObj["$letter-spacing"][key].$value;
        const cssVarName = `--letter-spacing-${name}`;
 
        // Add to CSS variables
        result.cssVariables.light.push(`${cssVarName}: ${convertToRem(value)};`);
 
        // Add to JavaScript tokens
        if (!result.jsTokens.typography.letterSpacing) {
          result.jsTokens.typography.letterSpacing = {};
        }
        if (!result.jsTokens.typography.letterSpacing.primitive) {
          result.jsTokens.typography.letterSpacing.primitive = {};
        }
        result.jsTokens.typography.letterSpacing.primitive[name] = `var(${cssVarName})`;
      }
    }
  }
 
  // Process font families
  if (typographyObj["$font-family"]) {
    for (const key in typographyObj["$font-family"]) {
      if (typographyObj["$font-family"][key].$value !== undefined) {
        const name = key.replace("$", "");
        const value = typographyObj["$font-family"][key].$value;
        const cssVarName = `--font-family-${name}`;
 
        // Add to CSS variables
        result.cssVariables.light.push(`${cssVarName}: "${value}";`);
 
        // Add to JavaScript tokens
        if (!result.jsTokens.typography.fontFamily) {
          result.jsTokens.typography.fontFamily = {};
        }
        if (!result.jsTokens.typography.fontFamily.primitive) {
          result.jsTokens.typography.fontFamily.primitive = {};
        }
        result.jsTokens.typography.fontFamily.primitive[name] = `var(${cssVarName})`;
      }
    }
  }
}
 
/**
 * Process primitive corner radius tokens
 * @param {Object} cornerRadiusObj - The corner radius object from primitives
 * @param {Object} result - The result object to populate
 */
function processPrimitiveCornerRadius(cornerRadiusObj, result) {
  for (const key in cornerRadiusObj) {
    if (cornerRadiusObj[key].$type === "number" && cornerRadiusObj[key].$value !== undefined) {
      const name = key.replace("$", "");
      const value = cornerRadiusObj[key].$value;
      const cssVarName = `--corner-radius-${name}`;
 
      let resolvedValue;
      if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
        const reference = value.substring(1, value.length - 1);
        const parts = reference.split(".");
 
        // If it's a reference to a primitive spacing value, directly use the corresponding CSS variable
        if (parts[0] === "@primitives") {
          const collectionKey = parts[1].replace("$", "");
          const valueKey = parts[2].replace("$", "");
          resolvedValue = `var(--${collectionKey}-${valueKey})`;
          result.cssVariables.light.push(`${cssVarName}: ${resolvedValue};`);
        } else {
          // Otherwise, try to resolve the value normally
          resolvedValue = resolveReference(value, variables);
          result.cssVariables.light.push(`${cssVarName}: ${convertToRem(resolvedValue)};`);
        }
      } else {
        // Not a reference, use directly
        resolvedValue = value;
        result.cssVariables.light.push(`${cssVarName}: ${convertToRem(resolvedValue)};`);
      }
 
      // Add to JavaScript tokens
      if (!result.jsTokens.cornerRadius.primitive) {
        result.jsTokens.cornerRadius.primitive = {};
      }
      result.jsTokens.cornerRadius.primitive[name] = `var(${cssVarName})`;
    }
  }
}
 
/**
 * Process sizing tokens from design variables
 * @param {Object} sizingObj - The spacing object from design variables
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 * @param {String} parentKey - The parent key for nested tokens
 */
function processSizingTokens(sizingObj, result, variables, parentKey = "") {
  for (const key in sizingObj) {
    if (key.startsWith("$")) {
      // process nested keys
      processSizingTokens(
        sizingObj[key],
        result,
        variables,
        // Fix the variable name from corder to corner
        `${parentKey ? `${parentKey}-` : ""}${key.replace(/\$/g, "").replace("corder", "corner")}`,
      );
      continue;
    }
 
    if (sizingObj[key].$type === "number" && sizingObj[key].$value !== undefined) {
      const name = key.replace("$", "");
      const value = sizingObj[key].$value;
      const tokenKey = parentKey || key;
      const jsTokenKey = camelCase(tokenKey.replace("$", ""));
      const cssVarName = `--${tokenKey}-${name}`;
 
      let resolvedValue;
      if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
        const reference = value.substring(1, value.length - 1);
        const parts = reference.split(".");
 
        // If it's a reference to a primitive spacing value, directly use the corresponding CSS variable
        if (parts[0] === "@primitives") {
          const collectionKey = parts[1].replace("$", "");
          const valueKey = parts[2].replace("$", "");
          resolvedValue = `var(--${collectionKey}-${valueKey})`;
          result.cssVariables.light.push(`${cssVarName}: ${resolvedValue};`);
        } else {
          // Otherwise, try to resolve the value normally
          resolvedValue = resolveReference(value, variables);
          result.cssVariables.light.push(`${cssVarName}: ${convertToRem(resolvedValue)};`);
        }
      } else {
        // Not a reference, use directly
        resolvedValue = value;
        result.cssVariables.light.push(`${cssVarName}: ${convertToRem(resolvedValue)};`);
      }
 
      // Add to JavaScript tokens
      if (!result.jsTokens[jsTokenKey]) {
        result.jsTokens[jsTokenKey] = {};
      }
 
      result.jsTokens[jsTokenKey][name] = `var(${cssVarName})`;
    }
  }
}
 
function processTokenCollection(collectionKey, subCollectionKey) {
  const collectionJsKey = camelCase(collectionKey);
  const subCollectionJsKey = camelCase(subCollectionKey);
  const subCollectionKeyRegex = new RegExp(`${subCollectionKey}\\-?`, "g");
  return function process(tokenCollection, result, variables, parentKey = subCollectionKey) {
    for (const key in tokenCollection) {
      if (key.startsWith("$")) {
        // process nested keys
        process(tokenCollection[key], result, variables, `${parentKey ? `${parentKey}-` : ""}${key.replace("$", "")}`);
        continue;
      }
 
      if (tokenCollection[key].$value !== undefined) {
        const isNumber = tokenCollection[key].$type === "number";
        const name = key.replace("$", "");
        const value = tokenCollection[key].$value;
        const cssVarName = `--${parentKey}-${name}`;
 
        let resolvedValue;
        if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
          const reference = value.substring(1, value.length - 1);
          const parts = reference.replace(`$${collectionKey}.`, "").split(".");
 
          // If it's a reference to a primitive spacing value, directly use the corresponding CSS variable
          if (parts[0] === "@primitives") {
            const collectionKey = parts[1].replace("$", "");
            const valueKey = parts[2].replace("$", "");
            resolvedValue = `var(--${collectionKey}-${valueKey})`;
            result.cssVariables.light.push(`${cssVarName}: ${resolvedValue};`);
          } else {
            // Otherwise, try to resolve the value normally
            resolvedValue = resolveReference(value, variables);
            result.cssVariables.light.push(`${cssVarName}: ${isNumber ? convertToRem(resolvedValue) : resolvedValue};`);
          }
        } else {
          // Not a reference, use directly
          resolvedValue = value;
          result.cssVariables.light.push(`${cssVarName}: ${resolvedValue};`);
        }
 
        // Add to JavaScript tokens
        if (!result.jsTokens[collectionJsKey]) {
          result.jsTokens[collectionJsKey] = {};
        }
        if (!result.jsTokens[collectionJsKey][subCollectionJsKey]) {
          result.jsTokens[collectionJsKey][subCollectionJsKey] = {};
        }
        const jsKey = `${parentKey ? `${parentKey}-` : ""}${name}`;
        result.jsTokens[collectionJsKey][subCollectionJsKey][jsKey.replace(subCollectionKeyRegex, "")] =
          `var(${cssVarName})`;
      }
    }
  };
}
 
/**
 * Process font size tokens
 * @param {Object} fontSizeObj - The font size object from typography
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 * @param {String} parentKey - The parent key for nested tokens
 */
const processFontSizeTokens = processTokenCollection("typography", "font-size");
 
/**
 * Process font weight tokens
 * @param {Object} fontWeightObj - The font weight object from typography
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 */
const processFontWeightTokens = processTokenCollection("typography", "font-weight");
 
/**
 * Process line height tokens
 * @param {Object} lineHeightObj - The line height object from typography
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 */
const processLineHeightTokens = processTokenCollection("typography", "line-height");
 
/**
 * Process letter spacing tokens
 * @param {Object} letterSpacingObj - The letter spacing object from typography
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 */
const processLetterSpacingTokens = processTokenCollection("typography", "letter-spacing");
 
/**
 * Process font family tokens
 * @param {Object} fontObj - The font family object from typography
 * @param {Object} result - The result object to populate
 */
const processFontFamilyTokens = processTokenCollection("typography", "font-family");
 
/**
 * Process typography tokens from design variables
 * @param {Object} typographyObj - The typography object from design variables
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 */
function processTypographyTokens(typographyObj, result, variables) {
  // Process font families
  if (typographyObj["$font-family"]) {
    processFontFamilyTokens(typographyObj["$font-family"], result, variables);
  }
 
  // Process font sizes
  if (typographyObj["$font-size"]) {
    processFontSizeTokens(typographyObj["$font-size"], result, variables);
  }
 
  // Process font weights
  if (typographyObj["$font-weight"]) {
    processFontWeightTokens(typographyObj["$font-weight"], result, variables);
  }
 
  // Process line heights
  if (typographyObj["$line-height"]) {
    processLineHeightTokens(typographyObj["$line-height"], result, variables);
  }
 
  // Process letter spacing
  if (typographyObj["$letter-spacing"]) {
    processLetterSpacingTokens(typographyObj["$letter-spacing"], result, variables);
  }
}
 
/**
 * Process color tokens from design variables
 * @param {Object} colorObj - The color object from design variables
 * @param {String} parentPath - The parent path for nesting
 * @param {Object} result - The result object to populate
 */
function processColorTokens(colorObj, parentPath, result, variables) {
  for (const key in colorObj) {
    if (typeof colorObj[key] === "object" && !Array.isArray(colorObj[key])) {
      const newPath = parentPath ? `${parentPath}-${key.replace(/\$/g, "")}` : key.replace(/\$/g, "");
 
      // If this is a color token with value and type
      if (colorObj[key].$type === "color" && colorObj[key].$value) {
        const name = parentPath ? `${parentPath}-${key.replace(/\$/g, "")}` : key.replace(/\$/g, "");
        const value = colorObj[key].$value;
        const cssVarName = `--color-${name.replace(/\$/g, "")}`;
 
        // Add to CSS variables for light mode
        if (
          colorObj[key].$variable_metadata &&
          colorObj[key].$variable_metadata.modes &&
          colorObj[key].$variable_metadata.modes.light
        ) {
          const lightValue = resolveColor(colorObj[key].$variable_metadata.modes.light, variables);
          result.cssVariables.light.push(`${cssVarName}: ${lightValue};`);
 
          if (shouldGenerateRawColorValue(name)) {
            const rawRgbValues = hexToRgbRaw(colorObj[key].$variable_metadata.modes.light, variables);
            result.cssVariables.light.push(`${cssVarName}-raw: ${rawRgbValues};`);
          }
        } else {
          const resolvedValue = resolveColor(value, variables);
          result.cssVariables.light.push(`${cssVarName}: ${resolvedValue};`);
 
          if (shouldGenerateRawColorValue(name)) {
            const rawRgbValues = hexToRgbRaw(value, variables);
            result.cssVariables.light.push(`${cssVarName}-raw: ${rawRgbValues};`);
          }
        }
 
        // Add to CSS variables for dark mode
        if (
          colorObj[key].$variable_metadata &&
          colorObj[key].$variable_metadata.modes &&
          colorObj[key].$variable_metadata.modes.dark
        ) {
          const darkValue = resolveColor(colorObj[key].$variable_metadata.modes.dark, variables);
          result.cssVariables.dark.push(`${cssVarName}: ${darkValue};`);
 
          if (shouldGenerateRawColorValue(name)) {
            const rawRgbValues = hexToRgbRaw(colorObj[key].$variable_metadata.modes.dark, variables);
            result.cssVariables.dark.push(`${cssVarName}-raw: ${rawRgbValues};`);
          }
        }
 
        // Add to JavaScript tokens
        addToJsTokens(result.jsTokens.colors, name.replace(/\$/g, ""), cssVarName);
      } else {
        // Recursively process nested color objects
        processColorTokens(colorObj[key], newPath, result, variables);
      }
    }
  }
}
 
/**
 * Process primitive colors
 * @param {Object} primitiveColors - The primitive colors object
 * @param {Object} result - The result object to populate
 * @param {Object} variables - The variables object for reference resolution
 */
function processPrimitiveColors(primitiveColors, result, variables) {
  for (const colorFamily in primitiveColors) {
    const familyName = colorFamily.replace("$", "");
 
    for (const shade in primitiveColors[colorFamily]) {
      try {
        if (primitiveColors[colorFamily][shade].$type === "color" && primitiveColors[colorFamily][shade].$value) {
          const name = `${familyName}-${shade}`;
          const value = primitiveColors[colorFamily][shade].$value;
          const cssVarName = `--color-${name}`;
 
          // Add to CSS variables, converting to RGB format for opacity support
          const rgbValue = hexToRgb(value);
          result.cssVariables.light.push(`${cssVarName}: ${rgbValue};`);
 
          // Add raw RGB values for primitives to support translucent colors
          // if dark mode is available
          if (
            primitiveColors[colorFamily][shade].$variable_metadata &&
            primitiveColors[colorFamily][shade].$variable_metadata.modes &&
            primitiveColors[colorFamily][shade].$variable_metadata.modes.dark
          ) {
            const rawRgbValues = hexToRgbRaw(value);
            result.cssVariables.light.push(`${cssVarName}-raw: ${rawRgbValues};`);
 
            const darkValue = primitiveColors[colorFamily][shade].$variable_metadata.modes.dark;
            const darkRgbValue = hexToRgb(darkValue);
            result.cssVariables.dark.push(`${cssVarName}: ${darkRgbValue};`);
 
            // Add raw RGB values for dark mode
            const darkRawRgbValues = hexToRgbRaw(darkValue);
            result.cssVariables.dark.push(`${cssVarName}-raw: ${darkRawRgbValues};`);
          }
 
          // Add to JavaScript tokens
          if (!result.jsTokens.colors.primitive) {
            result.jsTokens.colors.primitive = {};
          }
          if (!result.jsTokens.colors.primitive[familyName]) {
            result.jsTokens.colors.primitive[familyName] = {};
          }
 
          result.jsTokens.colors.primitive[familyName][shade] = `var(${cssVarName})`;
        }
      } catch (error) {
        console.warn(`Warning: Error processing primitive color ${colorFamily}.${shade}:`, error.message);
      }
    }
  }
}
 
/**
 * Convert hex color to RGB format for opacity support
 * @param {string} hex - Hex color code
 * @returns {string} - RGB color format as rgb(r, g, b) or raw r g b
 * @param {boolean} raw - Whether to return the raw RGB values
 */
function hexToRgb(hex, raw = false) {
  // Check if it's already in rgb/rgba format
  if (hex.startsWith("rgb")) {
    return raw ? hex.replace("rgb(", "").replace(")", "") : hex;
  }
 
  // Remove # if present
  hex = hex.replace(/^#/, "");
 
  // Parse the hex values
  let r;
  let g;
  let b;
  if (hex.length === 3) {
    // Convert 3-digit hex to 6-digit
    r = Number.parseInt(hex[0] + hex[0], 16);
    g = Number.parseInt(hex[1] + hex[1], 16);
    b = Number.parseInt(hex[2] + hex[2], 16);
  } else if (hex.length === 6) {
    r = Number.parseInt(hex.substring(0, 2), 16);
    g = Number.parseInt(hex.substring(2, 4), 16);
    b = Number.parseInt(hex.substring(4, 6), 16);
  } else {
    // Invalid hex, return as is
    return hex;
  }
 
  // Return RGB format
  return raw ? `${r} ${g} ${b}` : `rgb(${r} ${g} ${b})`;
}
 
/**
 * Convert hex color to raw RGB values for translucent color support
 * @param {string} hex - Hex color code or reference
 * @param {Object} variables - Variables for resolving references
 * @returns {string} - Raw RGB values as "r g b"
 */
function hexToRgbRaw(hex, variables) {
  // If it's a reference, try to resolve it
  if (typeof hex === "string" && hex.startsWith("{") && hex.endsWith("}") && variables) {
    const resolvedValue = resolveReference(hex, variables);
    if (resolvedValue !== hex) {
      return hexToRgbRaw(resolvedValue);
    }
  }
 
  // Check if it's already in rgb/rgba format
  if (typeof hex === "string" && hex.startsWith("rgb")) {
    // Extract the RGB values from the rgb() format
    const match = hex.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
    if (match) {
      return `${match[1]} ${match[2]} ${match[3]}`;
    }
    return hex;
  }
 
  if (typeof hex === "string") {
    return hexToRgb(hex, true);
  }
 
  return hex;
}
 
/**
 * Resolve color values, handling references to other variables
 * @param {String} value - The color value to resolve
 * @param {Object} variables - The variables object for reference resolution
 * @param {Boolean} asCssVariable - Whether to return the value as a CSS variable
 * @returns {String} - The resolved color value
 */
function resolveColor(value, variables, asCssVariable = true) {
  if (typeof value !== "string") return value;
 
  // Handle references like "{@primitives.$color.$sand.100}"
  if (value.startsWith("{") && value.endsWith("}")) {
    const reference = value.substring(1, value.length - 1);
    const parts = reference.split(".");
 
    if (asCssVariable) {
      // Remove 'primitive' from CSS variable references
      if (reference.startsWith("@primitives.$color")) {
        return `var(--color-${reference.replace("@primitives.$color.", "").replace(/[$\.]/g, "-").substring(1)})`;
      }
      return `var(--color-${reference
        .replace("@primitives.", "")
        .replace("$color.", "")
        .replace(/[$\.]/g, "-")
        .substring(1)})`;
    }
 
    // Navigate through the object to find the referenced value
    let current = variables;
    for (const part of parts) {
      if (current[part]) {
        current = current[part];
      } else {
        // If we can't resolve, return the CSS variable equivalent
        if (reference.startsWith("@primitives.$color")) {
          return `var(--color-${reference.replace("@primitives.$color.", "").replace(/[$\.]/g, "-").substring(1)})`;
        }
        return `var(--color-${reference.replace(/[@$\.]/g, "-").substring(1)})`;
      }
    }
 
    if (current.$value) {
      return hexToRgb(current.$value);
    }
 
    return value;
  }
 
  // Convert direct color values to RGB
  return hexToRgb(value);
}
 
/**
 * Resolve references to other variables
 * @param {String|Number} value - The value to resolve
 * @param {Object} variables - The variables object for reference resolution
 * @returns {String|Number} - The resolved value
 */
function resolveReference(value, variables) {
  if (typeof value !== "string") return value;
 
  // Handle references like "{@sizing.$spacing.base}"
  if (value.startsWith("{") && value.endsWith("}")) {
    const reference = value.substring(1, value.length - 1);
    const parts = reference.split(".");
 
    // Navigate through the object to find the referenced value
    let current = variables;
    for (const part of parts) {
      if (current[part]) {
        current = current[part];
      } else {
        // If we can't resolve, return the original value
        return value;
      }
    }
 
    if (current.$value !== undefined) {
      return current.$value;
    }
 
    return value;
  }
 
  return value;
}
 
/**
 * Add a token to the JavaScript tokens object
 * @param {Object} obj - The object to add to
 * @param {String} path - The path to add at
 * @param {String} cssVarName - The CSS variable name
 */
function addToJsTokens(obj, path, cssVarName) {
  const parts = path.split("-");
  let current = obj;
 
  // Handle the case where we have nested properties like "surface-hover"
  // which should be transformed to obj.surface.hover
  for (let i = 0; i < parts.length - 1; i++) {
    const part = parts[i];
 
    // Check if this is a terminal value (string) that we're trying to add properties to
    if (typeof current[part] === "string") {
      // Create a new object to replace the string value
      const oldValue = current[part];
      current[part] = {
        DEFAULT: oldValue,
      };
    } else if (!current[part]) {
      current[part] = {};
    }
 
    current = current[part];
  }
 
  const lastPart = parts[parts.length - 1];
 
  // If lastPart is something like "hover" and we're dealing with "surface-hover",
  // we should set it as a property of the "surface" object
  current[lastPart] = `var(${cssVarName})`;
}
 
/**
 * Generate CSS content
 * @param {Object} result - The processed tokens
 * @returns {String} - The CSS content
 */
function generateCssContent(result) {
  let content = "// Generated from design-tokens.json - DO NOT EDIT DIRECTLY\n\n";
 
  // Light mode variables (default)
  content += ":root {\n";
  result.cssVariables.light.forEach((variable) => {
    content += `  ${variable}\n`;
  });
  content += "}\n\n";
 
  // Dark mode variables
  content += '[data-color-scheme="dark"] {\n';
  result.cssVariables.dark.forEach((variable) => {
    content += `  ${variable}\n`;
  });
  content += "}\n";
 
  return content;
}
 
/**
 * Transform color object structure for better Tailwind CSS compatibility
 * @param {Object} colors - The color object to transform
 * @returns {Object} - The transformed color object
 */
function transformColorObjectForTailwind(colors) {
  const transformed = {};
 
  // Process each color category
  for (const category in colors) {
    transformed[category] = {};
    const colorGroup = colors[category];
 
    // Group variants like "surface-hover" under their base name with variants as properties
    for (const key in colorGroup) {
      const parts = key.split("-");
 
      // Skip if already processed
      if (parts.length === 1) {
        transformed[category][key] = colorGroup[key];
        continue;
      }
 
      // Handle cases like "surface-hover", "surface-active", etc.
      const baseName = parts[0];
      const variantName = parts.slice(1).join("-");
 
      if (!transformed[category][baseName]) {
        // Check if base color exists in original object
        if (colorGroup[baseName]) {
          transformed[category][baseName] = {
            DEFAULT: colorGroup[baseName],
          };
        } else {
          transformed[category][baseName] = {};
        }
      } else if (typeof transformed[category][baseName] === "string") {
        // Convert string value to object with DEFAULT property
        transformed[category][baseName] = {
          DEFAULT: transformed[category][baseName],
        };
      }
 
      // Add the variant
      transformed[category][baseName][variantName] = colorGroup[key];
    }
  }
 
  return transformed;
}
 
/**
 * Process JS tokens for output, merging primitive values
 * @param {Object} tokens - The tokens to process
 * @returns {Object} - The processed tokens
 */
function processJsTokens(tokens) {
  // Merge primitive values at all levels
  const merged = mergePrimitiveValues(tokens);
 
  // Then transform colors for Tailwind if they exist
  if (merged.colors) {
    merged.colors = transformColorObjectForTailwind(merged.colors);
  }
 
  return merged;
}
 
/**
 * Merge primitive values from nested structures
 * @param {Object} values - The object to process
 * @returns {Object} - The processed object with primitive values merged
 */
function mergePrimitiveValues(values) {
  if (typeof values !== "object" || values === null || Array.isArray(values)) {
    return values;
  }
 
  const result = {};
 
  // First, process all non-primitive keys and add them to the result
  for (const [key, value] of Object.entries(values)) {
    if (key !== "primitive") {
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        result[key] = mergePrimitiveValues(value);
      } else {
        result[key] = value;
      }
    }
  }
 
  // Then, if there's a primitive key, merge up its values into the result
  if (values.primitive) {
    if (typeof values.primitive === "object" && !Array.isArray(values.primitive)) {
      // Handle nested primitive objects (e.g., typography.primitive.fontSize)
      for (const [primKey, primValue] of Object.entries(values.primitive)) {
        result[primKey] = mergePrimitiveValues(primValue);
      }
    }
  }
 
  return result;
}
 
/**
 * Generate JS content from tokens
 * @param {Object} jsTokens - The JS tokens to convert to content
 * @returns {string} - The JS content
 */
function generateJsContent(jsTokens) {
  const content = `// This file is generated by the design-tokens-converter tool.
// Do not edit this file directly. Edit design-tokens.json instead.
 
const designTokens = ${JSON.stringify(processJsTokens(jsTokens), null, 2)};
 
module.exports = designTokens;
`;
 
  return content;
}
 
/**
 * Main function to run the design tokens converter
 */
const designTokensConverter = async () => {
  try {
    console.log("Reading design variables file from:", designVariablesPath);
 
    // Check if file exists before trying to read it
    try {
      await fs.access(designVariablesPath);
    } catch (error) {
      console.error(`Error: The design-tokens.json file does not exist at ${designVariablesPath}`);
      console.log("Please create this file by exporting your design tokens from Figma");
      return { success: false, error: "Design tokens file not found" };
    }
 
    const designVariablesData = await fs.readFile(designVariablesPath, "utf8");
 
    try {
      const variables = JSON.parse(designVariablesData);
 
      console.log("Processing design variables...");
      const processed = processDesignVariables(variables);
 
      console.log("Generating CSS...");
      const cssContent = generateCssContent(processed);
 
      console.log("Generating JavaScript...");
      const jsContent = generateJsContent(processed.jsTokens);
 
      // Ensure directory exists
      const cssDir = path.dirname(cssOutputPath);
      await fs.mkdir(cssDir, { recursive: true });
 
      // Write files
      await fs.writeFile(cssOutputPath, cssContent);
      await fs.writeFile(jsOutputPath, jsContent);
 
      console.log(`CSS variables written to ${cssOutputPath}`);
      console.log(`JavaScript tokens written to ${jsOutputPath}`);
 
      return { success: true };
    } catch (parseError) {
      console.error("Error parsing design tokens JSON:");
      console.trace(parseError);
      console.log("Please ensure your design-tokens.json file contains valid JSON");
      return { success: false, error: "JSON parsing error" };
    }
  } catch (error) {
    console.error("Error:", error);
    return { success: false, error: error.message };
  }
};
 
// Execute the function when this script is run directly
if (import.meta.url === `file://${process.argv[1]}`) {
  designTokensConverter().then((result) => {
    if (!result.success) {
      process.exit(1);
    }
    console.log("Design tokens conversion complete");
  });
}
 
export default designTokensConverter;