vize_atelier_core 0.232.0

Atelier Core - The core workshop for Vize Vue template parsing, transform lanes, and code generation
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
//! Snapshot and assertion tests for codegen.

use crate::compile;

fn result_output(result: &super::CodegenResult) -> vize_carton::String {
    let mut output =
        vize_carton::String::with_capacity(result.preamble.len() + result.code.len() + 1);
    output.push_str(&result.preamble);
    output.push('\n');
    output.push_str(&result.code);
    output
}

macro_rules! assert_codegen_snapshot {
    ($result:expr) => {{
        let output = result_output(&$result);
        insta::assert_snapshot!(output.as_str());
    }};
}

#[test]
fn test_codegen_simple_element() {
    let result = compile!("<div>hello</div>");
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_interpolation() {
    // When prefix_identifiers is false (default), expressions are not prefixed with _ctx.
    let result = compile!("<div>{{ msg }}</div>");
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_with_props() {
    let result = compile!(r#"<div id="app" class="container"></div>"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_component() {
    let result = compile!("<MyComponent />");
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_component_name_with_colon_uses_valid_identifier() {
    let allocator = bumpalo::Bump::new();
    let parser_opts = crate::ParserOptions {
        is_native_tag: Some(vize_carton::is_native_tag),
        ..Default::default()
    };
    let (mut root, errors) = crate::parse_with_options(
        &allocator,
        r#"<global:head title="Page Title" />"#,
        parser_opts,
    );
    assert!(errors.is_empty(), "Parse errors: {:?}", errors);

    crate::lane::transform(
        &allocator,
        &mut root,
        crate::TransformOptions::default(),
        None,
    );
    let output = result_output(&super::generate(&root, crate::CodegenOptions::default()));

    // Vue encodes non-word characters by char code (`:` -> 58), matching
    // `toValidAssetId` (issue #4422).
    assert!(output.contains(r#"const _component_global58head = _resolveComponent("global:head")"#));
    assert!(output.contains("_createBlock(_component_global58head"));
    assert!(!output.contains("_component_global:head"));
}

#[test]
fn test_codegen_self_component_resolve_marks_maybe_self_reference() {
    let result = compile!(
        "<FileTree />",
        super::CodegenOptions {
            component_name: Some("FileTree".into()),
            ..Default::default()
        }
    );
    let output = result_output(&result);

    assert!(
        output.contains(r#"const _component_FileTree = _resolveComponent("FileTree", true)"#),
        "self component resolution should pass maybeSelfReference. Got:\n{}",
        output
    );
}

#[test]
fn test_codegen_inline_setup_ref_component_prop_uses_value() {
    let allocator = bumpalo::Bump::new();
    let (mut root, errors) = crate::parse(&allocator, r#"<Child :initialText="initialText" />"#);
    assert!(errors.is_empty(), "Parse errors: {:?}", errors);

    let mut bindings = vize_carton::FxHashMap::default();
    bindings.insert("Child".into(), crate::BindingType::SetupConst);
    bindings.insert("initialText".into(), crate::BindingType::SetupRef);
    let binding_metadata = crate::BindingMetadata {
        bindings,
        props_aliases: vize_carton::FxHashMap::default(),
        is_script_setup: true,
    };

    crate::lane::transform(
        &allocator,
        &mut root,
        crate::TransformOptions {
            prefix_identifiers: true,
            inline: true,
            binding_metadata: Some(binding_metadata.clone()),
            ..Default::default()
        },
        None,
    );

    let output = result_output(&super::generate(
        &root,
        crate::CodegenOptions {
            prefix_identifiers: true,
            inline: true,
            binding_metadata: Some(binding_metadata),
            ..Default::default()
        },
    ));

    assert!(
        output.contains("initialText: initialText.value"),
        "component prop should unwrap setup refs in inline mode. Got:\n{}",
        output
    );
}

#[test]
fn test_root_directive_comment_does_not_create_fragment_hole() {
    let result =
        compile!("<!-- @vize:forget sections are labeled by their headings --><section></section>");

    assert_codegen_snapshot!(result);
}

#[test]
fn test_root_only_directive_comment_compiles_to_null() {
    let result = compile!("<!-- @vize:forget no render output -->");

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_pascal_case_dynamic_component() {
    let result = compile!(r#"<Component :is="current" :active-class="klass" />"#);

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_pascal_case_dynamic_component_inside_v_for() {
    let result =
        compile!(r#"<Component :is="item.component" v-for="item in items" :key="item.id" />"#);

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_numeric_component_v_for_uses_component_block() {
    let result = compile!(r#"<Child v-for="(id, index) in 4" :key="id" :label="String(index)" />"#);

    assert!(
        result.code.contains("_createBlock(_component_Child"),
        "numeric component v-for should render a component block. Got:\n{}",
        result.code
    );
    assert!(
        !result.code.contains(r#"_createElementVNode("Child""#),
        "numeric component v-for must not render Child as a native element. Got:\n{}",
        result.code
    );
}

#[test]
fn test_codegen_duplicate_attribute_keeps_first_occurrence() {
    // Regression for #958: a `<div id="a" id="b">x</div>` template
    // used to produce a 0-byte module marked as success because the
    // parser pushed a fatal-looking diagnostic and the SFC lane
    // discarded the template output. Codegen now dedupes by
    // attribute name (Vue parity: first wins); the parser
    // diagnostic is classified as recoverable so downstream
    // continues. The compile macro bails on parse errors, so this
    // test drives the lane by hand.
    let allocator = bumpalo::Bump::new();
    let (mut root, errors) = crate::parser::parse(&allocator, r#"<div id="a" id="b">x</div>"#);
    assert!(
        errors
            .iter()
            .any(|e| e.code == vize_relief::errors::ErrorCode::DuplicateAttribute),
        "expected a DuplicateAttribute diagnostic, got {errors:?}"
    );
    assert!(errors.iter().all(|e| e.is_recoverable()));
    crate::lane::transform(
        &allocator,
        &mut root,
        crate::options::TransformOptions::default(),
        None,
    );
    let result = crate::codegen::generate(&root, crate::options::CodegenOptions::default());
    assert!(!result.code.is_empty(), "compiled output must not be empty");
    assert!(
        result.code.contains(r#"id: "a""#),
        "expected first `id` to be retained, got:\n{}",
        result.code
    );
    assert!(
        !result.code.contains(r#"id: "b""#),
        "expected duplicate `id` to be dropped, got:\n{}",
        result.code
    );
}

#[test]
fn test_codegen_v_if_nested_branch_keys_reset_per_scope() {
    // Regression for #961 (Vue-parity): a nested v-if (inside another
    // v-if's branch) starts its key counter at 0 again, matching Vue's
    // recursive transform. Without the per-branch reset, sibling
    // sub-chains would consume keys from the outer counter and drift
    // from `@vue/compiler-sfc`.
    let result = compile!(r#"<div v-if="a"><span v-if="b">B</span><span v-else>C</span></div>"#);
    // Outer key 0, inner keys 0 and 1.
    let key_count_0 = result.code.matches("{ key: 0 }").count();
    assert!(
        key_count_0 >= 2,
        "expected outer + inner key 0 (>=2 occurrences), got {key_count_0}:\n{}",
        result.code
    );
    assert!(
        result.code.contains("{ key: 1 }"),
        "missing inner key 1:\n{}",
        result.code
    );
}

#[test]
fn test_codegen_v_if_sibling_chains_allocate_unique_branch_keys() {
    // Regression for #961: sibling `v-if`/`v-else` blocks must get keys
    // from a template-wide counter (Vue parity: 0,1,2,3 — not the
    // per-chain 0,1,0,1 vize used to emit), so a patch can't reuse a
    // first-block element for a second-block element.
    let result = compile!(
        r#"<div><div v-if="a">A</div><div v-else>B</div><div v-if="c">C</div><div v-else>D</div></div>"#
    );

    assert!(
        result.code.contains("{ key: 0 }"),
        "missing key 0:\n{}",
        result.code
    );
    assert!(
        result.code.contains("{ key: 1 }"),
        "missing key 1:\n{}",
        result.code
    );
    assert!(
        result.code.contains("{ key: 2 }"),
        "missing key 2:\n{}",
        result.code
    );
    assert!(
        result.code.contains("{ key: 3 }"),
        "missing key 3:\n{}",
        result.code
    );
}

#[test]
fn test_codegen_v_if_template_fragment_wraps_interpolation_in_text_vnode() {
    let result = compile!(
        r#"<p><template v-if="ready">{{ count }}</template><span v-if="pending">updating</span></p>"#
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_if_template_fragment_wraps_static_text_in_text_vnode() {
    let result = compile!(
        r#"<div><template v-if="ready">Found packages</template><span v-if="pending">updating</span></div>"#
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_preamble_module() {
    use crate::options::CodegenMode;
    let options = super::CodegenOptions {
        mode: CodegenMode::Module,
        ..Default::default()
    };
    let result = compile!("<div>hello</div>", options);
    insta::assert_snapshot!(result.preamble.as_str());
}

#[test]
fn test_codegen_v_model_on_component() {
    let result = compile!(r#"<MyComponent v-model="msg" />"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_model_with_arg() {
    let result = compile!(r#"<MyComponent v-model:title="pageTitle" />"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_model_on_input() {
    let result = compile!(r#"<input v-model="inputValue" />"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_model_without_expression_omits_empty_directive_binding() {
    let result = compile!(r#"<input v-model />"#);
    let output = result_output(&result);

    assert!(
        !output.contains("_vModelText, ]"),
        "value-less v-model must not emit malformed directive bindings:\n{}",
        output
    );
    assert!(
        !output.contains("_withDirectives"),
        "value-less native v-model should be removed before directive codegen:\n{}",
        output
    );
    assert!(output.contains(r#"_createElementBlock("input")"#));
}

#[test]
fn test_codegen_v_model_on_input_with_custom_directive() {
    let result = compile!(r#"<input v-model="inputValue" v-example />"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_nested_v_model_on_input_with_custom_directive() {
    let result = compile!(r#"<div><input v-model="inputValue" v-example /></div>"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_model_with_other_props() {
    // v-model with other props should not produce comments
    let result = compile!(r#"<MonacoEditor v-model="source" :language="editorLanguage" />"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_slot_fallback() {
    let result = compile!(r#"<slot name="label">{{ label }}</slot>"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_slot_without_fallback() {
    // Slot element without fallback should not have empty object or function
    let result = compile!(r#"<slot name="header"></slot>"#);
    insta::assert_snapshot!(result.code.as_str());
}

#[test]
fn test_codegen_conditional_slot_outlet_with_bound_props_uses_render_slot() {
    let result = compile!(r#"<slot v-if="show" name="updater" v-bind="{ number, update }" />"#);
    let output = result_output(&result);

    assert!(
        output.contains(r#"_renderSlot(_ctx.$slots, "updater""#),
        "conditional slot outlet should use renderSlot. Got:\n{}",
        output
    );
    assert!(
        output.contains(r#"_mergeProps({ number, update }, { key: 0 })"#),
        "v-bind object props should be merged with the branch key. Got:\n{}",
        output
    );
    assert!(
        !output.contains(r#"_createElementBlock("slot""#)
            && !output.contains(r#"_createElementVNode("slot""#),
        "slot outlets should not be emitted as literal slot elements. Got:\n{}",
        output
    );
}

#[test]
fn test_codegen_v_for_slot_outlet_with_bound_props_uses_render_slot() {
    let result = compile!(
        r#"<slot v-for="(item, index) of items" v-bind="{ key: item.id }" :item="item" :index="index" />"#
    );
    let output = result_output(&result);

    assert!(
        output.contains(r#"_renderSlot(_ctx.$slots, "default""#),
        "v-for slot outlet should use renderSlot. Got:\n{}",
        output
    );
    assert!(
        output.contains(r#"_mergeProps({ key: item.id }, { item: item, index: index })"#),
        "slot v-bind object props should be preserved with explicit props. Got:\n{}",
        output
    );
    assert!(
        !output.contains(r#"_createElementBlock("slot""#)
            && !output.contains(r#"_createElementVNode("slot""#),
        "slot outlets should not be emitted as literal slot elements. Got:\n{}",
        output
    );
}

#[test]
fn test_codegen_conditional_slot_with_else_does_not_append_undefined() {
    let result = compile!(
        r#"<MyDialog>
  <template v-if="step === 1" #header>First</template>
  <template v-else #header>Second</template>
</MyDialog>"#
    );
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_conditional_named_slot_preserves_implicit_default_slot() {
    let result = compile!(
        r#"<Parent>
  Not rendering!
  <template v-if="showNamed" #named>
    Named content
  </template>
</Parent>"#
    );
    let output = result_output(&result);

    assert!(
        output.contains("default: _withCtx(() => ["),
        "implicit default slot should be generated when createSlots is used:\n{}",
        output
    );
    assert!(
        output.contains("Not rendering!"),
        "default slot text should be preserved:\n{}",
        output
    );
    assert!(
        output.contains("name: \"named\""),
        "conditional named slot should still be dynamic:\n{}",
        output
    );
}

#[test]
fn test_codegen_looped_slot_key_and_index_aliases_stay_local_in_dynamic_args() {
    use crate::lane::transform;
    use crate::options::{CodegenOptions, TransformOptions};
    use crate::parser::parse;
    use bumpalo::Bump;

    let allocator = Bump::new();
    let (mut root, _) = parse(
        &allocator,
        r#"<Comp>
  <template v-for="(item, idx) in list" #default>
    <div :[idx]="item"></div>
  </template>
  <template v-for="(val, key) in obj" #item>
    <button @[key]="val"></button>
  </template>
</Comp>"#,
    );

    transform(
        &allocator,
        &mut root,
        TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );

    let result = super::generate(
        &root,
        CodegenOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
    );
    let output = result_output(&result);

    assert!(
        output.contains("[idx || \"\"]"),
        "looped slot index alias should remain local in dynamic prop args:\n{}",
        output
    );
    assert!(
        output.contains("_toHandlerKey(key)"),
        "looped slot key alias should remain local in dynamic event args:\n{}",
        output
    );
    assert!(
        !output.contains("_ctx.idx") && !output.contains("_ctx.key"),
        "looped slot key/index aliases must not be prefixed as outer scope refs:\n{}",
        output
    );
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_default_slot_with_v_if_is_stable() {
    let result = compile!(
        r#"<PageWithHeader>
  <div v-if="tab === 'overview'">Overview</div>
  <div v-else-if="tab === 'emojis'">Emojis</div>
  <div v-else>Charts</div>
</PageWithHeader>"#
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_dynamic_keyed_slot_child_uses_block() {
    let result = compile!(
        r#"<PageWithHeader>
  <div :key="tab">
    <MkPagination :paginator="paginator">
      <template #default="{ items }">{{ items.length }}</template>
    </MkPagination>
  </div>
</PageWithHeader>"#
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_forwarded_default_slot_is_marked_forwarded() {
    let result = compile!(r#"<MkSwiper><slot /></MkSwiper>"#);

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_if_branch_mixed_children_wrap_interpolations_in_text_vnodes() {
    let result = compile!(
        r#"<p v-if="speaker.affiliation || speaker.title">{{ speaker.affiliation }}<br v-if="speaker.affiliation && speaker.title" />{{ speaker.title }}</p>"#
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_if_branch_mixed_children_wraps_interpolation_in_text_vnode() {
    let result = compile!(
        r#"<div><label v-if="show">{{ msg }}<span v-if="required">*</span></label></div>"#
    );

    assert!(
        result
            .code
            .contains("_createTextVNode(_toDisplayString(msg), 1 /* TEXT */)"),
        "mixed children inside v-if branch should wrap interpolation in createTextVNode. Got:\n{}",
        result.code
    );
    assert!(
        !result.code.contains("[_toDisplayString(msg),"),
        "v-if branch should not emit raw string children inside arrays. Got:\n{}",
        result.code
    );
}

#[test]
fn test_codegen_v_for_aliases_without_parentheses_stay_local() {
    use crate::lane::transform;
    use crate::options::{CodegenOptions, TransformOptions};
    use crate::parser::parse;
    use bumpalo::Bump;

    let allocator = Bump::new();
    let (mut root, _) = parse(
        &allocator,
        r#"<div><template v-for="item, index of items" :key="index"><UserCard :user="item" :data-index="index" /></template></div>"#,
    );

    transform(
        &allocator,
        &mut root,
        TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );

    let result = super::generate(
        &root,
        CodegenOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_numeric_template_v_for_uses_fragment() {
    let result = compile!(
        r#"<div><template v-for="n in 4" :key="`set-${n}`"><button></button><span v-for="(icon, i) in icons" :key="`${n}-${i}`" :class="icon"></span></template></div>"#
    );

    assert!(
        !result.code.contains("\"template\""),
        "template v-for must not create a DOM template element. Got:\n{}",
        result.code
    );
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_v_for_scope_handlers_are_not_cached() {
    use crate::lane::transform;
    use crate::options::{CodegenOptions, TransformOptions};
    use crate::parser::parse;
    use bumpalo::Bump;

    let allocator = Bump::new();
    let (mut root, _) = parse(
        &allocator,
        r#"<button v-for="tab in tabs" :key="tab.id" @click="select(tab)">{{ tab.label }}</button>"#,
    );

    transform(
        &allocator,
        &mut root,
        TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );

    let result = super::generate(
        &root,
        CodegenOptions {
            prefix_identifiers: true,
            cache_handlers: true,
            ..Default::default()
        },
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_merged_v_on_handlers_are_cached() {
    use crate::lane::transform;
    use crate::options::{CodegenOptions, TransformOptions};
    use crate::parser::parse;
    use bumpalo::Bump;

    let allocator = Bump::new();
    let (mut root, _) = parse(
        &allocator,
        r#"<div @click="() => x++" @click.stop="() => y++"></div>"#,
    );

    transform(
        &allocator,
        &mut root,
        TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );

    let result = super::generate(
        &root,
        CodegenOptions {
            prefix_identifiers: true,
            cache_handlers: true,
            ..Default::default()
        },
    );
    let output = result_output(&result);

    assert!(
            output.contains("onClick: [_cache[0] || (_cache[0] = () => _ctx.x++), _cache[1] || (_cache[1] = _withModifiers(() => _ctx.y++, [\"stop\"]))]"),
            "merged same-event handlers should each be cached. Got:\n{}",
            output
        );
    insta::assert_snapshot!(output.as_str());
}

#[test]
fn test_codegen_v_on_option_modifier_events_are_not_merged() {
    // Issue #1172: events differing only by an option modifier
    // (.once/.capture/.passive) must compile to distinct props and never
    // be merged under one key.
    let once = result_output(&compile!(r#"<div @click="a" @click.once="b"></div>"#));
    assert!(
        once.contains("onClick: a") && once.contains("onClickOnce: b"),
        "@click and @click.once should be distinct props. Got:\n{}",
        once
    );
    assert!(
        !once.contains("onClick: ["),
        "@click and @click.once must not be merged into an array. Got:\n{}",
        once
    );

    let capture = result_output(&compile!(r#"<div @click.capture="a" @click="b"></div>"#));
    assert!(
        capture.contains("onClickCapture: a") && capture.contains("onClick: b"),
        "@click.capture and @click should be distinct props. Got:\n{}",
        capture
    );
    assert!(
        !capture.contains("onClick: ["),
        "@click.capture and @click must not be merged into an array. Got:\n{}",
        capture
    );
}

#[test]
fn test_codegen_scoped_slot_params_stay_local_in_handlers() {
    use crate::lane::transform;
    use crate::options::{CodegenOptions, TransformOptions};
    use crate::parser::parse;
    use bumpalo::Bump;

    let allocator = Bump::new();
    let (mut root, _) = parse(
        &allocator,
        r#"<CommonPaginator>
  <template #default="{ item, index }">
    <button @click="showHistory(item)">{{ index }}</button>
    <button @click="() => edit(item.id)">{{ item.id }}</button>
  </template>
</CommonPaginator>"#,
    );

    transform(
        &allocator,
        &mut root,
        TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );

    let result = super::generate(
        &root,
        CodegenOptions {
            prefix_identifiers: true,
            cache_handlers: true,
            ..Default::default()
        },
    );

    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_escape_newline_in_attribute() {
    // Attribute values containing newlines should be properly escaped
    let result = compile!(
        r#"<div style="
            color: red;
            background: blue;
        "></div>"#
    );
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_escape_special_chars_in_attribute() {
    // Attribute values should escape backslashes and quotes
    let result = compile!(r#"<div data-value="line1\nline2"></div>"#);
    assert_codegen_snapshot!(result);
}

#[test]
fn test_codegen_escape_multiline_style_attribute() {
    // Complex multiline style attribute (real-world case from Discord issue)
    let result = compile!(
        r#"<div style="
            display: flex;
            flex-direction: column;
        "></div>"#
    );
    assert_codegen_snapshot!(result);
}

fn compile_prefixed(source: &str) -> vize_carton::String {
    let allocator = bumpalo::Bump::new();
    let (mut root, errors) = crate::parse(&allocator, source);
    assert!(errors.is_empty(), "Parse errors: {:?}", errors);
    crate::lane::transform(
        &allocator,
        &mut root,
        crate::TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );
    result_output(&super::generate(
        &root,
        crate::CodegenOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
    ))
}

#[test]
fn test_codegen_looped_slot_index_alias_is_slot_param_for_dynamic_arg() {
    // Issue #1173: the index alias of a v-for on a slot template must be
    // registered as a slot param so a dynamic arg derived from it is not
    // wrongly _ctx-prefixed.
    let output = compile_prefixed(
        r#"<Comp><template v-for="(item, idx) in list" #default><div :[idx]="item"></div></template></Comp>"#,
    );
    assert!(
        output.contains("[idx || \"\"]"),
        "index alias should be a local slot param, not _ctx-prefixed. Got:\n{}",
        output
    );
    assert!(
        !output.contains("_ctx.idx"),
        "index alias must not be _ctx-prefixed. Got:\n{}",
        output
    );
}

#[test]
fn test_codegen_looped_slot_key_alias_is_slot_param_for_dynamic_arg() {
    // Issue #1173: the key alias (object iteration) of a v-for on a slot
    // template must be registered as a slot param.
    let output = compile_prefixed(
        r#"<Comp><template v-for="(val, key) in obj" #default><div :[key]="val"></div></template></Comp>"#,
    );
    assert!(
        output.contains("[key || \"\"]"),
        "key alias should be a local slot param, not _ctx-prefixed. Got:\n{}",
        output
    );
    assert!(
        !output.contains("_ctx.key"),
        "key alias must not be _ctx-prefixed. Got:\n{}",
        output
    );
}

#[test]
fn test_codegen_static_style_merged_with_dynamic_escapes_values() {
    // Issue #1171: a static `style` merged with `:style` must JSON-escape
    // key/value so a `"` does not terminate the JS string early.
    let output = result_output(&compile!(r#"<div style='content:"x"' :style="s"></div>"#));
    assert!(
        output.contains(r#"_normalizeStyle([{"content":"\"x\""}, s])"#),
        "static style values must be escaped. Got:\n{}",
        output
    );
}

#[test]
fn test_codegen_static_style_merged_with_dynamic_does_not_split_inside_parens() {
    // Issue #1171: a `;` inside `url(...)` must not be treated as a
    // declaration separator, and no orphan double comma must appear.
    let output = result_output(&compile!(
        r#"<div style="background:url(a;b);color:red" :style="s"></div>"#
    ));
    assert!(
        output.contains(r#"_normalizeStyle([{"background":"url(a;b)","color":"red"}, s])"#),
        "`;` inside parens must not split the declaration. Got:\n{}",
        output
    );
    assert!(
        !output.contains(",,"),
        "orphan parts must not produce a double comma. Got:\n{}",
        output
    );
}

/// Vue 1.x triple-mustache (`{{{ html }}}`) is the pre-Vue-2 `v-html`
/// equivalent: under the Vue 1.x dialect it renders the expression unescaped,
/// so codegen emits the bare expression instead of wrapping it in
/// `_toDisplayString`. Under the default Vue 3 dialect (and the non-`legacy`
/// build) `{{{ x }}}` stays a `{{ … }}` mustache and is escaped as usual.
#[cfg(feature = "legacy")]
#[test]
fn test_codegen_v1_triple_mustache_is_raw_unescaped() {
    use crate::lane::transform;
    use crate::options::{CodegenOptions, ParserOptions, TransformOptions};
    use crate::parser::parse_with_options;
    use bumpalo::Bump;
    use vize_carton::config::VueVersion;

    let allocator = Bump::new();
    let mut options = ParserOptions::default();
    options.dialect = VueVersion::V1;
    let (mut root, errors) = parse_with_options(&allocator, "<div>{{{ rawHtml }}}</div>", options);
    assert!(errors.is_empty(), "Parse errors: {errors:?}");

    transform(
        &allocator,
        &mut root,
        TransformOptions {
            dialect: VueVersion::V1,
            ..Default::default()
        },
        None,
    );
    let result = super::generate(&root, CodegenOptions::default());

    // Raw interpolation: the expression is emitted directly, never escaped.
    assert!(
        result.code.contains("rawHtml"),
        "raw expression should appear in output. Got:\n{}",
        result.code
    );
    assert!(
        !result.code.contains("_toDisplayString(rawHtml)"),
        "raw-HTML interpolation must not be escaped through _toDisplayString. Got:\n{}",
        result.code
    );
}

/// The default Vue 3 dialect keeps `{{{ x }}}` as a `{{ … }}` mustache (with a
/// stray brace) followed by a `}` text node, and the interpolation is escaped —
/// byte-identical to the non-`legacy` build.
#[cfg(feature = "legacy")]
#[test]
fn test_codegen_triple_mustache_escaped_under_default_dialect() {
    let result = compile!("<div>{{{ rawHtml }}}</div>");
    assert!(
        result.code.contains("_toDisplayString"),
        "default dialect escapes the interpolation. Got:\n{}",
        result.code
    );
}

// --- Source Map v3 emission (#1533) -----------------------------------------

/// A single decoded `mappings` segment: 0-indexed generated line/column and the
/// source line/column it points back to, plus the optional `names`-array index
/// when the segment carried a 5th VLQ field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DecodedSegment {
    generated_line: u32,
    generated_column: u32,
    source_line: u32,
    source_column: u32,
    name: Option<u32>,
}

const VLQ_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Decode one base64-VLQ value from `bytes`, returning the value and how many
/// base64 digits it consumed. Independent decoder so the test does not lean on
/// the encoder it is meant to validate.
fn decode_one_vlq(bytes: &[u8]) -> (i64, usize) {
    let mut result: u64 = 0;
    let mut shift = 0u32;
    let mut consumed = 0usize;
    for &c in bytes {
        let digit = VLQ_CHARS
            .iter()
            .position(|&b| b == c)
            .expect("valid base64") as u64;
        consumed += 1;
        result |= (digit & 0b1_1111) << shift;
        shift += 5;
        if digit & 0b10_0000 == 0 {
            break;
        }
    }
    let negative = result & 1 != 0;
    let magnitude = (result >> 1) as i64;
    (if negative { -magnitude } else { magnitude }, consumed)
}

/// Decode a full v3 `mappings` string into absolute decoded segments.
fn decode_mappings(mappings: &str) -> Vec<DecodedSegment> {
    let mut out = Vec::new();
    // Source index/line/column and the name index accumulate across the whole
    // document; generated column resets at each generated line (each `;`). The
    // name index only advances on segments that carry the optional 5th field.
    let mut source_line = 0i64;
    let mut source_column = 0i64;
    let mut name_index = 0i64;

    for (generated_line, line) in mappings.split(';').enumerate() {
        let mut generated_column = 0i64;
        for seg in line.split(',').filter(|s| !s.is_empty()) {
            let bytes = seg.as_bytes();
            let (d_gen_col, c1) = decode_one_vlq(bytes);
            let (_d_src_idx, c2) = decode_one_vlq(&bytes[c1..]);
            let (d_src_line, c3) = decode_one_vlq(&bytes[c1 + c2..]);
            let (d_src_col, c4) = decode_one_vlq(&bytes[c1 + c2 + c3..]);
            generated_column += d_gen_col;
            source_line += d_src_line;
            source_column += d_src_col;
            // A 5th VLQ field, when present, is the delta-encoded name index.
            let consumed = c1 + c2 + c3 + c4;
            let name = if consumed < bytes.len() {
                let (d_name, _c5) = decode_one_vlq(&bytes[consumed..]);
                name_index += d_name;
                Some(name_index as u32)
            } else {
                None
            };
            out.push(DecodedSegment {
                generated_line: generated_line as u32,
                generated_column: generated_column as u32,
                source_line: source_line as u32,
                source_column: source_column as u32,
                name,
            });
        }
    }
    out
}

/// Compile a template with `prefix_identifiers` so dynamic expressions surface
/// as `_ctx.<name>` in the output (the interesting mapping case).
fn compile_with_map(src: &str, filename: &str) -> super::CodegenResult {
    let allocator = bumpalo::Bump::new();
    let (mut root, errors) = crate::parser::parse(&allocator, src);
    assert!(errors.is_empty(), "Parse errors: {:?}", errors);
    crate::lane::transform(
        &allocator,
        &mut root,
        crate::options::TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );
    super::generate(
        &root,
        crate::options::CodegenOptions {
            prefix_identifiers: true,
            source_map: true,
            filename: filename.into(),
            ..Default::default()
        },
    )
}

/// Find the 0-indexed (line, column) of the first byte of `needle` in `code`,
/// counting columns in UTF-16 code units to match the source-map convention.
fn generated_position_of(code: &str, needle: &str) -> (u32, u32) {
    let byte_idx = code.find(needle).expect("needle present in generated code");
    let prefix = &code[..byte_idx];
    let line = prefix.bytes().filter(|&b| b == b'\n').count() as u32;
    let line_start = prefix.rfind('\n').map(|i| i + 1).unwrap_or(0);
    let column = code[line_start..byte_idx]
        .chars()
        .map(|c| c.len_utf16() as u32)
        .sum();
    (line, column)
}

#[test]
fn source_map_disabled_by_default_yields_none() {
    let result = compile!("<div>{{ msg }}</div>");
    assert!(
        result.map.is_none(),
        "map must be None when source_map flag is off"
    );
}

#[test]
fn source_map_enabled_emits_valid_v3_document() {
    let result = compile_with_map("<div>{{ msg }}</div>", "Foo.vue");
    let map = result
        .map
        .expect("map should be Some when source_map is on");

    let parsed: serde_json::Value = serde_json::from_str(&map).expect("map must be valid JSON");
    assert_eq!(parsed["version"], 3, "must be a v3 source map");
    assert_eq!(parsed["sources"][0], "Foo.vue");
    assert_eq!(parsed["sourcesContent"][0], "<div>{{ msg }}</div>");
    assert!(
        parsed["mappings"].as_str().is_some_and(|m| !m.is_empty()),
        "mappings must be a non-empty string"
    );
}

#[test]
fn source_map_maps_known_expression_and_tag_positions() {
    let src = "<div>{{ msg }}</div>";
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let segments = decode_mappings(parsed["mappings"].as_str().unwrap());

    // The `msg` identifier in the template starts at line 0, column 8
    // (`<div>{{ ` is eight chars). Its generated occurrence is `_ctx.msg`.
    let (gen_line, gen_col) = generated_position_of(&result.code, "_ctx.msg");
    let expr_seg = segments
        .iter()
        .find(|s| s.generated_line == gen_line && s.generated_column == gen_col)
        .expect("a segment should anchor the generated _ctx.msg expression");
    assert_eq!(
        (expr_seg.source_line, expr_seg.source_column),
        (0, 8),
        "expression should map back to `msg` in the template"
    );

    // The `<div>` tag name is at line 0, column 0; generated as `"div"`.
    let (tag_line, tag_col) = generated_position_of(&result.code, "\"div\"");
    // The anchor points at the tag name itself (just inside the opening quote).
    let tag_seg = segments
        .iter()
        .find(|s| s.generated_line == tag_line && s.generated_column == tag_col + 1)
        .expect("a segment should anchor the generated tag-name string");
    assert_eq!(
        (tag_seg.source_line, tag_seg.source_column),
        (0, 0),
        "element tag should map back to the `<div>` open tag"
    );
}

#[test]
fn source_map_does_not_alter_generated_code() {
    // The hard invariant: enabling source maps is purely additive — the `code`
    // and `preamble` strings must be byte-for-byte identical with the flag off.
    let src = r#"<div :id="dynId" @click="onClick">{{ msg }}<span>{{ count }}</span></div>"#;

    let with_map = compile_with_map(src, "Foo.vue");

    let allocator = bumpalo::Bump::new();
    let (mut root, errors) = crate::parser::parse(&allocator, src);
    assert!(errors.is_empty(), "Parse errors: {:?}", errors);
    crate::lane::transform(
        &allocator,
        &mut root,
        crate::options::TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );
    let without_map = super::generate(
        &root,
        crate::options::CodegenOptions {
            prefix_identifiers: true,
            source_map: false,
            filename: "Foo.vue".into(),
            ..Default::default()
        },
    );

    assert_eq!(
        with_map.code.as_str(),
        without_map.code.as_str(),
        "generated code must be byte-identical regardless of source_map flag"
    );
    assert_eq!(
        with_map.preamble.as_str(),
        without_map.preamble.as_str(),
        "preamble must be byte-identical regardless of source_map flag"
    );
    assert!(with_map.map.is_some());
    assert!(without_map.map.is_none());
}

#[test]
fn source_map_handles_multiline_template() {
    // A template spanning multiple lines exercises non-zero source lines.
    let src = "<div>\n  {{ msg }}\n</div>";
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let segments = decode_mappings(parsed["mappings"].as_str().unwrap());

    // `msg` is on source line 1 (0-indexed), column 5 (`  {{ ` before it).
    let (gen_line, gen_col) = generated_position_of(&result.code, "_ctx.msg");
    let expr_seg = segments
        .iter()
        .find(|s| s.generated_line == gen_line && s.generated_column == gen_col)
        .expect("expression segment present");
    assert_eq!(
        (expr_seg.source_line, expr_seg.source_column),
        (1, 5),
        "expression should map to line 1, column 5 of the multiline template"
    );
}

/// Resolve `name` indices on decoded segments against the v3 `names` array,
/// returning the names of every segment that carried one (in segment order).
fn named_symbols<'a>(segments: &[DecodedSegment], names: &'a [serde_json::Value]) -> Vec<&'a str> {
    segments
        .iter()
        .filter_map(|s| s.name)
        .map(|i| names[i as usize].as_str().expect("names entry is a string"))
        .collect()
}

#[test]
fn source_map_anchors_static_attribute_name_and_value() {
    // `id="app"` is a static attribute. Both the generated prop key `id` and
    // the value literal `"app"` should map back to their source positions, and
    // the key's symbol should land in `names`.
    let src = r#"<div id="app">x</div>"#;
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let names = parsed["names"].as_array().unwrap();
    let segments = decode_mappings(parsed["mappings"].as_str().unwrap());

    // Source: `id` name starts at column 5 (`<div ` precedes it); its value
    // content `app` starts at column 9 (`<div id="` precedes it).
    let attr_name_seg = segments
        .iter()
        .find(|s| s.source_line == 0 && s.source_column == 5)
        .expect("a segment should anchor the static attribute name");
    assert!(
        attr_name_seg.name.is_some(),
        "static attribute name segment should carry a names index"
    );
    assert_eq!(
        names[attr_name_seg.name.unwrap() as usize],
        "id",
        "attribute name symbol should be recorded in `names`"
    );

    let value_col = src.find("app").unwrap() as u32;
    assert!(
        segments
            .iter()
            .any(|s| s.source_line == 0 && s.source_column == value_col),
        "a segment should anchor the static attribute value"
    );

    assert!(
        named_symbols(&segments, names).contains(&"id"),
        "`names` should contain the attribute key symbol"
    );
}

#[test]
fn source_map_anchors_text_vnode_content() {
    // A standalone text child becomes `_createTextVNode("hello")`; the string
    // literal should map back to the text's position in the template. Wrapping
    // the text in a `<pre>` keeps it from being hoisted/merged into the element.
    let src = "<div>{{ x }}hello</div>";
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let segments = decode_mappings(parsed["mappings"].as_str().unwrap());

    // `hello` starts at source column 12 (`<div>{{ x }}` precedes it).
    let text_col = src.find("hello").unwrap() as u32;
    let (gen_line, gen_col) = generated_position_of(&result.code, "\"hello\"");
    let text_seg = segments
        .iter()
        // The anchor points just inside the opening quote (col + 1).
        .find(|s| s.generated_line == gen_line && s.generated_column == gen_col + 1)
        .expect("a segment should anchor the generated text literal");
    assert_eq!(
        (text_seg.source_line, text_seg.source_column),
        (0, text_col),
        "text content should map back to its template position"
    );
}

#[test]
fn source_map_anchors_comment_vnode_content() {
    // An HTML comment becomes `_createCommentVNode("note")`; the string literal
    // should map back to the comment's position.
    let src = "<div><!--note--></div>";
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let segments = decode_mappings(parsed["mappings"].as_str().unwrap());

    let comment_byte = src.find("<!--note-->").unwrap() as u32;
    let (gen_line, gen_col) = generated_position_of(&result.code, "\"note\"");
    let comment_seg = segments
        .iter()
        .find(|s| s.generated_line == gen_line && s.generated_column == gen_col + 1)
        .expect("a segment should anchor the generated comment literal");
    assert_eq!(
        (comment_seg.source_line, comment_seg.source_column),
        (0, comment_byte),
        "comment content should map back to the `<!--` open position"
    );
}

#[test]
fn source_map_anchors_dynamic_prop_key_with_name() {
    // `:id="dynId"` generates an `id:` object key. The key should map back to
    // the v-bind argument and record `id` in `names`.
    let src = r#"<div :id="dynId">x</div>"#;
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let names = parsed["names"].as_array().unwrap();
    let segments = decode_mappings(parsed["mappings"].as_str().unwrap());

    // The v-bind arg `id` starts at source column 6 (`<div :` precedes it).
    let key_col = src.find(":id").unwrap() as u32 + 1;
    let key_seg = segments
        .iter()
        .find(|s| s.source_line == 0 && s.source_column == key_col && s.name.is_some())
        .expect("a named segment should anchor the v-bind prop key");
    assert_eq!(
        names[key_seg.name.unwrap() as usize],
        "id",
        "v-bind prop key symbol should be recorded in `names`"
    );
}

#[test]
fn source_map_names_array_deduplicates_repeated_symbols() {
    // The same static attribute name on two elements should yield a single
    // `names` entry shared by both segments.
    let src = r#"<div id="a"><span id="b">x</span></div>"#;
    let result = compile_with_map(src, "Foo.vue");
    let map = result.map.expect("map should be Some");
    let parsed: serde_json::Value = serde_json::from_str(&map).unwrap();
    let names = parsed["names"].as_array().unwrap();

    let id_count = names.iter().filter(|n| n.as_str() == Some("id")).count();
    assert_eq!(
        id_count, 1,
        "`id` should appear exactly once in `names` even across two elements"
    );
}

#[test]
fn source_map_static_attr_and_text_do_not_alter_generated_code() {
    // The additive invariant extended to the new anchor kinds: a template that
    // exercises static attributes, a dynamic prop key, text, and a comment must
    // still produce byte-identical `code`/`preamble` with source maps off.
    let src = r#"<div id="app" :title="t"><!--c-->hello {{ x }}</div>"#;

    let with_map = compile_with_map(src, "Foo.vue");

    let allocator = bumpalo::Bump::new();
    let (mut root, errors) = crate::parser::parse(&allocator, src);
    assert!(errors.is_empty(), "Parse errors: {:?}", errors);
    crate::lane::transform(
        &allocator,
        &mut root,
        crate::options::TransformOptions {
            prefix_identifiers: true,
            ..Default::default()
        },
        None,
    );
    let without_map = super::generate(
        &root,
        crate::options::CodegenOptions {
            prefix_identifiers: true,
            source_map: false,
            filename: "Foo.vue".into(),
            ..Default::default()
        },
    );

    assert_eq!(
        with_map.code.as_str(),
        without_map.code.as_str(),
        "generated code must be byte-identical regardless of source_map flag"
    );
    assert_eq!(
        with_map.preamble.as_str(),
        without_map.preamble.as_str(),
        "preamble must be byte-identical regardless of source_map flag"
    );
    assert!(without_map.map.is_none());
}