tauri-typegen 0.5.2

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
//! End-to-end integration tests
//! Tests complete Rust → TypeScript translation pipeline
//!
//! These tests verify the FULL pipeline works correctly, not individual components.
//! Component-level testing is done in unit tests (src/**/*.rs).

mod common;
mod fixtures;

use common::{TestGenerator, TestProject};

/// Test complete vanilla TypeScript generation from Rust to TS
#[test]
fn test_vanilla_typescript_full_pipeline() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct User {
            pub id: String,
            pub name: String,
            pub email: String,
        }

        #[tauri::command]
        pub fn get_user(user_id: String) -> Result<User, String> {
            Ok(User {
                id: user_id,
                name: "Test User".to_string(),
                email: "test@example.com".to_string(),
            })
        }

        #[tauri::command]
        pub fn create_user(name: String, email: String) -> Result<User, String> {
            Ok(User {
                id: "123".to_string(),
                name,
                email,
            })
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    assert_eq!(commands.len(), 2);

    let generator = TestGenerator::new();
    let files = generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("none"),
        None,
    );

    // Verify all expected files are generated
    assert!(files.contains(&"types.ts".to_string()));
    assert!(files.contains(&"commands.ts".to_string()));
    assert!(files.contains(&"index.ts".to_string()));

    // Verify types.ts content
    let types = generator.read_file("types.ts");
    assert!(types.contains("export interface User"));
    assert!(types.contains("id: string"));
    assert!(types.contains("name: string"));
    assert!(types.contains("email: string"));

    // Verify NO Zod schemas in vanilla TS
    assert!(!types.contains("z.object"));
    assert!(!types.contains("UserSchema"));

    // Verify commands.ts content
    let commands_file = generator.read_file("commands.ts");
    assert!(commands_file.contains("export async function getUser"));
    assert!(commands_file.contains("export async function createUser"));
    assert!(commands_file.contains("invoke"));

    // Verify index.ts exports
    let index = generator.read_file("index.ts");
    assert!(index.contains("export * from './types'"));
    assert!(index.contains("export * from './commands'"));
}

/// Test complete Zod TypeScript generation from Rust to TS with validation
#[test]
fn test_zod_typescript_full_pipeline() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct Product {
            pub id: String,
            pub name: String,
            pub price: f64,
            pub in_stock: bool,
        }

        #[tauri::command]
        pub fn get_product(product_id: String) -> Result<Product, String> {
            Ok(Product {
                id: product_id,
                name: "Widget".to_string(),
                price: 19.99,
                in_stock: true,
            })
        }

        #[tauri::command]
        pub fn create_product(name: String, price: f64) -> Result<Product, String> {
            Ok(Product {
                id: "123".to_string(),
                name,
                price,
                in_stock: true,
            })
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    assert_eq!(commands.len(), 2);

    let generator = TestGenerator::new();
    let files = generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("zod"),
        None,
    );

    // Verify all expected files are generated
    assert!(files.contains(&"types.ts".to_string()));
    assert!(files.contains(&"commands.ts".to_string()));
    assert!(files.contains(&"index.ts".to_string()));

    // Verify types.ts with Zod schemas
    let types = generator.read_file("types.ts");

    // Struct schema - should exist with zod validation
    assert!(
        types.contains("ProductSchema"),
        "Should generate ProductSchema"
    );
    assert!(
        types.contains("z.object") || types.contains("z.string"),
        "Should use zod validators"
    );

    // Type aliases should exist
    assert!(
        types.contains("Product") && types.contains("export"),
        "Should export Product type"
    );

    // Verify commands.ts uses schemas for validation
    let commands_file = generator.read_file("commands.ts");
    assert!(commands_file.contains("getProduct") || commands_file.contains("get_product"));
    assert!(commands_file.contains("createProduct") || commands_file.contains("create_product"));
}

