vize_atelier_sfc 0.40.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
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
//! Core inline script compilation logic.
//!
//! Contains the main `compile_script_setup_inline` function that handles
//! compilation of `<script setup>` with inline template mode.

use std::borrow::Cow;

use oxc_allocator::Allocator;
use oxc_ast::ast::{Expression, Statement};
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType};
use vize_carton::{String, ToCompactString};

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

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

const VAPOR_RENDER_ALIAS_BASE: &str = "__vaporRender";
const VAPOR_TEMPLATE_REF_SETTER: &str = "vaporTemplateRefSetter";

/// Compile script setup with inline template (Vue's inline template mode)
#[allow(clippy::too_many_arguments)]
pub fn compile_script_setup_inline(
    content: &str,
    component_name: &str,
    is_ts: bool,
    source_is_ts: bool,
    is_vapor: bool,
    template: TemplateParts<'_>,
    normal_script_content: Option<&str>,
    css_vars: &[Cow<'_, str>],
    scope_id: &str,
    filename: Option<&str>,
) -> Result<ScriptCompileResult, SfcError> {
    let mut ctx = ScriptCompileContext::new(content);

    // Merge type definitions from normal <script> block so that
    // defineProps<TypeRef>() can resolve types defined there.
    if let Some(normal_src) = normal_script_content {
        if !normal_src.is_empty() {
            ctx.collect_types_from(normal_src);
        }
    }
    if let Some(path) = filename {
        ctx.collect_imported_types_from_path(content, path);
        if let Some(normal_src) = normal_script_content {
            if !normal_src.is_empty() {
                ctx.collect_imported_types_from_path(normal_src, path);
            }
        }
    }
    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_compact_string());

    // Check if we need mergeDefaults import (props destructure with defaults)
    // For type-based props (defineProps<{...}>()), defaults are inlined into the prop definitions
    // so mergeDefaults is NOT needed. Only runtime-based props (defineProps([...])) need it.
    let has_props_destructure = ctx.macros.props_destructure.is_some();
    let has_type_based_props = ctx
        .macros
        .define_props
        .as_ref()
        .is_some_and(|p| p.type_args.is_some());
    let needs_merge_defaults = has_props_destructure
        && !has_type_based_props
        && 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();

    // Check if defineSlots was used
    let has_define_slots = ctx.macros.define_slots.is_some();
    let needs_vapor_setup_context = is_vapor && !template.render_fn.is_empty();
    let vapor_render_alias = needs_vapor_setup_context
        .then(|| build_vapor_render_alias(content, normal_script_content, template.render_fn));

    // withAsyncContext import comes first if needed
    let setup_code_for_await = {
        let (_, slines, _) = parse_script_content(content, is_ts);
        slines.join("\n")
    };
    let is_async = contains_top_level_await(&setup_code_for_await, source_is_ts);
    if is_async {
        if is_vapor {
            if needs_vapor_setup_context {
                output.extend_from_slice(
                    b"import { withAsyncContext as _withAsyncContext, defineVaporComponent as _defineVaporComponent, getCurrentInstance as _getCurrentInstance, proxyRefs as _proxyRefs } from 'vue'\n",
                );
            } else {
                output.extend_from_slice(
                    b"import { withAsyncContext as _withAsyncContext, defineVaporComponent as _defineVaporComponent } from 'vue'\n",
                );
            }
        } else if is_ts {
            output.extend_from_slice(
                b"import { withAsyncContext as _withAsyncContext, defineComponent as _defineComponent } from 'vue'\n",
            );
        } else {
            output.extend_from_slice(
                b"import { withAsyncContext as _withAsyncContext } from 'vue'\n",
            );
        }
    }

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

    // useSlots import if defineSlots was used
    if has_define_slots {
        output.extend_from_slice(b"import { useSlots as _useSlots } 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");
    }

    // useCssVars import if style has v-bind()
    let has_css_vars = !css_vars.is_empty();
    if has_css_vars {
        output.extend_from_slice(
            b"import { useCssVars as _useCssVars, unref as _unref } from 'vue'\n",
        );
    }

    // Vue's compiler-sfc does not use PropType in output - props are defined with
    // runtime type constructors (String, Number, etc.) and optional/required flags.
    let needs_prop_type = false;

    // Component helper import (skip if already emitted with withAsyncContext)
    if is_vapor && !is_async {
        if needs_vapor_setup_context {
            output.extend_from_slice(
                b"import { defineVaporComponent as _defineVaporComponent, getCurrentInstance as _getCurrentInstance, proxyRefs as _proxyRefs } from 'vue'\n",
            );
        } else {
            output.extend_from_slice(
                b"import { defineVaporComponent as _defineVaporComponent } from 'vue'\n",
            );
        }
    } else if is_ts && !is_async {
        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 and setup lines from script content
    let (user_imports, setup_lines, ts_declarations) = parse_script_content(content, is_ts);

    // 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());
    }

    if !template.render_fn.is_empty() {
        output.push(b'\n');
        output.extend_from_slice(template.render_fn.as_bytes());
        if let Some(alias) = vapor_render_alias.as_ref() {
            output.extend_from_slice(b"const ");
            output.extend_from_slice(alias.as_bytes());
            output.extend_from_slice(b" = render\n");
        }
    }

    // User imports (after hoisted consts) - deduplicate to avoid "already declared" errors
    let deduped_imports = dedupe_imports(&user_imports, is_ts);
    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 props_emits_buf = build_props_emits(&ctx, is_ts, needs_prop_type, needs_merge_defaults);

    // Collect model names from defineModel calls (needed before props)
    let model_infos: Vec<(String, String, Option<String>)> = collect_model_infos(&ctx);

    // Build additional props/emits from models
    let model_props_emits_buf = build_model_props_emits(
        &ctx,
        &model_infos,
        is_ts,
        needs_prop_type,
        needs_merge_defaults,
    );

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

    // Separate hoisted consts (literal consts that can be module-level) from setup code
    let (hoisted_lines, setup_body_lines) = separate_hoisted_consts(&transformed_setup, &ctx);

    // 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()
        .is_some_and(|emits| emits.binding_name.is_some());
    let has_expose = ctx.macros.define_expose.is_some();

    if has_options {
        // Use Object.assign for defineOptions
        if is_vapor {
            output.extend_from_slice(
                b"export default /*@__PURE__*/_defineVaporComponent(Object.assign(",
            );
        } else {
            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
        if is_vapor {
            output.extend_from_slice(
                b"export default /*@__PURE__*/_defineVaporComponent(Object.assign(__default__, {\n",
            );
        } else {
            output.extend_from_slice(b"export default /*@__PURE__*/Object.assign(__default__, {\n");
        }
    } else if is_vapor {
        output.extend_from_slice(b"export default /*@__PURE__*/_defineVaporComponent({\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);
    output.extend_from_slice(&model_props_emits_buf);
    if !template.render_fn.is_empty() {
        output.extend_from_slice(b"  ");
        output.extend_from_slice(template.render_fn_name.as_bytes());
        output.extend_from_slice(b": ");
        if let Some(alias) = vapor_render_alias.as_ref() {
            output.extend_from_slice(alias.as_bytes());
        } else {
            output.extend_from_slice(template.render_fn_name.as_bytes());
        }
        output.extend_from_slice(b",\n");
    }

    // 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 || needs_vapor_setup_context {
        if has_emit_binding || needs_vapor_setup_context {
            setup_args.push("emit: __emit");
        } else {
            setup_args.push("emit: $emit");
        }
    }
    if needs_vapor_setup_context {
        setup_args.push("attrs: __attrs");
        setup_args.push("slots: __slots");
    }

    // 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"
    };

    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');

    // Add __temp/__restore declarations for async setup
    if is_async {
        if is_ts {
            output.extend_from_slice(b"let __temp: any, __restore: any\n\n");
        } else {
            output.extend_from_slice(b"let __temp, __restore\n\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");
        }
    }

    // Slots binding: const slots = _useSlots()
    if let Some(ref slots_macro) = ctx.macros.define_slots {
        if let Some(ref binding_name) = slots_macro.binding_name {
            output.extend_from_slice(b"const ");
            output.extend_from_slice(binding_name.as_bytes());
            output.extend_from_slice(b" = _useSlots()\n");
        }
    }

    // Output setup code lines (non-hoisted), transforming await expressions for async setup
    if is_async {
        let transformed_async = transform_await_expressions(&setup_body_lines, source_is_ts);
        for line in &transformed_async {
            output.extend_from_slice(line.as_bytes());
            output.push(b'\n');
        }
    } else {
        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");
    }

    // useCssVars injection for v-bind() in <style>
    if has_css_vars {
        output.extend_from_slice(b"_useCssVars((_ctx) => ({\n");
        for (i, var_expr) in css_vars.iter().enumerate() {
            output.extend_from_slice(b"  \"");
            output.extend_from_slice(scope_id.as_bytes());
            output.extend_from_slice(b"-");
            output.extend_from_slice(var_expr.as_bytes());
            output.extend_from_slice(b"\": (_unref(");
            output.extend_from_slice(var_expr.as_bytes());
            output.extend_from_slice(b"))");
            if i < css_vars.len() - 1 {
                output.extend_from_slice(b",");
            }
            output.extend_from_slice(b"\n");
        }
        output.extend_from_slice(b"}))\n");
    }

    // Inline render function as return (blank line before)
    output.push(b'\n');
    emit_render_return(
        &mut output,
        &template,
        is_ts,
        is_vapor,
        vapor_render_alias.as_deref(),
        &ctx,
    );

    output.extend_from_slice(b"}\n");
    output.push(b'\n');
    if is_vapor && (has_options || has_default_export) {
        output.extend_from_slice(b"}))\n");
    } else if has_options || has_default_export || is_ts || is_vapor {
        // 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
    #[allow(clippy::disallowed_types)]
    let output_str: std::string::String =
        unsafe { std::string::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: String = 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 = code.replace("$event => { ", "($event: any) => { ");
        }
        code.into()
    } 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),
    })
}

