alef 0.22.27

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
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
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
//! Service-API codegen for the NAPI-RS (Node.js/TypeScript) backend.
//!
//! Generates two outputs per [`ServiceDef`]:
//!
//! 1. **`service.rs`** — Rust napi glue that wraps each registered JavaScript
//!    callable as `Arc<dyn <HandlerContractDef::trait_name>>` via an async
//!    callback bridge using ThreadsafeFunction, builds the core service via the
//!    owner type's registration and run entrypoints, and exposes a `#[napi]`
//!    entry point.
//!
//! 2. **`service.ts`** — An idiomatic TypeScript class mirroring the service's
//!    constructor, configurator methods, and registration methods (supporting
//!    both decorator and direct-register duality), with a `run(...)`/entrypoint
//!    that delegates to the native function.
//!
//! All names are derived entirely from the [`ApiSurface`] IR — no transport-
//! or domain-specific assumptions are made anywhere in this module.

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{ApiSurface, EntrypointKind, HandlerContractDef, RegistrationDef, ServiceDef, TypeRef};
use heck::{ToSnakeCase, ToUpperCamelCase};
use std::path::PathBuf;

// ───────────────────────────────────────────────────────────────── helpers ──

/// Convert a `TypeRef` to a TypeScript type annotation string.
fn typescript_type_annotation(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => "string".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "boolean".to_owned(),
                PrimitiveType::F32 | PrimitiveType::F64 => "number".to_owned(),
                _ => "number".to_owned(),
            }
        }
        TypeRef::Bytes => "Buffer".to_owned(),
        TypeRef::Optional(inner) => format!("{} | undefined", typescript_type_annotation(inner)),
        TypeRef::Vec(inner) => format!("{}[]", typescript_type_annotation(inner)),
        TypeRef::Map(k, v) => format!(
            "Record<{}, {}>",
            typescript_type_annotation(k),
            typescript_type_annotation(v)
        ),
        TypeRef::Unit => "void".to_owned(),
        TypeRef::Named(n) => n.clone(),
        TypeRef::Json => "any".to_owned(),
        TypeRef::Path => "string".to_owned(),
        TypeRef::Duration => "number".to_owned(),
    }
}

/// Find the `HandlerContractDef` by trait name in the surface.
fn find_contract<'a>(api: &'a ApiSurface, trait_name: &str) -> Option<&'a HandlerContractDef> {
    api.handler_contracts.iter().find(|c| c.trait_name == trait_name)
}

// ──────────────────────────────────────────────────────────── TypeScript output ──

/// Generate the idiomatic TypeScript service class (`service.ts`).
///
/// Produces a TypeScript module containing one class per service. Each class
/// exposes:
/// - A constructor mirroring [`ServiceDef::constructor`].
/// - Configurator methods from [`ServiceDef::configurators`].
/// - Registration methods from [`ServiceDef::registrations`] supporting both
///   decorator and direct-register patterns.
/// - A `run(...)` method derived from the first [`EntrypointKind::Run`]
///   entrypoint.
pub(super) fn gen_service_ts(api: &ApiSurface, native_module: &str) -> String {
    let mut out = String::new();

    // TypeScript preamble: import native bindings + types
    out.push_str("// Auto-generated service API class\n\n");
    out.push_str("import type { ");

    let mut imports = vec!["JsObject".to_owned()];
    for contract in &api.handler_contracts {
        // We'll import the wire DTO types for type annotations
        if let Some(req_ty) = &contract.wire_request_type {
            imports.push(req_ty.clone());
        }
        if let Some(resp_ty) = &contract.wire_response_type {
            imports.push(resp_ty.clone());
        }
    }
    // Add service constructor and configurator param types
    if let Some(service) = api.services.first() {
        for param in &service.constructor.params {
            if let TypeRef::Named(name) = &param.ty {
                imports.push(name.clone());
            }
        }
        for method in &service.configurators {
            for param in &method.params {
                if let TypeRef::Named(name) = &param.ty {
                    imports.push(name.clone());
                }
            }
        }
        // Add registration variant wrapper types, metadata param types, and fixed enum types
        for reg in &service.registrations {
            for variant in &reg.variants {
                if let Some(wrapper_call) = &variant.wrapper_call {
                    imports.push(wrapper_call.wrapper_type_name.clone());
                    // Extract enum types from Fixed args (e.g., "mycrate::Method::Get" → "Method")
                    for arg in &wrapper_call.args {
                        if let crate::core::ir::WrapperConstructorArg::Fixed {
                            param_name: _,
                            value_expr,
                        } = arg
                        {
                            // Split on :: and take the second-to-last part (the type name).
                            // "mycrate::Method::Get" → ["mycrate", "Method", "Get"] → "Method"
                            let parts: Vec<&str> = value_expr.split("::").collect();
                            if parts.len() >= 2 {
                                imports.push(parts[parts.len() - 2].to_string());
                            }
                        }
                    }
                }
                for param in &variant.signature_params {
                    if let TypeRef::Named(name) = &param.ty {
                        imports.push(name.clone());
                    }
                }
            }
        }
    }
    // Remove duplicates
    imports.sort();
    imports.dedup();

    out.push_str(&imports.join(", "));
    out.push_str(" } from \"../index\";\n");
    out.push_str(&format!(
        "import {{ {}_run }} from \"../index\";\n\n",
        api.services[0].name.to_snake_case()
    ));

    for service in &api.services {
        gen_service_class_ts(&mut out, service, api, native_module);
    }

    out
}

fn gen_service_class_ts(out: &mut String, service: &ServiceDef, api: &ApiSurface, _native_module: &str) {
    let class_name = &service.name;

    // Class docstring
    if !service.doc.is_empty() {
        out.push_str(&format!("/**\n * {}\n */\n", service.doc.trim().replace('\n', "\n * ")));
    }

    out.push_str(&format!("export class {class_name} {{\n"));
    out.push_str("  private _registrations: Array<[string, any[], (...args: any[]) => any]> = [];\n\n");

    // Static factory method for Node.js binding compatibility
    {
        let ctor = &service.constructor;
        let mut params = Vec::new();
        for p in &ctor.params {
            let ty = typescript_type_annotation(&p.ty);
            if p.optional {
                params.push(format!("{}: {} = undefined", p.name, ty));
            } else {
                params.push(format!("{}: {}", p.name, ty));
            }
        }

        let param_sig = params.join(", ");
        out.push_str("  /**\n");
        out.push_str(&format!("   * Create a new {class_name} instance.\n"));
        out.push_str("   */\n");
        if param_sig.is_empty() {
            out.push_str(&format!("  static new(): {class_name} {{\n"));
            out.push_str(&format!("    return new {class_name}();\n"));
        } else {
            out.push_str(&format!("  static new({param_sig}): {class_name} {{\n"));
            let params_for_ctor: Vec<&str> = ctor.params.iter().map(|p| p.name.as_str()).collect();
            out.push_str(&format!(
                "    return new {class_name}({});\n",
                params_for_ctor.join(", ")
            ));
        }
        out.push_str("  }\n\n");
    }

    // Constructor
    {
        let ctor = &service.constructor;
        let mut params = Vec::new();
        for p in &ctor.params {
            let ty = typescript_type_annotation(&p.ty);
            if p.optional {
                params.push(format!("{}: {} = undefined", p.name, ty));
            } else {
                params.push(format!("{}: {}", p.name, ty));
            }
        }

        out.push_str("  /**\n");
        if !ctor.doc.is_empty() {
            out.push_str(&format!("   * {}\n", ctor.doc.trim().replace('\n', "\n   * ")));
        }
        out.push_str("   */\n");

        let param_sig = params.join(", ");
        out.push_str(&format!("  constructor({param_sig}) {{\n"));
        out.push_str("    // Constructor initialization (parameters stored for future use)\n");
        out.push_str("  }\n\n");
    }

    // Configurator methods
    for method in &service.configurators {
        let mut params = Vec::new();
        for p in &method.params {
            let ty = typescript_type_annotation(&p.ty);
            if p.optional {
                params.push(format!("{}: {} = undefined", p.name, ty));
            } else {
                params.push(format!("{}: {}", p.name, ty));
            }
        }

        out.push_str("  /**\n");
        if !method.doc.is_empty() {
            out.push_str(&format!("   * {}\n", method.doc.trim().replace('\n', "\n   * ")));
        }
        out.push_str("   */\n");

        let param_sig = params.join(", ");
        let method_name = &method.name;
        out.push_str(&format!("  {method_name}({param_sig}): this {{\n"));
        out.push_str("    return this;\n");
        out.push_str("  }\n\n");
    }

    // Registration methods: support both decorator and direct patterns
    for reg in &service.registrations {
        gen_registration_method_ts(out, reg, service, api);
    }

    // Entrypoint methods
    for ep in &service.entrypoints {
        let mut params = Vec::new();
        for p in &ep.params {
            let ty = typescript_type_annotation(&p.ty);
            if p.optional {
                params.push(format!("{}: {} = undefined", p.name, ty));
            } else {
                params.push(format!("{}: {}", p.name, ty));
            }
        }

        let param_sig = params.join(", ");
        let ep_name = &ep.method;

        out.push_str("  /**\n");
        if !ep.doc.is_empty() {
            out.push_str(&format!("   * {}\n", ep.doc.trim().replace('\n', "\n   * ")));
        }
        out.push_str("   */\n");

        match ep.kind {
            EntrypointKind::Run => {
                out.push_str(&format!("  async {ep_name}({param_sig}): Promise<void> {{\n"));
                // Call native run function
                let native_fn = format!("{}_{}", class_name.to_snake_case(), ep_name);
                out.push_str(&format!("    return await {}(this._registrations", native_fn));
                for p in &ep.params {
                    out.push_str(&format!(", {}", p.name));
                }
                out.push_str(");\n");
                out.push_str("  }\n\n");
            }
            EntrypointKind::Finalize => {
                let return_ty = typescript_type_annotation(&ep.return_type);
                out.push_str(&format!("  {ep_name}({param_sig}): {return_ty} {{\n"));
                // Call native finalize function
                let native_fn = format!("{}_{}", class_name.to_snake_case(), ep_name);
                out.push_str(&format!("    return {}(this._registrations", native_fn));
                for p in &ep.params {
                    out.push_str(&format!(", {}", p.name));
                }
                out.push_str(");\n");
                out.push_str("  }\n\n");
            }
        }
    }

    while out.ends_with("\n\n") {
        out.pop();
    }
    out.push_str("}\n");
}

