scythe-codegen 0.19.0

Polyglot code generation backends for scythe
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
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
use std::fmt::Write;

use scythe_backend::manifest::BackendManifest;
use scythe_backend::naming::{composite_type_name, enum_type_name, to_camel_case, to_pascal_case};
use scythe_core::analyzer::{CompositeInfo, NestedStructInfo};
use scythe_core::errors::{ErrorCode, ScytheError};
use scythe_core::parser::QueryCommand;

use crate::backend_trait::ResolvedColumn;

/// Supported TypeScript row type styles for generated code.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TsRowType {
    #[default]
    Interface,
    Zod,
}

impl TsRowType {
    /// Parse a row_type option string into a `TsRowType`.
    pub fn from_option(value: &str) -> Result<Self, ScytheError> {
        match value {
            "interface" => Ok(Self::Interface),
            "zod" => Ok(Self::Zod),
            _ => Err(ScytheError::new(
                ErrorCode::InvalidConfig,
                format!("invalid row_type '{}': expected 'interface' or 'zod'", value),
            )),
        }
    }
}

/// Case convention for row/interface field names, as selected by the
/// `field_case` backend option.
///
/// Naming the field (`NamingConfig.field_case`, read centrally in
/// `resolve.rs`) and remapping the *runtime* row to match it are two
/// separate concerns: renaming alone would type-check but return `undefined`
/// for every field once `Camel` disagrees with what the driver actually
/// returns. This enum drives the latter -- see
/// [`generate_ts_one_row_remap`] and [`generate_ts_many_row_remap`], which a
/// backend's `apply_options` selects between based on the same
/// `field_case` option string that also sets `NamingConfig.field_case`, so
/// the two never drift apart.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TsFieldCase {
    #[default]
    Snake,
    Camel,
}

impl TsFieldCase {
    /// Parse a field_case option string into a `TsFieldCase`.
    pub fn from_option(value: &str) -> Result<Self, ScytheError> {
        match value {
            "snake_case" => Ok(Self::Snake),
            "camelCase" => Ok(Self::Camel),
            _ => Err(ScytheError::new(
                ErrorCode::InvalidConfig,
                format!("invalid field_case '{}': expected 'snake_case' or 'camelCase'", value),
            )),
        }
    }
}

/// Which declared row-type shape a reconstructed row object literal has to
/// satisfy.
///
/// A remap builds a plain object literal and returns it against the query
/// function's declared row type, so the cast on each field has to agree with
/// what that type declares for it. The two shapes disagree about exactly one
/// class of column — see [`TsRowShape::cast_type`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TsRowShape {
    /// Plain interface (`outer_join_unions = false`, and every `:grouped`
    /// parent/child struct): every field is declared at `full_type`.
    #[default]
    Flat,
    /// Discriminated union (`outer_join_unions = true`): see
    /// [`generate_ts_union_row_struct`].
    Union,
}

impl TsRowShape {
    /// The shape a backend declares given its `outer_join_unions` setting.
    pub fn from_outer_join_unions(outer_join_unions: bool) -> Self {
        if outer_join_unions { Self::Union } else { Self::Flat }
    }

    /// The TypeScript type a reconstructed field must be cast to so the
    /// object literal stays assignable to the declared row type.
    ///
    /// `full_type` everywhere except a join discriminant under
    /// [`TsRowShape::Union`]. There, [`generate_ts_union_row_struct`]
    /// declares the column as `lang_type` in the matched variant and as
    /// literal `null` in the unmatched one, and `T | null` is assignable to
    /// neither — casting through `full_type` is a TS2322, not a widening.
    /// `lang_type` would stay sound under `Flat` as well (`T` is assignable
    /// to `T | null`), but `Flat` keeps `full_type` so the generated text is
    /// unchanged for the shape that never needed the narrowing.
    pub fn cast_type(self, col: &ResolvedColumn) -> &str {
        if self == Self::Union && col.is_join_discriminant() {
            return &col.lang_type;
        }
        &col.full_type
    }
}

/// Parse a boolean backend option strictly.
///
/// Accepts (case-insensitively) `true`/`false`, `1`/`0`, and `yes`/`no`. Any
/// other value — a typo, `"on"`, an empty string — is rejected with an error
/// naming the option and the offending value, rather than being silently
/// coerced to `false` as `matches!` or `== "true"` would do.
pub fn parse_bool_option(option_name: &str, value: &str) -> Result<bool, ScytheError> {
    match value.to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" => Ok(true),
        "false" | "0" | "no" => Ok(false),
        _ => Err(ScytheError::new(
            ErrorCode::InvalidConfig,
            format!("invalid {option_name} '{value}': expected 'true'/'false', '1'/'0', or 'yes'/'no'"),
        )),
    }
}

/// Escape a SQL string for safe splicing into a JS backtick template
/// literal.
///
/// Order matters: backslash must be escaped first, so the backslashes this
/// pass inserts ahead of a backtick or `${` are not themselves re-escaped by
/// a later pass. Left unescaped, a backslash in the source SQL (e.g.
/// `E'\n'`) would escape whatever JS character follows it; a literal
/// backtick (idiomatic identifier quoting in MySQL/MariaDB — `` `users`.`id` ``)
/// would terminate the template literal early; and a literal `${` would open
/// a live JS interpolation — worse still inside a Kysely `sql` tag, where
/// `${}` is a parameter binding.
pub fn escape_ts_template_literal(sql: &str) -> String {
    sql.replace('\\', "\\\\").replace('`', "\\`").replace("${", "\\${")
}