/// Emit the render function return statement or setup binding return.
fn emit_render_return(
    output: &mut vize_carton::Vec<u8>,
    template: &TemplateParts<'_>,
    is_ts: bool,
    is_vapor: bool,
    vapor_render_alias: Option<&str>,
    ctx: &ScriptCompileContext,
) {
    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');
        }

        if template.render_is_block {
            for line in template.render_body.lines() {
                if line.trim().is_empty() {
                    output.push(b'\n');
                    continue;
                }

                output.extend_from_slice(b"  ");
                output.extend_from_slice(line.as_bytes());
                output.push(b'\n');
            }
        } else {
            // 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());
                }
            }
            if first_line {
                output.extend_from_slice(b"  return null");
            }
            output.push(b'\n');
        }
        output.extend_from_slice(b"}\n");
    } else {
        let setup_bindings = collect_setup_bindings(ctx);
        if is_vapor && !template.render_fn.is_empty() {
            let needs_template_ref_setter = template.render_fn.contains("_createTemplateRefSetter");
            if needs_template_ref_setter {
                output.extend_from_slice(b"const ");
                output.extend_from_slice(VAPOR_TEMPLATE_REF_SETTER.as_bytes());
                output.extend_from_slice(b" = _createTemplateRefSetter()\n");
            }
            output.extend_from_slice(b"const __returned__ = { ");
            let mut binding_index = 0usize;
            if needs_template_ref_setter {
                output.extend_from_slice(VAPOR_TEMPLATE_REF_SETTER.as_bytes());
                binding_index += 1;
            }
            for name in setup_bindings.iter() {
                if binding_index > 0 {
                    output.extend_from_slice(b", ");
                }
                binding_index += 1;
                output.extend_from_slice(name.as_bytes());
            }
            output.extend_from_slice(b" }\n");
            output.extend_from_slice(b"Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n");
            output.extend_from_slice(b"const __instance = _getCurrentInstance()\n");
            output.extend_from_slice(b"const __ctx = _proxyRefs(__returned__)\n");
            output.extend_from_slice(b"if (__instance) __instance.setupState = __ctx\n");
            output.extend_from_slice(b"return ");
            output.extend_from_slice(vapor_render_alias.unwrap_or("render").as_bytes());
            output.extend_from_slice(b"(__ctx, __props, __emit, __attrs, __slots)\n");
        } else if !setup_bindings.is_empty() {
            // No template (e.g., Musea art files) -- return setup bindings as an object
            // so they're accessible for runtime template compilation (compileToFunction).
            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");
        } else if !template.render_fn.is_empty() {
            output.extend_from_slice(b"return {}\n");
        }
    }
}

