vize_atelier_sfc 0.8.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
//! SFC compilation implementation.
//!
//! This is the main entry point for compiling Vue Single File Components.
//! Following the Vue.js core structure, template/script/style compilation
//! is delegated to specialized modules.

use crate::compile_script::{compile_script_setup_inline, TemplateParts};
use crate::compile_template::{
    compile_template_block, compile_template_block_vapor, extract_template_parts,
    extract_template_parts_full,
};
use crate::rewrite_default::rewrite_default;
use crate::script::ScriptCompileContext;
use crate::types::*;

// Re-export ScriptCompileResult for public API
pub use crate::compile_script::ScriptCompileResult;

/// Compile an SFC descriptor into JavaScript and CSS
pub fn compile_sfc(
    descriptor: &SfcDescriptor,
    options: SfcCompileOptions,
) -> Result<SfcCompileResult, SfcError> {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    let mut code = String::new();
    let mut css = None;

    let filename = options.script.id.as_deref().unwrap_or("anonymous.vue");

    // Generate scope ID from filename
    let scope_id = generate_scope_id(filename);
    let has_scoped = descriptor.styles.iter().any(|s| s.scoped);

    // Detect vapor mode from script attrs
    let is_vapor = descriptor
        .script_setup
        .as_ref()
        .map(|s| s.attrs.contains_key("vapor"))
        .unwrap_or(false)
        || descriptor
            .script
            .as_ref()
            .map(|s| s.attrs.contains_key("vapor"))
            .unwrap_or(false);

    // source_has_ts: whether source uses TypeScript (detected from lang="ts")
    // Used for: parsing source as TS, preserving TS declarations, resolving type references
    let source_has_ts = descriptor
        .script_setup
        .as_ref()
        .and_then(|s| s.lang.as_ref())
        .is_some_and(|l| l == "ts" || l == "tsx")
        || descriptor
            .script
            .as_ref()
            .and_then(|s| s.lang.as_ref())
            .is_some_and(|l| l == "ts" || l == "tsx");
    // is_ts controls output format:
    // - true: output TypeScript (add `: any` annotations, defineComponent wrapper)
    // - false: output JavaScript (no type annotations)
    // Auto-detected from source lang, or set by explicit options.
    // When true, TypeScript is preserved in output (downstream tools like Vite strip it via .ts suffix).
    let is_ts = options.script.is_ts || options.template.is_ts || source_has_ts;

    // Extract component name from filename
    let component_name = extract_component_name(filename);

    // Determine output mode based on script type
    let has_script_setup = descriptor.script_setup.is_some();
    let has_script = descriptor.script.is_some();
    let has_template = descriptor.template.is_some();

    // Case 1: Template only - just output render function
    if !has_script && !has_script_setup && has_template {
        let template = descriptor.template.as_ref().unwrap();
        // Enable hoisting for template-only SFCs (hoisted consts go at module level)
        let mut template_opts = options.template.clone();
        let mut dom_opts = template_opts.compiler_options.take().unwrap_or_default();
        dom_opts.hoist_static = true;
        template_opts.compiler_options = Some(dom_opts);
        let template_result = compile_template_block(
            template,
            &template_opts,
            &scope_id,
            has_scoped,
            is_ts,
            None,
            None,
        );

        match template_result {
            Ok(template_code) => {
                // Wrap template-only SFC in a proper component with export default.
                // Convert "export function render(" to "function render(" and add component wrapper.
                let wrapped = template_code.replace("export function render(", "function render(");
                let mut output = String::with_capacity(wrapped.len() + 128);
                output.push_str(&wrapped);
                output.push_str("\nconst _sfc_main = {};\n");
                output.push_str("_sfc_main.render = render;\n");
                output.push_str("export default _sfc_main;\n");
                code = output;
            }
            Err(e) => errors.push(e),
        }

        // Compile styles
        let all_css = compile_styles(&descriptor.styles, &scope_id, &options.style, &mut warnings);
        if !all_css.is_empty() {
            css = Some(all_css);
        }

        return Ok(SfcCompileResult {
            code,
            css,
            map: None,
            errors,
            warnings,
            bindings: None,
        });
    }

    // Case 2: Script (non-setup) + Template - rewrite default and compile template
    if has_script && !has_script_setup {
        let script = descriptor.script.as_ref().unwrap();

        // Check if source script is TypeScript
        let source_is_ts = script
            .lang
            .as_ref()
            .is_some_and(|l| l == "ts" || l == "tsx");

        // Rewrite `export default` to `const _sfc_main = ...`
        // Parse as TypeScript if source is TypeScript
        let (rewritten_script, _has_default) =
            rewrite_default(&script.content, "_sfc_main", source_is_ts);

        // Transpile TypeScript to JavaScript if needed
        let final_script = if source_is_ts && !is_ts {
            crate::compile_script::typescript::transform_typescript_to_js(&rewritten_script)
        } else {
            rewritten_script
        };

        // Compile template if present
        if has_template {
            let template = descriptor.template.as_ref().unwrap();
            let mut template_opts = options.template.clone();
            let mut dom_opts = template_opts.compiler_options.take().unwrap_or_default();
            dom_opts.hoist_static = true;
            template_opts.compiler_options = Some(dom_opts);

            let template_result = compile_template_block(
                template,
                &template_opts,
                &scope_id,
                has_scoped,
                is_ts,
                None, // No bindings for normal scripts
                None, // No Croquis for normal scripts
            );

            match template_result {
                Ok(template_code) => {
                    // Extract template parts (imports, hoisted, render function)
                    let (template_imports, template_hoisted, render_fn) =
                        extract_template_parts_full(&template_code);

                    // Build output: imports + script + hoisted + render + export
                    code.push_str(&template_imports);
                    if !template_imports.is_empty() {
                        code.push('\n');
                    }
                    code.push_str(&final_script);
                    code.push('\n');

                    // Add hoisted declarations
                    if !template_hoisted.is_empty() {
                        code.push_str(&template_hoisted);
                        code.push('\n');
                    }

                    // Add render function (without imports - they're already at top)
                    code.push_str(&render_fn);
                    code.push('\n');

                    // Export the component with render attached
                    code.push_str("_sfc_main.render = render\n");
                    code.push_str("export default _sfc_main\n");
                }
                Err(e) => {
                    errors.push(e);
                    // Fall back to just the script
                    code = script.content.to_string();
                    code.push('\n');
                }
            }
        } else {
            // No template - just output rewritten script and export
            code.push_str(&final_script);
            code.push_str("\nexport default _sfc_main\n");
        }

        // Compile styles
        let all_css = compile_styles(&descriptor.styles, &scope_id, &options.style, &mut warnings);
        if !all_css.is_empty() {
            css = Some(all_css);
        }

        return Ok(SfcCompileResult {
            code,
            css,
            map: None,
            errors,
            warnings,
            bindings: None,
        });
    }

    // Case 3: Script setup with inline template
    // If we reach here without script_setup, it means the SFC has no content
    let script_setup = match descriptor.script_setup.as_ref() {
        Some(s) => s,
        None => {
            return Err(SfcError {
                message:
                    "At least one <template> or <script> is required in a single file component."
                        .to_string(),
                code: None,
                loc: None,
            });
        }
    };

    // Extract normal script content if present (for type definitions, imports, etc.)
    // When both <script> and <script setup> exist, normal script content should be preserved
    // (except for export default which is handled by script setup)
    let normal_script_content = if has_script {
        let script = descriptor.script.as_ref().unwrap();
        // Check if source is TypeScript
        let source_is_ts = script
            .lang
            .as_ref()
            .is_some_and(|l| l == "ts" || l == "tsx");
        Some(extract_normal_script_content(
            &script.content,
            source_is_ts,
            is_ts,
        ))
    } else {
        None
    };

    // 1. Croquis parser: rich analysis with ReactivityTracker
    let croquis = crate::script::analyze_script_setup_to_summary(&script_setup.content);
    let mut script_bindings = croquis_to_legacy_bindings(&croquis.bindings);

    // 2. ScriptCompileContext: needed for macro span info and TypeScript type resolution
    //    (Croquis doesn't resolve type references like `defineProps<Props>()`)
    let mut ctx = ScriptCompileContext::new(&script_setup.content);
    ctx.analyze();

    // 3. Merge Props bindings from ScriptCompileContext (type resolution fallback)
    //    Croquis can't resolve interface references, so we take Props from the legacy analyzer
    for (name, bt) in &ctx.bindings.bindings {
        if matches!(bt, BindingType::Props | BindingType::PropsAliased) {
            script_bindings.bindings.entry(name.clone()).or_insert(*bt);
        }
    }

    // Also register exported bindings from normal script (e.g., export const n = 1)
    // These are accessible in the template without _ctx. prefix
    if has_script {
        let script = descriptor.script.as_ref().unwrap();
        let normal_ctx = ScriptCompileContext::new(&script.content);
        // Extract exported variable names from normal script
        for line in script.content.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("export const ") || trimmed.starts_with("export let ") {
                let rest = if let Some(r) = trimmed.strip_prefix("export const ") {
                    r
                } else {
                    trimmed.strip_prefix("export let ").unwrap()
                };
                // Extract variable name before = or : or whitespace
                if let Some(name_end) =
                    rest.find(|c: char| c == '=' || c == ':' || c.is_whitespace())
                {
                    let name = rest[..name_end].trim();
                    if !name.is_empty() && !name.starts_with('{') && !name.starts_with('[') {
                        script_bindings
                            .bindings
                            .insert(name.to_string(), BindingType::SetupConst);
                    }
                }
            }
        }
        drop(normal_ctx);
    }

    // Compile template with bindings (if present) to get the render function
    let template_result = if let Some(template) = &descriptor.template {
        if is_vapor {
            Some(compile_template_block_vapor(
                template, &scope_id, has_scoped,
            ))
        } else {
            Some(compile_template_block(
                template,
                &options.template,
                &scope_id,
                has_scoped,
                is_ts,
                Some(&script_bindings), // Pass bindings for proper ref handling
                Some(croquis),          // Pass Croquis for enhanced transforms
            ))
        }
    } else {
        None
    };

    // Extract template parts for inline mode (imports, hoisted, preamble, render_body)
    let (template_imports, template_hoisted, template_preamble, render_body) =
        match &template_result {
            Some(Ok(template_code)) => extract_template_parts(template_code),
            Some(Err(e)) => {
                errors.push(e.clone());
                (String::new(), String::new(), String::new(), String::new())
            }
            None => (String::new(), String::new(), String::new(), String::new()),
        };

    // Compile script setup using inline mode to match Vue's @vue/compiler-sfc output format:
    // 1. Template imports (from "vue")
    // 2. User imports
    // 3. Hoisted literal consts (module-level)
    // 4. export default { __name, props?, emits?, setup(__props) { ... return (_ctx, _cache) => { ... } } }
    // Detect if the source script setup uses TypeScript
    let source_is_ts = script_setup
        .lang
        .as_ref()
        .is_some_and(|l| l == "ts" || l == "tsx");

    let script_result = compile_script_setup_inline(
        &script_setup.content,
        &component_name,
        is_ts,
        source_is_ts,
        TemplateParts {
            imports: &template_imports,
            hoisted: &template_hoisted,
            preamble: &template_preamble,
            render_body: &render_body,
        },
        normal_script_content.as_deref(),
    )?;

    // The inline mode compile_script_setup_inline generates a complete output
    // including imports, hoisted vars, and `export default { ... }` with inline render
    code.push_str(&script_result.code);

    // Compile styles
    let all_css = compile_styles(&descriptor.styles, &scope_id, &options.style, &mut warnings);
    if !all_css.is_empty() {
        css = Some(all_css);
    }

    Ok(SfcCompileResult {
        code,
        css,
        map: None,
        errors,
        warnings,
        bindings: script_result.bindings,
    })
}