/// Escape a SQL string for safe splicing into a double-quoted JS string
/// literal.
///
/// Used by the oracledb backend, which binds SQL text as a plain
/// double-quoted string rather than a template literal, so `` ` `` and `${`
/// are inert there but a literal `"` would terminate the string early.
/// Backslash is escaped first for the same reason as
/// [`escape_ts_template_literal`].
pub fn escape_ts_double_quoted_literal(sql: &str) -> String {
    sql.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Render `name` as a TypeScript/JavaScript object or interface property
/// key, quoting it when it is not a valid bare identifier.
///
/// `interface Foo { class: string }` is legal TS -- reserved words are fine
/// unquoted as property keys, only *identifier shape* matters. A column
/// named `with-dash`, `my col`, or `1st` is not a valid identifier, so
/// emitting it bare (`with-dash: string;`) produces `TS1131`/`TS1351`
/// (#215); quoting it (`"with-dash": string;`) is valid in every property-key
/// position TypeScript has: interface members, type literal members, and
/// object literals.
///
/// `__proto__` is deliberately *not* special-cased here: quoted or bare, an
/// object literal key spelled exactly `__proto__` sets the prototype instead
/// of defining an own property. That is a separate bug from #215's
/// "not a valid identifier" class and is not something this function's
/// contract (produce a syntactically valid property key) can fix by itself.
pub fn ts_property_key(name: &str) -> String {
    if is_ts_identifier(name) {
        name.to_string()
    } else {
        format!("\"{}\"", escape_ts_double_quoted_literal(name))
    }
}

/// Render a property *read* of `name` off `object`, using dot access when
/// `name` is a valid bare identifier and bracket access otherwise.
///
/// The read counterpart of [`ts_property_key`], and the other half of #215:
/// quoting the declared key is not enough if the generated code then reads
/// it back with `row.first name` or `item.2fa`, neither of which parses.
/// `row["first name"]` and `item["2fa"]` are valid in every position a dot
/// access is.
///
/// A reserved word stays on the dot form deliberately: `row.class` is legal
/// property access in ES5+ (only *bindings* may not be keywords), so #215's
/// rule here is identifier shape, exactly as it is for the key position.
pub fn ts_member_access(object: &str, name: &str) -> String {
    if is_ts_identifier(name) {
        format!("{object}.{name}")
    } else {
        format!("{object}[\"{}\"]", escape_ts_double_quoted_literal(name))
    }
}

/// Render a bracket property read `object['name']` with `name` escaped for
/// the single-quoted JS string literal it is spliced into.
///
/// The backends whose driver hands back an untyped row read every column
/// this way, because the key is the raw SQL column name and bracket access
/// works for any of them. Splicing the name in unescaped is still wrong for
/// one shape #215 covers: a column named `it's` produced `row['it's']`,
/// which closes the string after `it` and does not parse.
///
/// Deliberately always brackets rather than reusing [`ts_member_access`]:
/// these call sites are reading a raw driver row, and switching the
/// overwhelmingly common identifier case to dot access would rewrite every
/// generated file in the repository to say the same thing a second way.
pub fn ts_index_access(object: &str, name: &str) -> String {
    format!("{object}['{}']", escape_ts_single_quoted_literal(name))
}

/// Escape a string for splicing into a single-quoted JS string literal.
///
/// The single-quote counterpart of [`escape_ts_double_quoted_literal`], with
/// backslash escaped first for the same reason.
fn escape_ts_single_quoted_literal(value: &str) -> String {
    value.replace('\\', "\\\\").replace('\'', "\\'")
}

/// Whether `name` is a valid TypeScript/JavaScript identifier: starts with
/// a letter, `_`, or `$`, followed by letters, digits, `_`, or `$`. (Unicode
/// identifier characters beyond ASCII are conservatively treated as
/// requiring quoting -- rare in SQL column names, and quoting is always
/// syntactically valid even when it was not strictly necessary.)
fn is_ts_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

/// Map an already-resolved TypeScript type expression to the Zod schema
/// whose `z.infer` is exactly that type.
///
/// This is keyed on the *TypeScript* type, not on the neutral SQL type,
/// which is the whole point (#216). `row_type = "zod"` used to consult a
/// hardcoded neutral-type table while `row_type = "interface"` resolved the
/// very same column through the backend manifest's `[types.scalars]`, so the
/// two modes disagreed wherever a manifest departed from that table's
/// assumptions -- and every TypeScript manifest departs from it somewhere.
/// On `typescript-node-sqlite`, for one file: `bool` is `number` in the
/// manifest and `z.boolean()` in the table, `decimal` is `number` versus
/// `z.string()`, `datetime` is `string` versus `z.date()`, `json` is
/// `Record<string, unknown>` versus `z.unknown()`. Four of six columns
/// declared one type under `interface` and a different one under `zod`, on
/// the same backend and the same query. Deriving the schema from the type
/// the manifest already produced makes that disagreement unrepresentable.
///
/// The fallback is `z.custom<T>()` rather than `z.unknown()`: `z.custom`
/// infers exactly `T` for any `T`, so an unrecognised manifest type (a
/// hand-written `[types.scalars]` override naming a project's own type)
/// still yields a schema whose inferred type matches the interface. It
/// performs no runtime check without a validator, which is the honest
/// outcome -- scythe has no way to know how to validate a type it has never
/// seen -- whereas `z.unknown()` would have silently widened the field.
pub fn ts_type_to_zod(ts_type: &str) -> String {
    let ts_type = ts_type.trim();
    if let Some(base) = ts_type.strip_suffix(" | null") {
        return format!("{}.nullable()", ts_type_to_zod(base));
    }
    if let Some(element) = ts_type.strip_prefix("Array<").and_then(|value| value.strip_suffix('>')) {
        return format!("z.array({})", ts_type_to_zod(element));
    }
    if let Some(element) = ts_type.strip_suffix("[]") {
        return format!("z.array({})", ts_type_to_zod(element));
    }
    match ts_type {
        "boolean" => "z.boolean()".to_string(),
        "number" => "z.number()".to_string(),
        "bigint" => "z.bigint()".to_string(),
        "string" => "z.string()".to_string(),
        "Date" => "z.date()".to_string(),
        "unknown" => "z.unknown()".to_string(),
        // The two binary runtimes any TypeScript manifest maps `bytes` to.
        // Both are real constructors, so `z.instanceof` resolves as a value
        // and infers the class type back.
        "Buffer" | "Uint8Array" => format!("z.instanceof({ts_type})"),
        "Record<string, unknown>" => "z.record(z.string(), z.unknown())".to_string(),
        _ => format!("z.custom<{ts_type}>()"),
    }
}

pub fn resolve_ts_json_runtime_type(neutral_type: &str, manifest: &BackendManifest) -> Result<String, ScytheError> {
    let neutral_type = neutral_type.trim();
    if let Some(inner) = container_inner(neutral_type, "nullable") {
        return Ok(format!("{} | null", resolve_ts_json_runtime_type(inner, manifest)?));
    }
    if let Some(inner) = container_inner(neutral_type, "array") {
        return Ok(format!("Array<{}>", resolve_ts_json_runtime_type(inner, manifest)?));
    }
    if let Some(inner) = container_inner(neutral_type, "json_nested") {
        return resolve_ts_json_runtime_type(inner, manifest);
    }
    if let Some(inner) = container_inner(neutral_type, "json_typed") {
        return Ok(inner.to_string());
    }
    if let Some(sql_name) = neutral_type.strip_prefix("enum::") {
        return Ok(enum_type_name(sql_name, &manifest.naming));
    }
    if let Some(sql_name) = neutral_type.strip_prefix("composite::") {
        return Ok(format!("{}Json", composite_type_name(sql_name, &manifest.naming)));
    }

    let runtime_type = match neutral_type {
        "bool" => "boolean",
        "int16" | "int32" | "int64" | "float32" | "float64" | "decimal" => "number",
        "string" | "bytes" | "uuid" | "date" | "time" | "time_tz" | "datetime" | "datetime_tz" | "interval"
        | "inet" => "string",
        "json" => "unknown",
        "json_array" => "Array<unknown>",
        custom if custom.chars().next().is_some_and(char::is_uppercase) => custom,
        _ => {
            return Err(ScytheError::new(
                ErrorCode::InternalError,
                format!("unsupported TypeScript JSON runtime type: {neutral_type}"),
            ));
        }
    };
    Ok(runtime_type.to_string())
}

pub fn generate_ts_nested_interface(
    nested: &NestedStructInfo,
    manifest: &BackendManifest,
) -> Result<String, ScytheError> {
    generate_ts_nested_interface_with_field_case(nested, manifest, TsFieldCase::Snake)
}

pub fn generate_ts_nested_interface_with_field_case(
    nested: &NestedStructInfo,
    manifest: &BackendManifest,
    field_case: TsFieldCase,
) -> Result<String, ScytheError> {
    let name = to_pascal_case(&nested.name);
    let mut out = String::new();
    let _ = writeln!(out, "/** JSON object produced for {}. */", nested.name);
    let _ = writeln!(out, "export interface {name} {{");
    for field in &nested.fields {
        let mut field_type = resolve_ts_json_runtime_type(&field.neutral_type, manifest)?;
        if field.nullable {
            field_type.push_str(" | null");
        }
        let field_name = match field_case {
            TsFieldCase::Snake => field.name.clone(),
            TsFieldCase::Camel => to_camel_case(&field.name).into_owned(),
        };
        let _ = writeln!(out, "\t{}: {field_type};", ts_property_key(&field_name));
    }
    let _ = write!(out, "}}");
    Ok(out)
}

pub fn generate_ts_json_composite_interface(
    composite: &CompositeInfo,
    manifest: &BackendManifest,
) -> Result<String, ScytheError> {
    generate_ts_json_composite_interface_with_field_case(composite, manifest, TsFieldCase::Snake)
}

pub fn generate_ts_json_composite_interface_with_field_case(
    composite: &CompositeInfo,
    manifest: &BackendManifest,
    field_case: TsFieldCase,
) -> Result<String, ScytheError> {
    let name = format!("{}Json", composite_type_name(&composite.sql_name, &manifest.naming));
    let mut out = String::new();
    let _ = writeln!(
        out,
        "/** JSON representation of composite type {}. */",
        composite.sql_name
    );
    let _ = writeln!(out, "export interface {name} {{");
    for field in &composite.fields {
        let mut field_type = resolve_ts_json_runtime_type(&field.neutral_type, manifest)?;
        if field.nullable {
            field_type.push_str(" | null");
        }
        let field_name = match field_case {
            TsFieldCase::Snake => field.name.clone(),
            TsFieldCase::Camel => to_camel_case(&field.name).into_owned(),
        };
        let _ = writeln!(out, "\t{}: {field_type};", ts_property_key(&field_name));
    }
    let _ = write!(out, "}}");
    Ok(out)
}

fn container_inner<'a>(neutral_type: &'a str, container: &str) -> Option<&'a str> {
    neutral_type
        .strip_prefix(container)?
        .strip_prefix('<')?
        .strip_suffix('>')
        .map(str::trim)
}

/// Render the plain TypeScript interface for a row.
///
/// Shared by every TypeScript backend so the shape cannot drift between them.
pub fn generate_ts_interface_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    generate_ts_interface_row_struct_with_base(struct_name, query_name, columns, None)
}

/// As [`generate_ts_interface_row_struct`], but extending `base` when the
/// target requires it (mysql2's `RowDataPacket`).
pub fn generate_ts_interface_row_struct_with_base(
    struct_name: &str,
    query_name: &str,
    columns: &[ResolvedColumn],
    base: Option<&str>,
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    match base {
        Some(base) => {
            let _ = writeln!(out, "export interface {} extends {} {{", struct_name, base);
        }
        None => {
            let _ = writeln!(out, "export interface {} {{", struct_name);
        }
    }
    for col in columns {
        let _ = writeln!(out, "\t{}: {};", ts_property_key(&col.field_name), col.full_type);
    }
    let _ = write!(out, "}}");
    out
}

/// Group the columns that an outer join can null out together.
///
/// Returns the groups in first-appearance order, keeping only those with at
/// least one discriminant — a column that was `NOT NULL` in the schema and so
/// can only be null when the join found no row. A group without a discriminant
/// carries no information a union could express, because every column in it was
/// independently nullable anyway.
fn discriminated_join_groups(columns: &[ResolvedColumn]) -> Vec<String> {
    let mut groups: Vec<String> = Vec::new();
    for col in columns {
        if let Some(group) = &col.join_group
            && !groups.contains(group)
            && columns
                .iter()
                .any(|c| c.join_group.as_ref() == Some(group) && c.is_join_discriminant())
        {
            groups.push(group.clone());
        }
    }
    groups
}