/// Test complete pipeline with commands, channels, and events together
#[test]
fn test_complete_app_with_commands_channels_and_events() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use tauri::Manager;
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct Message {
            pub id: String,
            pub content: String,
            pub timestamp: u64,
        }

        #[tauri::command]
        pub fn send_message(
            content: String,
            app: tauri::AppHandle,
            on_progress: tauri::ipc::Channel<f32>,
        ) -> Result<Message, String> {
            let msg = Message {
                id: "123".to_string(),
                content,
                timestamp: 1234567890,
            };

            // Emit event
            app.emit("message-sent", msg.clone()).ok();

            // Send channel progress
            on_progress.send(100.0).ok();

            Ok(msg)
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    let events = analyzer.get_discovered_events();
    let all_channels = analyzer.get_all_discovered_channels(&commands);

    // Verify analysis found everything
    assert_eq!(commands.len(), 1);
    assert_eq!(events.len(), 1);
    assert_eq!(all_channels.len(), 1);

    // Generate with Zod
    let generator = TestGenerator::new();
    let files = generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("zod"),
        None,
    );

    // Should generate all files including events
    assert!(files.contains(&"types.ts".to_string()));
    assert!(files.contains(&"commands.ts".to_string()));
    assert!(files.contains(&"events.ts".to_string()));
    assert!(files.contains(&"index.ts".to_string()));

    // Verify types.ts
    let types = generator.read_file("types.ts");
    assert!(types.contains("Message"), "Should contain Message type");
    assert!(
        types.contains("MessageSchema"),
        "Should contain MessageSchema"
    );
    assert!(
        types.contains("Channel") || types.contains("channel"),
        "Should reference Channel"
    );

    // Verify commands.ts has channel parameter
    let commands_file = generator.read_file("commands.ts");
    assert!(
        commands_file.contains("sendMessage"),
        "Should contain sendMessage function"
    );
    assert!(
        commands_file.contains("Channel") || commands_file.contains("channel"),
        "Should use Channel in signature"
    );

    // Verify events.ts
    let events_file = generator.read_file("events.ts");
    assert!(
        events_file.contains("MessageSent") || events_file.contains("message"),
        "Should contain message-sent event listener"
    );

    // Verify index.ts exports everything
    let index = generator.read_file("index.ts");
    assert!(index.contains("export * from './types'"));
    assert!(index.contains("export * from './commands'"));
    assert!(index.contains("export * from './events'"));
}

/// Test serde attributes are properly translated through the full pipeline
#[test]
fn test_serde_rename_full_pipeline() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct UserProfile {
            pub user_id: String,
            pub first_name: String,
            pub last_name: String,
            #[serde(rename = "emailAddress")]
            pub email: String,
        }

        #[tauri::command]
        #[serde(rename_all = "camelCase")]
        pub fn get_profile(user_id: String) -> Result<UserProfile, String> {
            Ok(UserProfile {
                user_id,
                first_name: "John".to_string(),
                last_name: "Doe".to_string(),
                email: "john@example.com".to_string(),
            })
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("zod"),
        None,
    );

    let types = generator.read_file("types.ts");

    // Verify struct fields use camelCase from serde (field names, not necessarily exact zod syntax)
    assert!(
        types.contains("userId"),
        "Should use userId from camelCase rename"
    );
    assert!(
        types.contains("firstName"),
        "Should use firstName from camelCase rename"
    );
    assert!(
        types.contains("lastName"),
        "Should use lastName from camelCase rename"
    );

    // Verify explicit rename overrides rename_all
    assert!(
        types.contains("emailAddress"),
        "Should use emailAddress from explicit rename"
    );
}

/// Test empty project generates no TypeScript files
#[test]
fn test_empty_project_no_generation() {
    let project = TestProject::new();

    // Empty Rust file with no commands
    project.write_file(
        "main.rs",
        r#"
        fn main() {
            println!("Hello, world!");
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    assert_eq!(commands.len(), 0);

    let generator = TestGenerator::new();
    let files = generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("none"),
        None,
    );

    // Should still generate index.ts even with no commands
    // but types.ts and commands.ts should be minimal/empty
    assert!(files.contains(&"index.ts".to_string()));
}

/// Test complex nested types are properly resolved through dependencies
#[test]
fn test_deeply_nested_types_full_pipeline() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};
        use std::collections::HashMap;

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct Address {
            pub street: String,
            pub city: String,
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct Contact {
            pub email: String,
            pub address: Address,
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct User {
            pub id: String,
            pub contacts: Vec<Contact>,
        }

        #[tauri::command]
        pub fn get_user_map() -> HashMap<String, User> {
            HashMap::new()
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("none"),
        None,
    );

    let types = generator.read_file("types.ts");

    // All types should be generated
    assert!(types.contains("export interface Address"));
    assert!(types.contains("export interface Contact"));
    assert!(types.contains("export interface User"));

    // Verify nested references
    assert!(types.contains("address: Address"));
    assert!(types.contains("contacts: Contact[]") || types.contains("contacts: Array<Contact>"));

    // Verify complex return type
    let commands_file = generator.read_file("commands.ts");
    assert!(
        commands_file.contains("Record<string, User>")
            || commands_file.contains("{ [key: string]: User }")
    );
}

/// Test event payload type discovery when emitting from helper functions
/// Verifies that variable types are correctly inferred from function parameters
#[test]
fn test_event_payload_discovery_from_helper_function() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use tauri::{AppHandle, Manager};
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct ProgressUpdate {
            pub task_id: String,
            pub progress: f64,
            pub message: String,
        }

        /// Command that uses a helper function to emit events
        #[tauri::command]
        pub async fn process_task(app: AppHandle, task_id: String) -> Result<String, String> {
            let update = ProgressUpdate {
                task_id: task_id.clone(),
                progress: 50.0,
                message: "Processing".to_string(),
            };
            emit_progress(app, &update);
            Ok(format!("Task {} completed", task_id))
        }

        /// Helper function that emits the event with a reference parameter
        pub fn emit_progress(app: AppHandle, update: &ProgressUpdate) {
            app.emit("progress-update", update).unwrap();
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    let events = analyzer.get_discovered_events();

    // Verify the command was found
    assert_eq!(commands.len(), 1);

    // Verify the event was discovered with correct payload type
    assert_eq!(events.len(), 1, "Should discover one event");
    assert_eq!(events[0].event_name, "progress-update");
    assert_eq!(
        events[0].payload_type, "ProgressUpdate",
        "Should infer ProgressUpdate type from function parameter, got: {}",
        events[0].payload_type
    );

    // Generate code and verify struct is included
    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("zod"),
        None,
    );

    let types = generator.read_file("types.ts");
    assert!(
        types.contains("ProgressUpdate"),
        "Should include ProgressUpdate in types.ts. Got:\n{}",
        types
    );

    let events_file = generator.read_file("events.ts");
    assert!(
        events_file.contains("ProgressUpdate"),
        "Should reference ProgressUpdate in events.ts. Got:\n{}",
        events_file
    );
}