fn gen_registration_method_ts(out: &mut String, reg: &RegistrationDef, service: &ServiceDef, _api: &ApiSurface) {
    let method_name = &reg.method;
    let _class_name = &service.name;

    // Build metadata param signature (excluding the callback param)
    let mut meta_params: Vec<String> = reg
        .metadata_params
        .iter()
        .map(|p| {
            let ty = typescript_type_annotation(&p.ty);
            if p.optional {
                format!("{}: {} = undefined", p.name, ty)
            } else {
                format!("{}: {}", p.name, ty)
            }
        })
        .collect();

    // Decorator-factory form: supports @app.register(meta1, meta2) decorator syntax
    let meta_sig = meta_params.join(", ");

    out.push_str("  /**\n");
    if !reg.doc.is_empty() {
        out.push_str(&format!("   * {}\n", reg.doc.trim().replace('\n', "\n   * ")));
    }
    out.push_str("   */\n");

    out.push_str(&format!(
        "  {method_name}({meta_sig}): (fn: (...args: any[]) => any) => (...args: any[]) => any {{\n"
    ));

    // Closure that collects metadata and the callback
    let meta_names: Vec<&str> = reg.metadata_params.iter().map(|p| p.name.as_str()).collect();
    let meta_array = if meta_names.is_empty() {
        "[]".to_owned()
    } else {
        format!("[{}]", meta_names.join(", "))
    };

    out.push_str("    return (fn: (...args: any[]) => any) => {\n");
    out.push_str(&format!(
        "      this._registrations.push([\"{method_name}\", {meta_array}, fn]);\n"
    ));
    out.push_str("      return fn;\n");
    out.push_str("    };\n");
    out.push_str("  }\n\n");

    // Also expose a direct (non-decorator) register variant
    let direct_name = format!("register_{method_name}");
    if direct_name != *method_name {
        out.push_str("  /**\n");
        out.push_str(&format!("   * Register a {method_name} callback directly.\n"));
        out.push_str("   */\n");

        meta_params.push("handler: (...args: any[]) => any".to_string());
        let full_sig = meta_params.join(", ");
        out.push_str(&format!("  {direct_name}({full_sig}): this {{\n"));
        out.push_str(&format!(
            "    this._registrations.push([\"{method_name}\", {meta_array}, handler]);\n"
        ));
        out.push_str("    return this;\n");
        out.push_str("  }\n\n");
    }

    // Emit registration variants (shortcut methods)
    for variant in &reg.variants {
        gen_registration_variant_method_ts(out, variant, reg, service);
    }
}

/// Emit a TypeScript shortcut method for one registration variant.
///
/// The emission style depends on [`RegistrationVariant::style`]:
/// - [`RegistrationVariantStyle::VerbDecorator`] — only the direct method form
///   (`app.get(path, handler)` returning `this` for chaining).
/// - [`RegistrationVariantStyle::Builder`] — only the decorator-factory form
///   (`app.get(path)` returning a function that accepts the handler).
/// - [`RegistrationVariantStyle::Hybrid`] — both forms (overloaded).
fn gen_registration_variant_method_ts(
    out: &mut String,
    variant: &crate::core::ir::RegistrationVariant,
    reg: &RegistrationDef,
    _service: &ServiceDef,
) {
    use crate::core::ir::RegistrationVariantStyle;

    let variant_name = &variant.name;
    let base_method = &reg.method;

    // Build signature from variant's signature_params (without handler)
    let variant_params_no_handler: Vec<String> = variant
        .signature_params
        .iter()
        .map(|p| {
            let ty = typescript_type_annotation(&p.ty);
            if p.optional {
                format!("{}: {} = undefined", p.name, ty)
            } else {
                format!("{}: {}", p.name, ty)
            }
        })
        .collect();

    // Metadata array (shared by both forms)
    let metadata_array = if let Some(wrapper_call) = &variant.wrapper_call {
        let wrapper_type = &wrapper_call.wrapper_type_name;

        // Build the constructor args by substituting Fixed args and pulling Free args
        let mut ctor_args = Vec::new();
        for arg in &wrapper_call.args {
            match arg {
                crate::core::ir::WrapperConstructorArg::Fixed {
                    param_name: _,
                    value_expr,
                } => {
                    // Fixed args are Rust value expressions like "mycrate::Method::Get".
                    // Extract the type and variant for TypeScript: "mycrate::Method::Get" → "Method.Get"
                    let parts: Vec<&str> = value_expr.split("::").collect();
                    let ts_expr = if parts.len() >= 2 {
                        format!("{}.{}", parts[parts.len() - 2], parts[parts.len() - 1])
                    } else {
                        value_expr.clone()
                    };
                    ctor_args.push(ts_expr);
                }
                crate::core::ir::WrapperConstructorArg::Free { param } => {
                    // Free args come from the variant's signature params
                    ctor_args.push(param.name.clone());
                }
            }
        }
        let ctor_arg_str = ctor_args.join(", ");
        let metadata_param = &wrapper_call.metadata_param;

        // Return a tuple: (wrapper construction code, metadata array expression)
        let wrapper_code = format!("    const {metadata_param} = new {wrapper_type}({ctor_arg_str});\n");
        (wrapper_code, format!("[{metadata_param}]"))
    } else {
        // No wrapper constructor: build metadata array from variant params
        let mut metadata_values = Vec::new();
        for param in &variant.signature_params {
            metadata_values.push(param.name.clone());
        }

        let metadata_expr = if metadata_values.is_empty() {
            "[]".to_owned()
        } else {
            format!("[{}]", metadata_values.join(", "))
        };
        ("".to_owned(), metadata_expr)
    };

    match variant.style {
        RegistrationVariantStyle::VerbDecorator => {
            // Direct method form only: `app.get(path, handler): this`
            emit_variant_direct_method(
                out,
                variant_name,
                &variant_params_no_handler,
                base_method,
                &metadata_array.0,
                &metadata_array.1,
                variant,
            );
        }
        RegistrationVariantStyle::Builder => {
            // Decorator-factory form only: `app.get(path): (handler) => any`
            emit_variant_decorator_factory(
                out,
                variant_name,
                &variant_params_no_handler,
                base_method,
                &metadata_array.0,
                &metadata_array.1,
                variant,
            );
        }
        RegistrationVariantStyle::Hybrid => {
            // Both forms
            emit_variant_direct_method(
                out,
                variant_name,
                &variant_params_no_handler,
                base_method,
                &metadata_array.0,
                &metadata_array.1,
                variant,
            );
            emit_variant_decorator_factory(
                out,
                variant_name,
                &variant_params_no_handler,
                base_method,
                &metadata_array.0,
                &metadata_array.1,
                variant,
            );
        }
    }
}