/// Render a row type that expresses outer-join nullability as a discriminated
/// union instead of independent per-column optionals.
///
/// For a `LEFT JOIN` where the joined relation projects at least one `NOT NULL`
/// column, the flat interface is sound but imprecise: it admits rows the query
/// can never produce. Given
///
/// ```sql
/// SELECT u.id, u.name, o.total, o.notes
/// FROM users u LEFT JOIN orders o ON u.id = o.user_id
/// ```
///
/// where `orders.total` is `NOT NULL` and `orders.notes` is not, a flat shape
/// admits `{ total: null, notes: "gift" }` — unreachable, because `total` is
/// null exactly when no order matched, and then `notes` is null too.
///
/// Columns from the inner side stay in a base object; each discriminated join
/// group contributes one matched/unmatched alternative.
///
/// Falls back to the plain interface when there is nothing to discriminate, so
/// callers can use this unconditionally.
/// `base` is intersected into the result when the target requires the row to
/// extend a driver type (mysql2's `RowDataPacket`). A union cannot use
/// `extends`, so it is expressed as an intersection instead.
pub fn generate_ts_union_row_struct(
    struct_name: &str,
    query_name: &str,
    columns: &[ResolvedColumn],
    base: Option<&str>,
) -> String {
    let groups = discriminated_join_groups(columns);
    if groups.is_empty() {
        return generate_ts_interface_row_struct_with_base(struct_name, query_name, columns, base);
    }

    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    match base {
        Some(base) => {
            let _ = writeln!(out, "export type {} = {} & {{", struct_name, base);
        }
        None => {
            let _ = writeln!(out, "export type {} = {{", struct_name);
        }
    }

    // ~keep Not just `join_group.is_none()`: a column belonging to a join group
    // that `discriminated_join_groups` dropped -- one where every projected
    // column was already nullable in the schema -- has no union variant to
    // live in, so filtering on `is_none()` alone omitted it from the row
    // type entirely. A query with two LEFT JOINs where only one joined
    // relation projects a NOT NULL column selected five columns and got a
    // type declaring three: silent on `typescript-pg`, which hands driver
    // rows back directly, and a compile error on the nine remap backends,
    // whose object literal then assigns properties the type does not
    // declare. Such a column is independently nullable, so `full_type` is
    // exactly right for it -- which is also what `TsRowShape::cast_type`
    // gives it, since it is not a join discriminant.
    for col in columns
        .iter()
        .filter(|c| c.join_group.as_ref().is_none_or(|group| !groups.contains(group)))
    {
        let _ = writeln!(out, "\t{}: {};", ts_property_key(&col.field_name), col.full_type);
    }
    let _ = write!(out, "}}");

    for group in &groups {
        let members: Vec<&ResolvedColumn> = columns
            .iter()
            .filter(|c| c.join_group.as_ref() == Some(group))
            .collect();

        let _ = writeln!(out, " & (");

        // Matched: the join found a row, so each column takes its own
        // schema nullability.
        let _ = write!(out, "\t| {{ ");
        for (index, col) in members.iter().enumerate() {
            if index > 0 {
                let _ = write!(out, "; ");
            }
            let matched_type = if col.nullable_before_join {
                col.full_type.as_str()
            } else {
                col.lang_type.as_str()
            };
            let _ = write!(out, "{}: {}", ts_property_key(&col.field_name), matched_type);
        }
        let _ = writeln!(out, " }}");

        // Unmatched: no row on the outer side, so every projected column is
        // null together.
        let _ = write!(out, "\t| {{ ");
        for (index, col) in members.iter().enumerate() {
            if index > 0 {
                let _ = write!(out, "; ");
            }
            let _ = write!(out, "{}: null", ts_property_key(&col.field_name));
        }
        let _ = writeln!(out, " }}");

        let _ = write!(out, ")");
    }

    // A type alias needs the terminator; the interface form does not.
    let _ = write!(out, ";");
    out
}

/// Generate a Zod schema and inferred type for a row struct.
pub fn generate_zod_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    let schema_name = format!("{struct_name}Schema");
    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    let _ = writeln!(out, "export const {} = z.object({{", schema_name);
    for col in columns {
        let zod_type = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", ts_property_key(&col.field_name), zod_type);
    }
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = write!(out, "export type {} = z.infer<typeof {}>;", struct_name, schema_name);
    out
}

/// Map a ResolvedColumn to its Zod schema expression, handling enums properly.
fn column_to_zod(col: &ResolvedColumn) -> String {
    column_to_zod_with_nullable(col, col.nullable)
}

/// As [`column_to_zod`], but with an explicit nullability instead of
/// `col.nullable`.
///
/// Needed by [`generate_zod_union_row_struct`]: inside the "matched" branch
/// of a discriminated union, a join-group column's schema nullability is
/// `col.nullable_before_join` (its own nullability, independent of the
/// join), not `col.nullable` (which the analyzer has already widened to
/// `true` for every column in the group).
fn column_to_zod_with_nullable(col: &ResolvedColumn, nullable: bool) -> String {
    if col.neutral_type.starts_with("enum::") {
        let base = if col.lang_type.starts_with("enum::") {
            col.lang_type
                .strip_prefix("enum::")
                .unwrap_or(&col.lang_type)
                .to_string()
        } else {
            col.lang_type.clone()
        };
        let schema_name = format!("{}Schema", base);
        if nullable {
            format!("{schema_name}.nullable()")
        } else {
            schema_name
        }
    } else {
        // Everything else is decided by the type the manifest already
        // resolved for this column, so `zod` and `interface` mode cannot
        // disagree -- see [`ts_type_to_zod`]. The one refinement layered on
        // top is `uuid`: `z.string().uuid()` still infers `string`, so it
        // agrees with the manifest while validating more than a bare
        // `z.string()` would.
        let base = if col.neutral_type == "uuid" && col.lang_type == "string" {
            "z.string().uuid()".to_string()
        } else {
            ts_type_to_zod(&col.lang_type)
        };
        if nullable { format!("{base}.nullable()") } else { base }
    }
}

/// Render a Zod schema that expresses outer-join nullability as a
/// discriminated union instead of independent per-column optionals.
///
/// This is the Zod counterpart to [`generate_ts_union_row_struct`]: the
/// inferred type of the generated schema matches the shape that function
/// produces. Grouping is computed by the same [`discriminated_join_groups`]
/// helper so the two can never drift apart on which joins qualify.
///
/// Falls back to [`generate_zod_row_struct`] when there is nothing to
/// discriminate, so callers can use this unconditionally — matching the
/// fallback behavior of `generate_ts_union_row_struct`.
pub fn generate_zod_union_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    let groups = discriminated_join_groups(columns);
    if groups.is_empty() {
        return generate_zod_row_struct(struct_name, query_name, columns);
    }

    let schema_name = format!("{struct_name}Schema");
    let mut out = String::new();
    let _ = writeln!(out, "/** Row type for {} queries. */", query_name);
    let _ = writeln!(out, "export const {} = z.object({{", schema_name);
    // ~keep Not just `join_group.is_none()`, for the same reason as the interface
    // path above: a column in a group `discriminated_join_groups` dropped --
    // one where every projected column was already nullable in the schema --
    // gets no union variant, so filtering on `is_none()` alone left it out of
    // the schema entirely and `z.infer` produced a type missing that field.
    for col in columns
        .iter()
        .filter(|c| c.join_group.as_ref().is_none_or(|group| !groups.contains(group)))
    {
        let zod_type = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", ts_property_key(&col.field_name), zod_type);
    }
    let _ = write!(out, "}})");

    for group in &groups {
        let members: Vec<&ResolvedColumn> = columns
            .iter()
            .filter(|c| c.join_group.as_ref() == Some(group))
            .collect();

        // Matched: the join found a row, so each column takes its own
        // pre-join schema nullability.
        let matched_fields: Vec<String> = members
            .iter()
            .map(|col| {
                format!(
                    "{}: {}",
                    ts_property_key(&col.field_name),
                    column_to_zod_with_nullable(col, col.nullable_before_join)
                )
            })
            .collect();
        // Unmatched: no row on the outer side, so every projected column is
        // null together.
        let unmatched_fields: Vec<String> = members
            .iter()
            .map(|col| format!("{}: z.null()", ts_property_key(&col.field_name)))
            .collect();

        let _ = write!(
            out,
            ".and(z.union([z.object({{ {} }}), z.object({{ {} }})]))",
            matched_fields.join(", "),
            unmatched_fields.join(", "),
        );
    }
    let _ = writeln!(out, ";");
    let _ = writeln!(out);
    let _ = write!(out, "export type {} = z.infer<typeof {}>;", struct_name, schema_name);
    out
}

/// Generate paired child + parent TypeScript interfaces for a `:grouped` query.
///
/// Child interface is emitted first so the parent's `children: ChildType[]` field
/// resolves without a forward reference.
pub fn generate_grouped_interface_structs(
    child_struct_name: &str,
    parent_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/** Child row type for grouped query. */");
    let _ = writeln!(out, "export interface {child_struct_name} {{");
    for col in child_columns {
        let _ = writeln!(out, "\t{}: {};", ts_property_key(&col.field_name), col.full_type);
    }
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(out, "/** Parent row type for grouped query. */");
    let _ = writeln!(out, "export interface {parent_struct_name} {{");
    for col in parent_columns {
        let _ = writeln!(out, "\t{}: {};", ts_property_key(&col.field_name), col.full_type);
    }
    let _ = writeln!(out, "\tchildren: {child_struct_name}[];");
    let _ = write!(out, "}}");
    out
}

/// Generate paired child + parent Zod schemas for a `:grouped` query.
///
/// Child schema is emitted first so the parent's `children: z.array(ChildSchema)`
/// reference resolves without a forward declaration.
pub fn generate_zod_grouped_structs(
    child_struct_name: &str,
    parent_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
) -> String {
    let child_schema = format!("{child_struct_name}Schema");
    let parent_schema = format!("{parent_struct_name}Schema");
    let mut out = String::new();
    let _ = writeln!(out, "/** Child row type for grouped query. */");
    let _ = writeln!(out, "export const {child_schema} = z.object({{");
    for col in child_columns {
        let zod = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", ts_property_key(&col.field_name), zod);
    }
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = writeln!(out, "export type {child_struct_name} = z.infer<typeof {child_schema}>;");
    let _ = writeln!(out);
    let _ = writeln!(out, "/** Parent row type for grouped query. */");
    let _ = writeln!(out, "export const {parent_schema} = z.object({{");
    for col in parent_columns {
        let zod = column_to_zod(col);
        let _ = writeln!(out, "\t{}: {},", ts_property_key(&col.field_name), zod);
    }
    let _ = writeln!(out, "\tchildren: z.array({child_schema}),");
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = write!(
        out,
        "export type {parent_struct_name} = z.infer<typeof {parent_schema}>;"
    );
    out
}

