vize_atelier_sfc 0.2.0

Atelier SFC - The Single File Component workshop for Vize
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
//! Inline mode script compilation.
//!
//! This module handles compilation of script setup with inline template mode,
//! where the render function is inlined into the setup function.

use crate::script::{transform_destructured_props, ScriptCompileContext};
use crate::types::SfcError;

use super::function_mode::{contains_top_level_await, dedupe_imports};
use super::macros::{
    is_macro_call_line, is_multiline_macro_start, is_paren_macro_start, is_props_destructure_line,
};
use super::props::{
    extract_emit_names_from_type, extract_prop_types_from_type, extract_with_defaults_defaults,
};
use super::typescript::transform_typescript_to_js;
use super::{ScriptCompileResult, TemplateParts};

/// Compile script setup with inline template (Vue's inline template mode)
pub fn compile_script_setup_inline(
    content: &str,
    component_name: &str,
    is_ts: bool,
    source_is_ts: bool,
    template: TemplateParts<'_>,
    normal_script_content: Option<&str>,
) -> Result<ScriptCompileResult, SfcError> {
    let mut ctx = ScriptCompileContext::new(content);
    ctx.analyze();

    // Use arena-allocated Vec for better performance
    let bump = vize_carton::Bump::new();
    let mut output: vize_carton::Vec<u8> = vize_carton::Vec::with_capacity_in(4096, &bump);

    // Store normal script content to add AFTER TypeScript transformation
    // This preserves type definitions that would otherwise be stripped
    let preserved_normal_script = normal_script_content
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());

    // Check if we need mergeDefaults import (props destructure with defaults)
    let has_props_destructure = ctx.macros.props_destructure.is_some();
    let needs_merge_defaults = has_props_destructure
        && ctx
            .macros
            .props_destructure
            .as_ref()
            .map(|d| d.bindings.values().any(|b| b.default.is_some()))
            .unwrap_or(false);

    // Check if defineModel was used
    let has_define_model = !ctx.macros.define_models.is_empty();

    // mergeDefaults import comes first if needed
    if needs_merge_defaults {
        output.extend_from_slice(b"import { mergeDefaults as _mergeDefaults } from 'vue'\n");
    }

    // useModel import if defineModel was used
    if has_define_model {
        output.extend_from_slice(b"import { useModel as _useModel } from 'vue'\n");
    }

    // Check if we need PropType import (type-based defineProps in TS mode)
    let needs_prop_type = is_ts
        && ctx
            .macros
            .define_props
            .as_ref()
            .is_some_and(|p| p.type_args.is_some());

    // defineComponent import for TypeScript
    if is_ts {
        if needs_prop_type {
            output.extend_from_slice(
                b"import { defineComponent as _defineComponent, type PropType } from 'vue'\n",
            );
        } else {
            output
                .extend_from_slice(b"import { defineComponent as _defineComponent } from 'vue'\n");
        }
    }

    // Template imports (Vue helpers)
    if !template.imports.is_empty() {
        output.extend_from_slice(template.imports.as_bytes());
        // Blank line after template imports
        output.push(b'\n');
    }

    // Extract user imports
    let mut user_imports = Vec::new();
    let mut setup_lines = Vec::new();
    // Collect TypeScript interfaces/types to preserve at module level (before export default)
    let mut ts_declarations: Vec<String> = Vec::new();

    // Parse script content - extract imports and setup code
    let mut in_import = false;
    let mut import_buffer = String::new();
    let mut in_destructure = false;
    let mut destructure_buffer = String::new();
    let mut brace_depth: i32 = 0;
    let mut in_macro_call = false;
    let mut macro_angle_depth: i32 = 0;
    let mut in_paren_macro_call = false;
    let mut paren_macro_depth: i32 = 0;
    let mut waiting_for_macro_close = false;
    // Track remaining parentheses after destructure's function call: `const { x } = func(\n...\n)`
    let mut in_destructure_call = false;
    let mut destructure_call_paren_depth: i32 = 0;
    // Track multiline object literals: const xxx = { ... }
    let mut in_object_literal = false;
    let mut object_literal_buffer = String::new();
    let mut object_literal_brace_depth: i32 = 0;
    // Track TypeScript-only declarations (interface, type) to skip them
    let mut in_ts_interface = false;
    let mut ts_interface_brace_depth: i32 = 0;
    let mut in_ts_type = false;
    let mut ts_type_depth: i32 = 0; // Track angle brackets and parens for complex types
                                    // Track template literals (backtick strings) to skip content inside them
    let mut in_template_literal = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Handle multi-line macro calls
        if in_macro_call {
            // Count angle brackets but ignore => (arrow functions)
            let line_no_arrow = trimmed.replace("=>", "");
            macro_angle_depth += line_no_arrow.matches('<').count() as i32;
            macro_angle_depth -= line_no_arrow.matches('>').count() as i32;
            let trimmed_no_semi_m = trimmed.trim_end_matches(';');
            if macro_angle_depth <= 0
                && (trimmed_no_semi_m.contains("()") || trimmed_no_semi_m.ends_with(')'))
            {
                in_macro_call = false;
            }
            continue;
        }

        // Handle remaining parentheses from destructure's function call
        // e.g., `const { x } = someFunc(\n  arg1,\n  arg2\n)`
        if in_destructure_call {
            destructure_call_paren_depth += trimmed.matches('(').count() as i32;
            destructure_call_paren_depth -= trimmed.matches(')').count() as i32;
            if destructure_call_paren_depth <= 0 {
                in_destructure_call = false;
            }
            continue;
        }

        if in_paren_macro_call {
            paren_macro_depth += trimmed.matches('(').count() as i32;
            paren_macro_depth -= trimmed.matches(')').count() as i32;
            if paren_macro_depth <= 0 {
                in_paren_macro_call = false;
            }
            continue;
        }

        if waiting_for_macro_close {
            destructure_buffer.push_str(line);
            destructure_buffer.push('\n');
            // Track angle brackets for type args (ignore => arrow functions)
            let line_no_arrow = trimmed.replace("=>", "");
            macro_angle_depth += line_no_arrow.matches('<').count() as i32;
            macro_angle_depth -= line_no_arrow.matches('>').count() as i32;
            let trimmed_no_semi_w = trimmed.trim_end_matches(';');
            if macro_angle_depth <= 0
                && (trimmed_no_semi_w.ends_with("()") || trimmed_no_semi_w.ends_with(')'))
            {
                waiting_for_macro_close = false;
                destructure_buffer.clear();
            }
            continue;
        }

        if in_destructure {
            destructure_buffer.push_str(line);
            destructure_buffer.push('\n');
            // Track both braces and angle brackets for type args (ignore => arrow functions)
            let line_no_arrow = trimmed.replace("=>", "");
            brace_depth += trimmed.matches('{').count() as i32;
            brace_depth -= trimmed.matches('}').count() as i32;
            macro_angle_depth += line_no_arrow.matches('<').count() as i32;
            macro_angle_depth -= line_no_arrow.matches('>').count() as i32;
            // Only consider closed when BOTH braces and angle brackets are balanced
            // and we have the closing parentheses
            if brace_depth <= 0 && macro_angle_depth <= 0 {
                let is_props_macro = destructure_buffer.contains("defineProps")
                    || destructure_buffer.contains("withDefaults");
                let trimmed_no_semi = trimmed.trim_end_matches(';');
                if is_props_macro
                    && !trimmed_no_semi.ends_with("()")
                    && !trimmed_no_semi.ends_with(')')
                {
                    waiting_for_macro_close = true;
                    continue;
                }
                in_destructure = false;
                if !is_props_macro {
                    // Not a props destructure - add to setup lines
                    for buf_line in destructure_buffer.lines() {
                        setup_lines.push(buf_line.to_string());
                    }
                }
                // Check if the destructure's RHS has an unclosed function call:
                // `} = someFunc(\n  arg1,\n)` — paren opens on this line, closes later
                let paren_balance = destructure_buffer.matches('(').count() as i32
                    - destructure_buffer.matches(')').count() as i32;
                if paren_balance > 0 {
                    in_destructure_call = true;
                    destructure_call_paren_depth = paren_balance;
                }
                destructure_buffer.clear();
            }
            continue;
        }

        // Detect macro call starts
        if is_paren_macro_start(trimmed)
            && !trimmed.starts_with("const {")
            && !trimmed.starts_with("let {")
        {
            in_paren_macro_call = true;
            paren_macro_depth =
                trimmed.matches('(').count() as i32 - trimmed.matches(')').count() as i32;
            continue;
        }

        if is_multiline_macro_start(trimmed)
            && !trimmed.starts_with("const {")
            && !trimmed.starts_with("let {")
        {
            in_macro_call = true;
            macro_angle_depth =
                trimmed.matches('<').count() as i32 - trimmed.matches('>').count() as i32;
            continue;
        }

        // Detect destructure start with type args: const { x } = defineProps<{...}>()
        // This pattern has both the destructure closing brace AND type arg opening angle bracket
        if (trimmed.starts_with("const {")
            || trimmed.starts_with("let {")
            || trimmed.starts_with("var {"))
            && (trimmed.contains("defineProps<") || trimmed.contains("withDefaults("))
        {
            // Check if it's complete on a single line (strip trailing semicolons)
            let trimmed_no_semi_d = trimmed.trim_end_matches(';');
            if !trimmed_no_semi_d.ends_with("()") && !trimmed_no_semi_d.ends_with(')') {
                // Multi-line: wait for completion
                in_destructure = true;
                destructure_buffer = line.to_string() + "\n";
                brace_depth =
                    trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
                macro_angle_depth =
                    trimmed.matches('<').count() as i32 - trimmed.matches('>').count() as i32;
                continue;
            } else {
                // Single line, complete - skip it
                continue;
            }
        }

        // Detect destructure where value starts on the next line:
        //   const { x, y } =
        //     defineProps<...>()
        // Braces are balanced on this line but the RHS is on the next line.
        if (trimmed.starts_with("const {")
            || trimmed.starts_with("let {")
            || trimmed.starts_with("var {"))
            && trimmed.contains('}')
            && trimmed.ends_with('=')
        {
            in_destructure = true;
            destructure_buffer = line.to_string() + "\n";
            brace_depth = 0; // braces are balanced on this line
            macro_angle_depth = 0;
            continue;
        }

        // Detect destructure start (without type args)
        if (trimmed.starts_with("const {")
            || trimmed.starts_with("let {")
            || trimmed.starts_with("var {"))
            && !trimmed.contains('}')
        {
            in_destructure = true;
            destructure_buffer = line.to_string() + "\n";
            brace_depth = trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
            macro_angle_depth = 0;
            continue;
        }

        // Skip single-line props destructure
        if is_props_destructure_line(trimmed) {
            continue;
        }

        // Handle multiline object literals: const xxx = { ... }
        if in_object_literal {
            object_literal_buffer.push_str(line);
            object_literal_buffer.push('\n');
            object_literal_brace_depth += trimmed.matches('{').count() as i32;
            object_literal_brace_depth -= trimmed.matches('}').count() as i32;
            if object_literal_brace_depth <= 0 {
                // Object literal is complete, add to setup_lines
                for buf_line in object_literal_buffer.lines() {
                    setup_lines.push(buf_line.to_string());
                }
                in_object_literal = false;
                object_literal_buffer.clear();
            }
            continue;
        }

        // Detect multiline object literal start: const xxx = { or const xxx: Type = {
        if (trimmed.starts_with("const ")
            || trimmed.starts_with("let ")
            || trimmed.starts_with("var "))
            && trimmed.contains('=')
            && trimmed.ends_with('{')
            && !trimmed.contains("defineProps")
            && !trimmed.contains("defineEmits")
            && !trimmed.contains("defineModel")
        {
            in_object_literal = true;
            object_literal_buffer = line.to_string() + "\n";
            object_literal_brace_depth =
                trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
            continue;
        }

        // Track template literals (backtick strings) - count unescaped backticks
        // We need to track this to avoid treating code inside template literals as real imports
        let backtick_count = line
            .chars()
            .fold((0, false), |(count, escaped), c| {
                if escaped {
                    (count, false)
                } else if c == '\\' {
                    (count, true)
                } else if c == '`' {
                    (count + 1, false)
                } else {
                    (count, false)
                }
            })
            .0;

        // Track if we were in template literal before this line
        let was_in_template_literal = in_template_literal;

        // Toggle template literal state for each unescaped backtick
        if backtick_count % 2 == 1 {
            in_template_literal = !in_template_literal;
        }

        // Skip import/macro detection for content inside template literals
        // but still add the content to setup_lines
        if was_in_template_literal {
            // This line is inside (or closes) a template literal
            if !trimmed.is_empty() && !is_macro_call_line(trimmed) {
                setup_lines.push(line.to_string());
            }
            continue;
        }

        // Handle imports (only when NOT inside template literal)
        if trimmed.starts_with("import ") {
            // Handle side-effect imports without semicolons (e.g., import '@/css/reset.scss')
            // These have no 'from' clause and are always single-line
            if !trimmed.contains(" from ") && (trimmed.contains('\'') || trimmed.contains('"')) {
                let mut imp = String::with_capacity(line.len() + 1);
                imp.push_str(line);
                imp.push('\n');
                user_imports.push(imp);
                continue;
            }
            in_import = true;
            import_buffer.clear();
        }

        if in_import {
            import_buffer.push_str(line);
            import_buffer.push('\n');
            if trimmed.ends_with(';') || (trimmed.contains(" from ") && !trimmed.ends_with(',')) {
                user_imports.push(import_buffer.clone());
                in_import = false;
            }
            continue;
        }

        // Handle TypeScript interface declarations (collect for TS output, skip for JS)
        if in_ts_interface {
            if is_ts {
                if let Some(last) = ts_declarations.last_mut() {
                    last.push('\n');
                    last.push_str(line);
                }
            }
            ts_interface_brace_depth += trimmed.matches('{').count() as i32;
            ts_interface_brace_depth -= trimmed.matches('}').count() as i32;
            if ts_interface_brace_depth <= 0 {
                in_ts_interface = false;
            }
            continue;
        }

        // Detect TypeScript interface start
        if trimmed.starts_with("interface ") || trimmed.starts_with("export interface ") {
            in_ts_interface = true;
            ts_interface_brace_depth =
                trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
            if is_ts {
                ts_declarations.push(line.to_string());
            }
            if ts_interface_brace_depth <= 0 {
                in_ts_interface = false;
            }
            continue;
        }

        // Detect TypeScript `declare` statements (e.g., `declare global { }`, `declare module '...' { }`)
        if trimmed.starts_with("declare ") {
            let has_brace = trimmed.contains('{');
            if has_brace {
                let depth =
                    trimmed.matches('{').count() as i32 - trimmed.matches('}').count() as i32;
                if depth > 0 {
                    // Multi-line declare block: reuse the interface brace tracking
                    in_ts_interface = true;
                    ts_interface_brace_depth = depth;
                }
                if is_ts {
                    ts_declarations.push(line.to_string());
                }
            } else {
                // Single-line declare (e.g., `declare const x: number`)
                if is_ts {
                    ts_declarations.push(line.to_string());
                }
            }
            continue;
        }

        // Handle TypeScript type declarations (collect for TS output, skip for JS)
        if in_ts_type {
            if is_ts {
                if let Some(last) = ts_declarations.last_mut() {
                    last.push('\n');
                    last.push_str(line);
                }
            }
            // Track balanced brackets for complex types like: type X = { a: string } | { b: number }
            // Strip `=>` before counting angle brackets to avoid misinterpreting arrow functions
            let line_no_arrow = trimmed.replace("=>", "__");
            ts_type_depth += trimmed.matches('{').count() as i32;
            ts_type_depth -= trimmed.matches('}').count() as i32;
            ts_type_depth += line_no_arrow.matches('<').count() as i32;
            ts_type_depth -= line_no_arrow.matches('>').count() as i32;
            ts_type_depth += trimmed.matches('(').count() as i32;
            ts_type_depth -= trimmed.matches(')').count() as i32;
            // Type declaration ends when balanced and NOT a continuation line
            // A line that starts with | or & is a union/intersection continuation
            let is_union_continuation = trimmed.starts_with('|') || trimmed.starts_with('&');
            // Type declaration ends when:
            // - brackets/parens are balanced (depth <= 0)
            // - line is NOT a continuation (doesn't start with | or &)
            // - line ends with semicolon, OR ends without continuation chars
            if ts_type_depth <= 0
                && !is_union_continuation
                && (trimmed.ends_with(';')
                    || (!trimmed.ends_with('|')
                        && !trimmed.ends_with('&')
                        && !trimmed.ends_with(',')
                        && !trimmed.ends_with('{')))
            {
                in_ts_type = false;
            }
            continue;
        }

        // Detect TypeScript type alias start
        // Guard: ensure the word after `type ` is a valid identifier start (letter, _, {),
        // not an operator like `===`. This avoids misdetecting `type === 'foo'` as a TS type.
        // `{` is also valid: `export type { Foo }` (re-export syntax).
        if (trimmed.starts_with("type ")
            && trimmed[5..]
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '{'))
            || (trimmed.starts_with("export type ")
                && trimmed[12..]
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '{'))
        {
            // Check if it's a single-line type
            let has_equals = trimmed.contains('=');
            if has_equals {
                // Strip `=>` before counting angle brackets (arrow functions are not type delimiters)
                let line_no_arrow = trimmed.replace("=>", "__");
                ts_type_depth = trimmed.matches('{').count() as i32
                    - trimmed.matches('}').count() as i32
                    + line_no_arrow.matches('<').count() as i32
                    - line_no_arrow.matches('>').count() as i32
                    + trimmed.matches('(').count() as i32
                    - trimmed.matches(')').count() as i32;
                // Check if complete on one line
                // A type is NOT complete if:
                // - brackets/parens aren't balanced (depth > 0)
                // - line ends with continuation characters (|, &, ,, {, =)
                if ts_type_depth <= 0
                    && (trimmed.ends_with(';')
                        || (!trimmed.ends_with('|')
                            && !trimmed.ends_with('&')
                            && !trimmed.ends_with(',')
                            && !trimmed.ends_with('{')
                            && !trimmed.ends_with('=')))
                {
                    // Single line type - collect for TS, skip for JS
                    if is_ts {
                        ts_declarations.push(line.to_string());
                    }
                    continue;
                }
                if is_ts {
                    ts_declarations.push(line.to_string());
                }
                in_ts_type = true;
            } else {
                // type without equals (e.g., `type X` on its own line) - rare but handle
                if is_ts {
                    ts_declarations.push(line.to_string());
                }
            }
            continue;
        }

        if !trimmed.is_empty() && !is_macro_call_line(trimmed) {
            // All user code goes to setup_lines
            // Hoisting user-defined consts is problematic without proper AST-based scope tracking
            // Template-generated _hoisted_X consts are handled separately by template.hoisted
            setup_lines.push(line.to_string());
        }
    }

    // Template hoisted consts (e.g., const _hoisted_1 = { class: "..." })
    // Must come BEFORE user imports to match Vue's output order
    if !template.hoisted.is_empty() {
        output.push(b'\n');
        output.extend_from_slice(template.hoisted.as_bytes());
    }

    // User imports (after hoisted consts) - deduplicate to avoid "already declared" errors
    let deduped_imports = dedupe_imports(&user_imports);
    for import in &deduped_imports {
        output.extend_from_slice(import.as_bytes());
    }

    // Output TypeScript declarations (interfaces, types) after user imports, before export default
    if !ts_declarations.is_empty() {
        output.push(b'\n');
        for decl in &ts_declarations {
            output.extend_from_slice(decl.as_bytes());
            output.push(b'\n');
        }
    }

    // Normal script content goes AFTER imports/hoisted, BEFORE component definition
    // This matches Vue's @vue/compiler-sfc output order
    let has_default_export = if let Some(ref normal_script) = preserved_normal_script {
        output.push(b'\n');
        output.extend_from_slice(normal_script.as_bytes());
        output.push(b'\n');
        normal_script.contains("const __default__")
    } else {
        false
    };

    // Collect props and emits definitions into a buffer (output later after hoisted consts)
    let mut props_emits_buf: Vec<u8> = Vec::new();

    // Props definition
    // Extract defaults from withDefaults if present
    let with_defaults_args = ctx
        .macros
        .with_defaults
        .as_ref()
        .map(|wd| extract_with_defaults_defaults(&wd.args));

    // Collect model names from defineModel calls (needed before props)
    let model_infos: Vec<(String, String, Option<String>)> = ctx
        .macros
        .define_models
        .iter()
        .map(|m| {
            let model_name = if m.args.trim().is_empty() {
                "modelValue".to_string()
            } else {
                let args = m.args.trim();
                if args.starts_with('\'') || args.starts_with('"') {
                    args.trim_matches(|c| c == '\'' || c == '"')
                        .split(',')
                        .next()
                        .unwrap_or("modelValue")
                        .trim_matches(|c| c == '\'' || c == '"')
                        .to_string()
                } else {
                    "modelValue".to_string()
                }
            };
            let binding_name = m.binding_name.clone().unwrap_or_else(|| model_name.clone());
            let options = if m.args.trim().is_empty() {
                None
            } else {
                let args = m.args.trim();
                if args.starts_with('{') {
                    Some(args.to_string())
                } else if args.contains(',') {
                    args.split_once(',')
                        .map(|(_, opts)| opts.trim().to_string())
                } else {
                    None
                }
            };
            (model_name, binding_name, options)
        })
        .collect();

    if let Some(ref props_macro) = ctx.macros.define_props {
        if let Some(ref type_args) = props_macro.type_args {
            // Resolve type references (interface/type alias names) to their definitions
            let resolved_type_args =
                resolve_type_args(type_args, &ctx.interfaces, &ctx.type_aliases);
            let prop_types = extract_prop_types_from_type(&resolved_type_args);
            if !prop_types.is_empty() || !model_infos.is_empty() {
                props_emits_buf.extend_from_slice(b"  props: {\n");
                let total_items = prop_types.len() + model_infos.len();
                let mut item_idx = 0;
                for (name, prop_type) in &prop_types {
                    item_idx += 1;
                    props_emits_buf.extend_from_slice(b"    ");
                    props_emits_buf.extend_from_slice(name.as_bytes());
                    props_emits_buf.extend_from_slice(b": { type: ");
                    props_emits_buf.extend_from_slice(prop_type.js_type.as_bytes());
                    if needs_prop_type {
                        if let Some(ref ts_type) = prop_type.ts_type {
                            if prop_type.js_type == "null" {
                                props_emits_buf.extend_from_slice(b" as unknown as PropType<");
                            } else {
                                props_emits_buf.extend_from_slice(b" as PropType<");
                            }
                            // Normalize multi-line types to single line
                            let normalized: String =
                                ts_type.split_whitespace().collect::<Vec<_>>().join(" ");
                            props_emits_buf.extend_from_slice(normalized.as_bytes());
                            props_emits_buf.push(b'>');
                        }
                    }
                    props_emits_buf.extend_from_slice(b", required: ");
                    props_emits_buf.extend_from_slice(if prop_type.optional {
                        b"false"
                    } else {
                        b"true"
                    });
                    let mut has_default = false;
                    if let Some(ref defaults) = with_defaults_args {
                        if let Some(default_val) = defaults.get(name.as_str()) {
                            props_emits_buf.extend_from_slice(b", default: ");
                            props_emits_buf.extend_from_slice(default_val.as_bytes());
                            has_default = true;
                        }
                    }
                    if !has_default {
                        if let Some(ref destructure) = ctx.macros.props_destructure {
                            if let Some(binding) = destructure.bindings.get(name.as_str()) {
                                if let Some(ref default_val) = binding.default {
                                    props_emits_buf.extend_from_slice(b", default: ");
                                    props_emits_buf.extend_from_slice(default_val.as_bytes());
                                }
                            }
                        }
                    }
                    props_emits_buf.extend_from_slice(b" }");
                    if item_idx < total_items {
                        props_emits_buf.push(b',');
                    }
                    props_emits_buf.push(b'\n');
                }
                for (model_name, _, options) in &model_infos {
                    props_emits_buf.extend_from_slice(b"    \"");
                    props_emits_buf.extend_from_slice(model_name.as_bytes());
                    props_emits_buf.extend_from_slice(b"\": ");
                    if let Some(opts) = options {
                        props_emits_buf.extend_from_slice(opts.as_bytes());
                    } else {
                        props_emits_buf.extend_from_slice(b"{}");
                    }
                    props_emits_buf.extend_from_slice(b",\n");
                }
                // Remove trailing comma from last prop
                if props_emits_buf.ends_with(b",\n") {
                    let len = props_emits_buf.len();
                    props_emits_buf[len - 2] = b'\n';
                    props_emits_buf.truncate(len - 1);
                }
                props_emits_buf.extend_from_slice(b"  },\n");
            }
        } else if !props_macro.args.is_empty() {
            if needs_merge_defaults {
                let destructure = ctx.macros.props_destructure.as_ref().unwrap();
                props_emits_buf.extend_from_slice(b"  props: /*@__PURE__*/_mergeDefaults(");
                props_emits_buf.extend_from_slice(props_macro.args.as_bytes());
                props_emits_buf.extend_from_slice(b", {\n");
                let defaults: Vec<_> = destructure
                    .bindings
                    .iter()
                    .filter_map(|(k, b)| b.default.as_ref().map(|d| (k.as_str(), d.as_str())))
                    .collect();
                for (i, (key, default_val)) in defaults.iter().enumerate() {
                    props_emits_buf.extend_from_slice(b"  ");
                    props_emits_buf.extend_from_slice(key.as_bytes());
                    props_emits_buf.extend_from_slice(b": ");
                    props_emits_buf.extend_from_slice(default_val.as_bytes());
                    if i < defaults.len() - 1 {
                        props_emits_buf.push(b',');
                    }
                    props_emits_buf.push(b'\n');
                }
                props_emits_buf.extend_from_slice(b"}),\n");
            } else {
                props_emits_buf.extend_from_slice(b"  props: ");
                props_emits_buf.extend_from_slice(props_macro.args.as_bytes());
                props_emits_buf.extend_from_slice(b",\n");
            }
        }
    }

    if !model_infos.is_empty() && ctx.macros.define_props.is_none() {
        props_emits_buf.extend_from_slice(b"  props: {\n");
        for (model_name, _binding_name, options) in &model_infos {
            // Model value prop
            props_emits_buf.extend_from_slice(b"    \"");
            props_emits_buf.extend_from_slice(model_name.as_bytes());
            props_emits_buf.extend_from_slice(b"\": ");
            if let Some(opts) = options {
                props_emits_buf.extend_from_slice(opts.as_bytes());
            } else {
                props_emits_buf.extend_from_slice(b"{}");
            }
            props_emits_buf.extend_from_slice(b",\n");
            // Model modifiers prop: "modelModifiers" for default, "<name>Modifiers" for named
            props_emits_buf.extend_from_slice(b"    \"");
            if model_name == "modelValue" {
                props_emits_buf.extend_from_slice(b"modelModifiers");
            } else {
                props_emits_buf.extend_from_slice(model_name.as_bytes());
                props_emits_buf.extend_from_slice(b"Modifiers");
            }
            props_emits_buf.extend_from_slice(b"\": {},\n");
        }
        // Remove trailing comma from last prop
        if props_emits_buf.ends_with(b",\n") {
            let len = props_emits_buf.len();
            props_emits_buf[len - 2] = b'\n';
            props_emits_buf.truncate(len - 1);
        }
        props_emits_buf.extend_from_slice(b"  },\n");
    }

    // Emits definition - combine defineEmits and defineModel emits
    let mut all_emits: Vec<String> = Vec::new();
    if let Some(ref emits_macro) = ctx.macros.define_emits {
        if !emits_macro.args.is_empty() {
            let args = emits_macro.args.trim();
            if args.starts_with('[') && args.ends_with(']') {
                let inner = &args[1..args.len() - 1];
                for part in inner.split(',') {
                    let name = part.trim().trim_matches(|c| c == '\'' || c == '"');
                    if !name.is_empty() {
                        all_emits.push(name.to_string());
                    }
                }
            }
        } else if let Some(ref type_args) = emits_macro.type_args {
            let emit_names = extract_emit_names_from_type(type_args);
            all_emits.extend(emit_names);
        }
    }
    for (model_name, _, _) in &model_infos {
        let mut name = String::with_capacity(7 + model_name.len());
        name.push_str("update:");
        name.push_str(model_name);
        all_emits.push(name);
    }
    if !all_emits.is_empty() {
        props_emits_buf.extend_from_slice(b"  emits: [");
        for (i, name) in all_emits.iter().enumerate() {
            if i > 0 {
                props_emits_buf.extend_from_slice(b", ");
            }
            props_emits_buf.push(b'"');
            props_emits_buf.extend_from_slice(name.as_bytes());
            props_emits_buf.push(b'"');
        }
        props_emits_buf.extend_from_slice(b"],\n");
    }

    // Setup code body - transform props destructure references and separate hoisted/setup code
    let setup_code = setup_lines.join("\n");
    let transformed_setup = if let Some(ref destructure) = ctx.macros.props_destructure {
        transform_destructured_props(&setup_code, destructure)
    } else {
        setup_code
    };

    // Separate hoisted consts (literal consts that can be module-level) from setup code
    let mut hoisted_lines: Vec<String> = Vec::new();
    let mut setup_body_lines: Vec<String> = Vec::new();
    let mut in_multiline_value = false;
    for line in transformed_setup.lines() {
        let trimmed = line.trim();
        // Track multi-line template literals / strings - don't hoist individual lines
        if in_multiline_value {
            setup_body_lines.push(line.to_string());
            // Count unescaped backticks to detect end of template literal
            let backticks = trimmed
                .chars()
                .fold((0usize, false), |(count, escaped), c| {
                    if escaped {
                        (count, false)
                    } else if c == '\\' {
                        (count, true)
                    } else if c == '`' {
                        (count + 1, false)
                    } else {
                        (count, false)
                    }
                })
                .0;
            if backticks % 2 == 1 {
                in_multiline_value = false;
            }
            continue;
        }
        // Check if this is a literal const that should be hoisted
        if trimmed.starts_with("const ") && !trimmed.starts_with("const {") {
            // Check for multi-line template literal (unclosed backtick)
            if let Some(eq_pos) = trimmed.find('=') {
                let value_part = trimmed[eq_pos + 1..].trim();
                let backticks = value_part
                    .chars()
                    .fold((0usize, false), |(count, escaped), c| {
                        if escaped {
                            (count, false)
                        } else if c == '\\' {
                            (count, true)
                        } else if c == '`' {
                            (count + 1, false)
                        } else {
                            (count, false)
                        }
                    })
                    .0;
                if backticks % 2 == 1 {
                    // Unclosed template literal - don't hoist, mark as multi-line
                    in_multiline_value = true;
                    setup_body_lines.push(line.to_string());
                    continue;
                }
            }
            // Extract variable name and check if it's LiteralConst
            if let Some(name) = extract_const_name(trimmed) {
                if matches!(
                    ctx.bindings.bindings.get(&name),
                    Some(crate::types::BindingType::LiteralConst)
                ) {
                    hoisted_lines.push(line.to_string());
                    continue;
                }
            }
        }
        setup_body_lines.push(line.to_string());
    }

    // Output hoisted literal consts (before export default)
    if !hoisted_lines.is_empty() {
        for line in &hoisted_lines {
            output.extend_from_slice(line.as_bytes());
            output.push(b'\n');
        }
    }

    // Start export default
    output.push(b'\n');
    let has_options = ctx.macros.define_options.is_some();

    // Setup function - include destructured args based on macros used
    let has_emit = ctx.macros.define_emits.is_some();
    let has_emit_binding = ctx
        .macros
        .define_emits
        .as_ref()
        .map(|e| e.binding_name.is_some())
        .unwrap_or(false);
    let has_expose = ctx.macros.define_expose.is_some();

    if has_options {
        // Use Object.assign for defineOptions
        output.extend_from_slice(b"export default /*@__PURE__*/Object.assign(");
        let options_args = ctx.macros.define_options.as_ref().unwrap().args.trim();
        output.extend_from_slice(options_args.as_bytes());
        output.extend_from_slice(b", {\n");
    } else if has_default_export {
        // Normal script has export default that was rewritten to __default__
        // Use Object.assign to merge with setup component
        output.extend_from_slice(b"export default /*@__PURE__*/Object.assign(__default__, {\n");
    } else if is_ts {
        // TypeScript: use _defineComponent with __PURE__ annotation
        output.extend_from_slice(b"export default /*@__PURE__*/_defineComponent({\n");
    } else {
        output.extend_from_slice(b"export default {\n");
    }
    output.extend_from_slice(b"  __name: '");
    output.extend_from_slice(component_name.as_bytes());
    output.extend_from_slice(b"',\n");

    // Output props and emits definitions
    output.extend_from_slice(&props_emits_buf);

    // Build setup function signature based on what macros are used
    let mut setup_args = Vec::new();
    if has_expose {
        setup_args.push("expose: __expose");
    }
    if has_emit {
        if has_emit_binding {
            setup_args.push("emit: __emit");
        } else {
            setup_args.push("emit: $emit");
        }
    }

    // Add `: any` type annotation to __props when there are typed props in TypeScript mode
    // but NOT when needs_prop_type (defineComponent infers the type from PropType<T>)
    let has_typed_props = is_ts
        && ctx
            .macros
            .define_props
            .as_ref()
            .is_some_and(|p| p.type_args.is_some() || !p.args.is_empty());
    let props_param = if has_typed_props && !needs_prop_type {
        "__props: any"
    } else {
        "__props"
    };

    // Detect top-level await to generate async setup()
    let setup_code_for_await_check: String = setup_lines.join("\n");
    let is_async = contains_top_level_await(&setup_code_for_await_check, source_is_ts);

    let async_prefix = if is_async {
        "  async setup("
    } else {
        "  setup("
    };
    if setup_args.is_empty() {
        output.extend_from_slice(async_prefix.as_bytes());
        output.extend_from_slice(props_param.as_bytes());
        output.extend_from_slice(b") {\n");
    } else {
        output.extend_from_slice(async_prefix.as_bytes());
        output.extend_from_slice(props_param.as_bytes());
        output.extend_from_slice(b", { ");
        output.extend_from_slice(setup_args.join(", ").as_bytes());
        output.extend_from_slice(b" }) {\n");
    }

    // Always add a blank line after setup signature
    output.push(b'\n');

    // Emit binding: const emit = __emit
    if let Some(ref emits_macro) = ctx.macros.define_emits {
        if let Some(ref binding_name) = emits_macro.binding_name {
            output.extend_from_slice(b"const ");
            output.extend_from_slice(binding_name.as_bytes());
            output.extend_from_slice(b" = __emit\n");
        }
    }

    // Props binding: const props = __props
    if let Some(ref props_macro) = ctx.macros.define_props {
        if let Some(ref binding_name) = props_macro.binding_name {
            output.extend_from_slice(b"const ");
            output.extend_from_slice(binding_name.as_bytes());
            output.extend_from_slice(b" = __props\n");
        }
    }

    // Model bindings: const model = _useModel(__props, 'modelValue')
    if !model_infos.is_empty() {
        for (model_name, binding_name, _) in &model_infos {
            output.extend_from_slice(b"const ");
            output.extend_from_slice(binding_name.as_bytes());
            output.extend_from_slice(b" = _useModel(__props, \"");
            output.extend_from_slice(model_name.as_bytes());
            output.extend_from_slice(b"\")\n");
        }
    }

    // Output setup code lines (non-hoisted)
    for line in &setup_body_lines {
        output.extend_from_slice(line.as_bytes());
        output.push(b'\n');
    }

    // defineExpose: transform to __expose(...)
    if let Some(ref expose_macro) = ctx.macros.define_expose {
        let args = expose_macro.args.trim();
        output.extend_from_slice(b"__expose(");
        output.extend_from_slice(args.as_bytes());
        output.extend_from_slice(b")\n");
    }

    // Inline render function as return (blank line before)
    output.push(b'\n');
    if !template.render_body.is_empty() {
        if is_ts {
            output.extend_from_slice(b"return (_ctx: any,_cache: any) => {\n");
        } else {
            output.extend_from_slice(b"return (_ctx, _cache) => {\n");
        }

        // Output component/directive resolution statements (preamble)
        for line in template.preamble.lines() {
            if !line.trim().is_empty() {
                output.extend_from_slice(b"  ");
                output.extend_from_slice(line.as_bytes());
                output.push(b'\n');
            }
        }
        if !template.preamble.is_empty() {
            output.push(b'\n');
        }

        // Indent the render body properly
        let mut first_line = true;
        for line in template.render_body.lines() {
            if first_line {
                output.extend_from_slice(b"  return ");
                output.extend_from_slice(line.as_bytes());
                first_line = false;
            } else {
                output.push(b'\n');
                // Preserve existing indentation by adding 2 spaces (setup indent)
                if !line.trim().is_empty() {
                    output.extend_from_slice(b"  ");
                }
                output.extend_from_slice(line.as_bytes());
            }
        }
        output.push(b'\n');
        output.extend_from_slice(b"}\n");
    } else {
        // No template (e.g., Musea art files) — return setup bindings as an object
        // so they're accessible for runtime template compilation (compileToFunction).
        use crate::types::BindingType;
        let setup_bindings: Vec<&String> = ctx
            .bindings
            .bindings
            .iter()
            .filter(|(_, bt)| {
                matches!(
                    bt,
                    BindingType::SetupLet
                        | BindingType::SetupMaybeRef
                        | BindingType::SetupRef
                        | BindingType::SetupReactiveConst
                        | BindingType::SetupConst
                        | BindingType::LiteralConst
                )
            })
            .map(|(name, _)| name)
            .collect();
        if !setup_bindings.is_empty() {
            output.extend_from_slice(b"return { ");
            for (i, name) in setup_bindings.iter().enumerate() {
                if i > 0 {
                    output.extend_from_slice(b", ");
                }
                output.extend_from_slice(name.as_bytes());
            }
            output.extend_from_slice(b" }\n");
        }
    }

    output.extend_from_slice(b"}\n");
    output.push(b'\n');
    if has_options || has_default_export || is_ts {
        // Close defineComponent() or Object.assign()
        output.extend_from_slice(b"})\n");
    } else {
        output.extend_from_slice(b"}\n");
    }

    // Convert arena Vec<u8> to String - SAFETY: we only push valid UTF-8
    let output_str = unsafe { String::from_utf8_unchecked(output.into_iter().collect()) };

    // Normal script content is already embedded in the output buffer (after imports, before component def)
    let final_code = if is_ts || !source_is_ts {
        // Preserve output as-is when:
        // - is_ts: output should be TypeScript (preserve for downstream toolchains)
        // - !source_is_ts: source is already JavaScript, no TS to strip
        //   (OXC codegen would reformat the code, breaking carefully crafted template output)
        let mut code = output_str;
        // Add TypeScript annotations to $event parameters in event handlers
        if is_ts {
            code = code.replace("$event => (", "($event: any) => (");
        }
        code
    } else {
        // Source is TypeScript but output should be JavaScript - transform to strip TS syntax
        transform_typescript_to_js(&output_str)
    };

    Ok(ScriptCompileResult {
        code: final_code,
        bindings: Some(ctx.bindings),
    })
}