/// Emit the direct method form for a registration variant: `app.get(path, handler): this`.
fn emit_variant_direct_method(
    out: &mut String,
    variant_name: &str,
    variant_params: &[String],
    base_method: &str,
    wrapper_code: &str,
    metadata_array: &str,
    variant: &crate::core::ir::RegistrationVariant,
) {
    let mut full_params = variant_params.to_vec();
    full_params.push("handler: (...args: any[]) => any".to_string());
    let full_sig = full_params.join(", ");

    out.push_str("  /**\n");
    if let Some(doc) = &variant.doc {
        out.push_str(&format!("   * {}\n", doc.trim().replace('\n', "\n   * ")));
    } else {
        out.push_str(&format!("   * Register a {} callback directly.\n", variant_name));
    }
    out.push_str("   */\n");

    out.push_str(&format!("  {variant_name}({full_sig}): this {{\n"));
    out.push_str(wrapper_code);
    out.push_str(&format!(
        "    this._registrations.push([\"{base_method}\", {metadata_array}, handler]);\n"
    ));
    out.push_str("    return this;\n");
    out.push_str("  }\n\n");
}

/// Emit the decorator-factory form for a registration variant: `app.get(path): (handler) => any`.
fn emit_variant_decorator_factory(
    out: &mut String,
    variant_name: &str,
    variant_params: &[String],
    base_method: &str,
    wrapper_code: &str,
    metadata_array: &str,
    variant: &crate::core::ir::RegistrationVariant,
) {
    let sig = variant_params.join(", ");

    out.push_str("  /**\n");
    if let Some(doc) = &variant.doc {
        out.push_str(&format!("   * {}\n", doc.trim().replace('\n', "\n   * ")));
    } else {
        out.push_str(&format!(
            "   * Register a {} callback via decorator factory.\n",
            variant_name
        ));
    }
    out.push_str("   */\n");

    out.push_str(&format!(
        "  {variant_name}({sig}): (fn: (...args: any[]) => any) => (...args: any[]) => any {{\n"
    ));
    out.push_str(wrapper_code);
    out.push_str("    return (fn: (...args: any[]) => any) => {\n");
    out.push_str(&format!(
        "      this._registrations.push([\"{base_method}\", {metadata_array}, fn]);\n"
    ));
    out.push_str("      return fn;\n");
    out.push_str("    };\n");
    out.push_str("  }\n\n");
}

// ──────────────────────────────────────────────────────────────── Rust glue ──

/// Generate the Rust napi glue module (`service.rs`).
///
/// For each service this emits:
/// - A `{ContractName}Bridge` struct that wraps a `ThreadsafeFunction` callable
///   and implements the handler contract trait, using NAPI's ThreadsafeFunction
///   to call JavaScript async callables from Rust async code.
/// - A `#[napi]` `{snake_service}_{entrypoint}` function that accepts the
///   collected registrations list and any entrypoint params, builds the native
///   service, and drives it.
pub(super) fn gen_service_rs(api: &ApiSurface, config: &ResolvedCrateConfig) -> String {
    let core_import = config.core_import_name();
    let mut out = String::new();

    // File-level allow attributes to keep clippy happy in generated code
    out.push_str("#![allow(clippy::too_many_arguments, clippy::unused_async)]\n\n");
    out.push_str("use napi::bindgen_prelude::*;\n");
    out.push_str("use napi::threadsafe_function::ThreadsafeFunction;\n");
    out.push_str("use napi_derive::napi;\n");
    out.push_str("use std::sync::Arc;\n\n");

    // Emit one handler bridge per unique handler contract referenced by any registration
    let referenced_contracts: Vec<&HandlerContractDef> = {
        let mut names: Vec<&str> = api
            .services
            .iter()
            .flat_map(|s| s.registrations.iter())
            .map(|r| r.callback_contract.as_str())
            .collect();
        names.sort_unstable();
        names.dedup();
        names.iter().filter_map(|n| find_contract(api, n)).collect()
    };

    for contract in &referenced_contracts {
        gen_handler_bridge(&mut out, contract, &core_import);
    }

    // Emit one napi function per service × entrypoint
    for service in &api.services {
        for ep in &service.entrypoints {
            gen_run_napi_function(&mut out, service, ep, api, &core_import);
        }
    }

    // Emit per-verb registration shortcuts wrapped in an impl block per service.
    // These methods use `&self` with interior mutability (via the configured
    // `host_app_inner_accessor`) and live inside an `impl` block — emitting them as
    // top-level free functions produces invalid Rust.
    let prefix = config.node_type_prefix();
    for service in &api.services {
        let has_variants = service.registrations.iter().any(|r| !r.variants.is_empty());
        if !has_variants {
            continue;
        }
        let app_type_name = format!("{prefix}{}", service.name);
        let mut variant_methods = String::new();
        for reg in &service.registrations {
            for variant in &reg.variants {
                gen_variant_napi_method(&mut variant_methods, service, reg, variant, api, &core_import, config);
            }
        }
        // Indent all method bodies by 4 spaces to sit inside the impl block
        let indented: String = variant_methods
            .lines()
            .map(|line| {
                if line.is_empty() {
                    String::new()
                } else {
                    format!("    {line}")
                }
            })
            .collect::<Vec<_>>()
            .join("\n");
        out.push_str(&format!("use crate::{app_type_name};\n\n"));
        // napi-rs requires `#[napi]` on the impl block for any method-level `#[napi]`
        // attributes to register with the runtime — without it the `napi` macro
        // rejects `&self` receivers with "arguments cannot be `self`".
        out.push_str(&format!("#[napi]\nimpl {app_type_name} {{\n"));
        out.push_str(&indented);
        if !indented.ends_with('\n') {
            out.push('\n');
        }
        out.push_str("}\n");
    }

    out
}