/// Render the `field: value,` lines of a TypeScript object literal for a
/// row's columns, one per line, at the given `indent`.
///
/// `row_access(sql_col_name, ts_full_type)` returns the TypeScript expression
/// that reads that column from the current row variable -- see
/// [`generate_ts_grouped_fold_body`] for the per-backend examples.
///
/// `shape` picks the type each field is cast to, so the literal stays
/// assignable to the row type the caller declared -- see
/// [`TsRowShape::cast_type`].
///
/// Shared by both halves of `generate_ts_grouped_fold_body` -- the parent
/// object and the child object it pushes into `children` -- so their field
/// lists cannot drift apart. Also used by [`generate_ts_one_row_remap`] and
/// [`generate_ts_many_row_remap`] for `:one`/`:many` row construction under
/// `field_case = "camelCase"`. Callers own the surrounding `{ ... }` and any
/// additional properties (e.g. `children: []`), since those differ between
/// call sites.
pub fn generate_ts_row_object_literal(
    columns: &[ResolvedColumn],
    indent: &str,
    shape: TsRowShape,
    row_access: impl Fn(&str, &str) -> String,
) -> String {
    let mut out = String::new();
    for col in columns {
        let _ = writeln!(
            out,
            "{indent}{}: {},",
            ts_property_key(&col.field_name),
            row_access(&col.name, shape.cast_type(col))
        );
    }
    out
}

/// Render the `throw new Error(...)` statement a `:one` query emits when no
/// row matched, unindented -- the caller splices it at whatever depth its
/// surrounding `if` block sits at.
///
/// A plain `Error`, not a scythe-defined error class (#192): no TypeScript
/// or JavaScript backend emits a custom error type into generated output
/// today -- every backend's try/catch already re-throws a driver failure
/// as-is (`throw error;`), so a caller of a generated query function
/// already has to handle a bare `Error` from it, and a `:one` miss joins
/// that same surface instead of adding a second, differently-typed one to
/// tell apart. Introducing an exported class would also need a
/// run-once-per-generated-file emission slot this trait does not have --
/// the only such dedup machinery lives in the file assembler (`scythe-cli`,
/// outside this crate), and it is keyed by SQL type name, not by "this file
/// happens to contain a `:one` query".
pub fn ts_row_not_found_throw(query_name: &str) -> String {
    format!(
        "throw new Error(\"no row found for query: {}\");",
        escape_ts_double_quoted_literal(query_name)
    )
}

/// Render a `:one`/`:opt` return body that reconstructs the row field by
/// field instead of trusting a blind cast of the driver's raw row.
///
/// Assumes the caller has already bound the raw driver row (or
/// `undefined`/`null`, if none matched) to a local `row`. Null-checks it,
/// then builds the return value via [`generate_ts_row_object_literal`],
/// using the same `row_access` closure the backend already passes to
/// [`generate_ts_grouped_fold_body`] to read a named column off a raw row.
///
/// A blind `as StructName` cast of the driver's row (what every `:one`/
/// `:opt` used before this existed, and still does under the default
/// `field_case = "snake_case"`, where it is sound) is unsound once
/// `field_case = "camelCase"` renames the declared fields: the driver still
/// returns snake_case keys, so `tsc` reports no error while every field
/// reads back `undefined` at runtime.
///
/// `shape` must be the shape of the row type the enclosing function
/// declares, so the literal is assignable to it -- see
/// [`TsRowShape::cast_type`].
///
/// `command` picks the missing-row branch (#192): `QueryCommand::One` throws
/// via [`ts_row_not_found_throw`], naming the query `query_name`; anything
/// else (`QueryCommand::Opt`, the only other caller) keeps the pre-#192
/// `return null;`.
pub fn generate_ts_one_row_remap(
    columns: &[ResolvedColumn],
    shape: TsRowShape,
    command: &QueryCommand,
    query_name: &str,
    row_access: impl Fn(&str, &str) -> String,
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "\tif (!row) {{");
    if matches!(command, QueryCommand::One) {
        let _ = writeln!(out, "\t\t{}", ts_row_not_found_throw(query_name));
    } else {
        let _ = writeln!(out, "\t\treturn null;");
    }
    let _ = writeln!(out, "\t}}");
    let _ = writeln!(out, "\treturn {{");
    out.push_str(&generate_ts_row_object_literal(columns, "\t\t", shape, row_access));
    let _ = writeln!(out, "\t}};");
    out
}

/// Render a `:many` return body that reconstructs each row field by field
/// instead of trusting a blind cast of the driver's raw rows.
///
/// Assumes the caller has already bound the raw driver rows to a local
/// `rows` array. Maps each one (bound to `row` inside the callback) through
/// [`generate_ts_row_object_literal`]. See [`generate_ts_one_row_remap`] for
/// why this exists instead of a blind cast, and for what `shape` selects.
pub fn generate_ts_many_row_remap(
    columns: &[ResolvedColumn],
    shape: TsRowShape,
    row_access: impl Fn(&str, &str) -> String,
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "\treturn rows.map((row) => ({{");
    out.push_str(&generate_ts_row_object_literal(columns, "\t\t", shape, row_access));
    let _ = writeln!(out, "\t}}));");
    out
}

/// Generate the client-side fold body for a `:grouped` query.
///
/// `row_access(sql_col_name, ts_full_type)` returns the TypeScript expression that
/// reads that column from the current `row` loop variable.  Examples:
/// - pg/mysql2 (dot access):   `|name, ty| format!("row.{name} as {ty}")`
/// - postgres.js/mssql/duckdb: `|name, ty| format!("row['{}'] as {}", name, ty)`
/// - Oracle (uppercase keys):  `|name, ty| format!("row['{}'] as {}", name.to_uppercase(), ty)`
///
/// Every TypeScript-mode caller casts. pg and mysql2 hand back rows whose
/// fields are already `any` (`QueryResult<any>` and `RowDataPacket`'s index
/// signature), so the cast is not load-bearing *today* -- but the `:one` and
/// `:many` paths in those same two backends have always cast, and a fold that
/// silently disagreed with its neighbours would be the thing to break first if
/// either driver's row type were ever narrowed.
///
/// The `javascript-*` emit mode is the sole exception and must never cast:
/// `as T` is not valid JavaScript. Those callers pass `|name, _ty|` by
/// necessity, not by preference.
///
/// The helper emits the fold loop into a string that is appended directly inside
/// the function body; the caller is responsible for surrounding braces.
///
/// The parent and child objects are always built at [`TsRowShape::Flat`]:
/// `:grouped` declares its structs through
/// [`generate_grouped_interface_structs`] (or its Zod twin), which emits a
/// plain object per struct at `full_type` regardless of the backend's
/// `outer_join_unions` setting, so there is no union variant here to agree
/// with.
///
/// `js_mode` drops the `: Type` local-variable annotations and the
/// `Map<unknown, Type>` generic argument, neither of which plain JavaScript
/// can parse -- the JSDoc-mode counterpart used by the `javascript-*` emit
/// mode. The fold logic itself (the `Map`-based grouping loop) is identical
/// either way, so this stays one function rather than a duplicated one.
pub fn generate_ts_grouped_fold_body(
    parent_struct_name: &str,
    _child_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
    key_col_name: &str,
    js_mode: bool,
    row_access: impl Fn(&str, &str) -> String,
) -> String {
    let key_type = parent_columns
        .iter()
        .find(|c| c.name == key_col_name)
        .map_or("unknown", |c| c.full_type.as_str());

    let mut out = String::new();
    if js_mode {
        let _ = writeln!(out, "\tconst result = [];");
        let _ = writeln!(out, "\tconst index = new Map();");
    } else {
        let _ = writeln!(out, "\tconst result: {parent_struct_name}[] = [];");
        let _ = writeln!(out, "\tconst index = new Map<unknown, {parent_struct_name}>();");
    }
    let _ = writeln!(out, "\tfor (const row of flatRows) {{");
    let _ = writeln!(out, "\t\tconst key = {};", row_access(key_col_name, key_type));
    let _ = writeln!(out, "\t\tlet parent = index.get(key);");
    let _ = writeln!(out, "\t\tif (!parent) {{");
    let _ = writeln!(out, "\t\t\tparent = {{");
    out.push_str(&generate_ts_row_object_literal(
        parent_columns,
        "\t\t\t\t",
        TsRowShape::Flat,
        &row_access,
    ));
    let _ = writeln!(out, "\t\t\t\tchildren: [],");
    let _ = writeln!(out, "\t\t\t}};");
    let _ = writeln!(out, "\t\t\tindex.set(key, parent);");
    let _ = writeln!(out, "\t\t\tresult.push(parent);");
    let _ = writeln!(out, "\t\t}}");
    let _ = writeln!(out, "\t\tparent.children.push({{");
    out.push_str(&generate_ts_row_object_literal(
        child_columns,
        "\t\t\t",
        TsRowShape::Flat,
        &row_access,
    ));
    let _ = writeln!(out, "\t\t}});");
    let _ = writeln!(out, "\t}}");
    let _ = writeln!(out, "\treturn result;");
    out
}

/// Render `name` as a JSDoc `@property`/`@param` name token.
///
/// JSDoc tag syntax has no quoted or bracketed name form -- the name is a
/// bare, whitespace-delimited token right after the `{type}` capture -- so
/// neither of #215's two TypeScript answers to a hostile column name apply
/// here. [`ts_property_key`]'s `"my col"` quoting and [`ts_index_access`]'s
/// `row["my col"]` bracket access are both TypeScript/JavaScript *value*
/// syntax; a `@property`/`@param` name is not a value position and cannot
/// carry a string literal or a bracket expression. This is the same "no
/// quoted form" situation `scythe_backend::naming::param_name` already
/// resolves for parameter bindings across every target language, so the fix
/// here is the same one: fold every character an identifier cannot hold
/// into `_`, and prefix a leading digit so the token still opens like one.
///
/// The JSDoc name can therefore read differently from the row struct's own
/// field spelling, which deliberately keeps the raw SQL column name (see
/// [`ts_property_key`]'s doc comment) because it is cast straight onto the
/// driver's row. That divergence is unavoidable once the name has to fit a
/// syntax with no quoting at all -- it is the same trade-off every
/// `sanitize_field_names` backend already accepts, for the same reason.
pub fn js_doc_name(name: &str) -> String {
    if is_ts_identifier(name) {
        return name.to_string();
    }
    let mut mangled = String::with_capacity(name.len());
    for ch in name.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' || ch == '$' {
            mangled.push(ch);
        } else {
            mangled.push('_');
        }
    }
    if mangled.starts_with(|c: char| c.is_ascii_digit()) {
        mangled.insert(0, '_');
    }
    mangled
}