fn build_vapor_render_alias(
    content: &str,
    normal_script_content: Option<&str>,
    template_render_fn: &str,
) -> String {
    let mut suffix = 0usize;
    loop {
        let candidate = build_vapor_render_alias_candidate(suffix);
        let candidate_str = candidate.as_str();
        if !content.contains(candidate_str)
            && normal_script_content.is_none_or(|script| !script.contains(candidate_str))
            && !template_render_fn.contains(candidate_str)
        {
            return candidate;
        }
        suffix += 1;
    }
}

fn build_vapor_render_alias_candidate(suffix: usize) -> String {
    let mut candidate = String::from(VAPOR_RENDER_ALIAS_BASE);
    if suffix == 0 {
        return candidate;
    }

    candidate.push('_');
    append_usize(&mut candidate, suffix);
    candidate
}

fn append_usize(target: &mut String, value: usize) {
    let mut buffer = [0u8; 20];
    let mut index = buffer.len();
    let mut remaining = value;

    loop {
        index -= 1;
        buffer[index] = b'0' + (remaining % 10) as u8;
        remaining /= 10;
        if remaining == 0 {
            break;
        }
    }

    let digits = std::str::from_utf8(&buffer[index..]).expect("usize digits should be ASCII");
    target.push_str(digits);
}