/// Emit the `{ContractName}Bridge` struct + trait impl.
///
/// Pattern mirrors the proven hand-written handler.rs: wrap the ThreadsafeFunction
/// and call it with the request DTO, await the Promise, and extract the response DTO.
///
/// The ThreadsafeFunction uses `serde_json::Value` for both request and response,
/// which napi 3.x supports natively via its serde bridge.
fn gen_handler_bridge(out: &mut String, contract: &HandlerContractDef, core_import: &str) {
    let trait_name = &contract.trait_name;
    let bridge_name = format!("{}Bridge", trait_name.to_upper_camel_case());
    let dispatch_name = &contract.dispatch.name;

    // Determine wire types for conversion on the handler side
    let req_type = contract.wire_request_type.as_deref().unwrap_or("serde_json::Value");
    let resp_type = contract.wire_response_type.as_deref().unwrap_or("serde_json::Value");

    // The ThreadsafeFunction uses serde_json::Value for both input and output, which
    // napi 3.x supports natively. The JS side receives and returns JSON-serializable
    // values that are transparently converted by napi's serde bridge.
    out.push_str(&format!(
        "/// Generated NAPI bridge for the `{trait_name}` contract.\n\
         ///\n\
         /// Wraps a JavaScript callable (async) via ThreadsafeFunction\n\
         /// so it can be used as `Arc<dyn {trait_name}>` from Rust async code.\n\
         pub struct {bridge_name} {{\n    \
             handler_fn: ThreadsafeFunction<serde_json::Value, serde_json::Value>,\n\
         }}\n\n"
    ));

    out.push_str(&format!(
        "impl {bridge_name} {{\n    \
             /// Create a bridge from a JavaScript callable.\n    \
             pub fn new(handler_fn: ThreadsafeFunction<serde_json::Value, serde_json::Value>) -> Self {{\n        \
                 Self {{ handler_fn }}\n    \
             }}\n\
         }}\n\n"
    ));

    // SAFETY comment for Send/Sync: ThreadsafeFunction is Send+Sync once we never call
    // it without a valid NAPI env handle (which we do within async Tokio spawns).
    out.push_str(&format!(
        "// SAFETY: ThreadsafeFunction is Send+Sync. We call it only from async contexts\n\
         // where the NAPI env is valid (within the async task spawned by call_async).\n\
         unsafe impl Send for {bridge_name} {{}}\n\
         unsafe impl Sync for {bridge_name} {{}}\n\n"
    ));

    // Leading dispatch parameters the bridge ignores (e.g. a foreign framework type the
    // contract's dispatch method receives but the wire bridge does not consume). Their concrete
    // types cannot be reconstructed from the sanitized surface, so the library supplies them
    // verbatim via `dispatch_extra_params`. Each is emitted as a `, {decl}` prefix argument.
    let extra_param: String = contract
        .dispatch_extra_params
        .iter()
        .map(|p| format!(", {p}"))
        .collect();
    let wire_name = contract.wire_param_name.as_deref().unwrap_or("request");

    // Compute request/response path types (mirror pyo3's req_path/resp_path construction)
    let req_path = if req_type == "Value" {
        "serde_json::Value".to_string()
    } else {
        format!("{core_import}::{req_type}")
    };
    let resp_path = if resp_type == "Value" {
        "serde_json::Value".to_string()
    } else {
        format!("{core_import}::{resp_type}")
    };

    // The future's `Output` is the contract dispatch's real return type when the library
    // supplies one (`dispatch_return_type`); otherwise the bridge yields the wire response
    // wrapped in a boxed-error `Result`. When a `response_adapter` is configured, the inner
    // fallible computation produces the wire `Result` and the adapter converts it into the
    // dispatch return type — keeping the generator ignorant of the library's response model.
    let box_err = "Box<dyn std::error::Error + Send + Sync>";
    // Fully qualify `Result` as `std::result::Result` so the bare `Result`
    // resolved through `use napi::bindgen_prelude::*` (which re-exports
    // `napi::Result<T, S = Status>`) does not shadow it. Without the
    // qualification the wire_output annotation parses as
    // `napi::Result<Response, Box<dyn Error>>` =
    // `std::result::Result<Response, napi::Error<Box<dyn Error>>>`, which
    // fails the `S: AsRef<str>` bound on `napi::Error<S>`.
    let wire_output = format!("std::result::Result<{resp_path}, {box_err}>");
    let output_type = contract
        .dispatch_return_type
        .clone()
        .unwrap_or_else(|| wire_output.clone());
    let tail = match &contract.response_adapter {
        Some(adapter) => format!("{adapter}(outcome)"),
        None => "outcome".to_string(),
    };

    // Trait impl: call the ThreadsafeFunction and await the Promise. The
    // method returns a boxed future directly (matching the canonical
    // object-safe async-trait shape the contract declares) rather than via
    // the async_trait macro, so it satisfies traits whose dispatch method is
    // hand-written as `-> Pin<Box<dyn Future<..> + Send + '_>>`.
    //
    // We serialize the request to a serde_json::Value before calling, then
    // deserialize the serde_json::Value response. napi 3.x implements
    // ToNapiValue/FromNapiValue for serde_json::Value via its serde bridge.
    //
    // CRITICAL: Explicitly type the `resp_json` result to avoid type inference
    // from propagating the outer Box<dyn Error + Send + Sync> error type back into
    // the napi::Error generic type, which would fail the `S: AsRef<str>` bound.
    out.push_str(&format!(
        "impl {core_import}::{trait_name} for {bridge_name} {{\n    \
             fn {dispatch_name}(\n        \
                 &self{extra_param},\n        \
                 {wire_name}: {req_path},\n    \
             ) -> std::pin::Pin<Box<dyn std::future::Future<Output = {output_type}> + Send + '_>> {{\n        \
                 Box::pin(async move {{\n            \
                     // Serialize request to JSON and call the ThreadsafeFunction\n            \
                     let outcome: {wire_output} = async move {{\n                \
                         let req_json = serde_json::to_value(&{wire_name})\n                            \
                             .map_err(|e| Box::new(e) as {box_err})?;\n                \
                         let resp_json = self.handler_fn\n                    \
                             .call_async(Ok(req_json))\n                    \
                             .await\n                    \
                             .map_err(|e| Box::new(e) as {box_err})?;\n                \
                         serde_json::from_value(resp_json)\n                    \
                             .map_err(|e| Box::new(e) as {box_err})\n            \
                     }}\n            \
                     .await;\n\n            \
                     {tail}\n        \
                 }})\n    \
             }}\n\
         }}\n\n"
    ));
}

/// Emit the `#[napi]` entry point for one service × entrypoint.
///
/// The function:
/// 1. Accepts the registrations list (Vec of [method_name, metadata, callback] tuples).
/// 2. Constructs the native service owner via its constructor.
/// 3. Iterates registrations, wraps each callable in the appropriate bridge,
///    and calls the owner's registration method.
/// 4. Calls the owner's entrypoint (awaiting if async).
fn gen_run_napi_function(
    out: &mut String,
    service: &ServiceDef,
    ep: &crate::core::ir::EntrypointDef,
    api: &ApiSurface,
    core_import: &str,
) {
    let service_snake = service.name.to_snake_case();
    let fn_name = format!("{service_snake}_{}", ep.method);
    let owner_path = &service.rust_path;
    let ep_method = &ep.method;

    // Build the function signature
    let mut rust_params = vec![
        "registrations: Vec<(String, Vec<serde_json::Value>, ThreadsafeFunction<serde_json::Value, serde_json::Value>)>".to_owned(),
    ];
    for p in &ep.params {
        let rust_ty = typeref_to_rust_type(&p.ty, core_import);
        rust_params.push(format!("{}: {}", p.name, rust_ty));
    }
    let param_sig = rust_params.join(", ");

    // Return type
    let return_ty = match ep.kind {
        EntrypointKind::Run => "()".to_owned(),
        EntrypointKind::Finalize => {
            // For Finalize, we'd need to return a DTO or Object — for now use ()
            "()".to_owned()
        }
    };

    out.push_str(&format!(
        "/// Drive `{owner_path}::{ep_method}` from JavaScript.\n\
         ///\n\
         /// Each entry in `registrations` is a `[method_name, metadata, callback]` triple\n\
         /// produced by the TypeScript service class.\n\
         #[napi]\n\
         pub async fn {fn_name}({param_sig}) -> napi::Result<{return_ty}> {{\n"
    ));

    // Build the owner instance via its constructor
    let ctor_call = build_ctor_call_napi(service, owner_path);
    out.push_str(&format!("    let mut owner = {ctor_call};\n\n"));

    // Iterate registrations and dispatch
    out.push_str("    for (method_name, _metadata, handler_fn) in registrations {\n");
    out.push_str("        match method_name.as_str() {\n");

    for reg in &service.registrations {
        let reg_method = &reg.method;
        let contract_name = &reg.callback_contract;

        if let Some(contract) = find_contract(api, contract_name) {
            // Check if any metadata param is opaque. If so, skip this registration
            // in the generic app_run function since opaque types cannot be serialized
            // from JavaScript. Verb shortcuts (get, post, etc.) use wrapper_call to
            // construct opaque params, so they handle the registration differently.
            let has_opaque_metadata = reg.metadata_params.iter().any(|p| {
                if let TypeRef::Named(n) = &p.ty {
                    api.types
                        .iter()
                        .find(|t| &t.name == n && !t.is_trait && t.is_opaque)
                        .is_some()
                } else {
                    false
                }
            });

            if has_opaque_metadata {
                // Skip generic registration for this method in app_run.
                // Verb variants (which use wrapper_call to construct opaque params)
                // are sufficient for the binding-side API.
                continue;
            }

            let bridge_name = format!("{}Bridge", contract.trait_name.to_upper_camel_case());

            out.push_str(&format!("            \"{reg_method}\" => {{\n"));
            out.push_str(&format!(
                "                let bridge = {bridge_name}::new(handler_fn);\n"
            ));
            out.push_str(&format!(
                "                let handler: Arc<dyn {core_import}::{contract_name}> = Arc::new(bridge);\n"
            ));

            // Extract and convert metadata params from serde_json::Value entries
            if !reg.metadata_params.is_empty() {
                for (idx, param) in reg.metadata_params.iter().enumerate() {
                    let param_name = &param.name;
                    let rust_ty = typeref_to_rust_type(&param.ty, core_import);
                    out.push_str(&format!("                let {param_name}: {rust_ty} = {{\n"));
                    out.push_str(&format!(
                        "                    let val = _metadata.get({idx}).ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"missing metadata parameter at index {idx}\"))?;\n"
                    ));
                    out.push_str(&format!(
                        "                    {}\n",
                        gen_metadata_extraction(&param.ty, core_import, api)
                    ));
                    out.push_str("                };\n");
                }
                let meta_names: Vec<&str> = reg.metadata_params.iter().map(|p| p.name.as_str()).collect();
                out.push_str(&format!(
                    "                owner.{reg_method}({}, handler)\n",
                    meta_names.join(", ")
                ));
            } else {
                out.push_str(&format!("                owner.{reg_method}(handler)\n"));
            }

            // Handle error if the registration is fallible
            if reg.error_type.is_some() {
                out.push_str(
                    "                    .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?;\n",
                );
            } else {
                out.push_str("                    ;\n");
            }
            out.push_str("            }\n");
        }
    }

    out.push_str("            _ => {}\n");
    out.push_str("        }\n");
    out.push_str("    }\n\n");

    // Call the entrypoint
    let ep_call = build_ep_call_napi(ep, service, core_import);
    out.push_str(&ep_call);

    out.push_str("    Ok(())\n}\n\n");
}