/// Helper to compile all style blocks
fn compile_styles(
    styles: &[SfcStyleBlock],
    scope_id: &str,
    base_opts: &StyleCompileOptions,
    warnings: &mut Vec<SfcError>,
) -> String {
    let mut all_css = String::new();
    for style in styles {
        let style_opts = StyleCompileOptions {
            id: {
                let mut id = String::with_capacity(scope_id.len() + 7);
                id.push_str("data-v-");
                id.push_str(scope_id);
                id
            },
            scoped: style.scoped,
            ..base_opts.clone()
        };
        match crate::style::compile_style(style, &style_opts) {
            Ok(style_css) => {
                if !all_css.is_empty() {
                    all_css.push('\n');
                }
                all_css.push_str(&style_css);
            }
            Err(e) => warnings.push(e),
        }
    }
    all_css
}

/// Generate scope ID from filename
fn generate_scope_id(filename: &str) -> String {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    filename.hash(&mut hasher);
    let value = hasher.finish() & 0xFFFFFFFF;
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(8);
    for shift in (0..32).step_by(4).rev() {
        let digit = ((value >> shift) & 0xF) as usize;
        out.push(HEX[digit] as char);
    }
    out
}

/// Extract component name from filename
fn extract_component_name(filename: &str) -> String {
    std::path::Path::new(filename)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("anonymous")
        .to_string()
}