/// Render one JSDoc `@property` line for a row typedef.
///
/// This function's source is grepped by a dedicated test
/// (`test_js_property_line_source_cannot_emit_optional_syntax_into_the_name_position`)
/// to guarantee no future edit can reintroduce JSDoc's bracket-optional
/// (`[name]`) or `?`-suffix property syntax here. A nullable SQL column is a
/// property that is always present on the row and may hold `null` --
/// `{T | null}` -- never a property that may be *absent*, which is what
/// `[name]`/`name?` mean in JSDoc. `col.full_type` already carries the
/// `| null` suffix when `col.nullable` is true (computed once, upstream, by
/// the type resolver -- see [`ResolvedColumn`]), so this function has no
/// reason to branch on `col.nullable` at all: there is deliberately no such
/// conditional here for the grep guard to catch a regression of.
///
/// The name goes through [`js_doc_name`] because a column is not guaranteed
/// to be identifier-shaped and JSDoc's `@property` name has no quoted form
/// -- see that function's doc comment.
// jsdoc-property-line-start
pub fn js_property_line(col: &ResolvedColumn) -> String {
    format!(" * @property {{{}}} {}", col.full_type, js_doc_name(&col.field_name))
}
// jsdoc-property-line-end

/// True when every column's key can be spelled as a bare JSDoc `@property`
/// name. See [`render_row_typedef_body`] for why that governs which of two
/// `@typedef` forms a row gets.
fn every_key_is_a_bare_jsdoc_name(columns: &[ResolvedColumn]) -> bool {
    columns.iter().all(|col| is_ts_identifier(&col.field_name))
}

/// Render the `@typedef` line(s) describing a row's shape, choosing between
/// JSDoc's two forms according to whether any key needs quoting.
///
/// A generated row typedef describes the object the *driver* hands back:
/// the `javascript-*` query fns end in `return rows;`, so the runtime keys
/// are the column's own SQL spelling, exactly as in TypeScript mode, where
/// [`ts_property_key`] quotes rather than mangles for precisely this reason.
///
/// JSDoc has two ways to describe an object and they do not have the same
/// expressive power, which is what forces the branch here:
///
/// * `@typedef {object} Name` plus one `@property {T} key` line each. The
///   `@property` name is a bare token -- TypeScript's JSDoc parser rejects a
///   quoted one with `TS1003: Identifier expected` -- so this form simply
///   cannot describe a key like `my col`.
/// * `@typedef {{ "my col": string, id: number }} Name`, an inline object
///   type expression, which accepts quoted keys and checks clean.
///
/// Mangling the name to fit the first form would be a silent wrong answer,
/// not a cosmetic one: `@property {string} my_col` tells `tsc --checkJs`
/// that the row has a `my_col` property, so `row["my col"]` -- the access
/// that actually works at runtime -- becomes an error, while `row.my_col`
/// type-checks and is `undefined`. That is the same trade the row-key
/// contract rejects everywhere else in this file.
///
/// The `@property` form is kept for the overwhelmingly common all-identifier
/// case so ordinary generated output stays byte-identical and stays readable;
/// the type-literal form is used only where the first form would lie.
fn render_row_typedef_body(out: &mut String, struct_name: &str, columns: &[ResolvedColumn], children_of: Option<&str>) {
    if every_key_is_a_bare_jsdoc_name(columns) {
        let _ = writeln!(out, " * @typedef {{object}} {}", struct_name);
        for col in columns {
            let _ = writeln!(out, "{}", js_property_line(col));
        }
        if let Some(child_struct_name) = children_of {
            let _ = writeln!(out, " * @property {{{}[]}} children", child_struct_name);
        }
        return;
    }

    let mut fields: Vec<String> = columns
        .iter()
        .map(|col| format!("{}: {}", ts_property_key(&col.field_name), col.full_type))
        .collect();
    if let Some(child_struct_name) = children_of {
        fields.push(format!("children: {child_struct_name}[]"));
    }
    let _ = writeln!(out, " * @typedef {{{{ {} }}}} {}", fields.join(", "), struct_name);
}

/// Render a plain-JS JSDoc `@typedef` for a row -- the JSDoc-mode
/// counterpart of [`generate_ts_interface_row_struct`], used by the
/// `javascript-*` emit mode of the TypeScript backends (#81). The
/// nullable-as-`T | null` rule applies uniformly here too, via either
/// [`js_property_line`] or the column's `full_type` directly; see
/// [`render_row_typedef_body`] for which form a given row gets.
pub fn generate_js_typedef_row_struct(struct_name: &str, query_name: &str, columns: &[ResolvedColumn]) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/**");
    let _ = writeln!(out, " * Row type for {} queries.", query_name);
    render_row_typedef_body(&mut out, struct_name, columns, None);
    let _ = write!(out, " */");
    out
}

/// Render a generic JSDoc `@typedef` from arbitrary `(name, type)` fields --
/// used for `:batch` params objects, which are built from [`ResolvedParam`]s
/// rather than [`ResolvedColumn`]s and so carry no SQL nullability to encode,
/// and for composite type typedefs.
///
/// `name` goes through [`js_doc_name`] like every other JSDoc name token.
/// `ResolvedParam::field_name` is already identifier-mangled unconditionally
/// (`scythe_backend::naming::param_name` has no `sanitize_field_names`
/// opt-out, unlike columns), so this is a no-op for the batch-params caller;
/// it is load-bearing for the composite-field caller, whose names go through
/// `to_camel_case` only and can still carry non-identifier characters.
pub fn generate_js_typedef(type_name: &str, description: &str, fields: &[(String, String)]) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/**");
    let _ = writeln!(out, " * {}", description);
    let _ = writeln!(out, " * @typedef {{object}} {}", type_name);
    for (name, ty) in fields {
        let _ = writeln!(out, " * @property {{{}}} {}", ty, js_doc_name(name));
    }
    let _ = write!(out, " */");
    out
}

/// Render paired child + parent JSDoc `@typedef`s for a `:grouped` query --
/// the JSDoc-mode counterpart of [`generate_grouped_interface_structs`].
pub fn generate_js_grouped_typedef_structs(
    child_struct_name: &str,
    parent_struct_name: &str,
    parent_columns: &[ResolvedColumn],
    child_columns: &[ResolvedColumn],
) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/**");
    let _ = writeln!(out, " * Child row type for grouped query.");
    render_row_typedef_body(&mut out, child_struct_name, child_columns, None);
    let _ = writeln!(out, " */");
    let _ = writeln!(out);
    let _ = writeln!(out, "/**");
    let _ = writeln!(out, " * Parent row type for grouped query.");
    render_row_typedef_body(&mut out, parent_struct_name, parent_columns, Some(child_struct_name));
    let _ = write!(out, " */");
    out
}

/// Render a JSDoc inline type cast: `/** @type {T} */ (expr)`.
///
/// The JSDoc analog of a TypeScript `as T` assertion, for plain `.js` files
/// checked with `tsc --checkJs`. `as` is TS-only syntax and would make the
/// file fail to parse as JavaScript, so the `javascript-*` emit mode uses
/// this everywhere a TypeScript backend would write `expr as T`.
pub fn js_type_cast(ty: &str, expr: &str) -> String {
    format!("/** @type {{{ty}}} */ ({expr})")
}

/// Render a JSDoc block combining a one-line description, one `@param` tag
/// per `(name, type)` pair, and a `@returns` tag -- the JSDoc-mode
/// counterpart of a TypeScript function's inline `(name: Type): Ret`
/// annotations, which a plain `.js` file cannot carry on the signature
/// itself.
///
/// `name` goes through [`js_doc_name`] for the same reason [`js_property_line`]
/// does. Every caller today passes an already-mangled `ResolvedParam::field_name`
/// (or a literal like `"sql"`/`"items"`/`"count"`), so this is a no-op in
/// practice, but it keeps `@param` from becoming the one JSDoc position that
/// silently regresses if a future caller ever hands it a raw SQL name.
pub fn generate_jsdoc_fn_header(description: &str, sig_params: &[(String, String)], ret_type: &str) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "/**");
    let _ = writeln!(out, " * {}", description);
    for (name, ty) in sig_params {
        let _ = writeln!(out, " * @param {{{}}} {}", ty, js_doc_name(name));
    }
    let _ = writeln!(out, " * @returns {{{}}}", ret_type);
    let _ = write!(out, " */");
    out
}

/// Render a JS function signature line with plain parameter names and no
/// type annotations -- the JSDoc-mode counterpart of a TypeScript
/// `name: Type` signature (see [`generate_jsdoc_fn_header`] for where the
/// types go instead).
pub fn js_fn_signature_line(is_async: bool, name: &str, sig_params: &[(String, String)]) -> String {
    let params_inline = sig_params.iter().map(|(n, _)| n.clone()).collect::<Vec<_>>().join(", ");
    let keyword = if is_async {
        "export async function"
    } else {
        "export function"
    };
    format!("{keyword} {name}({params_inline}) {{")
}