fn collect_setup_bindings(ctx: &ScriptCompileContext) -> Vec<&str> {
    use crate::types::BindingType;

    ctx.bindings
        .bindings
        .iter()
        .filter(|(_, bt)| {
            matches!(
                bt,
                BindingType::SetupLet
                    | BindingType::SetupMaybeRef
                    | BindingType::SetupRef
                    | BindingType::SetupReactiveConst
                    | BindingType::SetupConst
                    | BindingType::LiteralConst
            )
        })
        .map(|(name, _)| name.as_str())
        .collect()
}

/// Parse script content to extract imports, setup lines, and TypeScript declarations.
///
/// Returns a tuple of (user_imports, setup_lines, ts_declarations).
fn parse_script_content(content: &str, is_ts: bool) -> (Vec<String>, Vec<String>, Vec<String>) {
    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::default();
    let mut in_destructure = false;
    let mut destructure_buffer = String::default();
    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;
    let mut destructure_call_keep_lines = false; // true for regular function calls (keep args in output)
                                                 // Track multiline object literals: const xxx = { ... }
    let mut in_object_literal = false;
    let mut object_literal_buffer = String::default();
    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
    let mut ts_type_pending_end = false; // True when type may have ended on `}` but need to check next line
                                         // 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) and comments
            let cleaned = strip_comments_for_counting(trimmed);
            let line_no_arrow = cleaned.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 {
            let cleaned = strip_comments_for_counting(trimmed);
            destructure_call_paren_depth += cleaned.matches('(').count() as i32;
            destructure_call_paren_depth -= cleaned.matches(')').count() as i32;
            // For regular (non-macro) function calls, keep argument lines in setup output
            if destructure_call_keep_lines {
                setup_lines.push(line.to_compact_string());
            }
            if destructure_call_paren_depth <= 0 {
                in_destructure_call = false;
            }
            continue;
        }

        if in_paren_macro_call {
            let cleaned = strip_comments_for_counting(trimmed);
            paren_macro_depth += cleaned.matches('(').count() as i32;
            paren_macro_depth -= cleaned.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 and comments)
            let cleaned = strip_comments_for_counting(trimmed);
            let line_no_arrow = cleaned.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 and comments)
            let cleaned = strip_comments_for_counting(trimmed);
            let line_no_arrow = cleaned.replace("=>", "");
            brace_depth += cleaned.matches('{').count() as i32;
            brace_depth -= cleaned.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_compact_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_call_keep_lines = !is_props_macro;
                }
                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_compact_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_compact_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_compact_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_compact_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_compact_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_compact_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_compact_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_compact_string());
                }
            } else {
                // Single-line declare (e.g., `declare const x: number`)
                if is_ts {
                    ts_declarations.push(line.to_compact_string());
                }
            }
            continue;
        }

        // Handle TypeScript type declarations (collect for TS output, skip for JS)
        if in_ts_type {
            let is_type_continuation = trimmed.starts_with('|')
                || trimmed.starts_with('&')
                || trimmed.starts_with('?')
                || trimmed.starts_with(':');

            // Handle pending end from previous line's closing `}`
            if ts_type_pending_end {
                ts_type_pending_end = false;
                if is_type_continuation {
                    // Continue the type - next union/intersection variant
                    if is_ts {
                        if let Some(last) = ts_declarations.last_mut() {
                            last.push('\n');
                            last.push_str(line);
                        }
                    }
                    let cleaned = strip_comments_for_counting(trimmed);
                    let line_no_arrow = cleaned.replace("=>", "__");
                    ts_type_depth += cleaned.matches('{').count() as i32;
                    ts_type_depth -= cleaned.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 += cleaned.matches('(').count() as i32;
                    ts_type_depth -= cleaned.matches(')').count() as i32;
                    continue;
                } else {
                    // NOT a continuation - type truly ended on the previous line
                    in_ts_type = false;
                    // Fall through to normal line processing below
                }
            }

            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 cleaned = strip_comments_for_counting(trimmed);
                let line_no_arrow = cleaned.replace("=>", "__");
                ts_type_depth += cleaned.matches('{').count() as i32;
                ts_type_depth -= cleaned.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 += cleaned.matches('(').count() as i32;
                ts_type_depth -= cleaned.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
                // 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
                    && (trimmed.ends_with(';')
                        || (!is_type_continuation
                            && !trimmed.ends_with('|')
                            && !trimmed.ends_with('&')
                            && !trimmed.ends_with(',')
                            && !trimmed.ends_with('{')))
                {
                    // If the line ends with `}` (without `;`), the next line might be a union continuation
                    if trimmed.ends_with('}') && !trimmed.ends_with("};") {
                        ts_type_pending_end = true;
                    } else {
                        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 {
                    if trimmed.ends_with(';') {
                        // Definitely complete single-line type
                        if is_ts {
                            ts_declarations.push(line.to_compact_string());
                        }
                        continue;
                    }
                    if !trimmed.ends_with('|')
                        && !trimmed.ends_with('&')
                        && !trimmed.ends_with(',')
                        && !trimmed.ends_with('{')
                        && !trimmed.ends_with('=')
                    {
                        // Possibly complete, but next line may be conditional type continuation (? / :)
                        if is_ts {
                            ts_declarations.push(line.to_compact_string());
                        }
                        in_ts_type = true;
                        ts_type_pending_end = true;
                        continue;
                    }
                }
                if is_ts {
                    ts_declarations.push(line.to_compact_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_compact_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_compact_string());
        }
    }

    (user_imports, setup_lines, ts_declarations)
}

/// Build props and emits definition buffer from context macros.
fn build_props_emits(
    ctx: &ScriptCompileContext,
    _is_ts: bool,
    needs_prop_type: bool,
    needs_merge_defaults: bool,
) -> Vec<u8> {
    let mut props_emits_buf: Vec<u8> = Vec::new();

    // 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>)> = collect_model_infos(ctx);

    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;
                    // Try to resolve type references for props that resolved to `null`
                    let resolved_js_type = if prop_type.js_type == "null" {
                        if let Some(ref ts_type) = prop_type.ts_type {
                            super::super::props::resolve_prop_js_type(
                                ts_type,
                                &ctx.interfaces,
                                &ctx.type_aliases,
                            )
                            .unwrap_or_else(|| prop_type.js_type.clone())
                        } else {
                            prop_type.js_type.clone()
                        }
                    } else {
                        prop_type.js_type.clone()
                    };
                    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(resolved_js_type.as_bytes());
                    if needs_prop_type {
                        if let Some(ref ts_type) = prop_type.ts_type {
                            if resolved_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 =
                                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");
            }
        }
    }

    props_emits_buf
}