/// Extract content from normal script block that should be preserved when both
/// `<script>` and `<script setup>` exist.
/// This includes imports, type definitions, interfaces, but excludes `export default`.
///
/// Parameters:
/// - `content`: The script content
/// - `source_is_ts`: Whether the source script is TypeScript (has lang="ts")
/// - `output_is_ts`: Whether to preserve TypeScript in output (false = transpile to JS)
fn extract_normal_script_content(content: &str, source_is_ts: bool, output_is_ts: bool) -> String {
    use oxc_allocator::Allocator;
    use oxc_ast::ast::Statement;
    use oxc_codegen::Codegen;
    use oxc_parser::Parser;
    use oxc_semantic::SemanticBuilder;
    use oxc_span::{GetSpan, SourceType};
    use oxc_transformer::{TransformOptions, Transformer, TypeScriptOptions};

    // Always parse as TypeScript if source is TypeScript
    let source_type = if source_is_ts {
        SourceType::ts()
    } else {
        SourceType::mjs()
    };

    let allocator = Allocator::default();
    let ret = Parser::new(&allocator, content, source_type).parse();

    if !ret.errors.is_empty() {
        // If parsing fails, return original content minus any obvious export default
        return content
            .lines()
            .filter(|line| !line.trim().starts_with("export default"))
            .collect::<Vec<_>>()
            .join("\n");
    }

    let program = ret.program;
    let mut output = String::new();
    let mut last_end = 0;

    // Collect spans of statements to skip (export default declarations)
    let mut skip_spans: Vec<(u32, u32)> = Vec::new();

    // Collect spans to rewrite: (start, end, replacement)
    let mut rewrites: Vec<(u32, u32, String)> = Vec::new();

    for stmt in program.body.iter() {
        match stmt {
            // Rewrite export default declarations to const __default__ = ...
            Statement::ExportDefaultDeclaration(decl) => {
                // Find the span of "export default" keyword portion
                let stmt_start = stmt.span().start;
                let stmt_end = stmt.span().end;
                let stmt_text = &content[stmt_start as usize..stmt_end as usize];
                // Replace "export default" with "const __default__ ="
                let rewritten = stmt_text.replacen("export default", "const __default__ =", 1);
                rewrites.push((stmt_start, stmt_end, rewritten));
                let _ = decl; // suppress unused
            }
            // Skip named exports that include default: export { foo as default }
            Statement::ExportNamedDeclaration(decl) => {
                let has_default_export = decl.specifiers.iter().any(|s| {
                    matches!(&s.exported, oxc_ast::ast::ModuleExportName::IdentifierName(name) if name.name == "default")
                        || matches!(&s.exported, oxc_ast::ast::ModuleExportName::IdentifierReference(name) if name.name == "default")
                });
                if has_default_export {
                    skip_spans.push((stmt.span().start, stmt.span().end));
                }
            }
            _ => {}
        }
    }

    // Build output by copying content, applying rewrites and skipping as needed
    // Merge all modifications into a sorted list
    let mut modifications: Vec<(u32, u32, Option<String>)> = Vec::new();
    for (start, end, replacement) in rewrites {
        modifications.push((start, end, Some(replacement)));
    }
    for (start, end) in &skip_spans {
        modifications.push((*start, *end, None));
    }
    modifications.sort_by_key(|m| m.0);

    for (start, end, replacement) in &modifications {
        output.push_str(&content[last_end..*start as usize]);
        if let Some(repl) = replacement {
            output.push_str(repl);
        }
        last_end = *end as usize;
    }
    if last_end < content.len() {
        output.push_str(&content[last_end..]);
    }

    let extracted = output.trim().to_string();

    // If source is TypeScript and we need JavaScript output, transpile
    if source_is_ts && !output_is_ts {
        // Re-parse the extracted content
        let allocator2 = Allocator::default();
        let ret2 = Parser::new(&allocator2, &extracted, SourceType::ts()).parse();
        if ret2.errors.is_empty() {
            let mut program2 = ret2.program;

            // Run semantic analysis
            let semantic_ret = SemanticBuilder::new().build(&program2);
            if semantic_ret.errors.is_empty() {
                let scoping = semantic_ret.semantic.into_scoping();

                // Transform TypeScript to JavaScript
                // Use only_remove_type_imports to preserve imports that might be used in template
                let transform_options = TransformOptions {
                    typescript: TypeScriptOptions {
                        only_remove_type_imports: true,
                        ..Default::default()
                    },
                    ..Default::default()
                };
                let transform_ret =
                    Transformer::new(&allocator2, std::path::Path::new(""), &transform_options)
                        .build_with_scoping(scoping, &mut program2);

                if transform_ret.errors.is_empty() {
                    // Generate JavaScript code
                    return Codegen::new().build(&program2).code;
                }
            }
        }
    }

    extracted
}