/// Build the Rust constructor call for the service owner.
fn build_ctor_call_napi(service: &ServiceDef, owner_path: &str) -> String {
    if service.constructor.params.is_empty() {
        format!("{owner_path}::{}()", service.constructor.name)
    } else {
        // For a first-pass implementation where constructor params are not
        // yet threaded through, fall back to zero-arg constructor.
        format!("{owner_path}::{}()", service.constructor.name)
    }
}

/// Build the entrypoint invocation for a service method.
fn build_ep_call_napi(ep: &crate::core::ir::EntrypointDef, _service: &ServiceDef, _core_import: &str) -> String {
    let ep_method = &ep.method;
    let ep_args: Vec<String> = ep.params.iter().map(|p| p.name.clone()).collect();
    let args_str = ep_args.join(", ");

    if ep.is_async {
        // Drive the async entrypoint directly (this function is already async)
        format!(
            "    owner.{ep_method}({args_str})\n        \
             .await\n        \
             .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?;\n"
        )
    } else {
        if ep.error_type.is_some() {
            format!(
                "    owner.{ep_method}({args_str})\n        \
                 .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?;\n"
            )
        } else {
            format!("    owner.{ep_method}({args_str});\n")
        }
    }
}

/// Emit one `#[napi]` async shortcut method for a registration variant on the App class.
///
/// The method signature mirrors the variant's `signature_params` + a handler callback,
/// builds the wrapper via the `WrapperConstructorCall` (if present), and delegates to
/// the base registration method on the inner host-app value.
fn gen_variant_napi_method(
    out: &mut String,
    service: &ServiceDef,
    reg: &RegistrationDef,
    variant: &crate::core::ir::RegistrationVariant,
    api: &ApiSurface,
    core_import: &str,
    config: &ResolvedCrateConfig,
) {
    let variant_name = &variant.name;
    let base_method = &reg.method;
    let contract_name = &reg.callback_contract;

    // Look up the optional inner-accessor expression for this service's config.
    // When present, verb methods call `{accessor}.{base_method}(...)` instead of
    // `self.{base_method}(...)`, allowing the wrapper type to dereference an inner
    // field (e.g. `Arc<Mutex<Owner>>`) before dispatching.
    let inner_accessor: String = config
        .services
        .iter()
        .find(|sc| sc.owner_type == service.name)
        .and_then(|sc| sc.host_app_inner_accessor.as_deref())
        .map(|s| s.to_owned())
        .unwrap_or_else(|| "self".to_owned());

    // Build method signature from variant's signature_params.
    // napi-rs only accepts `&self` (or no receiver) on `#[napi]` methods — `&mut self`
    // is rejected by the `napi` macro. Mutation of the underlying owner is expected to
    // go through interior mutability via `host_app_inner_accessor` (e.g.
    // `self.inner.lock().expect(...)` when the wrapper holds an `Arc<Mutex<_>>`).
    let mut rust_params = vec!["&self".to_owned()];
    for p in &variant.signature_params {
        let rust_ty = typeref_to_rust_type(&p.ty, core_import);
        rust_params.push(format!("{}: {}", p.name, rust_ty));
    }
    rust_params.push("handler: ThreadsafeFunction<serde_json::Value, serde_json::Value>".to_string());
    let param_sig = rust_params.join(", ");

    out.push_str(&format!(
        "/// Register a handler via the `{variant_name}` variant shortcut.\n"
    ));
    if let Some(doc) = &variant.doc {
        out.push_str(&format!("///\n/// {}\n", doc.trim()));
    }
    out.push_str(&format!(
        "#[napi]\npub fn {variant_name}({param_sig}) -> napi::Result<()> {{\n"
    ));

    // If there's a wrapper constructor call, build the wrapper first
    if let Some(wrapper_call) = &variant.wrapper_call {
        let wrapper_path = &wrapper_call.wrapper_type_path;
        let constructor = &wrapper_call.constructor_method;

        // Build the constructor args
        let mut ctor_args = Vec::new();
        for arg in &wrapper_call.args {
            match arg {
                crate::core::ir::WrapperConstructorArg::Fixed {
                    param_name: _,
                    value_expr,
                } => {
                    ctor_args.push(value_expr.clone());
                }
                crate::core::ir::WrapperConstructorArg::Free { param } => {
                    ctor_args.push(param.name.clone());
                }
            }
        }
        let ctor_arg_str = ctor_args.join(", ");

        out.push_str(&format!(
            "    let {} = {}::{}({});\n",
            wrapper_call.metadata_param, wrapper_path, constructor, ctor_arg_str
        ));
    }

    // Build the metadata argument list for the base registration call.
    // When a wrapper_call is present, its metadata_param IS the single metadata
    // argument and the signature_params have already been consumed by the wrapper
    // constructor — do NOT include them again.
    // When no wrapper_call is present, metadata comes directly from signature_params.
    let mut metadata_names: Vec<String> = Vec::new();
    if let Some(wrapper_call) = &variant.wrapper_call {
        metadata_names.push(wrapper_call.metadata_param.clone());
    } else {
        for p in &variant.signature_params {
            metadata_names.push(p.name.clone());
        }
    }

    // Create the handler bridge and call base registration
    if let Some(contract) = find_contract(api, contract_name) {
        let bridge_name = format!("{}Bridge", contract.trait_name.to_upper_camel_case());
        out.push_str(&format!("    let bridge = {bridge_name}::new(handler);\n"));
        out.push_str(&format!(
            "    let handler_arc: std::sync::Arc<dyn {core_import}::{contract_name}> = std::sync::Arc::new(bridge);\n"
        ));
    }

    // Call the base registration method via the inner accessor or self
    let meta_args = metadata_names.join(", ");
    if inner_accessor == "self" {
        if !metadata_names.is_empty() {
            out.push_str(&format!("    self.{base_method}({meta_args}, handler_arc)\n"));
        } else {
            out.push_str(&format!("    self.{base_method}(handler_arc)\n"));
        }
    } else {
        // Accessor may return &mut or MutexGuard — bind to a named variable
        out.push_str(&format!("    let mut inner = {inner_accessor};\n"));
        if !metadata_names.is_empty() {
            out.push_str(&format!("    inner.{base_method}({meta_args}, handler_arc)\n"));
        } else {
            out.push_str(&format!("    inner.{base_method}(handler_arc)\n"));
        }
    }

    // Handle error if the registration is fallible
    if reg.error_type.is_some() {
        out.push_str("        .map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))?;\n");
    } else {
        out.push_str("        ;\n");
    }

    out.push_str("    Ok(())\n");
    out.push_str("}\n\n");
}

