tauri-typegen 0.5.0

A rust crate that automatically generates TypeScript models and bindings from your Tauri commands
Documentation
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
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
use serde::{Deserialize, Serialize};
use serde_rename_rule::RenameRule;

/// Represents the structure of a type for code generation
/// This allows generators to work with parsed type information instead of string parsing
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum TypeStructure {
    /// Primitive types: "string", "number", "boolean", "void"
    Primitive(String),

    /// Array/Vec types: `Vec<T>` -> `Array(T)`
    Array(Box<TypeStructure>),

    /// Map types: `HashMap<K, V>`, `BTreeMap<K, V>` -> `Map { key: K, value: V }`
    Map {
        key: Box<TypeStructure>,
        value: Box<TypeStructure>,
    },

    /// Set types: `HashSet<T>`, `BTreeSet<T>` -> `Set(T)`
    Set(Box<TypeStructure>),

    /// Tuple types: `(T, U, V)` -> `Tuple([T, U, V])`
    Tuple(Vec<TypeStructure>),

    /// Optional types: `Option<T>` -> `Optional(T)`
    Optional(Box<TypeStructure>),

    /// Result types: `Result<T, E>` -> `Result(T)` (error type ignored for TS)
    Result(Box<TypeStructure>),

    /// Custom/User-defined types
    Custom(String),
}

impl Default for TypeStructure {
    fn default() -> Self {
        // Default to string for test compatibility
        TypeStructure::Primitive("string".to_string())
    }
}

/// Represents the kind of an enum variant for discriminated union generation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum EnumVariantKind {
    /// Unit variant: `Quit`
    Unit,
    /// Tuple variant with unnamed fields: `Move(i32, i32)` or `Write(String)`
    Tuple(Vec<TypeStructure>),
    /// Struct variant with named fields: `ChangeColor { r: u8, g: u8, b: u8 }`
    Struct(Vec<FieldInfo>),
}

/// Information about an enum variant for discriminated union generation
#[derive(Debug, Clone)]
pub struct EnumVariantInfo {
    /// The variant name (e.g., "Quit", "Move", "ChangeColor")
    pub name: String,
    /// The kind of variant and its associated data
    pub kind: EnumVariantKind,
    /// Serde rename attribute: #[serde(rename = "...")]
    pub serde_rename: Option<String>,
}

impl EnumVariantInfo {
    /// Returns true if this is a unit variant (no associated data)
    pub fn is_unit(&self) -> bool {
        matches!(self.kind, EnumVariantKind::Unit)
    }

    /// Returns true if this is a tuple variant (unnamed fields)
    pub fn is_tuple(&self) -> bool {
        matches!(self.kind, EnumVariantKind::Tuple(_))
    }

    /// Returns true if this is a struct variant (named fields)
    pub fn is_struct(&self) -> bool {
        matches!(self.kind, EnumVariantKind::Struct(_))
    }

    /// Returns the tuple fields if this is a tuple variant
    pub fn tuple_fields(&self) -> Option<&Vec<TypeStructure>> {
        match &self.kind {
            EnumVariantKind::Tuple(fields) => Some(fields),
            _ => None,
        }
    }

    /// Returns the struct fields if this is a struct variant
    pub fn struct_fields(&self) -> Option<&Vec<FieldInfo>> {
        match &self.kind {
            EnumVariantKind::Struct(fields) => Some(fields),
            _ => None,
        }
    }
}

pub struct CommandInfo {
    pub name: String,
    pub file_path: String,
    pub line_number: usize,
    pub parameters: Vec<ParameterInfo>,
    pub return_type: String, // Rust return type (e.g., "Vec<Banana>")
    /// Structured representation of the return type for generators
    pub return_type_structure: TypeStructure,
    pub is_async: bool,
    pub channels: Vec<ChannelInfo>,
    /// Serde rename_all attribute: #[serde(rename_all = "...")]
    /// Applied to command function, affects parameter/channel serialization
    pub serde_rename_all: Option<RenameRule>,
}

impl CommandInfo {
    /// Helper for tests: Create a CommandInfo
    #[doc(hidden)]
    pub fn new_for_test(
        name: impl Into<String>,
        file_path: impl Into<String>,
        line_number: usize,
        parameters: Vec<ParameterInfo>,
        return_type: impl Into<String>,
        is_async: bool,
        channels: Vec<ChannelInfo>,
    ) -> Self {
        use crate::analysis::type_resolver::TypeResolver;
        let return_type_str = return_type.into();
        let type_resolver = TypeResolver::new();
        let return_type_structure = type_resolver.parse_type_structure(&return_type_str);

        Self {
            name: name.into(),
            file_path: file_path.into(),
            line_number,
            parameters,
            return_type: return_type_str,
            return_type_structure,
            is_async,
            channels,
            serde_rename_all: None,
        }
    }
}