/// Convert Croquis BindingMetadata (CompactString keys) to legacy BindingMetadata (String keys)
fn croquis_to_legacy_bindings(src: &vize_croquis::analysis::BindingMetadata) -> BindingMetadata {
    let mut dst = BindingMetadata::default();
    dst.is_script_setup = src.is_script_setup;
    for (name, bt) in src.iter() {
        dst.bindings.insert(name.to_string(), bt);
    }
    for (local, key) in &src.props_aliases {
        dst.props_aliases.insert(local.to_string(), key.to_string());
    }
    dst
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{parse_sfc, SfcParseOptions};

    #[test]
    fn test_generate_scope_id() {
        let id = generate_scope_id("src/App.vue");
        assert_eq!(id.len(), 8);
    }

    #[test]
    fn test_extract_component_name() {
        assert_eq!(extract_component_name("src/App.vue"), "App");
        assert_eq!(extract_component_name("MyComponent.vue"), "MyComponent");
    }

    #[test]
    #[ignore = "TODO: fix v-model prop quoting"]
    fn test_v_model_on_component_in_sfc() {
        let source = r#"<script setup>
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
const msg = ref('')
</script>

<template>
  <MyComponent v-model="msg" :language="'en'" />
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions::default();
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        // Should NOT contain /* v-model */ comment
        assert!(
            !result.code.contains("/* v-model */"),
            "Should not contain v-model comment. Got:\n{}",
            result.code
        );
        // Should contain modelValue and onUpdate:modelValue
        assert!(
            result.code.contains("\"modelValue\":"),
            "Should have modelValue prop. Got:\n{}",
            result.code
        );
        assert!(
            result.code.contains("\"onUpdate:modelValue\":"),
            "Should have onUpdate:modelValue prop. Got:\n{}",
            result.code
        );
    }

    #[test]
    #[ignore = "TODO: fix inline mode ref handling"]
    fn test_bindings_passed_to_template() {
        let source = r#"<script setup lang="ts">
import { ref } from 'vue';
import MonacoEditor from './MonacoEditor.vue';
const selectedPreset = ref('test');
const options = ref({ ssr: false });
function handleChange(val: string) { selectedPreset.value = val; }
</script>
<template>
  <div>{{ selectedPreset }}</div>
  <select :value="selectedPreset" @change="handleChange($event.target.value)">
    <option value="a">A</option>
  </select>
  <input type="checkbox" v-model="options.ssr" />
  <MonacoEditor />
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions::default();
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("=== COMPILED OUTPUT ===\n{}", result.code);

        // In non-inline mode with binding metadata, setup bindings are accessed via $setup
        // This is the correct Vue 3 behavior when binding metadata is passed to the template compiler
        assert!(
            result.code.contains("$setup.selectedPreset"),
            "selectedPreset should have $setup prefix in non-inline mode with bindings. Got:\n{}",
            result.code
        );
        assert!(
            result.code.contains("$setup.handleChange"),
            "handleChange should have $setup prefix in non-inline mode with bindings. Got:\n{}",
            result.code
        );
        // Verify options is in __returned__
        assert!(
            result.code.contains("options"),
            "options should be in __returned__. Got:\n{}",
            result.code
        );
        // Verify options.ssr access has $setup prefix
        assert!(
            result.code.contains("$setup.options"),
            "options.ssr should have $setup prefix. Got:\n{}",
            result.code
        );
        // Verify MonacoEditor is in __returned__ (imported component used in template)
        assert!(
            result.code.contains("MonacoEditor"),
            "MonacoEditor should be in __returned__. Got:\n{}",
            result.code
        );
    }

    #[test]
    #[ignore = "TODO: fix nested v-if prefix"]
    fn test_nested_v_if_no_double_prefix() {
        // Test with a component inside nested v-if to prevent hoisting
        let source = r#"<script setup lang="ts">
import { ref } from 'vue';
import CodeHighlight from './CodeHighlight.vue';
const output = ref(null);
</script>
<template>
<div v-if="output">
  <div v-if="output.preamble" class="preamble">
    <CodeHighlight :code="output.preamble" />
  </div>
</div>
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions::default();
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("=== NESTED V-IF OUTPUT ===\n{}", result.code);

        // Should NOT contain double $setup prefix
        assert!(
            !result.code.contains("$setup.$setup"),
            "Should NOT have double $setup prefix. Got:\n{}",
            result.code
        );

        // Should contain single $setup prefix for output
        assert!(
            result.code.contains("$setup.output"),
            "Should have single $setup prefix for output. Got:\n{}",
            result.code
        );

        // Should contain CodeHighlight component with :code prop
        assert!(
            result.code.contains("CodeHighlight"),
            "Should contain CodeHighlight. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_typescript_preserved_in_event_handler() {
        // When is_ts=true, TypeScript is preserved in the output
        // (matching Vue's @vue/compiler-sfc behavior - TS stripping is the bundler's job)
        let source = r#"<script setup lang="ts">
type PresetKey = 'a' | 'b'
function handlePresetChange(key: PresetKey) {}
</script>

<template>
  <select @change="handlePresetChange(($event.target).value)">
    <option value="a">A</option>
  </select>
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions {
            script: ScriptCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        // Print output for debugging
        eprintln!("TypeScript SFC output:\n{}", result.code);

        // TypeScript type alias should be preserved at module level
        assert!(
            result.code.contains("type PresetKey"),
            "Should preserve type alias with lang='ts'. Got:\n{}",
            result.code
        );
        // TypeScript function parameter types should be preserved in setup body
        assert!(
            result.code.contains("key: PresetKey"),
            "Should preserve function parameter type with lang='ts'. Got:\n{}",
            result.code
        );
        // Should have the event handler expression
        assert!(
            result.code.contains("handlePresetChange"),
            "Should have event handler. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_typescript_function_types_preserved() {
        // When is_ts=true, TypeScript is preserved in the output
        // (matching Vue's @vue/compiler-sfc behavior - TS stripping is the bundler's job)
        let source = r#"<script setup lang="ts">
interface Item {
  id: number;
  name: string;
}

const getNumberOfItems = (
  items: Item[]
): string => {
  return items.length.toString();
};

const foo: string = "bar";
const count: number = 42;

function processData(data: Record<string, unknown>): void {
  console.log(data);
}
</script>

<template>
  <div>{{ foo }}</div>
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions {
            script: ScriptCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("TypeScript function types output:\n{}", result.code);

        // TypeScript interface should be preserved at module level
        assert!(
            result.code.contains("interface Item"),
            "Should preserve interface with lang='ts'. Got:\n{}",
            result.code
        );
        // TypeScript annotations should be preserved in setup body
        assert!(
            result.code.contains(": Item[]"),
            "Should preserve array type annotation with lang='ts'. Got:\n{}",
            result.code
        );
        // Should contain the runtime logic
        assert!(
            result.code.contains("foo"),
            "Should have variable foo. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_full_sfc_props_destructure() {
        let input = r#"<script setup lang="ts">
import { computed } from 'vue'

const {
  name,
  count = 0,
} = defineProps<{
  name: string
  count?: number
}>()

const doubled = computed(() => count * 2)
</script>

<template>
  <div class="card">
    <h2>{{ name }}</h2>
    <p>Count: {{ count }} (doubled: {{ doubled }})</p>
  </div>
</template>"#;

        let parse_opts = SfcParseOptions::default();
        let descriptor = parse_sfc(input, parse_opts).unwrap();

        let mut compile_opts = SfcCompileOptions::default();
        compile_opts.script.id = Some("test.vue".to_string());
        let result = compile_sfc(&descriptor, compile_opts).unwrap();

        eprintln!("=== Full SFC props destructure output ===\n{}", result.code);

        // Props should use __props. prefix in template
        assert!(
            result.code.contains("__props.name") || result.code.contains("name"),
            "Should have name access. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_let_var_unref() {
        let input = r#"
<script setup>
const a = 1
let b = 2
var c = 3
</script>

<template>
  <div>{{ a }} {{ b }} {{ c }}</div>
</template>
"#;

        let parse_opts = SfcParseOptions::default();
        let descriptor = parse_sfc(input, parse_opts).unwrap();

        let mut compile_opts = SfcCompileOptions::default();
        compile_opts.script.id = Some("test.vue".to_string());
        let result = compile_sfc(&descriptor, compile_opts).unwrap();

        eprintln!("Let/var unref test output:\n{}", result.code);

        // Check that bindings are correctly identified
        if let Some(bindings) = &result.bindings {
            eprintln!("Bindings:");
            for (name, binding_type) in &bindings.bindings {
                eprintln!("  {} => {:?}", name, binding_type);
            }
            assert!(
                matches!(bindings.bindings.get("a"), Some(BindingType::LiteralConst)),
                "a should be LiteralConst"
            );
            assert!(
                matches!(bindings.bindings.get("b"), Some(BindingType::SetupLet)),
                "b should be SetupLet"
            );
            assert!(
                matches!(bindings.bindings.get("c"), Some(BindingType::SetupLet)),
                "c should be SetupLet"
            );
        }

        // Check for _unref import
        assert!(
            result.code.contains("unref as _unref"),
            "Should import _unref. Got:\n{}",
            result.code
        );

        // Check that let/var variables are wrapped with _unref
        // In inline mode, setup bindings are accessed directly (no $setup. prefix)
        assert!(
            result.code.contains("_unref(b)"),
            "b should be wrapped with _unref. Got:\n{}",
            result.code
        );
        assert!(
            result.code.contains("_unref(c)"),
            "c should be wrapped with _unref. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_extract_normal_script_content() {
        let input = r#"import type { NuxtRoute } from "@typed-router";
import { useBreakpoint } from "./_utils";
import Button from "./Button.vue";

interface TabItem {
  name: string;
  label: string;
}

export default {
  name: 'Tab'
}
"#;
        // Test preserving TypeScript output
        let result = extract_normal_script_content(input, true, true);
        eprintln!("Extracted normal script content (preserve TS):\n{}", result);

        // Should contain imports
        assert!(
            result.contains("import type { NuxtRoute }"),
            "Should contain type import"
        );
        assert!(
            result.contains("import { useBreakpoint }"),
            "Should contain named import"
        );
        assert!(
            result.contains("import Button"),
            "Should contain default import"
        );

        // Should contain interface
        assert!(
            result.contains("interface TabItem"),
            "Should contain interface"
        );

        // Should NOT contain export default
        assert!(
            !result.contains("export default"),
            "Should NOT contain export default"
        );
    }

    #[test]
    fn test_compile_both_script_blocks() {
        let source = r#"<script lang="ts">
import type { RouteLocation } from "vue-router";

interface TabItem {
  name: string;
  label: string;
}

export type { TabItem };
</script>

<script setup lang="ts">
const { items } = defineProps<{
  items: Array<TabItem>;
}>();
</script>

<template>
  <div v-for="item in items" :key="item.name">
    {{ item.label }}
  </div>
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        eprintln!(
            "Descriptor script: {:?}",
            descriptor.script.as_ref().map(|s| &s.content)
        );
        eprintln!(
            "Descriptor script_setup: {:?}",
            descriptor.script_setup.as_ref().map(|s| &s.content)
        );

        // Use is_ts = true to preserve TypeScript output
        let opts = SfcCompileOptions {
            script: ScriptCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            template: TemplateCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("=== COMPILED OUTPUT ===\n{}", result.code);

        // Should contain the type import (when is_ts = true, TypeScript is preserved)
        assert!(
            result.code.contains("RouteLocation") || result.code.contains("interface TabItem"),
            "Should contain type definitions from normal script. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_define_model_basic() {
        let source = r#"<script setup>
const model = defineModel()
</script>

<template>
  <input v-model="model">
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions::default();
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("=== defineModel OUTPUT ===\n{}", result.code);

        // Should have useModel import
        assert!(
            result.code.contains("useModel as _useModel"),
            "Should import useModel. Got:\n{}",
            result.code
        );

        // Should have modelValue prop
        assert!(
            result.code.contains("modelValue"),
            "Should have modelValue prop. Got:\n{}",
            result.code
        );

        // Should have update:modelValue emit
        assert!(
            result.code.contains("update:modelValue"),
            "Should have update:modelValue emit. Got:\n{}",
            result.code
        );

        // Should have _useModel call in setup
        assert!(
            result.code.contains("_useModel(__props"),
            "Should use _useModel in setup. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_define_model_with_name() {
        let source = r#"<script setup>
const title = defineModel('title')
</script>

<template>
  <input v-model="title">
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");
        let opts = SfcCompileOptions::default();
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("=== defineModel with name OUTPUT ===\n{}", result.code);

        // Should have title prop
        assert!(
            result.code.contains("title:") || result.code.contains("\"title\""),
            "Should have title prop. Got:\n{}",
            result.code
        );

        // Should have update:title emit
        assert!(
            result.code.contains("update:title"),
            "Should have update:title emit. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_non_script_setup_typescript_preserved() {
        // Non-script-setup SFC with is_ts=true preserves TypeScript in the output
        // (matching Vue's @vue/compiler-sfc behavior - TS stripping is the bundler's job)
        let source = r#"<script lang="ts">
interface Props {
    name: string;
    count?: number;
}

export default {
    name: 'MyComponent',
    props: {
        name: String,
        count: Number
    } as Props,
    setup(props: Props) {
        const message: string = `Hello, ${props.name}!`;
        return { message };
    }
}
</script>

<template>
    <div>{{ message }}</div>
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");

        let opts = SfcCompileOptions {
            script: ScriptCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!("=== Non-script-setup TS output ===\n{}", result.code);

        // TypeScript should be preserved when is_ts=true
        assert!(
            result.code.contains("interface Props") || result.code.contains(": Props"),
            "Should preserve TypeScript with is_ts=true. Got:\n{}",
            result.code
        );

        // Should still contain the component logic
        assert!(
            result.code.contains("name: 'MyComponent'")
                || result.code.contains("name: \"MyComponent\""),
            "Should have component name. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_non_script_setup_typescript_preserved_when_is_ts() {
        // Non-script-setup SFC with lang="ts" and is_ts=true should preserve TypeScript
        let source = r#"<script lang="ts">
interface Props {
    name: string;
}

export default {
    props: {} as Props
}
</script>

<template>
    <div></div>
</template>"#;

        let descriptor =
            parse_sfc(source, SfcParseOptions::default()).expect("Failed to parse SFC");

        // Compile with is_ts = true to preserve TypeScript
        let opts = SfcCompileOptions {
            script: ScriptCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            template: TemplateCompileOptions {
                is_ts: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let result = compile_sfc(&descriptor, opts).expect("Failed to compile SFC");

        eprintln!(
            "=== Non-script-setup TS preserved output ===\n{}",
            result.code
        );

        // Should still contain TypeScript syntax when is_ts = true
        assert!(
            result.code.contains("interface Props") || result.code.contains("as Props"),
            "Should preserve TypeScript when is_ts = true. Got:\n{}",
            result.code
        );
    }
}