/// Build model-specific props and emits when defineModel is used without defineProps,
/// plus the emits array combining defineEmits and defineModel emits.
fn build_model_props_emits(
    ctx: &ScriptCompileContext,
    model_infos: &[(String, String, Option<String>)],
    _is_ts: bool,
    _needs_prop_type: bool,
    _needs_merge_defaults: bool,
) -> Vec<u8> {
    let mut buf: Vec<u8> = Vec::new();

    if !model_infos.is_empty() && ctx.macros.define_props.is_none() {
        buf.extend_from_slice(b"  props: {\n");
        for (model_name, _binding_name, options) in model_infos {
            // Model value prop
            buf.extend_from_slice(b"    \"");
            buf.extend_from_slice(model_name.as_bytes());
            buf.extend_from_slice(b"\": ");
            if let Some(opts) = options {
                buf.extend_from_slice(opts.as_bytes());
            } else {
                buf.extend_from_slice(b"{}");
            }
            buf.extend_from_slice(b",\n");
            // Model modifiers prop: "modelModifiers" for default, "<name>Modifiers" for named
            buf.extend_from_slice(b"    \"");
            if model_name == "modelValue" {
                buf.extend_from_slice(b"modelModifiers");
            } else {
                buf.extend_from_slice(model_name.as_bytes());
                buf.extend_from_slice(b"Modifiers");
            }
            buf.extend_from_slice(b"\": {},\n");
        }
        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_compact_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() {
        buf.extend_from_slice(b"  emits: [");
        for (i, name) in all_emits.iter().enumerate() {
            if i > 0 {
                buf.extend_from_slice(b", ");
            }
            buf.push(b'"');
            buf.extend_from_slice(name.as_bytes());
            buf.push(b'"');
        }
        buf.extend_from_slice(b"],\n");
    }

    buf
}

/// Collect model info from defineModel calls.
///
/// Returns Vec of (model_name, binding_name, options).
fn collect_model_infos(ctx: &ScriptCompileContext) -> Vec<(String, String, Option<String>)> {
    ctx.macros
        .define_models
        .iter()
        .map(|m| {
            let model_name = if m.args.trim().is_empty() {
                "modelValue".to_compact_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_compact_string()
                } else {
                    "modelValue".to_compact_string()
                }
            };
            let binding_name = m
                .binding_name
                .as_deref()
                .map(String::from)
                .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_compact_string())
                } else if args.contains(',') {
                    args.split_once(',')
                        .map(|(_, opts)| opts.trim().to_compact_string())
                } else {
                    None
                }
            };
            (model_name, binding_name, options)
        })
        .collect()
}