pub struct ParameterInfo {
    pub name: String,
    pub rust_type: String,
    pub is_optional: bool,
    /// Structured representation of the type for generators
    pub type_structure: TypeStructure,
    /// Serde rename attribute (optional, for future extensibility)
    /// Parameters are serialized following Tauri/JS conventions (camelCase)
    pub serde_rename: Option<String>,
}

#[derive(Clone, Debug)]
pub struct StructInfo {
    pub name: String,
    pub fields: Vec<FieldInfo>,
    pub file_path: String,
    pub is_enum: bool,
    /// Serde rename_all attribute: #[serde(rename_all = "...")]
    pub serde_rename_all: Option<RenameRule>,
    /// Serde tag attribute for enums: #[serde(tag = "...")]
    /// Used for internally-tagged enum representation
    pub serde_tag: Option<String>,
    /// Enum variants with full type information (only populated for enums)
    /// When populated, provides richer variant data than the `fields` vector
    pub enum_variants: Option<Vec<EnumVariantInfo>>,
}

impl StructInfo {
    /// Returns true if this is a simple enum (all unit variants)
    /// Simple enums can be represented as TypeScript string literal unions
    pub fn is_simple_enum(&self) -> bool {
        if !self.is_enum {
            return false;
        }

        match &self.enum_variants {
            Some(variants) => variants.iter().all(|v| v.is_unit()),
            // Fallback to checking fields for backward compatibility
            None => self.fields.iter().all(|f| f.rust_type == "enum_variant"),
        }
    }

    /// Returns true if this is a complex enum (has tuple or struct variants)
    /// Complex enums need discriminated union representation in TypeScript
    pub fn is_complex_enum(&self) -> bool {
        self.is_enum && !self.is_simple_enum()
    }