/// Generate code to extract and convert a metadata parameter from a `serde_json::Value`.
///
/// Returns a Rust expression that converts `val` (a `&serde_json::Value`) to the target type.
/// The generated code uses serde_json's native coercion and type conversions.
#[allow(clippy::only_used_in_recursion)]
fn gen_metadata_extraction(ty: &TypeRef, core_import: &str, api: &ApiSurface) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => {
            "val.as_str().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected string metadata\"))?.to_owned()".to_owned()
        }
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => {
                    "val.as_bool().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected bool metadata\"))?".to_owned()
                }
                PrimitiveType::F64 => {
                    "val.as_f64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))?".to_owned()
                }
                PrimitiveType::F32 => {
                    "val.as_f64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as f32".to_owned()
                }
                PrimitiveType::U8 => {
                    "val.as_u64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as u8".to_owned()
                }
                PrimitiveType::U16 => {
                    "val.as_u64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as u16".to_owned()
                }
                PrimitiveType::U32 => {
                    "val.as_u64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as u32".to_owned()
                }
                PrimitiveType::U64 | PrimitiveType::Usize => {
                    "val.as_u64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))?".to_owned()
                }
                PrimitiveType::I8 => {
                    "val.as_i64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as i8".to_owned()
                }
                PrimitiveType::I16 => {
                    "val.as_i64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as i16".to_owned()
                }
                PrimitiveType::I32 => {
                    "val.as_i64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))? as i32".to_owned()
                }
                PrimitiveType::I64 | PrimitiveType::Isize => {
                    "val.as_i64().ok_or_else(|| napi::Error::new(napi::Status::InvalidArg, \"expected number metadata\"))?".to_owned()
                }
            }
        }
        TypeRef::Optional(inner) => {
            let inner_extraction = gen_metadata_extraction(inner, core_import, api);
            format!("if val.is_null() {{ None }} else {{ Some({{ {inner_extraction} }}) }}")
        }
        TypeRef::Named(n) => {
            // Check if this Named type is opaque in the API surface
            let is_opaque = api.types
                .iter()
                .find(|t| &t.name == n && !t.is_trait && t.is_opaque)
                .is_some();

            if is_opaque {
                // For opaque types: deserialize as the NAPI binding wrapper class,
                // then unwrap .inner to get the core type.
                // This follows the pattern: extract wrapper, then unwrap.inner
                format!(
                    "{{ \
                        let binding = serde_json::from_value::<crate::{name}>(val.clone()) \
                            .map_err(|e| napi::Error::from_reason(format!(\"opaque type deserialization failed: {{}}\", e)))?; \
                        binding.inner.clone() \
                    }}",
                    name = n
                )
            } else {
                // For non-opaque Named types: deserialize directly via serde_json
                "serde_json::from_value(val.clone())
                    .map_err(|e| napi::Error::from_reason(format!(\"metadata deserialization failed: {}\", e)))?".to_owned()
            }
        }
        _ => {
            // For other complex types: deserialize directly from serde_json::Value
            "serde_json::from_value(val.clone())
                .map_err(|e| napi::Error::from_reason(format!(\"metadata deserialization failed: {}\", e)))?".to_owned()
        }
    }
}

/// Map a `TypeRef` to a Rust type string for use in generated function signatures.
fn typeref_to_rust_type(ty: &TypeRef, core_import: &str) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => "String".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "bool".to_owned(),
                PrimitiveType::U8 => "u8".to_owned(),
                PrimitiveType::U16 => "u16".to_owned(),
                PrimitiveType::U32 => "u32".to_owned(),
                PrimitiveType::U64 => "u64".to_owned(),
                PrimitiveType::I8 => "i8".to_owned(),
                PrimitiveType::I16 => "i16".to_owned(),
                PrimitiveType::I32 => "i32".to_owned(),
                PrimitiveType::I64 => "i64".to_owned(),
                PrimitiveType::F32 => "f32".to_owned(),
                PrimitiveType::F64 => "f64".to_owned(),
                PrimitiveType::Usize => "usize".to_owned(),
                PrimitiveType::Isize => "isize".to_owned(),
            }
        }
        TypeRef::Bytes => "Vec<u8>".to_owned(),
        TypeRef::Optional(inner) => format!("Option<{}>", typeref_to_rust_type(inner, core_import)),
        TypeRef::Vec(inner) => format!("Vec<{}>", typeref_to_rust_type(inner, core_import)),
        TypeRef::Map(k, v) => format!(
            "std::collections::HashMap<{}, {}>",
            typeref_to_rust_type(k, core_import),
            typeref_to_rust_type(v, core_import)
        ),
        TypeRef::Unit => "()".to_owned(),
        TypeRef::Named(n) => format!("{core_import}::{n}"),
        TypeRef::Json => "serde_json::Value".to_owned(),
        TypeRef::Path => "std::path::PathBuf".to_owned(),
        TypeRef::Duration => "std::time::Duration".to_owned(),
    }
}

// ──────────────────────────────────────────────────────── public entry point ──

/// Generate all service-API files for the napi backend.
///
/// Returns up to four `GeneratedFile`s per non-empty service list:
/// - `{output_dir}/service.rs`   — Rust napi glue
/// - `{node_pkg}/service.ts`     — idiomatic TypeScript class (legacy: packages/node/)
/// - `crates/{name}-node/service.ts` — idiomatic TypeScript class (for index.js re-export)
/// - `crates/{name}-node/service.js` — idiomatic JavaScript class (transpiled from TS, runtime-compatible)
pub fn generate(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    if api.services.is_empty() {
        return Ok(vec![]);
    }

    use crate::core::config::resolve_output_dir;

    let output_dir = resolve_output_dir(config.output_paths.get("node"), &config.name, "crates/{name}-node/src/");
    let crate_root = {
        let p = PathBuf::from(&output_dir);
        match p.file_name().and_then(|n| n.to_str()) {
            Some("src") => p.parent().map(|parent| parent.to_path_buf()).unwrap_or(p),
            _ => p,
        }
    };
    let package_name = config.name.replace('-', "_");

    // Rust glue
    let service_rs = gen_service_rs(api, config);

    // TypeScript wrapper
    let service_ts = gen_service_ts(api, &package_name);

    // JavaScript version (TypeScript with types stripped)
    let _service_js = strip_typescript_annotations(&service_ts);

    // Node package output base: derive from package_name or use default
    let output_base = config
        .node
        .as_ref()
        .and_then(|n| n.package_name.as_ref())
        .map(|p| PathBuf::from(format!("packages/node/{}", p)))
        .unwrap_or_else(|| PathBuf::from(format!("packages/node/{}", package_name)));

    Ok(vec![
        GeneratedFile {
            path: PathBuf::from(&output_dir).join("service.rs"),
            content: service_rs,
            generated_header: true,
        },
        GeneratedFile {
            path: output_base.join("service.ts"),
            content: service_ts.clone(),
            generated_header: true,
        },
        GeneratedFile {
            path: crate_root.join("service.ts"),
            content: service_ts,
            generated_header: true,
        },
        // Note: service.js is transpiled from service.ts by removing type annotations.
        // Since JavaScript doesn't have TypeScript's type syntax, we emit service.ts as-is
        // but the post-build step in index.js will reference './service' which requires
        // Node to either: (a) have TypeScript loader registered, or (b) have service.ts
        // compiled to JS during build. For now, we omit service.js and rely on index.js
        // to use a try-catch fallback.
        // GeneratedFile {
        //     path: crate_root.join("service.js"),
        //     content: service_js,
        //     generated_header: true,
        // },
    ])
}