/// Separate hoisted consts (literal consts that can be module-level) from setup code.
///
/// Returns (hoisted_lines, setup_body_lines).
fn separate_hoisted_consts(
    transformed_setup: &str,
    ctx: &ScriptCompileContext,
) -> (Vec<String>, Vec<String>) {
    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_compact_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 const where value is on the next line (e.g., `const x =\n  'value'`)
            if let Some(eq_pos) = trimmed.find('=') {
                let value_part = trimmed[eq_pos + 1..].trim();
                // If value part is empty, the value is on the next line - don't hoist
                if value_part.is_empty() {
                    setup_body_lines.push(line.to_compact_string());
                    continue;
                }
                // Check for multi-line template literal (unclosed backtick)
                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_compact_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.as_str()),
                    Some(crate::types::BindingType::LiteralConst)
                ) {
                    hoisted_lines.push(line.to_compact_string());
                    continue;
                }
            }
        }
        setup_body_lines.push(line.to_compact_string());
    }

    (hoisted_lines, setup_body_lines)
}

/// Transform top-level await expressions to use `_withAsyncContext`.
///
/// Handles two patterns:
/// 1. `const x = await expr` → `const x = (\n  ([__temp,__restore] = _withAsyncContext(() => expr)),\n  __temp = await __temp,\n  __restore(),\n  __temp\n)`
/// 2. `await expr` (statement) → `;(\n  ([__temp,__restore] = _withAsyncContext(() => expr)),\n  await __temp,\n  __restore()\n)`
fn transform_await_expressions(lines: &[String], is_ts: bool) -> Vec<String> {
    let mut source = String::default();
    for (idx, line) in lines.iter().enumerate() {
        if idx > 0 {
            source.push('\n');
        }
        source.push_str(line);
    }

    transform_await_source(&source, is_ts)
        .lines()
        .map(|line| line.to_compact_string())
        .collect()
}

const AWAIT_WRAP_PREFIX: &str = "async function __vize_async_setup__() {\n";
const AWAIT_WRAP_SUFFIX: &str = "\n}";

