alef 0.91.0

Opinionated polyglot binding generator for Rust libraries
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
use super::*;
use crate::core::ir::{EnumVariant, FieldDef, ParamDef, TypeDef, TypeRef};

#[test]
fn format_jsdoc_escapes_embedded_block_comment_closers() {
    let lines = format_jsdoc("Supports literal `/** example */` syntax.", "  ");

    assert_eq!(lines, vec!["  /** Supports literal `/** example * /` syntax. */"]);
}

fn make_param(name: &str, optional: bool) -> ParamDef {
    ParamDef {
        name: name.to_string(),
        ty: TypeRef::String,
        optional,
        default: None,
        sanitized: false,
        typed_default: None,
        is_ref: false,
        is_mut: false,
        newtype_wrapper: None,
        original_type: None,
        map_is_ahash: false,
        map_key_is_cow: false,
        vec_inner_is_ref: false,
        map_is_btree: false,
        core_wrapper: crate::core::ir::CoreWrapper::None,
    }
}

/// TypeScript TS1016: required parameter must not follow optional parameter.
/// A visitor method like `visit_code_block(ctx, lang?: Option<str>, code: str)`
/// must be reordered to `visit_code_block(ctx, code, lang?)` in the `.d.ts`.
#[test]
fn dts_params_reorders_required_after_optional() {
    let params = vec![
        make_param("ctx", false),
        make_param("lang", true),
        make_param("code", false),
    ];
    let result = dts_params(&params, &ahash::AHashSet::new());
    let ctx_pos = result.find("ctx:").expect("ctx not found");
    let code_pos = result.find("code:").expect("code not found");
    let lang_pos = result.find("lang?:").expect("lang? not found");
    assert!(ctx_pos < lang_pos, "ctx should come before lang?: {result}");
    assert!(code_pos < lang_pos, "code should come before lang?: {result}");
}

/// When params are already in valid order (all required before all optional),
/// the output must be unchanged — no unnecessary reordering.
#[test]
fn dts_params_preserves_already_valid_order() {
    let params = vec![
        make_param("ctx", false),
        make_param("code", false),
        make_param("lang", true),
    ];
    let result = dts_params(&params, &ahash::AHashSet::new());
    assert_eq!(result, "ctx: string, code: string, lang?: string | undefined | null");
}

/// All-required params: order must be preserved exactly.
#[test]
fn dts_params_all_required_preserves_order() {
    let params = vec![make_param("a", false), make_param("b", false), make_param("c", false)];
    let result = dts_params(&params, &ahash::AHashSet::new());
    assert_eq!(result, "a: string, b: string, c: string");
}

#[test]
fn dts_params_treats_defaulted_params_as_optional() {
    let mut params = vec![make_param("path", false), make_param("config", false)];
    params[1].default = Some("Default::default()".to_string());
    let result = dts_params(&params, &ahash::AHashSet::new());
    assert_eq!(
        result, "path: string, config?: string | undefined | null",
        "defaulted params must be optional in generated declarations"
    );
}