/// Extract the variable name from a const declaration line.
/// e.g., "const msg = 'hello'" -> Some("msg")
/// e.g., "const count = ref(0)" -> Some("count")
/// e.g., "const { a, b } = obj" -> None (destructure)
fn extract_const_name(line: &str) -> Option<String> {
    let rest = line.trim().strip_prefix("const ")?;
    // Skip destructuring patterns
    if rest.starts_with('{') || rest.starts_with('[') {
        return None;
    }
    // Extract identifier before = or : (type annotation)
    let name_end = rest.find(|c: char| c == '=' || c == ':' || c.is_whitespace())?;
    let name = rest[..name_end].trim();
    if name.is_empty() {
        return None;
    }
    Some(name.to_string())
}

/// Resolve type args that may be interface/type alias references.
/// For `defineProps<Props>()` where `Props` is an interface name, resolves to the interface body.
/// For intersection types like `BaseProps & ExtendedProps`, merges all interface bodies.
/// For inline types like `{ msg: string }`, returns as-is.
fn resolve_type_args(
    type_args: &str,
    interfaces: &vize_carton::FxHashMap<String, String>,
    type_aliases: &vize_carton::FxHashMap<String, String>,
) -> String {
    let content = type_args.trim();

    // Already an inline object type
    if content.starts_with('{') {
        return content.to_string();
    }

    // Handle intersection types: BaseProps & ExtendedProps
    if content.contains('&') {
        let parts: Vec<&str> = content.split('&').collect();
        let mut merged_props = Vec::new();
        for part in parts {
            let resolved = resolve_single_type_ref(part.trim(), interfaces, type_aliases);
            if let Some(body) = resolved {
                let body = body.trim();
                let inner = if body.starts_with('{') && body.ends_with('}') {
                    &body[1..body.len() - 1]
                } else {
                    body
                };
                let trimmed = inner.trim();
                if !trimmed.is_empty() {
                    merged_props.push(trimmed.to_string());
                }
            }
        }
        if !merged_props.is_empty() {
            let joined = merged_props.join("; ");
            let mut result = String::with_capacity(joined.len() + 4);
            result.push_str("{ ");
            result.push_str(&joined);
            result.push_str(" }");
            return result;
        }
        return content.to_string();
    }

    // Single type reference
    if let Some(body) = resolve_single_type_ref(content, interfaces, type_aliases) {
        let body = body.trim();
        if body.starts_with('{') {
            return body.to_string();
        }
        let mut result = String::with_capacity(body.len() + 4);
        result.push_str("{ ");
        result.push_str(body);
        result.push_str(" }");
        return result;
    }

    // Unresolvable - return as-is
    content.to_string()
}

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

    /// Helper to compile a minimal script setup and return the output code
    fn compile_setup(script_content: &str) -> String {
        let empty_template = TemplateParts {
            imports: "",
            hoisted: "",
            preamble: "",
            render_body: "null",
        };
        let result = compile_script_setup_inline(
            script_content,
            "TestComponent",
            false, // is_ts = false (JS output, strip TS)
            true,  // source_is_ts = true
            empty_template,
            None,
        )
        .expect("compilation should succeed");
        result.code
    }

    /// Helper to compile with is_ts=true (TypeScript output)
    fn compile_setup_ts(script_content: &str) -> String {
        let empty_template = TemplateParts {
            imports: "",
            hoisted: "",
            preamble: "",
            render_body: "null",
        };
        let result = compile_script_setup_inline(
            script_content,
            "TestComponent",
            true, // is_ts = true (TS output)
            true, // source_is_ts = true
            empty_template,
            None,
        )
        .expect("compilation should succeed");
        result.code
    }

    #[test]
    fn test_declare_global_not_in_setup_body_ts() {
        let content = r#"
import { ref } from 'vue'

const handleClick = () => {
  console.log('click')
}

declare global {
  interface Window {
    EyeDropper: any
  }
}

const x = ref(0)
"#;
        let output = compile_setup_ts(content);
        let setup_start = output.find("setup(").expect("should have setup function");
        let setup_body = &output[setup_start..];
        assert!(
            !setup_body.contains("declare global"),
            "declare global should NOT be inside setup function body. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_export_type_reexport_stripped() {
        let content = r#"
import { ref } from 'vue'
import type { FilterType } from './types'

export type { FilterType }

const x = ref(0)
"#;
        let output = compile_setup(content);
        let setup_start = output.find("setup(").expect("should have setup");
        let setup_body = &output[setup_start..];
        assert!(
            !setup_body.contains("export type"),
            "export type re-export should not be inside setup body. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_type_as_variable_at_line_start() {
        let content = r#"
import { ref } from 'vue'

const type = ref('material-symbols')
const identifier =
  type === 'material-symbols' ? 'name' : 'ligature'
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("type ==="),
            "`type ===` continuation line should be preserved. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_destructure_with_multiline_function_call() {
        let content = r#"
import { ref, toRef } from 'vue'
import { useSomething } from './useSomething'

const fileInputRef = ref()

const {
  handleSelect,
  handleChange,
} = useSomething(
  fileInputRef,
  {
    onError: (e) => console.log(e),
    onSuccess: () => console.log('ok'),
  },
  toRef(() => 'test'),
)

const other = ref(1)
"#;
        let output = compile_setup(content);
        assert!(
            !output.contains("fileInputRef,"),
            "Function call args should not leak as bare statements. Got:\n{}",
            output
        );
        assert!(
            output.contains("const other = ref(1)"),
            "Code after destructure should be present. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_side_effect_import_without_semicolons() {
        let content = r#"
import { watch } from 'vue'
import '@/css/oldReset.scss'

const { dialogRef } = provideDialog()

watch(
  dialogRef,
  (val) => {
    console.log(val)
  },
  { immediate: true },
)
"#;
        let output = compile_setup_ts(content);
        assert!(
            output.contains("watch("),
            "watch() call should be in setup body. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_export_type_with_arrow_function_member() {
        let content = r#"
import { computed } from 'vue'
import { useRoute } from 'vue-router'

export type MenuSelectorOption = {
  label: string
  onClick: () => void
}

const route = useRoute()
const heading = computed(() => route.name)
"#;
        let output = compile_setup_ts(content);
        assert!(
            output.contains("export type MenuSelectorOption"),
            "export type should be at module level. Got:\n{}",
            output
        );
        let setup_start = output.find("setup(").expect("should have setup");
        let setup_body = &output[setup_start..];
        assert!(
            setup_body.contains("const route = useRoute()"),
            "const route should be inside setup body. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_define_props_with_trailing_semicolon() {
        // Semicolons at end of defineProps() should not prevent macro detection
        let content = r#"
import { ref } from 'vue'

interface Props {
    msg: string
}

const { msg } = defineProps<Props>();
const count = ref(0)
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("props: {"),
            "should generate props declaration even with trailing semicolon. Got:\n{}",
            output
        );
        assert!(
            output.contains("msg:"),
            "should include msg prop. Got:\n{}",
            output
        );
        assert!(
            output.contains("const count = ref(0)"),
            "code after defineProps should be present. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_multiline_define_props_with_trailing_semicolon() {
        // Multi-line defineProps with trailing semicolon on closing line
        let content = r#"
import { ref } from 'vue'

const { label, disabled } = defineProps<{
    label: string
    disabled?: boolean
}>();
const x = ref(1)
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("props: {"),
            "should generate props declaration for multiline defineProps with semicolon. Got:\n{}",
            output
        );
        assert!(
            output.contains("const x = ref(1)"),
            "code after defineProps should be present. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_with_defaults_trailing_semicolon() {
        // withDefaults with trailing semicolon
        let content = r#"
import { ref } from 'vue'

interface Props {
    msg: string
    count?: number
}

const { msg, count } = withDefaults(defineProps<Props>(), {
    count: 0,
});
const x = ref(1)
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("props: {"),
            "should generate props declaration for withDefaults with semicolon. Got:\n{}",
            output
        );
        assert!(
            output.contains("const x = ref(1)"),
            "code after withDefaults should be present. Got:\n{}",
            output
        );
    }

    /// Helper to compile with no template (empty render_body)
    fn compile_setup_no_template(script_content: &str) -> String {
        let empty_template = TemplateParts {
            imports: "",
            hoisted: "",
            preamble: "",
            render_body: "",
        };
        let result = compile_script_setup_inline(
            script_content,
            "TestComponent",
            false,
            true,
            empty_template,
            None,
        )
        .expect("compilation should succeed");
        result.code
    }

    #[test]
    fn test_no_template_returns_setup_bindings() {
        // When there's no template, setup bindings should be returned as an object
        let content = r#"
import { ref, computed } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)
"#;
        let output = compile_setup_no_template(content);
        assert!(
            output.contains("return {"),
            "no-template case should return setup bindings. Got:\n{}",
            output
        );
        assert!(
            output.contains("count"),
            "should return count binding. Got:\n{}",
            output
        );
        assert!(
            output.contains("doubled"),
            "should return doubled binding. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_no_template_returns_imported_bindings() {
        // Imported bindings should also be returned for runtime template compilation
        let content = r#"
import { onMounted } from 'vue'

onMounted(() => {
    console.log('mounted')
})
"#;
        let output = compile_setup_no_template(content);
        assert!(
            output.contains("return {") && output.contains("onMounted"),
            "no-template case should return imported bindings too (for runtime template access). Got:\n{}",
            output
        );
    }

    #[test]
    fn test_export_type_generates_props_declaration() {
        let content = r#"
export type MenuItemProps = {
    id: string
    label: string
    routeName: string
    disabled?: boolean
}
const { label, disabled, routeName } = defineProps<MenuItemProps>()
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("props: {"),
            "should generate props declaration for export type. Got:\n{}",
            output
        );
        assert!(
            output.contains("label:") && output.contains("String"),
            "should include label prop. Got:\n{}",
            output
        );
        assert!(
            output.contains("routeName:") && output.contains("String"),
            "should include routeName prop. Got:\n{}",
            output
        );
        assert!(
            output.contains("disabled:"),
            "should include disabled prop. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_define_props_destructure_value_on_next_line() {
        // Pattern: const { ... } =\n  defineProps<...>()
        // The destructure pattern is complete on line 1, but defineProps is on line 2.
        let content = r#"
import { computed } from 'vue'

interface TimetableCell {
    type: string
    title: string
    startTime: string
}

const { type, title, startTime } =
  defineProps<TimetableCell>();
const accentColor = computed(() => type === 'event' ? 'primary' : 'secondary')
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("props: {"),
            "should generate props declaration for next-line defineProps. Got:\n{}",
            output
        );
        assert!(
            output.contains("type:") && output.contains("String"),
            "should include type prop. Got:\n{}",
            output
        );
        assert!(
            output.contains("title:") && output.contains("String"),
            "should include title prop. Got:\n{}",
            output
        );
        // Verify props destructure references are transformed correctly in setup body
        let setup_start = output.find("setup(").expect("should have setup");
        let setup_body = &output[setup_start..];
        assert!(
            setup_body.contains("__props.type"),
            "destructured prop 'type' should be rewritten to __props.type in setup body. Got:\n{}",
            output
        );
        assert!(
            !setup_body.contains("const { __props."),
            "destructure declaration should NOT appear in setup body. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_define_props_destructure_value_on_next_line_with_semicolon() {
        // Same pattern with trailing semicolon
        let content = r#"
import { ref } from 'vue'

interface Props {
    msg: string
    count: number
}

const { msg, count } =
  defineProps<Props>();
const doubled = ref(count * 2)
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("props: {"),
            "should generate props declaration. Got:\n{}",
            output
        );
        assert!(
            output.contains("msg:") && output.contains("String"),
            "should include msg prop. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_non_props_destructure_value_on_next_line() {
        // Ensure regular (non-defineProps) destructures with value on next line
        // still work correctly
        let content = r#"
import { ref, toRefs } from 'vue'

const state = ref({ x: 1, y: 2 })
const { x, y } =
  toRefs(state.value)
const sum = ref(x.value + y.value)
"#;
        let output = compile_setup(content);
        assert!(
            output.contains("toRefs("),
            "non-props destructure should be preserved in setup body. Got:\n{}",
            output
        );
        assert!(
            output.contains("const sum = ref("),
            "code after destructure should be present. Got:\n{}",
            output
        );
    }
}

/// Resolve a single type name to its definition body.
fn resolve_single_type_ref(
    name: &str,
    interfaces: &vize_carton::FxHashMap<String, String>,
    type_aliases: &vize_carton::FxHashMap<String, String>,
) -> Option<String> {
    // Strip generic params: Props<T> -> Props
    let base_name = if let Some(idx) = name.find('<') {
        name[..idx].trim()
    } else {
        name.trim()
    };

    if let Some(body) = interfaces.get(base_name) {
        return Some(body.clone());
    }
    if let Some(body) = type_aliases.get(base_name) {
        return Some(body.clone());
    }
    None
}