/// Convert TypeScript service wrapper to CommonJS JavaScript.
/// Simple approach: convert imports and output with // type comments removed.
/// Uses a brute-force regex-like approach to handle `: Type` patterns.
fn strip_typescript_annotations(ts_code: &str) -> String {
    let mut result = String::new();

    for line in ts_code.lines() {
        let mut modified_line = line.to_string();

        // Convert `import type { ... } from 'module'` → `const { ... } = require('module')`
        if modified_line.trim().starts_with("import type {") && modified_line.contains("from") {
            if let Some(start_brace) = modified_line.find('{') {
                if let Some(end_brace) = modified_line.rfind('}') {
                    if let Some(from_pos) = modified_line.find("from") {
                        let imports = modified_line[start_brace..=end_brace].to_string();
                        let module_part = modified_line[from_pos..].trim();
                        modified_line = format!("const {imports} = require({}", &module_part[5..]);
                    }
                }
            }
            result.push_str(&modified_line);
            result.push('\n');
            continue;
        }

        // Convert `import { ... } from 'module'` → `const { ... } = require('module')`
        if modified_line.trim().starts_with("import {") && modified_line.contains("from") {
            if let Some(start_brace) = modified_line.find('{') {
                if let Some(end_brace) = modified_line.rfind('}') {
                    if let Some(from_pos) = modified_line.find("from") {
                        let imports = modified_line[start_brace..=end_brace].to_string();
                        let module_part = modified_line[from_pos..].trim();
                        modified_line = format!("const {imports} = require({}", &module_part[5..]);
                    }
                }
            }
            result.push_str(&modified_line);
            result.push('\n');
            continue;
        }

        // Remove `export` keyword from class declarations (they're not needed in CommonJS)
        if modified_line.trim().starts_with("export class") {
            modified_line = modified_line.replace("export class", "class");
        }

        // Remove `private` keyword
        if modified_line.contains("private ") {
            modified_line = modified_line.replace("private ", "");
        }

        // Remove `: Type` where Type is anything up to ) or , or = or {
        // Using a character-by-character approach
        let mut output = String::new();
        let chars: Vec<char> = modified_line.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            if i < chars.len() - 1 && chars[i] == ':' && !modified_line[..i].ends_with("://") {
                // Found a potential type annotation. Skip to the next ) , { or =
                let mut j = i + 1;
                // Skip whitespace
                while j < chars.len() && (chars[j] == ' ' || chars[j] == '\t') {
                    j += 1;
                }
                // Skip the type (everything until we hit a boundary)
                let mut paren_depth = 0;
                let mut angle_depth = 0;
                while j < chars.len() {
                    match chars[j] {
                        '(' => paren_depth += 1,
                        ')' => {
                            if paren_depth == 0 {
                                break;
                            }
                            paren_depth -= 1;
                        }
                        '<' => angle_depth += 1,
                        '>' => angle_depth -= 1,
                        ',' | '=' | '{' | ';' if paren_depth == 0 && angle_depth == 0 => {
                            break;
                        }
                        _ => {}
                    }
                    j += 1;
                }
                // We've found the end of the type annotation. Skip to j.
                i = j;
                // Trim trailing space from output if present
                while !output.is_empty() && output.ends_with(' ') {
                    output.pop();
                }
                // Don't add extra spaces
                if i < chars.len() && chars[i] != ',' && chars[i] != ')' && !output.is_empty() {
                    output.push(' ');
                }
                continue;
            }

            output.push(chars[i]);
            i += 1;
        }

        modified_line = output;

        result.push_str(&modified_line);
        result.push('\n');
    }

    result
}