/// Regression test for a `.d.ts` that does not typecheck standalone: a type's own
/// declaration and every reference to that type elsewhere in the file must use the exact
/// same public name. `gen_dts` is called with a real NAPI-RS wrapper prefix ("Js") — the
/// prefix `#[napi(js_name = "...")]` strips off the compiled Rust struct name — to prove the
/// prefix can never leak into either side. Both `dts_type`'s `TypeRef::Named` arm and every
/// declaration site in `gen_dts` route the public name through the single
/// `naming::node_type_name` function, so they cannot independently disagree.
#[test]
fn dts_declaration_and_reference_names_agree_for_every_named_type() {
    let api = ApiSurface {
        types: vec![
            TypeDef {
                name: "Message".to_string(),
                ..Default::default()
            },
            TypeDef {
                name: "ChatCompletionRequest".to_string(),
                fields: vec![
                    FieldDef {
                        name: "messages".to_string(),
                        ty: TypeRef::Vec(Box::new(TypeRef::Named("Message".to_string()))),
                        optional: true,
                        ..Default::default()
                    },
                    FieldDef {
                        name: "stop".to_string(),
                        ty: TypeRef::Named("StopSequence".to_string()),
                        optional: true,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            TypeDef {
                name: "StopSequence".to_string(),
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "Js",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    let cases = [
        ("export interface Message {", "declaration of Message"),
        (
            "readonly messages?: Array<Message>",
            "reference to Message from ChatCompletionRequest.messages",
        ),
        ("export interface StopSequence {", "declaration of StopSequence"),
        (
            "readonly stop?: StopSequence",
            "reference to StopSequence from ChatCompletionRequest.stop",
        ),
    ];
    for (expected_line, description) in cases {
        assert!(
            dts.contains(expected_line),
            "{description}: expected to find {expected_line:?} in:\n{dts}"
        );
    }
    for leaked in ["JsMessage", "JsStopSequence", "JsChatCompletionRequest"] {
        assert!(
            !dts.contains(leaked),
            "no NAPI-RS wrapper prefix may leak into the .d.ts, found {leaked:?}:\n{dts}"
        );
    }
}

#[test]
fn trait_bridge_dts_return_type_wraps_async_methods_in_promise() {
    assert_eq!(
        trait_bridge_dts_return_type(&TypeRef::Named("ExtractionResult".to_string()), true),
        "Promise<ExtractionResult>"
    );
    assert_eq!(trait_bridge_dts_return_type(&TypeRef::Unit, true), "Promise<void>");
    assert_eq!(
        trait_bridge_dts_return_type(&TypeRef::Named("ExtractionResult".to_string()), false),
        "ExtractionResult"
    );
}

#[test]
fn plugin_trait_bridge_requires_name_in_typescript_interface() {
    let typ = TypeDef {
        name: "DocumentExtractor".to_string(),
        rust_path: String::new(),
        original_rust_path: String::new(),
        fields: Vec::new(),
        methods: Vec::new(),
        is_opaque: false,
        is_clone: false,
        is_copy: false,
        doc: String::new(),
        cfg: None,
        is_trait: true,
        has_default: false,
        has_stripped_cfg_fields: false,
        is_return_type: false,
        serde_rename_all: None,
        has_serde: false,
        serde_container_default: false,
        serde_container_conversion: Default::default(),
        super_traits: Vec::new(),
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_variant_wrapper: false,

        has_lifetime_params: false,
        has_private_fields: false,
        version: Default::default(),
    };
    let bridges = vec![crate::core::config::TraitBridgeConfig {
        trait_name: "DocumentExtractor".to_string(),
        super_trait: Some("Plugin".to_string()),
        ..Default::default()
    }];
    assert!(trait_bridge_requires_plugin_name(&typ, &bridges));
}

#[test]
fn adjacent_enum_dts_declares_runtime_namespace() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "Action".to_string(),
            serde_tag: Some("type".to_string()),
            serde_content: Some("output".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![
                EnumVariant {
                    name: "Skip".to_string(),
                    ..Default::default()
                },
                EnumVariant {
                    name: "Custom".to_string(),
                    fields: vec![FieldDef {
                        name: "_0".to_string(),
                        ty: TypeRef::String,
                        ..Default::default()
                    }],
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );
    assert!(dts.contains("| { type: 'custom'; output: string }"));
    assert!(dts.contains("export declare const Action: {"));
    assert!(dts.contains("readonly Skip: Action;"));
    assert!(dts.contains("Custom(output: string): Action;"));
}

/// Internally-tagged enums whose variants are newtype wrappers around struct types must
/// declare a discriminated union keyed by the variant-derived field name (e.g. `system`,
/// `user`) — not the tuple field's synthetic `_0` name, and not the napi glue's internal
/// flattened `#[napi(object)]` representation. Regression test for the `0:` key bug and for
/// the flattening regression introduced alongside its original fix (see
/// `internally_tagged_struct_variants_declare_discriminated_union` for the more common
/// struct-variant case).
#[test]
fn internally_tagged_newtype_variants_declare_discriminated_union() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "InternalNewtype".to_string(),
            serde_tag: Some("role".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![
                EnumVariant {
                    name: "System".to_string(),
                    fields: vec![FieldDef {
                        name: "_0".to_string(),
                        ty: TypeRef::Named("SystemMessage".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                EnumVariant {
                    name: "User".to_string(),
                    fields: vec![FieldDef {
                        name: "_0".to_string(),
                        ty: TypeRef::Named("UserMessage".to_string()),
                        ..Default::default()
                    }],
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert_eq!(
        dts.lines()
            .skip_while(|l| *l != "export type InternalNewtype =")
            .take(3)
            .collect::<Vec<_>>(),
        vec![
            "export type InternalNewtype =",
            "  | { role: 'system'; system: SystemMessage }",
            "  | { role: 'user'; user: UserMessage }",
        ],
        "expected a discriminated union keyed by the variant-derived field name, got:\n{dts}"
    );
    assert!(
        !dts.contains("0:"),
        "must not emit the tuple field's synthetic `_0` name as a `0:` key:\n{dts}"
    );
    assert!(
        !dts.contains("system?:") && !dts.contains("user?:"),
        "a field belonging to only one variant must not be optional:\n{dts}"
    );
}

/// The `FormatMetadata` defect this task fixes: when `ApiSurface::types` resolves the wrapped
/// struct, an internally-tagged newtype variant's `.d.ts` union member must flatten that
/// struct's OWN fields onto the tag object -- `{"format_type":"excel","sheet_count":2,...}` is
/// the real serde wire, never `{"format_type":"excel","excel":{"sheet_count":2,...}}`.
#[test]
fn internally_tagged_newtype_variant_flattens_wrapped_struct_when_type_resolves() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "FormatMetadata".to_string(),
            serde_tag: Some("format_type".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![EnumVariant {
                name: "Excel".to_string(),
                // `is_tuple` mirrors what the extractor emits for `Excel(ExcelMetadata)`: a
                // `Fields::Unnamed` variant sets the flag AND names the field `_0`. Setting only
                // the name models a NAMED-fields variant whose field is literally called `_0`,
                // which serde does not flatten. ~keep
                is_tuple: true,
                fields: vec![FieldDef {
                    name: "_0".to_string(),
                    ty: TypeRef::Named("ExcelMetadata".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }],
        types: vec![TypeDef {
            name: "ExcelMetadata".to_string(),
            fields: vec![
                FieldDef {
                    name: "sheet_count".to_string(),
                    ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::U32),
                    ..Default::default()
                },
                FieldDef {
                    name: "sheet_names".to_string(),
                    ty: TypeRef::Vec(Box::new(TypeRef::String)),
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert_eq!(
        dts.lines()
            .skip_while(|l| *l != "export type FormatMetadata =")
            .take(2)
            .collect::<Vec<_>>(),
        vec![
            "export type FormatMetadata =",
            // References the SAME idiomatic `ExcelMetadata` interface every other field in the
            // file uses -- not a second, JSON-shaped `__AlefWireExcelMetadata` duplicate. A
            // binding presents exactly one public shape per Rust type; `ExcelMetadata` already
            // gets `export interface ExcelMetadata { readonly sheetCount?: number; ... }`
            // declared below via the ordinary `Decl::Interface` path (`ExcelMetadata` is a plain,
            // non-opaque, non-transparent type in `api.types`), so this reuses it instead of
            // resynthesizing a snake_case sibling nobody but this passthrough path could see. ~keep
            "  | ({ formatType: \"excel\" } & ExcelMetadata)",
        ],
        "expected the wrapped struct's own fields flattened onto the tag object, got:\n{dts}"
    );
    assert!(
        !dts.contains("excel: ExcelMetadata") && !dts.contains("excel?: ExcelMetadata"),
        "must not declare the old nested `excel: ExcelMetadata` member once the type resolves:\n{dts}"
    );
    assert!(
        !dts.contains("__AlefWire"),
        "must not synthesize a duplicate JSON-shaped wire type once the payload resolves to an \
         idiomatic declared interface:\n{dts}"
    );
    assert!(
        dts.contains("export interface ExcelMetadata {") && dts.contains("readonly sheetCount: number"),
        "the idiomatic interface referenced by the union must actually be declared, in host \
         camelCase, elsewhere in the file:\n{dts}"
    );
}

/// The one struct shape that still needs a synthesized wire type: a
/// `#[serde(transparent)]` single-field newtype. Its wire form is the BARE inner value with no
/// wrapper object at all (`sheet_count` alone, not `{ inner: sheet_count }`), which the
/// idiomatic napi interface -- a real one-field struct -- cannot express, so referencing it
/// would describe the wrong shape.
#[test]
fn transparent_newtype_payload_still_collapses_to_its_inner_type() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "FormatMetadata".to_string(),
            serde_tag: Some("format_type".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![EnumVariant {
                name: "Excel".to_string(),
                is_tuple: true,
                fields: vec![FieldDef {
                    name: "_0".to_string(),
                    ty: TypeRef::Named("SheetCount".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }],
        types: vec![TypeDef {
            name: "SheetCount".to_string(),
            fields: vec![FieldDef {
                name: "_0".to_string(),
                ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::U32),
                ..Default::default()
            }],
            serde_container_conversion: crate::core::ir::SerdeContainerConversion {
                transparent: true,
                ..Default::default()
            },
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("({ formatType: \"excel\" } & __AlefWireSheetCount)"),
        "a transparent newtype has no idiomatic interface to reference (its wire form is the \
         bare inner value, not a wrapper object), so it must still synthesize its own alias:\n{dts}"
    );
    assert!(
        dts.contains("export type __AlefWireSheetCount = number;"),
        "the synthesized alias must collapse to the transparent field's inner type, not a \
         one-field wrapper object:\n{dts}"
    );
}

/// A struct with an explicit `#[serde(rename = "...")]` field must NOT reuse its idiomatic
/// `Decl::Interface`: that interface's `js_name` comes from `to_node_name` on the bare Rust
/// identifier alone (napi's ABI-level marshalling name), never from `serde_rename` -- but the
/// JSON this passthrough path actually emits IS keyed by the serde rename. Referencing the
/// interface here would advertise a property (`internalName`) the real JSON never carries,
/// while silently omitting the one it does (`external_name`). This must keep synthesizing its
/// own wire alias so the declared shape matches the actual JSON exactly.
#[test]
fn payload_field_with_explicit_serde_rename_declines_the_idiomatic_interface() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "FormatMetadata".to_string(),
            serde_tag: Some("format_type".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![EnumVariant {
                name: "Excel".to_string(),
                is_tuple: true,
                fields: vec![FieldDef {
                    name: "_0".to_string(),
                    ty: TypeRef::Named("ExcelMetadata".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }],
        types: vec![TypeDef {
            name: "ExcelMetadata".to_string(),
            fields: vec![FieldDef {
                name: "internal_name".to_string(),
                ty: TypeRef::String,
                serde_rename: Some("external_name".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("({ formatType: \"excel\" } & __AlefWireExcelMetadata)"),
        "must fall back to a synthesized wire alias once a field's serde rename could disagree \
         with the idiomatic interface's `to_node_name`-derived key, got:\n{dts}"
    );
    assert!(
        dts.contains("export type __AlefWireExcelMetadata = { external_name: string };"),
        "the synthesized wire type must key the field by its explicit serde rename VERBATIM \
         (`external_name` -- author intent, never recased), not the Rust identifier's camelCase \
         (`internalName`):\n{dts}"
    );
}

/// Negative control: adjacent tagging (`#[serde(tag, content)]`) nests a newtype variant's
/// payload under the `content` key by design and is handled by a different `gen_dts` branch
/// entirely -- it must never flatten, even when `ApiSurface::types` resolves the wrapped struct.
#[test]
fn adjacently_tagged_newtype_variant_keeps_nested_content_even_when_type_resolves() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "FormatMetadata".to_string(),
            serde_tag: Some("format_type".to_string()),
            serde_content: Some("data".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![EnumVariant {
                name: "Excel".to_string(),
                // `is_tuple` mirrors what the extractor emits for `Excel(ExcelMetadata)`: a
                // `Fields::Unnamed` variant sets the flag AND names the field `_0`. Setting only
                // the name models a NAMED-fields variant whose field is literally called `_0`,
                // which serde does not flatten. ~keep
                is_tuple: true,
                fields: vec![FieldDef {
                    name: "_0".to_string(),
                    ty: TypeRef::Named("ExcelMetadata".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }],
        types: vec![TypeDef {
            name: "ExcelMetadata".to_string(),
            fields: vec![FieldDef {
                name: "sheet_count".to_string(),
                ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::U32),
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    // Scoped to the `FormatMetadata` union member itself, not a global substring search:
    // `ExcelMetadata`'s own standalone `.d.ts` interface legitimately declares `sheetCount`
    // regardless of the flattening decision, so a bare `dts.contains("sheetCount")` would fire
    // even when adjacent tagging correctly nests the payload. ~keep
    assert_eq!(
        dts.lines()
            .skip_while(|l| *l != "export type FormatMetadata =")
            .take(2)
            .collect::<Vec<_>>(),
        vec![
            "export type FormatMetadata =",
            "  | { format_type: 'excel'; data: ExcelMetadata }",
        ],
        "adjacent tagging must keep the payload nested under its content field, not flatten it \
         onto the tag object:\n{dts}"
    );
}

/// The reported regression: an internally-tagged enum whose variants are struct variants
/// (e.g. `AuthConfig::Basic { username, password }`) must declare a real discriminated union
/// — one member per variant, each variant's own fields required — not a single flattened
/// object with every field made optional. Each variant serializes to its own flat object on
/// the wire (`{"type":"basic","username":"...","password":"..."}`), so the union is a
/// one-to-one match for what a caller actually receives.
#[test]
fn internally_tagged_struct_variants_declare_discriminated_union() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "AuthConfig".to_string(),
            serde_tag: Some("type".to_string()),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![
                EnumVariant {
                    name: "Basic".to_string(),
                    fields: vec![
                        FieldDef {
                            name: "username".to_string(),
                            ty: TypeRef::String,
                            ..Default::default()
                        },
                        FieldDef {
                            name: "password".to_string(),
                            ty: TypeRef::String,
                            ..Default::default()
                        },
                    ],
                    ..Default::default()
                },
                EnumVariant {
                    name: "Bearer".to_string(),
                    fields: vec![FieldDef {
                        name: "token".to_string(),
                        ty: TypeRef::String,
                        ..Default::default()
                    }],
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert_eq!(
        dts.lines()
            .skip_while(|l| *l != "export type AuthConfig =")
            .take(3)
            .collect::<Vec<_>>(),
        vec![
            "export type AuthConfig =",
            "  | { type: 'basic'; username: string; password: string }",
            "  | { type: 'bearer'; token: string }",
        ],
        "expected one discriminated-union member per variant with required fields, got:\n{dts}"
    );
    assert!(
        !dts.contains("username?:") && !dts.contains("password?:") && !dts.contains("token?:"),
        "a field belonging to only one variant must not be optional:\n{dts}"
    );
    assert!(
        !dts.contains("export type AuthConfig = {"),
        "must not emit a single flattened object type:\n{dts}"
    );
}

/// `#[serde(tag = "kind")] enum E { A, B }` serializes as `{"kind":"A"}` — internal tagging is
/// always an object, even when every variant is a unit variant. `is_data_enum` must not
/// require a data-bearing variant, or an all-unit internally-tagged enum wrongly falls back
/// to a plain string enum declaration.
#[test]
fn internally_tagged_all_unit_variants_declare_object_not_string_enum() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "InternalAllUnit".to_string(),
            serde_tag: Some("kind".to_string()),
            variants: vec![
                EnumVariant {
                    name: "A".to_string(),
                    ..Default::default()
                },
                EnumVariant {
                    name: "B".to_string(),
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("export type InternalAllUnit = { kind: 'A' | 'B' };"),
        "expected an object type matching the napi glue struct, got:\n{dts}"
    );
    assert!(
        !dts.contains("export declare enum InternalAllUnit"),
        "must not emit a plain string enum for an internally-tagged enum:\n{dts}"
    );
}

/// Regression test: a plain `#[napi(string_enum = "snake_case")]` declaration in `.d.ts` must
/// use the wire value napi-rs's own `convert_case`-based macro actually emits at runtime, not
/// the value `wire_variant_value`'s serde-oriented case transform computes. The two disagree for
/// a variant name with a letter-to-digit boundary (mirrors crawlberg's real
/// `JsContentFilterKind::Bm25`, whose only variant is `Bm25`): serde's helper gives `"bm25"`,
/// napi's actual runtime value is `"bm_25"`. Before this fix the `.d.ts` declared `Bm25 = "bm25"`,
/// so TypeScript accepted a string literal the Rust `FromNapiValue` conversion rejected.
#[test]
fn plain_string_enum_dts_uses_napis_own_case_algorithm_not_serdes() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "ContentFilterKind".to_string(),
            serde_rename_all: Some("snake_case".to_string()),
            variants: vec![EnumVariant {
                name: "Bm25".to_string(),
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("Bm25 = \"bm_25\","),
        "expected napi's own convert_case-derived wire value \"bm_25\", got:\n{dts}"
    );
    assert!(
        !dts.contains("Bm25 = \"bm25\","),
        "must not declare serde's wire value \"bm25\" — napi-rs rejects it at runtime:\n{dts}"
    );
}

/// `#[serde(untagged)]` enums serialize each variant as its own bare shape (no wrapper, no
/// discriminant) — a newtype variant as its inner value, a struct variant as its own object.
/// The napi glue already treats the whole enum as opaque `serde_json::Value`, so this is a
/// `.d.ts`-only fix: the union of real per-variant shapes.
#[test]
fn untagged_enum_declares_bare_union_of_variant_shapes() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "Untagged".to_string(),
            serde_untagged: true,
            variants: vec![
                EnumVariant {
                    name: "Single".to_string(),
                    is_tuple: true,
                    fields: vec![FieldDef {
                        name: "_0".to_string(),
                        ty: TypeRef::String,
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                EnumVariant {
                    name: "Pair".to_string(),
                    fields: vec![
                        FieldDef {
                            name: "x".to_string(),
                            ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::I32),
                            ..Default::default()
                        },
                        FieldDef {
                            name: "y".to_string(),
                            ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::I32),
                            ..Default::default()
                        },
                    ],
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("export type Untagged =\n  | string\n  | { x: number; y: number }"),
        "expected a bare union of each variant's own shape, got:\n{dts}"
    );
    assert!(
        !dts.contains("export declare enum Untagged"),
        "must not emit a plain string enum for an untagged data enum:\n{dts}"
    );
}

/// The other shape with no idiomatic declaration to reference: an OPAQUE struct. It gets a
/// `Decl::Class` (a handle wrapper with no plain-object shape), never a `Decl::Interface`, so a
/// JSON-passthrough payload reaching one still needs its own synthesized structural type.
#[test]
fn untagged_enum_variant_wrapping_an_opaque_struct_still_synthesizes_a_wire_type() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "Untagged".to_string(),
            serde_untagged: true,
            variants: vec![EnumVariant {
                name: "Handle".to_string(),
                is_tuple: true,
                fields: vec![FieldDef {
                    name: "_0".to_string(),
                    ty: TypeRef::Named("OpaqueThing".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        }],
        types: vec![TypeDef {
            name: "OpaqueThing".to_string(),
            is_opaque: true,
            fields: vec![FieldDef {
                name: "label".to_string(),
                ty: TypeRef::String,
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("export type Untagged =\n  | __AlefWireOpaqueThing"),
        "an opaque struct has no idiomatic non-class declaration to reference, so the union \
         must still resolve through a synthesized wire type, got:\n{dts}"
    );
    assert!(
        dts.contains("export type __AlefWireOpaqueThing = { label"),
        "the synthesized wire type must describe the struct's own JSON shape, got:\n{dts}"
    );
}

/// A variant-level `#[serde(untagged)]` on an otherwise default-tagged enum (e.g.
/// `OutputFormat { Plain, Markdown, ..., #[serde(untagged)] Custom(String) }`) must declare a
/// flat string-literal union over the unit variants -- respecting `serde_rename_all` -- plus a
/// `(string & {})` tail that widens the type to accept the `Custom` payload while keeping
/// editor autocomplete for the known literals. This must NOT be the container-level-untagged
/// shape (`untagged_enum_declares_bare_union_of_variant_shapes` above): unit variants here are
/// NOT `null`, they keep their name as a literal. ~keep
#[test]
fn variant_untagged_enum_declares_literal_union_with_string_widening_tail() {
    let api = ApiSurface {
        enums: vec![EnumDef {
            name: "OutputFormat".to_string(),
            serde_rename_all: Some("lowercase".to_string()),
            variants: vec![
                EnumVariant {
                    name: "Plain".to_string(),
                    ..Default::default()
                },
                EnumVariant {
                    name: "Markdown".to_string(),
                    ..Default::default()
                },
                EnumVariant {
                    name: "Custom".to_string(),
                    is_tuple: true,
                    fields: vec![FieldDef {
                        name: "_0".to_string(),
                        ty: TypeRef::String,
                        ..Default::default()
                    }],
                    serde_untagged: true,
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("export type OutputFormat = \"plain\" | \"markdown\" | (string & {});"),
        "expected a literal union with a string-widening tail, got:\n{dts}"
    );
    assert!(
        !dts.contains("export declare enum OutputFormat"),
        "must not emit a nominal #[napi(string_enum)] declaration for a data-carrying enum:\n{dts}"
    );
    assert!(
        !dts.contains("type_tag") && !dts.contains("{ type:"),
        "must not emit the tagged-object shape:\n{dts}"
    );
}

#[test]
fn gen_dts_includes_service_entrypoint_bridge_functions() {
    use crate::core::ir::{EntrypointDef, EntrypointKind, MethodDef, ReceiverKind, ServiceDef};
    let api = ApiSurface {
        crate_name: "test".to_string(),
        version: "0.1.0".to_string(),
        types: vec![],
        functions: vec![],
        enums: vec![],
        errors: vec![],
        excluded_type_paths: Default::default(),
        excluded_trait_names: Default::default(),
        services: vec![ServiceDef {
            name: "App".to_string(),
            rust_path: "test::App".to_string(),
            constructor: MethodDef {
                name: "new".to_string(),
                params: vec![],
                return_type: TypeRef::Named("App".to_string()),
                is_async: false,
                is_static: false,
                error_type: None,
                receiver: Some(ReceiverKind::Owned),
                cfg: None,
                doc: String::new(),
                sanitized: false,
                trait_source: None,
                returns_ref: false,
                returns_cow: false,
                return_newtype_wrapper: None,
                has_default_impl: false,
                binding_excluded: false,
                binding_exclusion_reason: None,
                version: Default::default(),
            },
            configurators: vec![],
            registrations: vec![],
            entrypoints: vec![EntrypointDef {
                method: "into_router".to_string(),
                kind: EntrypointKind::Finalize,
                is_async: true,
                params: vec![],
                return_type: TypeRef::Unit,
                error_type: None,
                doc: String::new(),
            }],
            doc: String::new(),
            cfg: None,
        }],
        handler_contracts: vec![],
        unsupported_public_items: vec![],
    };
    let dts = gen_dts(
        &api,
        "",
        &ahash::AHashSet::new(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );
    assert!(
        dts.contains("export declare function appIntoRouter"),
        "dts should declare appIntoRouter bridge function for App.into_router"
    );
    assert!(
        dts.contains("registrations: Array<[string, any[], (...args: any[]) => any]>"),
        "service entrypoint should have registrations parameter"
    );
    assert!(
        dts.contains("Promise<void>"),
        "async into_router entrypoint should return Promise<void>"
    );
}

/// Regression: `gen_opaque_struct_methods` (`types.rs`) never generates a `#[napi]` wrapper
/// for an opaque instance method that takes another opaque type by value — opaque types only
/// implement `FromNapiValue` by reference — unless an adapter overrides it. `gen_dts` used to
/// iterate every method with no such check, so `index.d.ts` promised a method the compiled
/// extension does not export.
#[test]
fn opaque_by_value_param_without_adapter_is_not_declared_in_dts() {
    use crate::core::ir::{MethodDef, ReceiverKind};

    let api = ApiSurface {
        types: vec![
            TypeDef {
                name: "Worker".to_string(),
                is_opaque: true,
                methods: vec![MethodDef {
                    name: "process".to_string(),
                    receiver: Some(ReceiverKind::Ref),
                    cfg: None,
                    params: vec![ParamDef {
                        name: "handle".to_string(),
                        ty: TypeRef::Named("Handle".to_string()),
                        is_ref: false,
                        ..Default::default()
                    }],
                    return_type: TypeRef::Unit,
                    ..Default::default()
                }],
                ..Default::default()
            },
            TypeDef {
                name: "Handle".to_string(),
                is_opaque: true,
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        !dts.contains("process("),
        "no #[napi] wrapper exists for an opaque-by-value param with no adapter override: {dts}"
    );
}

/// Regression, static side: `gen_static_method` never registers a sanitized static method
/// with no adapter override either (see `opaque_static_method_is_dropped`).
#[test]
fn sanitized_static_method_without_adapter_is_not_declared_in_dts() {
    use crate::core::ir::MethodDef;

    let api = ApiSurface {
        types: vec![TypeDef {
            name: "Config".to_string(),
            is_opaque: true,
            methods: vec![MethodDef {
                name: "fromRaw".to_string(),
                receiver: None,
                cfg: None,
                is_static: true,
                sanitized: true,
                return_type: TypeRef::Named("Config".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        !dts.contains("static fromRaw"),
        "gen_static_method also drops a sanitized static method with no adapter override: {dts}"
    );
}

/// Control for the two regressions above: a delegatable instance method and a non-sanitized
/// static method must still be declared, proving the new filter doesn't over-drop.
#[test]
fn delegatable_methods_are_still_declared_in_dts() {
    use crate::core::ir::{MethodDef, ReceiverKind};

    let api = ApiSurface {
        types: vec![TypeDef {
            name: "Worker".to_string(),
            is_opaque: true,
            methods: vec![
                MethodDef {
                    name: "run".to_string(),
                    receiver: Some(ReceiverKind::Ref),
                    cfg: None,
                    return_type: TypeRef::Unit,
                    ..Default::default()
                },
                MethodDef {
                    name: "create".to_string(),
                    receiver: None,
                    cfg: None,
                    is_static: true,
                    return_type: TypeRef::Named("Worker".to_string()),
                    ..Default::default()
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    let dts = gen_dts(
        &api,
        "",
        &Default::default(),
        &[],
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        "",
        None,
    );

    assert!(
        dts.contains("run("),
        "delegatable instance method must still be declared: {dts}"
    );
    assert!(
        dts.contains("static create("),
        "non-sanitized static method must still be declared: {dts}"
    );
}