/// Generate a Zod enum schema from enum values.
///
/// `naming` is the backend manifest's [`NamingConfig`], and is what makes
/// the variant keys here identical to the ones the `interface` path emits
/// through [`scythe_backend::naming::enum_variant_name`] (#216). Calling
/// `to_pascal_case` directly instead -- which is what this did -- skips that
/// function's identifier sanitisation, so a SQL enum value that is not
/// already identifier-shaped came out differently in the two modes: the
/// value `in-active` became `InActive` under `interface` and `In-active`
/// under `zod`, and the latter is not a valid object key at all.
///
/// Both the `z.enum([...])` members and the const's values are string
/// literals holding a value that came from user DDL, so both go through
/// [`escape_ts_double_quoted_literal`]; an enum value containing a `"` or a
/// `\` would otherwise terminate or corrupt the literal.
pub fn generate_zod_enum(type_name: &str, values: &[String], naming: &scythe_backend::naming::NamingConfig) -> String {
    let schema_name = format!("{type_name}Schema");
    let mut out = String::new();
    let variants: Vec<String> = values
        .iter()
        .map(|v| format!("\"{}\"", escape_ts_double_quoted_literal(v)))
        .collect();
    let _ = writeln!(out, "export const {} = z.enum([{}]);", schema_name, variants.join(", "));
    let _ = writeln!(out);
    let _ = write!(out, "export type {} = z.infer<typeof {}>;", type_name, schema_name);
    let _ = writeln!(out);
    let _ = writeln!(out);
    let _ = writeln!(out, "export const {} = {{", type_name);
    for value in values {
        let key = scythe_backend::naming::enum_variant_name(value, naming);
        let _ = writeln!(
            out,
            "\t{}: \"{}\",",
            ts_property_key(&key),
            escape_ts_double_quoted_literal(value)
        );
    }
    let _ = write!(out, "}} as const;");
    out
}