// ───────────────────────────────────────────────────────────────────── tests ──

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{
        EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, PrimitiveType, ReceiverKind,
        RegistrationDef, ServiceDef, TypeRef,
    };

    /// Construct a minimal but realistic [`ApiSurface`] that exercises:
    /// - A service with a constructor, one configurator, one registration
    ///   (bound to an async handler contract), and Run entrypoint.
    /// - One [`HandlerContractDef`] with wire request/response DTO names.
    fn make_fixture_surface() -> ApiSurface {
        let constructor = MethodDef {
            name: "new".to_owned(),
            params: vec![],
            return_type: TypeRef::Unit,
            is_async: false,
            is_static: true,
            error_type: None,
            doc: "Create a new service owner.".to_owned(),
            receiver: None,
            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,
        };

        let configurator = MethodDef {
            name: "with_timeout".to_owned(),
            params: vec![ParamDef {
                name: "timeout_ms".to_owned(),
                ty: TypeRef::Primitive(PrimitiveType::U64),
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Named("TestService".to_owned()),
            is_async: false,
            is_static: false,
            error_type: None,
            doc: "Set request timeout.".to_owned(),
            receiver: Some(ReceiverKind::RefMut),
            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,
        };

        let registration = RegistrationDef {
            method: "add_handler".to_owned(),
            callback_param: "handler".to_owned(),
            callback_contract: "RequestHandler".to_owned(),
            metadata_params: vec![
                ParamDef {
                    name: "path".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                },
                ParamDef {
                    name: "method".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                },
            ],
            receiver: Some(ReceiverKind::RefMut),
            return_type: TypeRef::Unit,
            error_type: None,
            doc: "Register a request handler for a path and method.".to_owned(),
            variants: vec![],
        };

        let run_ep = EntrypointDef {
            method: "run".to_owned(),
            kind: EntrypointKind::Run,
            is_async: true,
            params: vec![ParamDef {
                name: "addr".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Unit,
            error_type: Some("ServiceError".to_owned()),
            doc: "Run the service.".to_owned(),
        };

        let service = ServiceDef {
            name: "TestService".to_owned(),
            rust_path: "my_crate::TestService".to_owned(),
            constructor,
            configurators: vec![configurator],
            registrations: vec![registration],
            entrypoints: vec![run_ep],
            doc: "A test service owner.".to_owned(),
            cfg: None,
        };

        let dispatch_method = MethodDef {
            name: "handle".to_owned(),
            params: vec![ParamDef {
                name: "request".to_owned(),
                ty: TypeRef::Named("RequestData".to_owned()),
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Named("ResponseData".to_owned()),
            is_async: true,
            is_static: false,
            error_type: Some("HandlerError".to_owned()),
            doc: "Dispatch a request.".to_owned(),
            receiver: Some(ReceiverKind::Ref),
            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,
        };

        let contract = HandlerContractDef {
            trait_name: "RequestHandler".to_owned(),
            rust_path: "my_crate::RequestHandler".to_owned(),
            dispatch: dispatch_method,
            optional_methods: vec![],
            wire_request_type: Some("RequestData".to_owned()),
            wire_response_type: Some("ResponseData".to_owned()),
            dispatch_extra_params: vec![],
            wire_param_name: None,
            dispatch_return_type: None,
            response_adapter: None,
            doc: "Async trait for handling requests.".to_owned(),
        };

        ApiSurface {
            crate_name: "my_crate".to_owned(),
            version: "0.1.0".to_owned(),
            services: vec![service],
            handler_contracts: vec![contract],
            ..ApiSurface::default()
        }
    }

    #[test]
    fn typescript_output_contains_service_class() {
        let surface = make_fixture_surface();
        let output = gen_service_ts(&surface, "my_crate");
        assert!(
            output.contains("export class TestService"),
            "expected `export class TestService` in output:\n{output}"
        );
    }

    #[test]
    fn typescript_output_contains_constructor() {
        let surface = make_fixture_surface();
        let output = gen_service_ts(&surface, "my_crate");
        assert!(
            output.contains("constructor()"),
            "expected `constructor()` in output:\n{output}"
        );
    }

    #[test]
    fn typescript_output_contains_private_registrations() {
        let surface = make_fixture_surface();
        let output = gen_service_ts(&surface, "my_crate");
        assert!(
            output.contains("private _registrations"),
            "expected `private _registrations` in output:\n{output}"
        );
    }

    #[test]
    fn typescript_output_contains_configurator() {
        let surface = make_fixture_surface();
        let output = gen_service_ts(&surface, "my_crate");
        assert!(
            output.contains("with_timeout(timeout_ms: number)"),
            "expected `with_timeout` configurator:\n{output}"
        );
        assert!(
            output.contains("return this;"),
            "expected `return this;` in configurator:\n{output}"
        );
    }

    #[test]
    fn typescript_output_contains_registration_method() {
        let surface = make_fixture_surface();
        let output = gen_service_ts(&surface, "my_crate");
        assert!(
            output.contains("add_handler(path: string, method: string)"),
            "expected `add_handler` registration method:\n{output}"
        );
    }

    #[test]
    fn typescript_output_contains_run_entrypoint() {
        let surface = make_fixture_surface();
        let output = gen_service_ts(&surface, "my_crate");
        assert!(
            output.contains("async run(addr: string)"),
            "expected `async run` entrypoint:\n{output}"
        );
    }

    #[test]
    fn rust_output_contains_handler_bridge() {
        let surface = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "my_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };
        let output = gen_service_rs(&surface, &config);
        assert!(
            output.contains("pub struct RequestHandlerBridge"),
            "expected `RequestHandlerBridge` struct in output:\n{output}"
        );
    }

    #[test]
    fn rust_output_contains_run_function() {
        let surface = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "my_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };
        let output = gen_service_rs(&surface, &config);
        assert!(
            output.contains("pub async fn test_service_run"),
            "expected `test_service_run` function in output:\n{output}"
        );
    }

    #[test]
    fn rust_output_contains_thread_safe_function() {
        let surface = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "my_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };
        let output = gen_service_rs(&surface, &config);
        assert!(
            output.contains("ThreadsafeFunction"),
            "expected `ThreadsafeFunction` in output:\n{output}"
        );
    }

    #[test]
    fn rust_output_implements_trait() {
        let surface = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "my_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };
        let output = gen_service_rs(&surface, &config);
        assert!(
            output.contains("impl my_crate::RequestHandler for RequestHandlerBridge"),
            "expected trait impl in output:\n{output}"
        );
    }

    #[test]
    fn rust_output_extracts_metadata_params() {
        let surface = make_fixture_surface();
        let config = ResolvedCrateConfig {
            name: "my_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };
        let output = gen_service_rs(&surface, &config);

        // Assert metadata params are extracted as real typed variables, not stubs
        assert!(
            !output.contains("/* TODO: extract metadata */"),
            "expected no TODO placeholder in output:\n{output}"
        );
        assert!(
            !output.contains("TODO: extract metadata"),
            "expected no TODO marker in output:\n{output}"
        );

        // Assert the "path" metadata param is extracted and declared with proper type
        assert!(
            output.contains("let path: String"),
            "expected `let path: String` extraction in output:\n{output}"
        );

        // Assert the "method" metadata param is extracted and declared with proper type
        assert!(
            output.contains("let method: String"),
            "expected `let method: String` extraction in output:\n{output}"
        );

        // Assert both metadata params are passed to the registration method call
        assert!(
            output.contains("owner.add_handler(path, method, handler)"),
            "expected owner.add_handler(path, method, handler) call in output:\n{output}"
        );

        // Assert metadata is accessed from the _metadata vector
        assert!(
            output.contains("_metadata.get("),
            "expected _metadata.get(...) access in output:\n{output}"
        );
    }

    #[test]
    fn registration_variants_emit_napi_methods() {
        use crate::core::ir::{RegistrationVariant, WrapperConstructorArg, WrapperConstructorCall};

        let mut surface = make_fixture_surface();

        // Add a variant to the registration
        if let Some(reg) = surface.services[0].registrations.first_mut() {
            reg.variants.push(RegistrationVariant {
                name: "get".to_owned(),
                overrides: vec![],
                wrapper_call: Some(WrapperConstructorCall {
                    metadata_param: "builder".to_owned(),
                    wrapper_type_path: "my_crate::RouteBuilder".to_owned(),
                    wrapper_type_name: "RouteBuilder".to_owned(),
                    constructor_method: "new".to_owned(),
                    args: vec![
                        WrapperConstructorArg::Fixed {
                            param_name: "method".to_owned(),
                            value_expr: "my_crate::Method::GET".to_owned(),
                        },
                        WrapperConstructorArg::Free {
                            param: ParamDef {
                                name: "path".to_owned(),
                                ty: TypeRef::String,
                                optional: false,
                                default: None,
                                ..ParamDef::default()
                            },
                        },
                    ],
                }),
                signature_params: vec![ParamDef {
                    name: "path".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                }],
                doc: Some("Register a GET handler.".to_owned()),
                style: Default::default(),
            });
        }

        let config = ResolvedCrateConfig {
            name: "my_crate".to_owned(),
            ..ResolvedCrateConfig::default()
        };
        let output = gen_service_rs(&surface, &config);

        // Assert the variant methods are wrapped in an impl block (default prefix "Js")
        assert!(
            output.contains("impl JsTestService {"),
            "expected `impl JsTestService {{` wrapping in output:\n{output}"
        );

        // Assert the use statement is emitted before the impl block
        assert!(
            output.contains("use crate::JsTestService;"),
            "expected `use crate::JsTestService;` in output:\n{output}"
        );

        // Assert the variant method is emitted with #[napi] (indented inside impl block)
        assert!(
            output.contains("#[napi]\n    pub fn get("),
            "expected `#[napi]\\n    pub fn get(` inside impl block in output:\n{output}"
        );

        // Assert the wrapper builder is constructed
        assert!(
            output.contains("my_crate::RouteBuilder::new("),
            "expected wrapper constructor call in output:\n{output}"
        );

        // Assert the fixed arg is substituted
        assert!(
            output.contains("my_crate::Method::GET"),
            "expected fixed arg substitution in output:\n{output}"
        );
    }

    #[test]
    fn typescript_variant_verb_decorator_style() {
        use crate::core::ir::{RegistrationVariant, RegistrationVariantStyle};

        let mut surface = make_fixture_surface();

        if let Some(reg) = surface.services[0].registrations.first_mut() {
            reg.variants.push(RegistrationVariant {
                name: "get".to_owned(),
                overrides: vec![],
                wrapper_call: None,
                signature_params: vec![ParamDef {
                    name: "path".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                }],
                doc: Some("Register a GET handler.".to_owned()),
                style: RegistrationVariantStyle::VerbDecorator,
            });
        }

        let output = gen_service_ts(&surface, "my_crate");

        // VerbDecorator should emit only the direct form: get(path, handler): this
        assert!(
            output.contains("get(path: string, handler: (...args: any[]) => any): this"),
            "expected VerbDecorator form `get(path, handler): this` in output:\n{output}"
        );

        // Should return `this` for chaining
        assert!(
            output.contains("return this;"),
            "expected `return this;` for chaining in VerbDecorator form:\n{output}"
        );

        // Should NOT emit decorator-factory form
        let get_count = output.matches("  get(").count();
        assert_eq!(
            get_count, 1,
            "expected exactly one `get(` method in VerbDecorator style, found {}: {}",
            get_count, output
        );
    }

    #[test]
    fn typescript_variant_builder_style() {
        use crate::core::ir::{RegistrationVariant, RegistrationVariantStyle};

        let mut surface = make_fixture_surface();

        if let Some(reg) = surface.services[0].registrations.first_mut() {
            reg.variants.push(RegistrationVariant {
                name: "get".to_owned(),
                overrides: vec![],
                wrapper_call: None,
                signature_params: vec![ParamDef {
                    name: "path".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                }],
                doc: Some("Register a GET handler.".to_owned()),
                style: RegistrationVariantStyle::Builder,
            });
        }

        let output = gen_service_ts(&surface, "my_crate");

        // Builder should emit only the decorator-factory form: get(path) returns a function
        assert!(
            output.contains("get(path: string): (fn: (...args: any[]) => any) => (...args: any[]) => any"),
            "expected Builder form `get(path): (fn) => ...` in output:\n{output}"
        );

        // Should return the handler unchanged (for decorator form)
        assert!(
            output.contains("return fn;"),
            "expected `return fn;` in Builder form:\n{output}"
        );

        // Should NOT emit direct form with handler parameter
        assert!(
            !output.contains("get(path: string, handler: (...args: any[]) => any): this"),
            "Builder form should not emit direct method with handler parameter:\n{output}"
        );
    }

    #[test]
    fn typescript_variant_hybrid_style() {
        use crate::core::ir::{RegistrationVariant, RegistrationVariantStyle};

        let mut surface = make_fixture_surface();

        if let Some(reg) = surface.services[0].registrations.first_mut() {
            reg.variants.push(RegistrationVariant {
                name: "get".to_owned(),
                overrides: vec![],
                wrapper_call: None,
                signature_params: vec![ParamDef {
                    name: "path".to_owned(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    ..ParamDef::default()
                }],
                doc: Some("Register a GET handler.".to_owned()),
                style: RegistrationVariantStyle::Hybrid,
            });
        }

        let output = gen_service_ts(&surface, "my_crate");

        // Hybrid should emit both forms
        assert!(
            output.contains("get(path: string, handler: (...args: any[]) => any): this"),
            "expected Hybrid to include direct form `get(path, handler): this`:\n{output}"
        );

        assert!(
            output.contains("get(path: string): (fn: (...args: any[]) => any) => (...args: any[]) => any"),
            "expected Hybrid to include factory form `get(path): (fn) => ...`:\n{output}"
        );

        // Should have both `return this;` and `return fn;`
        let this_count = output.matches("return this;").count();
        let fn_count = output.matches("return fn;").count();
        assert!(
            this_count >= 1 && fn_count >= 1,
            "Hybrid form should have both return forms; this={}, fn={}: {}",
            this_count,
            fn_count,
            output
        );
    }
}