    /// Returns the discriminator tag name for this enum
    /// Defaults to "type" if not specified via #[serde(tag = "...")]
    pub fn discriminator_tag(&self) -> &str {
        self.serde_tag.as_deref().unwrap_or("type")
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FieldInfo {
    pub name: String,
    pub rust_type: String,
    pub is_optional: bool,
    pub is_public: bool,
    pub validator_attributes: Option<ValidatorAttributes>,
    /// Serde rename attribute: #[serde(rename = "...")]
    pub serde_rename: Option<String>,
    /// Structured representation of the type for generators
    pub type_structure: TypeStructure,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ValidatorAttributes {
    pub length: Option<LengthConstraint>,
    pub range: Option<RangeConstraint>,
    pub email: bool,
    pub url: bool,
    pub custom_message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LengthConstraint {
    pub min: Option<u64>,
    pub max: Option<u64>,
    pub message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RangeConstraint {
    pub min: Option<f64>,
    pub max: Option<f64>,
    pub message: Option<String>,
}

// Event information for frontend event listeners
pub struct EventInfo {
    pub event_name: String,
    pub payload_type: String,
    /// Structured representation of the payload type for generators
    pub payload_type_structure: TypeStructure,
    pub file_path: String,
    pub line_number: usize,
}

// Channel information for streaming data from Rust to frontend
#[derive(Clone)]
pub struct ChannelInfo {
    pub parameter_name: String,
    pub message_type: String,
    pub command_name: String,
    pub file_path: String,
    pub line_number: usize,
    /// Serde rename attribute (optional, for future extensibility)
    /// Channel parameters are serialized following Tauri/JS conventions (camelCase)
    pub serde_rename: Option<String>,
    /// Structured representation of the message type for generators
    pub message_type_structure: TypeStructure,
}

impl ChannelInfo {
    /// Helper for tests: Create a ChannelInfo
    #[doc(hidden)]
    pub fn new_for_test(
        parameter_name: impl Into<String>,
        message_type: impl Into<String>,
        command_name: impl Into<String>,
        file_path: impl Into<String>,
        line_number: usize,
    ) -> Self {
        let message_type_str = message_type.into();
        Self {
            parameter_name: parameter_name.into(),
            message_type: message_type_str.clone(),
            command_name: command_name.into(),
            file_path: file_path.into(),
            line_number,
            serde_rename: None,
            // Parse message_type into TypeStructure for tests
            message_type_structure: crate::analysis::type_resolver::TypeResolver::new()
                .parse_type_structure(&message_type_str),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // TypeStructure tests
    mod type_structure {
        use super::*;

        #[test]
        fn test_default_is_string_primitive() {
            let default_type = TypeStructure::default();
            match default_type {
                TypeStructure::Primitive(name) => assert_eq!(name, "string"),
                _ => panic!("Default should be Primitive(\"string\")"),
            }
        }

        #[test]
        fn test_primitive_variants() {
            let types = vec!["string", "number", "boolean", "void"];
            for type_name in types {
                let primitive = TypeStructure::Primitive(type_name.to_string());
                match primitive {
                    TypeStructure::Primitive(name) => assert_eq!(name, type_name),
                    _ => panic!("Should be Primitive variant"),
                }
            }
        }

        #[test]
        fn test_array_wraps_inner_type() {
            let inner = TypeStructure::Primitive("number".to_string());
            let array = TypeStructure::Array(Box::new(inner));

            match array {
                TypeStructure::Array(boxed) => match *boxed {
                    TypeStructure::Primitive(name) => assert_eq!(name, "number"),
                    _ => panic!("Inner should be Primitive"),
                },
                _ => panic!("Should be Array variant"),
            }
        }

        #[test]
        fn test_map_has_key_and_value() {
            let key = TypeStructure::Primitive("string".to_string());
            let value = TypeStructure::Primitive("number".to_string());
            let map = TypeStructure::Map {
                key: Box::new(key),
                value: Box::new(value),
            };

            match map {
                TypeStructure::Map { key, value } => match (*key, *value) {
                    (TypeStructure::Primitive(k), TypeStructure::Primitive(v)) => {
                        assert_eq!(k, "string");
                        assert_eq!(v, "number");
                    }
                    _ => panic!("Key and value should be Primitives"),
                },
                _ => panic!("Should be Map variant"),
            }
        }

        #[test]
        fn test_set_wraps_inner_type() {
            let inner = TypeStructure::Primitive("string".to_string());
            let set = TypeStructure::Set(Box::new(inner));

            match set {
                TypeStructure::Set(boxed) => match *boxed {
                    TypeStructure::Primitive(name) => assert_eq!(name, "string"),
                    _ => panic!("Inner should be Primitive"),
                },
                _ => panic!("Should be Set variant"),
            }
        }

        #[test]
        fn test_tuple_with_multiple_types() {
            let types = vec![
                TypeStructure::Primitive("string".to_string()),
                TypeStructure::Primitive("number".to_string()),
                TypeStructure::Primitive("boolean".to_string()),
            ];
            let tuple = TypeStructure::Tuple(types);

            match tuple {
                TypeStructure::Tuple(types) => {
                    assert_eq!(types.len(), 3);
                    match &types[0] {
                        TypeStructure::Primitive(name) => assert_eq!(name, "string"),
                        _ => panic!("First type should be string"),
                    }
                }
                _ => panic!("Should be Tuple variant"),
            }
        }

        #[test]
        fn test_empty_tuple() {
            let tuple = TypeStructure::Tuple(vec![]);
            match tuple {
                TypeStructure::Tuple(types) => assert_eq!(types.len(), 0),
                _ => panic!("Should be Tuple variant"),
            }
        }

        #[test]
        fn test_optional_wraps_inner_type() {
            let inner = TypeStructure::Custom("User".to_string());
            let optional = TypeStructure::Optional(Box::new(inner));

            match optional {
                TypeStructure::Optional(boxed) => match *boxed {
                    TypeStructure::Custom(name) => assert_eq!(name, "User"),
                    _ => panic!("Inner should be Custom"),
                },
                _ => panic!("Should be Optional variant"),
            }
        }

        #[test]
        fn test_result_wraps_success_type() {
            let success = TypeStructure::Primitive("string".to_string());
            let result = TypeStructure::Result(Box::new(success));

            match result {
                TypeStructure::Result(boxed) => match *boxed {
                    TypeStructure::Primitive(name) => assert_eq!(name, "string"),
                    _ => panic!("Inner should be Primitive"),
                },
                _ => panic!("Should be Result variant"),
            }
        }

        #[test]
        fn test_custom_type() {
            let custom = TypeStructure::Custom("UserProfile".to_string());
            match custom {
                TypeStructure::Custom(name) => assert_eq!(name, "UserProfile"),
                _ => panic!("Should be Custom variant"),
            }
        }

        #[test]
        fn test_nested_structures() {
            // Vec<Option<HashMap<String, User>>>
            let user = TypeStructure::Custom("User".to_string());
            let map = TypeStructure::Map {
                key: Box::new(TypeStructure::Primitive("string".to_string())),
                value: Box::new(user),
            };
            let optional = TypeStructure::Optional(Box::new(map));
            let array = TypeStructure::Array(Box::new(optional));

            match array {
                TypeStructure::Array(arr_inner) => match *arr_inner {
                    TypeStructure::Optional(opt_inner) => match *opt_inner {
                        TypeStructure::Map { key, value } => match (*key, *value) {
                            (TypeStructure::Primitive(k), TypeStructure::Custom(v)) => {
                                assert_eq!(k, "string");
                                assert_eq!(v, "User");
                            }
                            _ => panic!("Map types incorrect"),
                        },
                        _ => panic!("Should be Map"),
                    },
                    _ => panic!("Should be Optional"),
                },
                _ => panic!("Should be Array"),
            }
        }

        #[test]
        fn test_clone_type_structure() {
            let original = TypeStructure::Primitive("string".to_string());
            let cloned = original.clone();

            match (original, cloned) {
                (TypeStructure::Primitive(o), TypeStructure::Primitive(c)) => {
                    assert_eq!(o, c);
                }
                _ => panic!("Clone should maintain variant"),
            }
        }

        #[test]
        fn test_serialize_deserialize_primitive() {
            let primitive = TypeStructure::Primitive("number".to_string());
            let json = serde_json::to_string(&primitive).unwrap();
            let deserialized: TypeStructure = serde_json::from_str(&json).unwrap();

            match deserialized {
                TypeStructure::Primitive(name) => assert_eq!(name, "number"),
                _ => panic!("Should deserialize to Primitive"),
            }
        }

        #[test]
        fn test_serialize_deserialize_complex() {
            let complex = TypeStructure::Array(Box::new(TypeStructure::Optional(Box::new(
                TypeStructure::Custom("User".to_string()),
            ))));

            let json = serde_json::to_string(&complex).unwrap();
            let deserialized: TypeStructure = serde_json::from_str(&json).unwrap();

            match deserialized {
                TypeStructure::Array(arr) => match *arr {
                    TypeStructure::Optional(opt) => match *opt {
                        TypeStructure::Custom(name) => assert_eq!(name, "User"),
                        _ => panic!("Should be Custom"),
                    },
                    _ => panic!("Should be Optional"),
                },
                _ => panic!("Should be Array"),
            }
        }
    }

    // ValidatorAttributes tests
    mod validator_attributes {
        use super::*;

        #[test]
        fn test_length_constraint() {
            let length = LengthConstraint {
                min: Some(5),
                max: Some(100),
                message: Some("Invalid length".to_string()),
            };

            assert_eq!(length.min, Some(5));
            assert_eq!(length.max, Some(100));
            assert_eq!(length.message, Some("Invalid length".to_string()));
        }

        #[test]
        fn test_range_constraint() {
            let range = RangeConstraint {
                min: Some(0.0),
                max: Some(10.5),
                message: Some("Out of range".to_string()),
            };

            assert_eq!(range.min, Some(0.0));
            assert_eq!(range.max, Some(10.5));
            assert_eq!(range.message, Some("Out of range".to_string()));
        }

        #[test]
        fn test_validator_attributes_email() {
            let validator = ValidatorAttributes {
                length: None,
                range: None,
                email: true,
                url: false,
                custom_message: None,
            };

            assert!(validator.email);
            assert!(!validator.url);
        }

        #[test]
        fn test_validator_attributes_with_length() {
            let validator = ValidatorAttributes {
                length: Some(LengthConstraint {
                    min: Some(1),
                    max: Some(50),
                    message: None,
                }),
                range: None,
                email: false,
                url: false,
                custom_message: None,
            };

            assert!(validator.length.is_some());
            let length = validator.length.unwrap();
            assert_eq!(length.min, Some(1));
            assert_eq!(length.max, Some(50));
        }

        #[test]
        fn test_serialize_validator_attributes() {
            let validator = ValidatorAttributes {
                length: Some(LengthConstraint {
                    min: Some(5),
                    max: Some(100),
                    message: None,
                }),
                range: None,
                email: true,
                url: false,
                custom_message: Some("Custom error".to_string()),
            };

            let json = serde_json::to_string(&validator).unwrap();
            let deserialized: ValidatorAttributes = serde_json::from_str(&json).unwrap();

            assert!(deserialized.email);
            assert_eq!(
                deserialized.custom_message,
                Some("Custom error".to_string())
            );
            assert!(deserialized.length.is_some());
        }

        #[test]
        fn test_validator_attributes_clone() {
            let original = ValidatorAttributes {
                length: None,
                range: Some(RangeConstraint {
                    min: Some(0.0),
                    max: Some(1.0),
                    message: None,
                }),
                email: false,
                url: true,
                custom_message: None,
            };

            let cloned = original.clone();
            assert!(cloned.url);
            assert!(cloned.range.is_some());
        }
    }

    // CommandInfo tests
    mod command_info {
        use super::*;

        #[test]
        fn test_new_for_test_creates_valid_command() {
            let params = vec![];
            let channels = vec![];

            let cmd = CommandInfo::new_for_test(
                "greet",
                "src/main.rs",
                10,
                params,
                "String",
                false,
                channels,
            );

            assert_eq!(cmd.name, "greet");
            assert_eq!(cmd.file_path, "src/main.rs");
            assert_eq!(cmd.line_number, 10);
            assert_eq!(cmd.return_type, "String");
            assert!(!cmd.is_async);
            assert!(cmd.serde_rename_all.is_none());
        }

        #[test]
        fn test_new_for_test_parses_return_type_structure() {
            let cmd = CommandInfo::new_for_test(
                "get_users",
                "src/api.rs",
                20,
                vec![],
                "Vec<String>",
                true,
                vec![],
            );

            // Should parse Vec<String> into Array(Primitive("string"))
            match cmd.return_type_structure {
                TypeStructure::Array(inner) => match *inner {
                    TypeStructure::Primitive(name) => assert_eq!(name, "string"),
                    _ => panic!("Should be string primitive"),
                },
                _ => panic!("Should be Array"),
            }
            assert!(cmd.is_async);
        }

        #[test]
        fn test_command_with_parameters() {
            let param = ParameterInfo {
                name: "user_id".to_string(),
                rust_type: "String".to_string(),
                is_optional: false,
                type_structure: TypeStructure::Primitive("string".to_string()),
                serde_rename: None,
            };

            let cmd = CommandInfo::new_for_test(
                "get_user",
                "src/api.rs",
                30,
                vec![param],
                "User",
                false,
                vec![],
            );

            assert_eq!(cmd.parameters.len(), 1);
            assert_eq!(cmd.parameters[0].name, "user_id");
            assert_eq!(cmd.parameters[0].rust_type, "String");
        }

        #[test]
        fn test_command_with_channels() {
            let channel = ChannelInfo::new_for_test(
                "progress",
                "u32",
                "download_file",
                "src/download.rs",
                40,
            );

            let cmd = CommandInfo::new_for_test(
                "download_file",
                "src/download.rs",
                40,
                vec![],
                "Result<(), String>",
                true,
                vec![channel],
            );

            assert_eq!(cmd.channels.len(), 1);
            assert_eq!(cmd.channels[0].parameter_name, "progress");
            assert_eq!(cmd.channels[0].message_type, "u32");
        }
    }

    // ChannelInfo tests
    mod channel_info {
        use super::*;

        #[test]
        fn test_new_for_test_creates_valid_channel() {
            let channel =
                ChannelInfo::new_for_test("updates", "String", "subscribe", "src/events.rs", 50);

            assert_eq!(channel.parameter_name, "updates");
            assert_eq!(channel.message_type, "String");
            assert_eq!(channel.command_name, "subscribe");
            assert_eq!(channel.file_path, "src/events.rs");
            assert_eq!(channel.line_number, 50);
            assert!(channel.serde_rename.is_none());
        }

        #[test]
        fn test_channel_parses_message_type_structure() {
            let channel =
                ChannelInfo::new_for_test("data", "Vec<u32>", "stream_data", "src/stream.rs", 60);

            // Should parse Vec<u32> into Array(Primitive("number"))
            match channel.message_type_structure {
                TypeStructure::Array(inner) => match *inner {
                    TypeStructure::Primitive(name) => assert_eq!(name, "number"),
                    _ => panic!("Should be number primitive"),
                },
                _ => panic!("Should be Array"),
            }
        }

        #[test]
        fn test_channel_clone() {
            let original =
                ChannelInfo::new_for_test("status", "bool", "monitor", "src/monitor.rs", 70);

            let cloned = original.clone();
            assert_eq!(cloned.parameter_name, "status");
            assert_eq!(cloned.message_type, "bool");
            assert_eq!(cloned.command_name, "monitor");
        }
    }

    // ParameterInfo tests
    mod parameter_info {
        use super::*;

        #[test]
        fn test_parameter_with_optional_type() {
            let param = ParameterInfo {
                name: "email".to_string(),
                rust_type: "Option<String>".to_string(),
                is_optional: true,
                type_structure: TypeStructure::Optional(Box::new(TypeStructure::Primitive(
                    "string".to_string(),
                ))),
                serde_rename: None,
            };

            assert!(param.is_optional);
            match param.type_structure {
                TypeStructure::Optional(_) => (),
                _ => panic!("Should be Optional"),
            }
        }

        #[test]
        fn test_parameter_with_serde_rename() {
            let param = ParameterInfo {
                name: "user_id".to_string(),
                rust_type: "String".to_string(),
                is_optional: false,
                type_structure: TypeStructure::Primitive("string".to_string()),
                serde_rename: Some("userId".to_string()),
            };

            assert_eq!(param.serde_rename, Some("userId".to_string()));
        }
    }

    // StructInfo tests
    mod struct_info {
        use super::*;

        #[test]
        fn test_struct_with_fields() {
            let field = FieldInfo {
                name: "name".to_string(),
                rust_type: "String".to_string(),
                is_optional: false,
                is_public: true,
                validator_attributes: None,
                serde_rename: None,
                type_structure: TypeStructure::Primitive("string".to_string()),
            };

            let struct_info = StructInfo {
                name: "User".to_string(),
                fields: vec![field],
                file_path: "src/models.rs".to_string(),
                is_enum: false,
                serde_rename_all: None,
                serde_tag: None,
                enum_variants: None,
            };

            assert_eq!(struct_info.name, "User");
            assert!(!struct_info.is_enum);
            assert_eq!(struct_info.fields.len(), 1);
        }

        #[test]
        fn test_enum_struct() {
            let struct_info = StructInfo {
                name: "Status".to_string(),
                fields: vec![],
                file_path: "src/types.rs".to_string(),
                is_enum: true,
                serde_rename_all: Some(RenameRule::CamelCase),
                serde_tag: None,
                enum_variants: None,
            };

            assert!(struct_info.is_enum);
            assert!(struct_info.serde_rename_all.is_some());
        }

        #[test]
        fn test_struct_clone() {
            let original = StructInfo {
                name: "Product".to_string(),
                fields: vec![],
                file_path: "src/product.rs".to_string(),
                is_enum: false,
                serde_rename_all: None,
                serde_tag: None,
                enum_variants: None,
            };

            let cloned = original.clone();
            assert_eq!(cloned.name, "Product");
            assert!(!cloned.is_enum);
        }

        #[test]
        fn test_simple_enum_detection() {
            // Simple enum with unit variants only
            let simple_enum = StructInfo {
                name: "Status".to_string(),
                fields: vec![
                    FieldInfo {
                        name: "Active".to_string(),
                        rust_type: "enum_variant".to_string(),
                        is_optional: false,
                        is_public: true,
                        validator_attributes: None,
                        serde_rename: None,
                        type_structure: TypeStructure::Custom("enum_variant".to_string()),
                    },
                    FieldInfo {
                        name: "Inactive".to_string(),
                        rust_type: "enum_variant".to_string(),
                        is_optional: false,
                        is_public: true,
                        validator_attributes: None,
                        serde_rename: None,
                        type_structure: TypeStructure::Custom("enum_variant".to_string()),
                    },
                ],
                file_path: "src/types.rs".to_string(),
                is_enum: true,
                serde_rename_all: None,
                serde_tag: None,
                enum_variants: None,
            };

            assert!(simple_enum.is_simple_enum());
            assert!(!simple_enum.is_complex_enum());
        }

        #[test]
        fn test_complex_enum_detection_via_fields() {
            // Complex enum detected via rust_type field (backward compatibility)
            let complex_enum = StructInfo {
                name: "Message".to_string(),
                fields: vec![
                    FieldInfo {
                        name: "Quit".to_string(),
                        rust_type: "enum_variant".to_string(),
                        is_optional: false,
                        is_public: true,
                        validator_attributes: None,
                        serde_rename: None,
                        type_structure: TypeStructure::Custom("enum_variant".to_string()),
                    },
                    FieldInfo {
                        name: "Move".to_string(),
                        rust_type: "enum_variant_tuple".to_string(),
                        is_optional: false,
                        is_public: true,
                        validator_attributes: None,
                        serde_rename: None,
                        type_structure: TypeStructure::Custom("enum_variant".to_string()),
                    },
                ],
                file_path: "src/types.rs".to_string(),
                is_enum: true,
                serde_rename_all: None,
                serde_tag: None,
                enum_variants: None,
            };

            assert!(!complex_enum.is_simple_enum());
            assert!(complex_enum.is_complex_enum());
        }

        #[test]
        fn test_complex_enum_detection_via_enum_variants() {
            // Complex enum with EnumVariantInfo populated
            let complex_enum = StructInfo {
                name: "Message".to_string(),
                fields: vec![],
                file_path: "src/types.rs".to_string(),
                is_enum: true,
                serde_rename_all: None,
                serde_tag: Some("type".to_string()),
                enum_variants: Some(vec![
                    EnumVariantInfo {
                        name: "Quit".to_string(),
                        kind: EnumVariantKind::Unit,
                        serde_rename: None,
                    },
                    EnumVariantInfo {
                        name: "Move".to_string(),
                        kind: EnumVariantKind::Tuple(vec![
                            TypeStructure::Primitive("number".to_string()),
                            TypeStructure::Primitive("number".to_string()),
                        ]),
                        serde_rename: None,
                    },
                ]),
            };

            assert!(!complex_enum.is_simple_enum());
            assert!(complex_enum.is_complex_enum());
        }

        #[test]
        fn test_discriminator_tag_default() {
            let enum_info = StructInfo {
                name: "Status".to_string(),
                fields: vec![],
                file_path: "src/types.rs".to_string(),
                is_enum: true,
                serde_rename_all: None,
                serde_tag: None,
                enum_variants: None,
            };

            assert_eq!(enum_info.discriminator_tag(), "type");
        }

        #[test]
        fn test_discriminator_tag_custom() {
            let enum_info = StructInfo {
                name: "Status".to_string(),
                fields: vec![],
                file_path: "src/types.rs".to_string(),
                is_enum: true,
                serde_rename_all: None,
                serde_tag: Some("kind".to_string()),
                enum_variants: None,
            };

            assert_eq!(enum_info.discriminator_tag(), "kind");
        }
    }

    // EnumVariantKind tests
    mod enum_variant_kind {
        use super::*;

        #[test]
        fn test_unit_variant() {
            let kind = EnumVariantKind::Unit;
            assert_eq!(kind, EnumVariantKind::Unit);
        }

        #[test]
        fn test_tuple_variant_single_field() {
            let kind = EnumVariantKind::Tuple(vec![TypeStructure::Primitive("string".to_string())]);

            match kind {
                EnumVariantKind::Tuple(fields) => {
                    assert_eq!(fields.len(), 1);
                    assert_eq!(fields[0], TypeStructure::Primitive("string".to_string()));
                }
                _ => panic!("Should be Tuple variant"),
            }
        }

        #[test]
        fn test_tuple_variant_multiple_fields() {
            let kind = EnumVariantKind::Tuple(vec![
                TypeStructure::Primitive("number".to_string()),
                TypeStructure::Primitive("number".to_string()),
            ]);

            match kind {
                EnumVariantKind::Tuple(fields) => {
                    assert_eq!(fields.len(), 2);
                }
                _ => panic!("Should be Tuple variant"),
            }
        }

        #[test]
        fn test_struct_variant() {
            let fields = vec![
                FieldInfo {
                    name: "r".to_string(),
                    rust_type: "u8".to_string(),
                    is_optional: false,
                    is_public: true,
                    validator_attributes: None,
                    serde_rename: None,
                    type_structure: TypeStructure::Primitive("number".to_string()),
                },
                FieldInfo {
                    name: "g".to_string(),
                    rust_type: "u8".to_string(),
                    is_optional: false,
                    is_public: true,
                    validator_attributes: None,
                    serde_rename: None,
                    type_structure: TypeStructure::Primitive("number".to_string()),
                },
            ];
            let kind = EnumVariantKind::Struct(fields);

            match kind {
                EnumVariantKind::Struct(f) => {
                    assert_eq!(f.len(), 2);
                    assert_eq!(f[0].name, "r");
                    assert_eq!(f[1].name, "g");
                }
                _ => panic!("Should be Struct variant"),
            }
        }

        #[test]
        fn test_serialize_deserialize() {
            let unit = EnumVariantKind::Unit;
            let json = serde_json::to_string(&unit).unwrap();
            let deserialized: EnumVariantKind = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized, EnumVariantKind::Unit);

            let tuple =
                EnumVariantKind::Tuple(vec![TypeStructure::Primitive("string".to_string())]);
            let json = serde_json::to_string(&tuple).unwrap();
            let deserialized: EnumVariantKind = serde_json::from_str(&json).unwrap();
            match deserialized {
                EnumVariantKind::Tuple(fields) => assert_eq!(fields.len(), 1),
                _ => panic!("Should deserialize to Tuple"),
            }
        }
    }

    // EnumVariantInfo tests
    mod enum_variant_info {
        use super::*;

        #[test]
        fn test_unit_variant_helpers() {
            let variant = EnumVariantInfo {
                name: "Quit".to_string(),
                kind: EnumVariantKind::Unit,
                serde_rename: None,
            };

            assert!(variant.is_unit());
            assert!(!variant.is_tuple());
            assert!(!variant.is_struct());
            assert!(variant.tuple_fields().is_none());
            assert!(variant.struct_fields().is_none());
        }

        #[test]
        fn test_tuple_variant_helpers() {
            let variant = EnumVariantInfo {
                name: "Move".to_string(),
                kind: EnumVariantKind::Tuple(vec![
                    TypeStructure::Primitive("number".to_string()),
                    TypeStructure::Primitive("number".to_string()),
                ]),
                serde_rename: None,
            };

            assert!(!variant.is_unit());
            assert!(variant.is_tuple());
            assert!(!variant.is_struct());

            let fields = variant.tuple_fields().unwrap();
            assert_eq!(fields.len(), 2);
            assert!(variant.struct_fields().is_none());
        }

        #[test]
        fn test_struct_variant_helpers() {
            let variant = EnumVariantInfo {
                name: "ChangeColor".to_string(),
                kind: EnumVariantKind::Struct(vec![FieldInfo {
                    name: "r".to_string(),
                    rust_type: "u8".to_string(),
                    is_optional: false,
                    is_public: true,
                    validator_attributes: None,
                    serde_rename: None,
                    type_structure: TypeStructure::Primitive("number".to_string()),
                }]),
                serde_rename: None,
            };

            assert!(!variant.is_unit());
            assert!(!variant.is_tuple());
            assert!(variant.is_struct());

            assert!(variant.tuple_fields().is_none());
            let fields = variant.struct_fields().unwrap();
            assert_eq!(fields.len(), 1);
            assert_eq!(fields[0].name, "r");
        }

        #[test]
        fn test_variant_with_serde_rename() {
            let variant = EnumVariantInfo {
                name: "Quit".to_string(),
                kind: EnumVariantKind::Unit,
                serde_rename: Some("quit".to_string()),
            };

            assert_eq!(variant.serde_rename, Some("quit".to_string()));
        }

        #[test]
        fn test_clone() {
            let original = EnumVariantInfo {
                name: "Write".to_string(),
                kind: EnumVariantKind::Tuple(vec![TypeStructure::Primitive("string".to_string())]),
                serde_rename: None,
            };

            let cloned = original.clone();
            assert_eq!(cloned.name, "Write");
            assert!(cloned.is_tuple());
        }
    }

    // FieldInfo tests
    mod field_info {
        use super::*;

        #[test]
        fn test_field_with_validator() {
            let validator = ValidatorAttributes {
                length: Some(LengthConstraint {
                    min: Some(1),
                    max: Some(100),
                    message: None,
                }),
                range: None,
                email: false,
                url: false,
                custom_message: None,
            };

            let field = FieldInfo {
                name: "username".to_string(),
                rust_type: "String".to_string(),
                is_optional: false,
                is_public: true,
                validator_attributes: Some(validator),
                serde_rename: None,
                type_structure: TypeStructure::Primitive("string".to_string()),
            };

            assert!(field.validator_attributes.is_some());
            let attrs = field.validator_attributes.unwrap();
            assert!(attrs.length.is_some());
        }

        #[test]
        fn test_private_field() {
            let field = FieldInfo {
                name: "internal_id".to_string(),
                rust_type: "u64".to_string(),
                is_optional: false,
                is_public: false,
                validator_attributes: None,
                serde_rename: None,
                type_structure: TypeStructure::Primitive("number".to_string()),
            };

            assert!(!field.is_public);
        }

        #[test]
        fn test_field_with_serde_rename() {
            let field = FieldInfo {
                name: "created_at".to_string(),
                rust_type: "String".to_string(),
                is_optional: true,
                is_public: true,
                validator_attributes: None,
                serde_rename: Some("createdAt".to_string()),
                type_structure: TypeStructure::Optional(Box::new(TypeStructure::Primitive(
                    "string".to_string(),
                ))),
            };

            assert_eq!(field.serde_rename, Some("createdAt".to_string()));
            assert!(field.is_optional);
        }

        #[test]
        fn test_field_clone() {
            let original = FieldInfo {
                name: "count".to_string(),
                rust_type: "i32".to_string(),
                is_optional: false,
                is_public: true,
                validator_attributes: None,
                serde_rename: None,
                type_structure: TypeStructure::Primitive("number".to_string()),
            };

            let cloned = original.clone();
            assert_eq!(cloned.name, "count");
            assert_eq!(cloned.rust_type, "i32");
        }
    }

    // EventInfo tests
    mod event_info {
        use super::*;

        #[test]
        fn test_event_info_creation() {
            let event = EventInfo {
                event_name: "user-updated".to_string(),
                payload_type: "User".to_string(),
                payload_type_structure: TypeStructure::Custom("User".to_string()),
                file_path: "src/events.rs".to_string(),
                line_number: 100,
            };

            assert_eq!(event.event_name, "user-updated");
            assert_eq!(event.payload_type, "User");
            match event.payload_type_structure {
                TypeStructure::Custom(name) => assert_eq!(name, "User"),
                _ => panic!("Should be Custom type"),
            }
        }

        #[test]
        fn test_event_with_primitive_payload() {
            let event = EventInfo {
                event_name: "progress".to_string(),
                payload_type: "u32".to_string(),
                payload_type_structure: TypeStructure::Primitive("number".to_string()),
                file_path: "src/progress.rs".to_string(),
                line_number: 50,
            };

            match event.payload_type_structure {
                TypeStructure::Primitive(name) => assert_eq!(name, "number"),
                _ => panic!("Should be Primitive type"),
            }
        }
    }
}