/// Test complex enum (discriminated union) TypeScript generation
#[test]
fn test_complex_enum_typescript_generation() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(tag = "type")]
        pub enum Message {
            Quit,
            Move(i32, i32),
            Write(String),
            ChangeColor { r: u8, g: u8, b: u8 },
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub enum Status {
            Active,
            Inactive,
            Pending,
        }

        #[tauri::command]
        pub fn send_message(msg: Message) -> Result<Status, String> {
            Ok(Status::Active)
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("none"),
        None,
    );

    let types = generator.read_file("types.ts");

    // Simple enum should be string literal union
    assert!(
        types.contains(r#"export type Status = "Active" | "Inactive" | "Pending";"#),
        "Simple enum should use string literal union. Got:\n{}",
        types
    );

    // Complex enum should be discriminated union
    assert!(
        types.contains("export type Message ="),
        "Complex enum should have type declaration. Got:\n{}",
        types
    );

    // Check for discriminated union structure
    assert!(
        types.contains(r#"type: "Quit""#),
        "Should have Quit variant. Got:\n{}",
        types
    );
    assert!(
        types.contains(r#"type: "Move""#),
        "Should have Move variant. Got:\n{}",
        types
    );
    assert!(
        types.contains(r#"type: "Write""#),
        "Should have Write variant. Got:\n{}",
        types
    );
    assert!(
        types.contains(r#"type: "ChangeColor""#),
        "Should have ChangeColor variant. Got:\n{}",
        types
    );

    // Check tuple variant has data field
    assert!(
        types.contains("data:"),
        "Tuple variants should have data field. Got:\n{}",
        types
    );

    // Check struct variant has named fields
    assert!(
        types.contains("r: number"),
        "Struct variant should have r field. Got:\n{}",
        types
    );
}

/// Test complex enum Zod schema generation (discriminated union)
#[test]
fn test_complex_enum_zod_generation() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};

        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(tag = "kind")]
        pub enum Action {
            Start,
            Move { x: i32, y: i32 },
            Send(String),
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub enum Status {
            Active,
            Inactive,
        }

        #[tauri::command]
        pub fn perform_action(action: Action) -> Result<Status, String> {
            Ok(Status::Active)
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("zod"),
        None,
    );

    let types = generator.read_file("types.ts");

    // Simple enum should use z.enum
    assert!(
        types.contains("StatusSchema = z.enum"),
        "Simple enum should use z.enum. Got:\n{}",
        types
    );
    assert!(
        types.contains(r#"["Active", "Inactive"]"#),
        "Simple enum should list variants. Got:\n{}",
        types
    );

    // Complex enum should use z.discriminatedUnion
    assert!(
        types.contains("ActionSchema = z.discriminatedUnion"),
        "Complex enum should use z.discriminatedUnion. Got:\n{}",
        types
    );

    // Check discriminator is "kind" (from serde tag)
    assert!(
        types.contains(r#"z.discriminatedUnion("kind""#),
        "Should use 'kind' as discriminator. Got:\n{}",
        types
    );

    // Check unit variant
    assert!(
        types.contains(r#"z.literal("Start")"#),
        "Should have Start variant. Got:\n{}",
        types
    );

    // Check struct variant with named fields
    assert!(
        types.contains(r#"z.literal("Move")"#),
        "Should have Move variant. Got:\n{}",
        types
    );
    assert!(
        types.contains("x:") && types.contains("y:"),
        "Move variant should have x and y fields. Got:\n{}",
        types
    );

    // Check tuple variant with data field
    assert!(
        types.contains(r#"z.literal("Send")"#),
        "Should have Send variant. Got:\n{}",
        types
    );
    assert!(
        types.contains("data:"),
        "Tuple variant should have data field. Got:\n{}",
        types
    );

    // Verify type inference
    assert!(
        types.contains("export type Action = z.infer<typeof ActionSchema>"),
        "Should export inferred Action type. Got:\n{}",
        types
    );
    assert!(
        types.contains("export type Status = z.infer<typeof StatusSchema>"),
        "Should export inferred Status type. Got:\n{}",
        types
    );
}

/// Test fully qualified types (::core::option::Option, ::std::vec::Vec) with nested types
/// This tests the fix for handling types with full module paths like Protobuf generated code
#[test]
fn test_fully_qualified_types_with_nested_structs() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        use serde::{Deserialize, Serialize};

        /// Simulates protobuf-generated field type with full qualification
        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct RtpParameters {
            pub mid: String,
            pub codecs: Vec<String>,
        }

        #[derive(Debug, Clone, Serialize, Deserialize)]
        pub struct ConsumedResponse {
            pub consumer_id: String,
            pub producer_id: String,
            pub kind: String,
            /// This field uses fully qualified Option type as in protobuf generated code
            pub rtp_parameters: ::core::option::Option<RtpParameters>,
        }

        #[tauri::command]
        pub fn get_consumed_response() -> Result<ConsumedResponse, String> {
            Ok(ConsumedResponse {
                consumer_id: "123".to_string(),
                producer_id: "456".to_string(),
                kind: "audio".to_string(),
                rtp_parameters: None,
            })
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();
    assert_eq!(commands.len(), 1);

    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("none"),
        None,
    );

    let types = generator.read_file("types.ts");

    // Both ConsumedResponse AND RtpParameters should be generated
    assert!(
        types.contains("export interface ConsumedResponse"),
        "Should generate ConsumedResponse type. Got:\n{}",
        types
    );
    assert!(
        types.contains("export interface RtpParameters"),
        "Should generate RtpParameters type (nested struct). Got:\n{}",
        types
    );

    // ConsumedResponse should reference RtpParameters
    assert!(
        types.contains("rtp_parameters?:") && types.contains("RtpParameters"),
        "ConsumedResponse should have rtp_parameters field of type RtpParameters. Got:\n{}",
        types
    );

    // RtpParameters fields should be present
    assert!(
        types.contains("mid:") && types.contains("codecs:"),
        "RtpParameters should have mid and codecs fields. Got:\n{}",
        types
    );
}

/// Regression test for issue #46: a command declared more than once under
/// mutually-exclusive `#[cfg(...)]` gates (the standard cross-platform Tauri
/// pattern) must produce a single TypeScript declaration, not duplicates that
/// trigger TS2323/TS2393/TS2451.
#[test]
fn test_cfg_gated_duplicate_command_emitted_once() {
    let project = TestProject::new();

    project.write_file(
        "main.rs",
        r#"
        #[tauri::command]
        #[cfg(target_os = "windows")]
        pub fn cmd_update_app_icon(variant: String) -> Result<(), String> {
            Ok(())
        }

        #[tauri::command]
        #[cfg(not(target_os = "windows"))]
        pub fn cmd_update_app_icon(variant: String) -> Result<(), String> {
            Err("Only supported on Windows".into())
        }
    "#,
    );

    let (analyzer, commands) = project.analyze();

    let generator = TestGenerator::new();
    generator.generate(
        &commands,
        analyzer.get_discovered_structs(),
        &analyzer,
        Some("zod"),
        None,
    );

    let commands_ts = generator.read_file("commands.ts");
    let fn_occurrences = commands_ts
        .matches("export async function cmdUpdateAppIcon")
        .count();
    assert_eq!(
        fn_occurrences, 1,
        "cfg-gated command should be emitted exactly once. Got:\n{}",
        commands_ts
    );

    // The generated Params type/schema must also be emitted once: duplicate
    // declarations would trigger TS2300 (duplicate identifier).
    let types_ts = generator.read_file("types.ts");
    let params_occurrences = types_ts
        .matches("export const CmdUpdateAppIconParamsSchema")
        .count();
    assert_eq!(
        params_occurrences, 1,
        "cfg-gated command's Params schema should be declared exactly once. Got:\n{}",
        types_ts
    );
}