fn transform_await_source(source: &str, is_ts: bool) -> String {
    if source.trim().is_empty() {
        return source.to_compact_string();
    }

    let mut wrapped =
        String::with_capacity(AWAIT_WRAP_PREFIX.len() + source.len() + AWAIT_WRAP_SUFFIX.len());
    wrapped.push_str(AWAIT_WRAP_PREFIX);
    wrapped.push_str(source);
    wrapped.push_str(AWAIT_WRAP_SUFFIX);

    let allocator = Allocator::default();
    let source_type = SourceType::default().with_typescript(is_ts);
    let parse_result = Parser::new(&allocator, &wrapped, source_type).parse();
    if !parse_result.errors.is_empty() {
        return source.to_compact_string();
    }

    let Some(Statement::FunctionDeclaration(func)) = parse_result.program.body.first() else {
        return source.to_compact_string();
    };
    let Some(body) = &func.body else {
        return source.to_compact_string();
    };

    let offset = AWAIT_WRAP_PREFIX.len();
    let mut cursor = 0usize;
    let mut transformed = String::with_capacity(source.len() + 128);

    for stmt in body.statements.iter() {
        let stmt_span = stmt.span();
        let Some(stmt_start) = stmt_span.start.try_into().ok().and_then(|start: usize| {
            start
                .checked_sub(offset)
                .filter(|start| *start <= source.len())
        }) else {
            return source.to_compact_string();
        };
        let Some(stmt_end) = stmt_span
            .end
            .try_into()
            .ok()
            .and_then(|end: usize| end.checked_sub(offset).filter(|end| *end <= source.len()))
        else {
            return source.to_compact_string();
        };

        if stmt_start < cursor || stmt_start > stmt_end {
            return source.to_compact_string();
        }

        transformed.push_str(&source[cursor..stmt_start]);

        if let Some(replacement) = transform_await_statement(source, stmt, offset) {
            transformed.push_str(&replacement);
        } else {
            transformed.push_str(&source[stmt_start..stmt_end]);
        }

        cursor = stmt_end;
    }

    transformed.push_str(&source[cursor..]);
    transformed
}

fn transform_await_statement(source: &str, stmt: &Statement<'_>, offset: usize) -> Option<String> {
    match stmt {
        Statement::ExpressionStatement(expr_stmt) => {
            let Expression::AwaitExpression(await_expr) = &expr_stmt.expression else {
                return None;
            };
            build_standalone_await_replacement(source, stmt.span(), await_expr.span(), offset)
        }
        Statement::VariableDeclaration(var_decl) => {
            if var_decl.declarations.len() != 1 {
                return None;
            }
            let declarator = var_decl.declarations.first()?;
            let init = declarator.init.as_ref()?;
            let Expression::AwaitExpression(await_expr) = init else {
                return None;
            };
            build_await_assignment_replacement(source, stmt.span(), await_expr.span(), offset)
        }
        _ => None,
    }
}

fn build_await_assignment_replacement(
    source: &str,
    stmt_span: oxc_span::Span,
    await_span: oxc_span::Span,
    offset: usize,
) -> Option<String> {
    let stmt_start = stmt_span.start as usize - offset;
    let stmt_end = stmt_span.end as usize - offset;
    let await_start = await_span.start as usize - offset;
    let await_end = await_span.end as usize - offset;

    let prefix = source.get(stmt_start..await_start)?;
    let expr = await_expression_source(source, await_start, await_end)?;
    let suffix = source.get(await_end..stmt_end)?;

    let mut out = String::with_capacity(prefix.len() + expr.len() + suffix.len() + 96);
    out.push_str(prefix);
    out.push_str(" (\n");
    out.push_str("  ([__temp,__restore] = _withAsyncContext(() => ");
    out.push_str(expr);
    out.push_str(")),\n");
    out.push_str("  __temp = await __temp,\n");
    out.push_str("  __restore(),\n");
    out.push_str("  __temp\n");
    out.push(')');
    out.push_str(suffix);
    Some(out)
}

fn build_standalone_await_replacement(
    source: &str,
    stmt_span: oxc_span::Span,
    await_span: oxc_span::Span,
    offset: usize,
) -> Option<String> {
    let stmt_start = stmt_span.start as usize - offset;
    let stmt_end = stmt_span.end as usize - offset;
    let await_start = await_span.start as usize - offset;
    let await_end = await_span.end as usize - offset;

    if stmt_start != await_start {
        return None;
    }

    let expr = await_expression_source(source, await_start, await_end)?;
    let suffix = source.get(await_end..stmt_end)?;

    let mut out = String::with_capacity(expr.len() + suffix.len() + 72);
    out.push_str(";(\n");
    out.push_str("  ([__temp,__restore] = _withAsyncContext(() => ");
    out.push_str(expr);
    out.push_str(")),\n");
    out.push_str("  await __temp,\n");
    out.push_str("  __restore()\n");
    out.push(')');
    out.push_str(suffix);
    Some(out)
}

fn await_expression_source(source: &str, start: usize, end: usize) -> Option<&str> {
    let await_source = source.get(start..end)?;
    let expr = await_source.strip_prefix("await")?.trim_start();
    if expr.is_empty() {
        return None;
    }
    Some(expr)
}