/// Render the JSDoc-mode enum definition: a frozen values object plus the
/// union `@typedef` derived from it.
///
/// `as const` is TypeScript-only syntax, so the literal narrowing the TS path
/// gets from it has to come from a JSDoc cast here. The cast must sit on the
/// *initializer expression*, never on the declaration:
///
/// ```js
/// export const XValues = /** @type {const} */ ({ A: "a" });  // narrows
/// /** @type {const} */ export const XValues = { A: "a" };    // TS2304
/// ```
///
/// There is no `const` *type* for JSDoc to name — `const` is only meaningful
/// as an assertion applied to an expression — so the declaration form was
/// never valid in any TypeScript version. All three `javascript-*` emitters
/// used it until the tool-validation schema grew an enum column and
/// `tsc --checkJs` rejected every one of them with
/// `TS2304: Cannot find name 'const'`.
///
/// It lives here, rather than as three byte-identical copies in
/// `typescript_pg.rs` / `typescript_postgres.rs` / `typescript_mysql2.rs`,
/// because those copies are exactly why one wrong spelling took three fixes
/// to remove.
pub fn generate_js_enum_def(type_name: &str, variants: &[(String, String)]) -> String {
    let values_name = format!("{type_name}Values");
    let mut out = String::new();
    let _ = writeln!(out, "export const {} = /** @type {{const}} */ ({{", values_name);
    for (variant, value) in variants {
        let _ = writeln!(out, "\t{}: \"{}\",", variant, value);
    }
    let _ = writeln!(out, "}});");
    let _ = writeln!(out);
    let _ = write!(
        out,
        "/** @typedef {{typeof {}[keyof typeof {}]}} {} */",
        values_name, values_name, type_name
    );
    out
}

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

    /// Regression coverage for #215: a column name that is not a valid TS
    /// identifier must be quoted, not spliced bare into a property-key
    /// position.
    #[test]
    fn ts_property_key_quotes_non_identifier_names() {
        assert_eq!(ts_property_key("with-dash"), "\"with-dash\"");
        assert_eq!(ts_property_key("my col"), "\"my col\"");
        assert_eq!(ts_property_key("1st"), "\"1st\"");
    }

    /// A reserved word is a valid TS property key unquoted -- #215 is about
    /// identifier *shape*, not keyword-ness (unlike #180/#151's field-name
    /// mangling, which is the opposite: keyword-ness, not shape).
    #[test]
    fn ts_property_key_leaves_valid_identifiers_and_keywords_bare() {
        assert_eq!(ts_property_key("user_id"), "user_id");
        assert_eq!(ts_property_key("class"), "class");
        assert_eq!(ts_property_key("_private"), "_private");
        assert_eq!(ts_property_key("$special"), "$special");
    }

    #[test]
    fn ts_property_key_escapes_a_quote_inside_the_name() {
        assert_eq!(ts_property_key("weird\"name"), "\"weird\\\"name\"");
    }

    fn postgres_manifest() -> BackendManifest {
        crate::backends::parse_manifest(include_str!("../../manifests/typescript-pg.toml"))
            .expect("TypeScript PostgreSQL manifest must parse")
    }

    #[test]
    fn json_runtime_types_follow_postgresql_json_encoding() {
        let manifest = postgres_manifest();
        assert_eq!(resolve_ts_json_runtime_type("decimal", &manifest).unwrap(), "number");
        assert_eq!(
            resolve_ts_json_runtime_type("datetime_tz", &manifest).unwrap(),
            "string"
        );
        assert_eq!(resolve_ts_json_runtime_type("bytes", &manifest).unwrap(), "string");
        assert_eq!(
            resolve_ts_json_runtime_type("enum::order_status", &manifest).unwrap(),
            "OrderStatus"
        );
        assert_eq!(
            resolve_ts_json_runtime_type("array<nullable<int32>>", &manifest).unwrap(),
            "Array<number | null>"
        );
        assert_eq!(
            resolve_ts_json_runtime_type("composite::shipping_address", &manifest).unwrap(),
            "ShippingAddressJson"
        );
        assert_eq!(
            resolve_ts_json_runtime_type("json_typed<ApiPayload>", &manifest).unwrap(),
            "ApiPayload"
        );
        assert!(resolve_ts_json_runtime_type("unknown", &manifest).is_err());
        assert!(resolve_ts_json_runtime_type("future_geography", &manifest).is_err());
    }

    #[test]
    fn nested_interface_preserves_raw_json_keys_and_required_nullability() {
        let nested = NestedStructInfo {
            name: "get_orders_row_orders".to_string(),
            fields: vec![
                scythe_core::analyzer::NestedFieldInfo {
                    name: "createdAt".to_string(),
                    neutral_type: "datetime_tz".to_string(),
                    nullable: false,
                },
                scythe_core::analyzer::NestedFieldInfo {
                    name: "delivery notes".to_string(),
                    neutral_type: "string".to_string(),
                    nullable: true,
                },
            ],
        };
        assert_eq!(
            generate_ts_nested_interface(&nested, &postgres_manifest()).unwrap(),
            "/** JSON object produced for get_orders_row_orders. */\n\
             export interface GetOrdersRowOrders {\n\
             \tcreatedAt: string;\n\
             \t\"delivery notes\": string | null;\n\
             }"
        );
    }

    #[test]
    fn json_composite_interface_is_distinct_from_driver_native_type() {
        let composite = CompositeInfo {
            sql_name: "shipping_address".to_string(),
            fields: vec![scythe_core::analyzer::CompositeFieldInfo {
                name: "zip_code".to_string(),
                neutral_type: "int32".to_string(),
                nullable: true,
            }],
        };
        assert_eq!(
            generate_ts_json_composite_interface(&composite, &postgres_manifest()).unwrap(),
            "/** JSON representation of composite type shipping_address. */\n\
             export interface ShippingAddressJson {\n\
             \tzip_code: number | null;\n\
             }"
        );
    }

    #[test]
    fn zod_array_uses_custom_nested_element_type_without_recursive_validation() {
        assert_eq!(
            ts_type_to_zod("Array<GetOrdersRowOrders | null>"),
            "z.array(z.custom<GetOrdersRowOrders>().nullable())"
        );
    }

    fn column(
        name: &str,
        lang_type: &str,
        nullable: bool,
        group: Option<&str>,
        nullable_before_join: bool,
    ) -> ResolvedColumn {
        ResolvedColumn {
            name: name.to_string(),
            field_name: name.to_string(),
            lang_type: lang_type.to_string(),
            full_type: if nullable {
                format!("{lang_type} | null")
            } else {
                lang_type.to_string()
            },
            neutral_type: "string".to_string(),
            sql_type: "text".to_string(),
            nullable,
            join_group: group.map(str::to_string),
            nullable_before_join,
        }
    }

    /// The example from the issue: `orders.total` is NOT NULL so it
    /// discriminates the join, while `orders.notes` is independently nullable.
    fn user_orders_columns() -> Vec<ResolvedColumn> {
        vec![
            column("id", "number", false, None, false),
            column("name", "string", false, None, false),
            column("total", "string", true, Some("o"), false),
            column("notes", "string", true, Some("o"), true),
        ]
    }

    #[test]
    fn emits_a_union_that_ties_the_outer_join_columns_together() {
        let out = generate_ts_union_row_struct("GetUserOrdersRow", "GetUserOrders", &user_orders_columns(), None);

        assert!(out.contains("export type GetUserOrdersRow = {"), "{out}");
        // Inner-side columns stay in the base object.
        assert!(out.contains("\tid: number;"), "{out}");
        assert!(out.contains("\tname: string;"), "{out}");
        // Matched: total is non-null, notes keeps its own nullability.
        assert!(out.contains("| { total: string; notes: string | null }"), "{out}");
        // Unmatched: the whole group is null together.
        assert!(out.contains("| { total: null; notes: null }"), "{out}");
        assert!(out.ends_with(");"), "type alias must be terminated: {out}");
    }

    /// Without a NOT NULL column on the outer side there is no discriminant,
    /// so the flat shape is already exact and a union would add nothing.
    #[test]
    fn falls_back_to_the_flat_interface_when_no_column_discriminates() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("notes", "string", true, Some("o"), true),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert!(out.contains("export interface R {"), "{out}");
        assert!(!out.contains(" & ("), "no union without a discriminant: {out}");
    }

    #[test]
    fn falls_back_to_the_flat_interface_when_there_is_no_outer_join() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("name", "string", false, None, false),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert_eq!(out, generate_ts_interface_row_struct("R", "Q", &columns));
    }

    /// mysql2 rows must extend RowDataPacket. A union cannot use `extends`, so
    /// the base is intersected instead.
    #[test]
    fn intersects_the_base_type_when_the_target_requires_one() {
        let out = generate_ts_union_row_struct("R", "Q", &user_orders_columns(), Some("RowDataPacket"));

        assert!(out.contains("export type R = RowDataPacket & {"), "{out}");
    }

    /// Two independently outer-joined relations each get their own
    /// match/no-match alternative rather than being conflated.
    #[test]
    fn emits_one_alternative_per_join_group() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("total", "string", true, Some("o"), false),
            column("addr", "string", true, Some("a"), false),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert!(out.contains("| { total: string }"), "{out}");
        assert!(out.contains("| { total: null }"), "{out}");
        assert!(out.contains("| { addr: string }"), "{out}");
        assert!(out.contains("| { addr: null }"), "{out}");
        assert_eq!(out.matches(" & (").count(), 2, "one group per relation: {out}");
    }

    /// This must fail before the fix: a join group `discriminated_join_groups`
    /// drops -- every projected column already nullable in the schema -- got
    /// no union variant, and the base-field loop filtered on
    /// `join_group.is_none()`, so its columns were declared nowhere. The
    /// query below selects four columns; the row type declared two. The
    /// whole-query case is caught by the flat-interface fallback, so only a
    /// query mixing a discriminated group with an undiscriminated one
    /// reaches it.
    #[test]
    fn keeps_columns_from_join_groups_that_carry_no_discriminant() {
        let columns = vec![
            column("id", "number", false, None, false),
            // Undiscriminated group: nullable in the schema before any join.
            column("bio", "string", true, Some("p"), true),
            column("website", "string", true, Some("p"), true),
            // Discriminated group: NOT NULL in the schema, so it can only be
            // null when the join found no row.
            column("label", "string", true, Some("b"), false),
        ];

        let out = generate_ts_union_row_struct("R", "Q", &columns, None);

        assert!(out.contains("bio: string | null;"), "{out}");
        assert!(out.contains("website: string | null;"), "{out}");
        assert!(out.contains("| { label: string }"), "{out}");
        assert!(out.contains("| { label: null }"), "{out}");
        assert_eq!(
            out.matches(" & (").count(),
            1,
            "only the discriminated group becomes a union: {out}"
        );
    }

    /// The Zod counterpart of the case above. The doc comment on
    /// `generate_zod_union_row_struct` promises its inferred type matches the
    /// interface form, so the two base-field filters have to agree; they did
    /// not, and `z.infer` produced a type missing the undiscriminated group's
    /// columns while the interface declared them.
    #[test]
    fn zod_keeps_columns_from_join_groups_that_carry_no_discriminant() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("bio", "string", true, Some("p"), true),
            column("website", "string", true, Some("p"), true),
            column("label", "string", true, Some("b"), false),
        ];

        let out = generate_zod_union_row_struct("R", "Q", &columns);

        assert!(out.contains("bio:"), "{out}");
        assert!(out.contains("website:"), "{out}");
        assert!(out.contains("label:"), "{out}");
    }

    #[test]
    fn escape_ts_template_literal_escapes_backtick_dollar_brace_and_backslash() {
        let out = escape_ts_template_literal(r"a`b${c}d\e");
        assert_eq!(out, r"a\`b\${c}d\\e");
    }

    /// Backslash must be escaped first: if `${` or `` ` `` were escaped
    /// before backslash, the backslash this pass inserts ahead of them
    /// would itself get doubled by the backslash pass, corrupting the
    /// escape sequence.
    #[test]
    fn escape_ts_template_literal_does_not_double_escape_inserted_backslashes() {
        let out = escape_ts_template_literal("`${x}");
        // Exactly one backslash ahead of each special character, not two.
        assert_eq!(out, r"\`\${x}");
    }

    #[test]
    fn escape_ts_template_literal_leaves_plain_sql_untouched() {
        let out = escape_ts_template_literal("SELECT id, name FROM users WHERE id = $1");
        assert_eq!(out, "SELECT id, name FROM users WHERE id = $1");
    }

    #[test]
    fn escape_ts_double_quoted_literal_escapes_quote_and_backslash() {
        let out = escape_ts_double_quoted_literal(r#"a"b\c"#);
        assert_eq!(out, r#"a\"b\\c"#);
    }

    #[test]
    fn parse_bool_option_accepts_true_spellings_case_insensitively() {
        for value in ["true", "True", "TRUE", "1", "yes", "Yes", "YES"] {
            assert!(
                parse_bool_option("outer_join_unions", value).unwrap(),
                "expected {value} to parse as true"
            );
        }
    }

    #[test]
    fn parse_bool_option_accepts_false_spellings_case_insensitively() {
        for value in ["false", "False", "FALSE", "0", "no", "No", "NO"] {
            assert!(
                !parse_bool_option("outer_join_unions", value).unwrap(),
                "expected {value} to parse as false"
            );
        }
    }

    /// This must fail before the fix: the old `matches!(value.as_str(), "true" | "1" | "yes")`
    /// silently mapped every one of these to `false` instead of reporting an error.
    #[test]
    fn parse_bool_option_rejects_unrecognized_values_with_an_error_naming_the_option() {
        for value in ["on", "maybe", ""] {
            let err =
                parse_bool_option("outer_join_unions", value).expect_err(&format!("expected '{value}' to be rejected"));
            let message = err.to_string();
            assert!(
                message.contains("outer_join_unions"),
                "error should name the option: {message}"
            );
            assert!(message.contains(value), "error should include the bad value: {message}");
        }
    }

    fn bytes_column(name: &str, lang_type: &str, nullable: bool) -> ResolvedColumn {
        ResolvedColumn {
            name: name.to_string(),
            field_name: name.to_string(),
            lang_type: lang_type.to_string(),
            full_type: if nullable {
                format!("{lang_type} | null")
            } else {
                lang_type.to_string()
            },
            neutral_type: "bytes".to_string(),
            sql_type: "bytea".to_string(),
            nullable,
            join_group: None,
            nullable_before_join: false,
        }
    }

    /// A binary column's runtime type is backend-specific. Hardcoding `Buffer`
    /// mis-validates on the backends whose driver yields `Uint8Array`, and is
    /// unresolvable in a browser where `Buffer` does not exist.
    #[test]
    fn test_zod_bytes_schema_follows_the_backend_runtime_type() {
        let buffer_schema =
            generate_zod_row_struct("GetBlobRow", "GetBlob", &[bytes_column("payload", "Buffer", false)]);
        assert!(
            buffer_schema.contains("z.instanceof(Buffer)"),
            "Buffer backends keep Buffer; got:\n{buffer_schema}"
        );

        let uint8_schema =
            generate_zod_row_struct("GetBlobRow", "GetBlob", &[bytes_column("payload", "Uint8Array", false)]);
        assert!(
            uint8_schema.contains("z.instanceof(Uint8Array)"),
            "Uint8Array backends must not emit Buffer; got:\n{uint8_schema}"
        );
        assert!(
            !uint8_schema.contains("Buffer"),
            "Uint8Array backends must not reference Buffer at all; got:\n{uint8_schema}"
        );
    }

    #[test]
    fn test_zod_bytes_schema_preserves_nullability() {
        let schema = generate_zod_row_struct("GetBlobRow", "GetBlob", &[bytes_column("payload", "Uint8Array", true)]);
        assert!(
            schema.contains("z.instanceof(Uint8Array).nullable()"),
            "nullable bytes must stay nullable; got:\n{schema}"
        );
    }

    /// The grouped Zod emitter used to call `neutral_to_zod` directly, which
    /// has no column context — so an enum column degraded to a bare
    /// `z.string()` and a bytes column always claimed `Buffer`.
    #[test]
    fn test_grouped_zod_structs_use_column_aware_schemas() {
        let mut enum_col = column("status", "UserStatus", false, None, false);
        enum_col.neutral_type = "enum::user_status".to_string();

        let grouped = generate_zod_grouped_structs(
            "GetUsersWithOrdersChildRow",
            "GetUsersWithOrdersRow",
            &[bytes_column("avatar", "Uint8Array", false)],
            &[enum_col],
        );

        assert!(
            grouped.contains("UserStatusSchema"),
            "grouped enum must use its enum schema, not z.string(); got:\n{grouped}"
        );
        assert!(
            grouped.contains("z.instanceof(Uint8Array)"),
            "grouped bytes must follow the backend type; got:\n{grouped}"
        );
    }

    #[test]
    fn test_ts_field_case_from_option_accepts_known_values() {
        assert_eq!(TsFieldCase::from_option("snake_case").unwrap(), TsFieldCase::Snake);
        assert_eq!(TsFieldCase::from_option("camelCase").unwrap(), TsFieldCase::Camel);
    }

    #[test]
    fn test_ts_field_case_from_option_rejects_unknown_values() {
        let err = TsFieldCase::from_option("PascalCase").expect_err("PascalCase is not a valid field_case");
        assert!(err.to_string().contains("field_case"), "{err}");
    }

    #[test]
    fn test_ts_field_case_default_is_snake() {
        assert_eq!(TsFieldCase::default(), TsFieldCase::Snake);
    }

    #[test]
    fn test_generate_ts_row_object_literal_matches_grouped_fold_field_lines() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("name", "string", false, None, false),
        ];
        let out = generate_ts_row_object_literal(&columns, "\t\t\t\t", TsRowShape::Flat, |name, ty| {
            format!("row.{name} as {ty}")
        });
        assert_eq!(
            out,
            "\t\t\t\tid: row.id as number,\n\t\t\t\tname: row.name as string,\n"
        );
    }

    #[test]
    fn test_generate_ts_row_object_literal_empty_columns_is_empty() {
        let out = generate_ts_row_object_literal(&[], "\t", TsRowShape::Flat, |name, ty| format!("row.{name} as {ty}"));
        assert_eq!(out, "");
    }

    /// This must fail before the fix: the remap always cast through
    /// `full_type`, but `generate_ts_union_row_struct` declares a join
    /// discriminant as `lang_type` in the matched variant and as literal
    /// `null` in the unmatched one. `string | null` is assignable to neither
    /// `{ total: string }` nor `{ total: null }`, so
    /// `field_case = "camelCase"` combined with `outer_join_unions = true`
    /// emitted a row object that does not type-check (TS2322).
    #[test]
    fn test_generate_ts_row_object_literal_union_shape_casts_discriminant_to_matched_type() {
        let columns = user_orders_columns();
        let out = generate_ts_row_object_literal(&columns, "\t", TsRowShape::Union, |name, ty| {
            format!("row['{name}'] as {ty}")
        });
        assert_eq!(
            out,
            "\tid: row['id'] as number,\n\
             \tname: row['name'] as string,\n\
             \ttotal: row['total'] as string,\n\
             \tnotes: row['notes'] as string | null,\n"
        );
    }

    /// The union shape narrows the discriminant only; `Flat` must keep the
    /// nullable cast, since a plain interface declares it as `T | null`.
    #[test]
    fn test_generate_ts_row_object_literal_flat_shape_keeps_full_type() {
        let columns = user_orders_columns();
        let out = generate_ts_row_object_literal(&columns, "\t", TsRowShape::Flat, |name, ty| {
            format!("row['{name}'] as {ty}")
        });
        assert!(
            out.contains("total: row['total'] as string | null,"),
            "flat rows declare the discriminant nullable; got:\n{out}"
        );
    }

    #[test]
    fn test_ts_row_shape_from_outer_join_unions() {
        assert_eq!(TsRowShape::from_outer_join_unions(false), TsRowShape::Flat);
        assert_eq!(TsRowShape::from_outer_join_unions(true), TsRowShape::Union);
        assert_eq!(TsRowShape::default(), TsRowShape::Flat);
    }

    /// A union row type whose group has no discriminant collapses back to a
    /// plain interface (see `discriminated_join_groups`), and the cast has
    /// to collapse with it -- a column that was already nullable in the
    /// schema is declared `T | null` in the matched variant too.
    #[test]
    fn test_ts_row_shape_union_keeps_full_type_for_non_discriminants() {
        let columns = user_orders_columns();
        let notes = columns.iter().find(|c| c.name == "notes").unwrap();
        assert_eq!(TsRowShape::Union.cast_type(notes), "string | null");
        let name = columns.iter().find(|c| c.name == "name").unwrap();
        assert_eq!(TsRowShape::Union.cast_type(name), "string");
    }

    #[test]
    fn test_generate_ts_one_row_remap_opt_null_checks_then_builds_fields() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("name", "string", false, None, false),
        ];
        let out = generate_ts_one_row_remap(&columns, TsRowShape::Flat, &QueryCommand::Opt, "GetUser", |name, ty| {
            format!("row['{name}'] as {ty}")
        });
        assert_eq!(
            out,
            "\tif (!row) {\n\
             \t\treturn null;\n\
             \t}\n\
             \treturn {\n\
             \t\tid: row['id'] as number,\n\
             \t\tname: row['name'] as string,\n\
             \t};\n"
        );
    }

    /// #192: `:one` must throw, not return `null`, when no row matched --
    /// silently returning `null` is the exact defect this test guards
    /// against regressing.
    #[test]
    fn test_generate_ts_one_row_remap_one_throws_instead_of_returning_null() {
        let columns = vec![column("id", "number", false, None, false)];
        let out = generate_ts_one_row_remap(&columns, TsRowShape::Flat, &QueryCommand::One, "GetUser", |name, ty| {
            format!("row['{name}'] as {ty}")
        });
        assert_eq!(
            out,
            "\tif (!row) {\n\
             \t\tthrow new Error(\"no row found for query: GetUser\");\n\
             \t}\n\
             \treturn {\n\
             \t\tid: row['id'] as number,\n\
             \t};\n"
        );
        assert!(!out.contains("return null"), "{out}");
    }

    #[test]
    fn test_ts_row_not_found_throw_escapes_the_query_name() {
        assert_eq!(
            ts_row_not_found_throw("weird\"name"),
            "throw new Error(\"no row found for query: weird\\\"name\");"
        );
    }

    #[test]
    fn test_generate_ts_many_row_remap_maps_each_row() {
        let columns = vec![column("id", "number", false, None, false)];
        let out = generate_ts_many_row_remap(&columns, TsRowShape::Flat, |name, ty| format!("row['{name}'] as {ty}"));
        assert_eq!(
            out,
            "\treturn rows.map((row) => ({\n\
             \t\tid: row['id'] as number,\n\
             \t}));\n"
        );
    }

    /// Structural guard for #81's critical correctness rule: a nullable
    /// column must be emitted as `{T | null}`, never as JSDoc's
    /// bracket-optional (`[name]`) or `?`-suffix property syntax (which mean
    /// the property may be *absent*, not that it may be `null`).
    ///
    /// This does not check the emitted *text* (that is
    /// [`test_js_property_line_never_emits_bracket_or_question_mark_syntax`]
    /// below) -- it greps [`js_property_line`]'s own *source*, between the
    /// `jsdoc-property-line-start`/`-end` markers, for the literal
    /// characters `[`, `]`, and `?`. Since none of those characters appear
    /// anywhere in that function's body, there is no `if col.nullable { ...
    /// } else { ... }` (or any other conditional) capable of selecting a
    /// bracket/question-mark form in the first place -- not just that the
    /// current logic happens not to produce one. A future edit that tried to
    /// reintroduce optional-property syntax would have to touch those
    /// characters and would fail this test before it could reach a `cargo
    /// test` run that exercises the output.
    #[test]
    fn test_js_property_line_source_cannot_emit_optional_syntax_into_the_name_position() {
        let source = include_str!("typescript_common.rs");
        let start = source
            .find("// jsdoc-property-line-start")
            .expect("marker comment must exist in this file");
        let end = source
            .find("// jsdoc-property-line-end")
            .expect("marker comment must exist in this file");
        let body = &source[start..end];

        assert!(
            !body.contains('['),
            "js_property_line's source must contain no '[' -- a bracket-optional code path \
             would need one: {body}"
        );
        assert!(
            !body.contains(']'),
            "js_property_line's source must contain no ']' -- a bracket-optional code path \
             would need one: {body}"
        );
        assert!(
            !body.contains('?'),
            "js_property_line's source must contain no '?' -- a question-mark-optional code \
             path would need one: {body}"
        );
    }

    /// Runtime companion to the source-level guard above: for both a
    /// nullable and a non-nullable column, the emitted `@property` line
    /// carries the type only -- never a bracket or `?` around the name.
    #[test]
    fn test_js_property_line_never_emits_bracket_or_question_mark_syntax() {
        let nullable = column("bio", "string", true, None, false);
        let non_nullable = column("id", "number", false, None, false);

        let nullable_line = js_property_line(&nullable);
        let non_nullable_line = js_property_line(&non_nullable);

        assert_eq!(nullable_line, " * @property {string | null} bio");
        assert_eq!(non_nullable_line, " * @property {number} id");
        assert!(!nullable_line.contains('['), "{nullable_line}");
        assert!(!nullable_line.contains(']'), "{nullable_line}");
        assert!(!nullable_line.contains('?'), "{nullable_line}");
    }

    #[test]
    fn test_generate_js_typedef_row_struct_matches_property_lines() {
        let columns = vec![
            column("id", "number", false, None, false),
            column("bio", "string", true, None, false),
        ];
        let out = generate_js_typedef_row_struct("GetUserRow", "GetUser", &columns);

        assert!(out.starts_with("/**\n"), "{out}");
        assert!(out.contains(" * Row type for GetUser queries.\n"), "{out}");
        assert!(out.contains(" * @typedef {object} GetUserRow\n"), "{out}");
        assert!(out.contains(" * @property {number} id\n"), "{out}");
        assert!(out.contains(" * @property {string | null} bio\n"), "{out}");
        assert!(out.ends_with(" */"), "{out}");
    }

    #[test]
    fn test_js_type_cast_wraps_expr_in_a_jsdoc_type_comment() {
        assert_eq!(
            js_type_cast("GetUserRow | undefined", "stmt.get()"),
            "/** @type {GetUserRow | undefined} */ (stmt.get())"
        );
    }

    #[test]
    fn test_generate_jsdoc_fn_header_renders_params_and_return() {
        let out = generate_jsdoc_fn_header(
            "Fetch a single row.",
            &[
                ("client".to_string(), "import(\"pg\").PoolClient".to_string()),
                ("id".to_string(), "number".to_string()),
            ],
            "Promise<Row | null>",
        );

        assert_eq!(
            out,
            "/**\n * Fetch a single row.\n * @param {import(\"pg\").PoolClient} client\n * @param {number} id\n \
             * @returns {Promise<Row | null>}\n */"
        );
    }

    #[test]
    fn test_js_fn_signature_line_has_no_type_annotations() {
        let sig_params = vec![
            ("client".to_string(), "import(\"pg\").PoolClient".to_string()),
            ("id".to_string(), "number".to_string()),
        ];
        assert_eq!(
            js_fn_signature_line(true, "getUserById", &sig_params),
            "export async function getUserById(client, id) {"
        );
        assert_eq!(
            js_fn_signature_line(false, "getUserById", &sig_params),
            "export function getUserById(client, id) {"
        );
    }

    /// The three option parsers reach the same user input by a different
    /// route, so they are pinned together rather than one standing in for all.
    #[test]
    fn should_classify_bad_option_values_as_invalid_config() {
        assert_eq!(
            TsRowType::from_option("zodd").expect_err("unknown row_type").code,
            ErrorCode::InvalidConfig
        );
        assert_eq!(
            TsFieldCase::from_option("CamelCase")
                .expect_err("unknown field_case")
                .code,
            ErrorCode::InvalidConfig
        );
        assert_eq!(
            parse_bool_option("structs_only", "maybe")
                .expect_err("non-boolean bool option")
                .code,
            ErrorCode::InvalidConfig
        );
    }
}