semver-analyzer-ts 0.0.4

TypeScript/JavaScript support for the semver-analyzer
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
//! Diff two `ComponentSourceProfile`s to produce `SourceLevelChange` entries.
//!
//! Each change is deterministic — a fact derived from comparing two AST-extracted
//! profiles. No confidence scores, no LLM involvement.

use crate::sd_types::{ComponentSourceProfile, SourceLevelCategory, SourceLevelChange};
use std::collections::BTreeSet;

/// Diff two component profiles and produce a list of source-level changes.
///
/// `old` is the profile from the previous version, `new` is the current version.
/// Both should be for the same component (same `name`).
pub fn diff_profiles(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
) -> Vec<SourceLevelChange> {
    let mut changes = Vec::new();
    let component = &new.name;

    diff_portal_usage(old, new, component, &mut changes);
    diff_context_dependencies(old, new, component, &mut changes);
    diff_context_providers(old, new, component, &mut changes);
    diff_forward_ref(old, new, component, &mut changes);
    diff_memo(old, new, component, &mut changes);
    diff_prop_defaults(old, new, component, &mut changes);
    diff_rendered_components(old, new, component, &mut changes);
    diff_dom_structure(old, new, component, &mut changes);
    diff_aria_attributes(old, new, component, &mut changes);
    diff_role_attributes(old, new, component, &mut changes);
    diff_data_attributes(old, new, component, &mut changes);
    diff_css_tokens(old, new, component, &mut changes);
    diff_prop_style_bindings(old, new, component, &mut changes);
    diff_managed_attributes(old, new, component, &mut changes);
    diff_children_slot(old, new, component, &mut changes);

    changes
}

// ── Portal usage ────────────────────────────────────────────────────────

fn diff_portal_usage(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    if old.uses_portal != new.uses_portal {
        let (desc, test_desc) = if new.uses_portal {
            (
                format!(
                    "{component} now uses createPortal — content renders outside the component's DOM subtree"
                ),
                Some("screen.getByText() and similar queries cannot find content rendered via portal. \
                     Use within(document.body).getByText() or configure baseElement in render options.".to_string()),
            )
        } else {
            (
                format!(
                    "{component} no longer uses createPortal — content renders inline in the component tree"
                ),
                Some("Content now renders inside the component tree. \
                     Remove any within(document.body) workarounds if they were used.".to_string()),
            )
        };

        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::PortalUsage,
            description: desc,
            old_value: Some(format!("uses_portal: {}", old.uses_portal)),
            new_value: Some(format!("uses_portal: {}", new.uses_portal)),
            has_test_implications: true,
            test_description: test_desc,
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }
}

// ── Context dependencies ────────────────────────────────────────────────

fn diff_context_dependencies(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Contexts added
    for ctx in &new.consumed_contexts {
        if !old.consumed_contexts.contains(ctx) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::ContextDependency,
                description: format!(
                    "{component} now requires {ctx} context provider. \
                     Rendering without this provider may cause runtime errors or incorrect behavior."
                ),
                old_value: None,
                new_value: Some(format!("useContext({ctx})")),
                has_test_implications: false,
                test_description: None,
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }

    // Contexts removed
    for ctx in &old.consumed_contexts {
        if !new.consumed_contexts.contains(ctx) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::ContextDependency,
                description: format!(
                    "{component} no longer consumes {ctx} context. \
                     It will no longer respond to changes from this provider."
                ),
                old_value: Some(format!("useContext({ctx})")),
                new_value: None,
                has_test_implications: false,
                test_description: None,
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── Context providers ───────────────────────────────────────────────────

fn diff_context_providers(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Provider added
    for ctx in &new.provided_contexts {
        if !old.provided_contexts.contains(ctx) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::ContextDependency,
                description: format!(
                    "{component} now provides {ctx} context to its children. \
                     Child components may now depend on this provider being present."
                ),
                old_value: None,
                new_value: Some(format!("<{ctx}.Provider>")),
                has_test_implications: true,
                test_description: Some(format!(
                    "Tests rendering children of {component} may need to account for \
                     the new {ctx} context provider."
                )),
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }

    // Provider removed — breaking for children that consumed it
    for ctx in &old.provided_contexts {
        if !new.provided_contexts.contains(ctx) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::ContextDependency,
                description: format!(
                    "{component} no longer provides {ctx} context. \
                     Child components that use useContext({ctx}) will receive the \
                     default value instead, which may cause runtime errors."
                ),
                old_value: Some(format!("<{ctx}.Provider>")),
                new_value: None,
                has_test_implications: true,
                test_description: Some(format!(
                    "Tests for child components of {component} that depend on {ctx} \
                     context will need to provide their own context wrapper."
                )),
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── forwardRef ──────────────────────────────────────────────────────────

fn diff_forward_ref(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    if old.is_forward_ref != new.is_forward_ref {
        let desc = if new.is_forward_ref {
            format!("{component} now forwards refs via forwardRef. Consumers can attach refs to the underlying DOM element.")
        } else {
            format!("{component} no longer forwards refs. Existing ref usage will stop working.")
        };

        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::ForwardRef,
            description: desc,
            old_value: Some(format!("is_forward_ref: {}", old.is_forward_ref)),
            new_value: Some(format!("is_forward_ref: {}", new.is_forward_ref)),
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }
}

// ── memo ────────────────────────────────────────────────────────────────

fn diff_memo(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    if old.is_memo != new.is_memo {
        let desc = if new.is_memo {
            format!("{component} is now wrapped in React.memo. It will skip re-renders when props are shallow-equal.")
        } else {
            format!("{component} is no longer wrapped in React.memo. It will re-render on every parent render.")
        };

        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::Memo,
            description: desc,
            old_value: Some(format!("is_memo: {}", old.is_memo)),
            new_value: Some(format!("is_memo: {}", new.is_memo)),
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }
}

// ── Prop defaults ───────────────────────────────────────────────────────

fn diff_prop_defaults(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Check for changed defaults
    for (prop, new_val) in &new.prop_defaults {
        match old.prop_defaults.get(prop) {
            Some(old_val) if old_val != new_val => {
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::PropDefault,
                    description: format!(
                        "Default value for '{prop}' prop on {component} changed from {old_val} to {new_val}"
                    ),
                    old_value: Some(old_val.clone()),
                    new_value: Some(new_val.clone()),
                    has_test_implications: false,
                    test_description: None,
                    element: None,
                    migration_from: None,
                    dependency_chain: None,
                });
            }
            None => {
                // New default added (prop existed but had no default, or prop is new)
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::PropDefault,
                    description: format!(
                        "Prop '{prop}' on {component} now has default value {new_val}"
                    ),
                    old_value: None,
                    new_value: Some(new_val.clone()),
                    has_test_implications: false,
                    test_description: None,
                    element: None,
                    migration_from: None,
                    dependency_chain: None,
                });
            }
            _ => {} // Same value, no change
        }
    }

    // Check for removed defaults
    for (prop, old_val) in &old.prop_defaults {
        if !new.prop_defaults.contains_key(prop) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::PropDefault,
                description: format!(
                    "Default value for '{prop}' prop on {component} removed (was {old_val})"
                ),
                old_value: Some(old_val.clone()),
                new_value: None,
                has_test_implications: false,
                test_description: None,
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── Rendered components ─────────────────────────────────────────────────

fn diff_rendered_components(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    let old_names: BTreeSet<&str> = old
        .rendered_components
        .iter()
        .map(|r| r.name.as_str())
        .collect();
    let new_names: BTreeSet<&str> = new
        .rendered_components
        .iter()
        .map(|r| r.name.as_str())
        .collect();

    for name in &new_names {
        if !old_names.contains(name) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::RenderedComponent,
                description: format!("{component} now internally renders {name}"),
                old_value: None,
                new_value: Some(name.to_string()),
                has_test_implications: false,
                test_description: None,
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }

    for name in &old_names {
        if !new_names.contains(name) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::RenderedComponent,
                description: format!("{component} no longer internally renders {name}"),
                old_value: Some(name.to_string()),
                new_value: None,
                has_test_implications: false,
                test_description: None,
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── DOM structure ───────────────────────────────────────────────────────

fn diff_dom_structure(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Elements added
    for (elem, count) in &new.rendered_elements {
        if !old.rendered_elements.contains_key(elem) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::DomStructure,
                description: format!("{component} now renders <{elem}> element"),
                old_value: None,
                new_value: Some(format!("<{elem}> (×{count})")),
                has_test_implications: true,
                test_description: Some(format!(
                    "New <{elem}> element may affect snapshot tests and DOM query selectors"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        }
    }

    // Elements removed
    for elem in old.rendered_elements.keys() {
        if !new.rendered_elements.contains_key(elem) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::DomStructure,
                description: format!("{component} no longer renders <{elem}> element"),
                old_value: Some(format!("<{elem}>")),
                new_value: None,
                has_test_implications: true,
                test_description: Some(format!(
                    "Removed <{elem}> element will break queries using this element type"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── ARIA attributes ─────────────────────────────────────────────────────

fn diff_aria_attributes(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Added
    for ((elem, attr), val) in &new.aria_attributes {
        if !old
            .aria_attributes
            .contains_key(&(elem.clone(), attr.clone()))
        {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::AriaChange,
                description: format!("{attr} attribute added to <{elem}> in {component}"),
                old_value: None,
                new_value: Some(val.clone()),
                has_test_implications: true,
                test_description: Some(format!(
                    "New {attr} on <{elem}> may affect getByRole/getByLabelText queries"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        } else if let Some(old_val) = old.aria_attributes.get(&(elem.clone(), attr.clone())) {
            if old_val != val {
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::AriaChange,
                    description: format!(
                        "{attr} on <{elem}> in {component} changed from '{old_val}' to '{val}'"
                    ),
                    old_value: Some(old_val.clone()),
                    new_value: Some(val.clone()),
                    has_test_implications: true,
                    test_description: Some(format!(
                        "Changed {attr} value will affect accessibility queries"
                    )),
                    element: Some(elem.clone()),
                    migration_from: None,
                    dependency_chain: None,
                });
            }
        }
    }

    // Removed
    for ((elem, attr), old_val) in &old.aria_attributes {
        if !new
            .aria_attributes
            .contains_key(&(elem.clone(), attr.clone()))
        {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::AriaChange,
                description: format!("{attr} attribute removed from <{elem}> in {component}"),
                old_value: Some(old_val.clone()),
                new_value: None,
                has_test_implications: true,
                test_description: Some(format!(
                    "Removed {attr} from <{elem}> will break queries using this attribute"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── Role attributes ─────────────────────────────────────────────────────

fn diff_role_attributes(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    for (elem, new_role) in &new.role_attributes {
        match old.role_attributes.get(elem) {
            Some(old_role) if old_role != new_role => {
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::RoleChange,
                    description: format!(
                        "role on <{elem}> in {component} changed from '{old_role}' to '{new_role}'"
                    ),
                    old_value: Some(old_role.clone()),
                    new_value: Some(new_role.clone()),
                    has_test_implications: true,
                    test_description: Some(format!(
                        "getByRole('{old_role}') must change to getByRole('{new_role}')"
                    )),
                    element: Some(elem.clone()),
                    migration_from: None,
                    dependency_chain: None,
                });
            }
            None => {
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::RoleChange,
                    description: format!("role='{new_role}' added to <{elem}> in {component}"),
                    old_value: None,
                    new_value: Some(new_role.clone()),
                    has_test_implications: true,
                    test_description: Some(format!(
                        "New role='{new_role}' on <{elem}> enables getByRole('{new_role}') queries"
                    )),
                    element: Some(elem.clone()),
                    migration_from: None,
                    dependency_chain: None,
                });
            }
            _ => {}
        }
    }

    for (elem, old_role) in &old.role_attributes {
        if !new.role_attributes.contains_key(elem) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::RoleChange,
                description: format!("role='{old_role}' removed from <{elem}> in {component}"),
                old_value: Some(old_role.clone()),
                new_value: None,
                has_test_implications: true,
                test_description: Some(format!(
                    "getByRole('{old_role}') will no longer find this element"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── Data attributes ─────────────────────────────────────────────────────

fn diff_data_attributes(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    for ((elem, attr), val) in &new.data_attributes {
        if !old
            .data_attributes
            .contains_key(&(elem.clone(), attr.clone()))
        {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::DataAttribute,
                description: format!("{attr} added to <{elem}> in {component}"),
                old_value: None,
                new_value: Some(val.clone()),
                has_test_implications: true,
                test_description: Some(format!(
                    "New {attr} on <{elem}> may affect getByTestId or OUIA selectors"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        }
    }

    for ((elem, attr), old_val) in &old.data_attributes {
        if !new
            .data_attributes
            .contains_key(&(elem.clone(), attr.clone()))
        {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::DataAttribute,
                description: format!("{attr} removed from <{elem}> in {component}"),
                old_value: Some(old_val.clone()),
                new_value: None,
                has_test_implications: true,
                test_description: Some(format!(
                    "Removed {attr} from <{elem}> will break selectors using this attribute"
                )),
                element: Some(elem.clone()),
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── CSS tokens ──────────────────────────────────────────────────────────

fn diff_css_tokens(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    for token in new.css_tokens_used.difference(&old.css_tokens_used) {
        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::CssToken,
            description: format!("{component} now uses CSS token {token}"),
            old_value: None,
            new_value: Some(token.clone()),
            has_test_implications: true,
            test_description: Some(format!(
                "New CSS class from {token} may affect toHaveClass assertions"
            )),
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }

    for token in old.css_tokens_used.difference(&new.css_tokens_used) {
        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::CssToken,
            description: format!("{component} no longer uses CSS token {token}"),
            old_value: Some(token.clone()),
            new_value: None,
            has_test_implications: true,
            test_description: Some(format!(
                "Removed CSS class from {token} will break toHaveClass assertions"
            )),
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }
}

// ── Prop-to-style bindings ──────────────────────────────────────────────

fn diff_prop_style_bindings(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Check each old binding: did the token disappear while the prop survived?
    for (prop, old_tokens) in &old.prop_style_bindings {
        let prop_still_exists = new.all_props.contains(prop);

        for token in old_tokens {
            let token_still_used = new.css_tokens_used.contains(token);
            let still_bound = new
                .prop_style_bindings
                .get(prop)
                .is_some_and(|t| t.contains(token));

            if prop_still_exists && !token_still_used {
                // The CSS token was removed entirely — prop is now a no-op
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::CssToken,
                    description: format!(
                        "{component} prop `{prop}` controlled CSS token `{token}` which has been removed — \
                         setting `{prop}` will have no visual effect"
                    ),
                    old_value: Some(format!("{prop}{token}")),
                    new_value: None,
                    has_test_implications: true,
                    test_description: Some(format!(
                        "Tests relying on `{prop}` to apply CSS class from `{token}` will no longer see that class"
                    )),
                    element: None,
                    migration_from: None,
                    dependency_chain: None,
                });
            } else if prop_still_exists && token_still_used && !still_bound {
                // The token still exists but the prop no longer controls it
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::CssToken,
                    description: format!(
                        "{component} prop `{prop}` no longer controls CSS token `{token}` — \
                         the class may now be applied unconditionally or via a different mechanism"
                    ),
                    old_value: Some(format!("{prop}{token}")),
                    new_value: None,
                    has_test_implications: true,
                    test_description: Some(format!(
                        "Tests toggling `{prop}` to control `{token}` may need updating"
                    )),
                    element: None,
                    migration_from: None,
                    dependency_chain: None,
                });
            }
        }
    }

    // Check for newly introduced bindings (informational)
    for (prop, new_tokens) in &new.prop_style_bindings {
        let is_new_prop = !old.all_props.contains(prop);
        let old_tokens = old.prop_style_bindings.get(prop);

        for token in new_tokens {
            let was_bound = old_tokens.is_some_and(|t| t.contains(token));

            if !is_new_prop && !was_bound {
                // Existing prop now controls a new style token
                changes.push(SourceLevelChange {
                    component: component.to_string(),
                    category: SourceLevelCategory::CssToken,
                    description: format!(
                        "{component} prop `{prop}` now controls CSS token `{token}`"
                    ),
                    old_value: None,
                    new_value: Some(format!("{prop}{token}")),
                    has_test_implications: true,
                    test_description: Some(format!(
                        "Setting `{prop}` will now apply CSS class from `{token}`"
                    )),
                    element: None,
                    migration_from: None,
                    dependency_chain: None,
                });
            }
        }
    }
}

// ── Managed attributes (prop overrides HTML attribute) ───────────────────

fn diff_managed_attributes(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    // Build lookup maps keyed by (prop_name, generator_function) for efficient diff
    let old_bindings: std::collections::HashSet<_> = old
        .managed_attributes
        .iter()
        .map(|b| (&b.prop_name, &b.generator_function))
        .collect();
    let new_bindings: std::collections::HashSet<_> = new
        .managed_attributes
        .iter()
        .map(|b| (&b.prop_name, &b.generator_function))
        .collect();

    // New managed attributes — component now overrides consumer-provided HTML attrs.
    // Only emit PropAttributeOverride changes for component-wins bindings.
    // Consumer-wins bindings (managed spread before rest) are tracked for
    // transitive behavioral change detection (Phase A.7) but don't generate
    // prop-override rules since the consumer can override the managed value.
    //
    // Also detects spread order transitions: when a binding existed in the old
    // version with `component_overrides: false` (consumer wins) and now has
    // `component_overrides: true` (component wins). This is the scenario where
    // consumer's explicit attribute values that worked before are now silently
    // overridden. (e.g., PF 5.3→5.4 changed OUIA spread order.)
    for binding in &new.managed_attributes {
        if !binding.component_overrides {
            continue;
        }
        let key = (&binding.prop_name, &binding.generator_function);

        // Check if the binding is brand new OR if it transitioned from consumer-wins
        let is_new_binding = !old_bindings.contains(&key);
        let old_was_consumer_wins = old.managed_attributes.iter().any(|b| {
            b.prop_name == binding.prop_name
                && b.generator_function == binding.generator_function
                && !b.component_overrides
        });

        if is_new_binding || old_was_consumer_wins {
            let attrs_list = if binding.overridden_attributes.is_empty() {
                "HTML attributes".to_string()
            } else {
                binding.overridden_attributes.join(", ")
            };

            let description = if old_was_consumer_wins {
                format!(
                    "{component}'s `{prop}` prop now silently overrides {attrs} via {func}(). \
                     Previously, consumer-provided values took precedence. \
                     Any explicit `{attrs}` attributes on this component will be ignored.",
                    prop = binding.prop_name,
                    attrs = attrs_list,
                    func = binding.generator_function,
                )
            } else {
                format!(
                    "{component}'s `{prop}` prop overrides {attrs} via {func}(). \
                     Use the `{prop}` prop instead of setting these HTML attributes directly.",
                    prop = binding.prop_name,
                    attrs = attrs_list,
                    func = binding.generator_function,
                )
            };

            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::PropAttributeOverride,
                description,
                old_value: if old_was_consumer_wins {
                    Some(format!(
                        "{}{} (consumer wins)",
                        binding.prop_name,
                        binding.overridden_attributes.join(", ")
                    ))
                } else {
                    None
                },
                new_value: Some(format!(
                    "{}{}{}",
                    binding.prop_name,
                    binding.overridden_attributes.join(", "),
                    if old_was_consumer_wins {
                        " (component wins)"
                    } else {
                        ""
                    }
                )),
                has_test_implications: true,
                test_description: Some(format!(
                    "DOM queries using {} will still work, but consumer code should \
                     use the `{}` prop for correct lifecycle management",
                    binding
                        .overridden_attributes
                        .first()
                        .unwrap_or(&"the managed attribute".to_string()),
                    binding.prop_name,
                )),
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }

    // Removed managed attributes — component no longer overrides.
    // Only emit for component-wins bindings (same filter as above).
    for binding in &old.managed_attributes {
        if !binding.component_overrides {
            continue;
        }
        let key = (&binding.prop_name, &binding.generator_function);
        if !new_bindings.contains(&key) {
            changes.push(SourceLevelChange {
                component: component.to_string(),
                category: SourceLevelCategory::PropAttributeOverride,
                description: format!(
                    "{component} no longer manages `{prop}` via {func}(). \
                     HTML attributes previously overridden by this prop can now be set directly.",
                    prop = binding.prop_name,
                    func = binding.generator_function,
                ),
                old_value: Some(format!(
                    "{}{}",
                    binding.prop_name,
                    binding.overridden_attributes.join(", ")
                )),
                new_value: None,
                has_test_implications: false,
                test_description: None,
                element: None,
                migration_from: None,
                dependency_chain: None,
            });
        }
    }
}

// ── Children slot ───────────────────────────────────────────────────────

fn diff_children_slot(
    old: &ComponentSourceProfile,
    new: &ComponentSourceProfile,
    component: &str,
    changes: &mut Vec<SourceLevelChange>,
) {
    if old.children_slot_path != new.children_slot_path
        && !old.children_slot_path.is_empty()
        && !new.children_slot_path.is_empty()
    {
        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::Composition,
            description: format!(
                "Internal wrapper structure around children in {component} changed from {} to {}",
                old.children_slot_path.join(" > "),
                new.children_slot_path.join(" > "),
            ),
            old_value: Some(old.children_slot_path.join(" > ")),
            new_value: Some(new.children_slot_path.join(" > ")),
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }

    if old.has_children_prop && !new.has_children_prop {
        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::Composition,
            description: format!("{component} no longer accepts children"),
            old_value: Some("children: React.ReactNode".into()),
            new_value: None,
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }

    if !old.has_children_prop && new.has_children_prop {
        changes.push(SourceLevelChange {
            component: component.to_string(),
            category: SourceLevelCategory::Composition,
            description: format!("{component} now accepts children"),
            old_value: None,
            new_value: Some("children: React.ReactNode".into()),
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: None,
            dependency_chain: None,
        });
    }
}

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

    fn make_profile(name: &str) -> ComponentSourceProfile {
        ComponentSourceProfile {
            name: name.to_string(),
            ..Default::default()
        }
    }

    #[test]
    fn test_diff_portal_added() {
        let old = make_profile("Dropdown");
        let mut new = make_profile("Dropdown");
        new.uses_portal = true;

        let changes = diff_profiles(&old, &new);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].category, SourceLevelCategory::PortalUsage);
        assert!(changes[0].has_test_implications);
        assert!(changes[0].test_description.is_some());
    }

    #[test]
    fn test_diff_context_added() {
        let old = make_profile("AccordionContent");
        let mut new = make_profile("AccordionContent");
        new.consumed_contexts = vec!["AccordionItemContext".into()];

        let changes = diff_profiles(&old, &new);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].category, SourceLevelCategory::ContextDependency);
        assert!(changes[0].description.contains("AccordionItemContext"));
    }

    #[test]
    fn test_diff_prop_default_changed() {
        let mut old = make_profile("Button");
        old.prop_defaults
            .insert("variant".into(), "'primary'".into());

        let mut new = make_profile("Button");
        new.prop_defaults
            .insert("variant".into(), "'secondary'".into());

        let changes = diff_profiles(&old, &new);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].category, SourceLevelCategory::PropDefault);
        assert!(changes[0].description.contains("primary"));
        assert!(changes[0].description.contains("secondary"));
    }

    #[test]
    fn test_diff_no_changes() {
        let mut profile = make_profile("Button");
        profile.uses_portal = false;
        profile
            .prop_defaults
            .insert("variant".into(), "'primary'".into());

        let changes = diff_profiles(&profile, &profile);
        assert!(changes.is_empty());
    }

    #[test]
    fn test_diff_role_changed() {
        let mut old = make_profile("Menu");
        old.role_attributes.insert("ul".into(), "menu".into());

        let mut new = make_profile("Menu");
        new.role_attributes.insert("ul".into(), "listbox".into());

        let changes = diff_profiles(&old, &new);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].category, SourceLevelCategory::RoleChange);
        assert!(changes[0]
            .test_description
            .as_ref()
            .unwrap()
            .contains("getByRole"));
    }

    #[test]
    fn test_diff_forward_ref_added() {
        let old = make_profile("Input");
        let mut new = make_profile("Input");
        new.is_forward_ref = true;

        let changes = diff_profiles(&old, &new);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].category, SourceLevelCategory::ForwardRef);
    }

    #[test]
    fn test_diff_css_token_changes() {
        let mut old = make_profile("Menu");
        old.css_tokens_used.insert("styles.menu".into());
        old.css_tokens_used.insert("styles.menuOldToken".into());

        let mut new = make_profile("Menu");
        new.css_tokens_used.insert("styles.menu".into());
        new.css_tokens_used.insert("styles.menuNewToken".into());

        let changes = diff_profiles(&old, &new);
        assert_eq!(changes.len(), 2); // one removed, one added
        let categories: Vec<_> = changes.iter().map(|c| &c.category).collect();
        assert!(categories
            .iter()
            .all(|c| **c == SourceLevelCategory::CssToken));
    }

    // ── Prop-to-style binding diff tests ───────────────────────────────

    /// Simulates the real PatternFly scenario: Menu's `isScrollable` prop
    /// controls `styles.modifiers.scrollable`. In the new version, the CSS
    /// token is removed but the prop remains — making it a silent no-op.
    #[test]
    fn test_diff_prop_style_binding_token_removed() {
        let mut old = make_profile("Menu");
        old.all_props.insert("isScrollable".into());
        old.all_props.insert("isPlain".into());
        old.css_tokens_used.insert("styles.menu".into());
        old.css_tokens_used
            .insert("styles.modifiers.scrollable".into());
        old.css_tokens_used.insert("styles.modifiers.plain".into());
        old.prop_style_bindings.insert(
            "isScrollable".into(),
            BTreeSet::from(["styles.modifiers.scrollable".to_string()]),
        );
        old.prop_style_bindings.insert(
            "isPlain".into(),
            BTreeSet::from(["styles.modifiers.plain".to_string()]),
        );

        // New version: `isScrollable` prop still exists but its CSS token is gone.
        // `isPlain` is unchanged.
        let mut new = make_profile("Menu");
        new.all_props.insert("isScrollable".into());
        new.all_props.insert("isPlain".into());
        new.css_tokens_used.insert("styles.menu".into());
        // styles.modifiers.scrollable REMOVED from css_tokens_used
        new.css_tokens_used.insert("styles.modifiers.plain".into());
        new.prop_style_bindings.insert(
            "isPlain".into(),
            BTreeSet::from(["styles.modifiers.plain".to_string()]),
        );

        let changes = diff_profiles(&old, &new);

        // Should have changes for:
        // 1. The css_tokens_used diff (scrollable removed) — from diff_css_tokens
        // 2. The prop-style binding break — from diff_prop_style_bindings
        let binding_changes: Vec<_> = changes
            .iter()
            .filter(|c| {
                c.description.contains("isScrollable") && c.description.contains("no visual effect")
            })
            .collect();
        assert_eq!(
            binding_changes.len(),
            1,
            "Expected one no-op prop change for isScrollable, got: {binding_changes:?}"
        );

        let change = &binding_changes[0];
        assert_eq!(change.category, SourceLevelCategory::CssToken);
        assert!(change.has_test_implications);
        assert!(
            change.description.contains("styles.modifiers.scrollable"),
            "Description should reference the removed token"
        );
    }

    /// The prop is removed along with the token — this is a clean removal,
    /// NOT a no-op. The prop-style diff should produce no change because
    /// the prop itself is gone (the structural diff handles prop removals).
    #[test]
    fn test_diff_prop_style_binding_both_prop_and_token_removed() {
        let mut old = make_profile("Menu");
        old.all_props.insert("isScrollable".into());
        old.css_tokens_used
            .insert("styles.modifiers.scrollable".into());
        old.prop_style_bindings.insert(
            "isScrollable".into(),
            BTreeSet::from(["styles.modifiers.scrollable".to_string()]),
        );

        // New version: prop AND token both removed
        let new = make_profile("Menu");

        let changes = diff_profiles(&old, &new);

        // The prop-style diff should NOT emit a no-op warning because the
        // prop itself was removed. Only the css_tokens diff should fire.
        let noop_changes: Vec<_> = changes
            .iter()
            .filter(|c| c.description.contains("no visual effect"))
            .collect();
        assert!(
            noop_changes.is_empty(),
            "No no-op warning expected when prop is also removed: {noop_changes:?}"
        );
    }

    /// The binding is removed but the token still exists — the prop no
    /// longer controls the class (it might be applied unconditionally now).
    #[test]
    fn test_diff_prop_style_binding_decoupled() {
        let mut old = make_profile("Menu");
        old.all_props.insert("isScrollable".into());
        old.css_tokens_used.insert("styles.menu".into());
        old.css_tokens_used
            .insert("styles.modifiers.scrollable".into());
        old.prop_style_bindings.insert(
            "isScrollable".into(),
            BTreeSet::from(["styles.modifiers.scrollable".to_string()]),
        );

        // New version: token still exists, prop still exists, but the
        // binding is gone (class now applied unconditionally)
        let mut new = make_profile("Menu");
        new.all_props.insert("isScrollable".into());
        new.css_tokens_used.insert("styles.menu".into());
        new.css_tokens_used
            .insert("styles.modifiers.scrollable".into());
        // No prop_style_bindings entry for isScrollable

        let changes = diff_profiles(&old, &new);

        let decoupled: Vec<_> = changes
            .iter()
            .filter(|c| {
                c.description.contains("isScrollable")
                    && c.description.contains("no longer controls")
            })
            .collect();
        assert_eq!(
            decoupled.len(),
            1,
            "Expected one decoupled change for isScrollable: {decoupled:?}"
        );
    }

    /// New binding introduced on an existing prop — informational change.
    #[test]
    fn test_diff_prop_style_binding_new_binding() {
        let mut old = make_profile("Card");
        old.all_props.insert("isCompact".into());
        old.css_tokens_used.insert("styles.card".into());
        // No binding in old version

        let mut new = make_profile("Card");
        new.all_props.insert("isCompact".into());
        new.css_tokens_used.insert("styles.card".into());
        new.css_tokens_used
            .insert("styles.modifiers.compact".into());
        new.prop_style_bindings.insert(
            "isCompact".into(),
            BTreeSet::from(["styles.modifiers.compact".to_string()]),
        );

        let changes = diff_profiles(&old, &new);

        let new_binding: Vec<_> = changes
            .iter()
            .filter(|c| {
                c.description.contains("isCompact") && c.description.contains("now controls")
            })
            .collect();
        assert_eq!(
            new_binding.len(),
            1,
            "Expected one new-binding change for isCompact: {new_binding:?}"
        );
    }

    /// No changes when both profiles have identical bindings.
    #[test]
    fn test_diff_prop_style_binding_no_changes() {
        let mut profile = make_profile("Menu");
        profile.all_props.insert("isScrollable".into());
        profile
            .css_tokens_used
            .insert("styles.modifiers.scrollable".into());
        profile.prop_style_bindings.insert(
            "isScrollable".into(),
            BTreeSet::from(["styles.modifiers.scrollable".to_string()]),
        );

        let changes = diff_profiles(&profile, &profile);

        let binding_changes: Vec<_> = changes
            .iter()
            .filter(|c| c.description.contains("isScrollable"))
            .collect();
        assert!(
            binding_changes.is_empty(),
            "No binding changes expected for identical profiles"
        );
    }

    // ── Managed attribute diff tests ────────────────────────────────────

    #[test]
    fn test_diff_managed_attribute_added() {
        use crate::sd_types::ManagedAttributeBinding;

        let old = make_profile("MenuToggle");
        let mut new = make_profile("MenuToggle");
        new.managed_attributes.push(ManagedAttributeBinding {
            prop_name: "ouiaId".into(),
            generator_function: "getOUIAProps".into(),
            target_element: "button".into(),
            overridden_attributes: vec![
                "data-ouia-component-id".into(),
                "data-ouia-component-type".into(),
            ],
            component_overrides: true,
        });

        let changes = diff_profiles(&old, &new);
        let managed: Vec<_> = changes
            .iter()
            .filter(|c| c.category == SourceLevelCategory::PropAttributeOverride)
            .collect();
        assert_eq!(
            managed.len(),
            1,
            "Expected one PropAttributeOverride change"
        );
        assert!(managed[0].description.contains("ouiaId"));
        assert!(managed[0].description.contains("getOUIAProps"));
        assert!(managed[0].has_test_implications);
    }

    #[test]
    fn test_diff_managed_attribute_removed() {
        use crate::sd_types::ManagedAttributeBinding;

        let mut old = make_profile("MenuToggle");
        old.managed_attributes.push(ManagedAttributeBinding {
            prop_name: "ouiaId".into(),
            generator_function: "getOUIAProps".into(),
            target_element: "button".into(),
            overridden_attributes: vec!["data-ouia-component-id".into()],
            component_overrides: true,
        });
        let new = make_profile("MenuToggle");

        let changes = diff_profiles(&old, &new);
        let managed: Vec<_> = changes
            .iter()
            .filter(|c| c.category == SourceLevelCategory::PropAttributeOverride)
            .collect();
        assert_eq!(managed.len(), 1);
        assert!(managed[0].description.contains("no longer manages"));
    }

    #[test]
    fn test_diff_managed_attribute_no_change() {
        use crate::sd_types::ManagedAttributeBinding;

        let binding = ManagedAttributeBinding {
            prop_name: "ouiaId".into(),
            generator_function: "getOUIAProps".into(),
            target_element: "button".into(),
            overridden_attributes: vec!["data-ouia-component-id".into()],
            component_overrides: true,
        };

        let mut profile = make_profile("MenuToggle");
        profile.managed_attributes.push(binding);

        let changes = diff_profiles(&profile, &profile);
        let managed: Vec<_> = changes
            .iter()
            .filter(|c| c.category == SourceLevelCategory::PropAttributeOverride)
            .collect();
        assert!(
            managed.is_empty(),
            "Expected no changes for identical managed attributes"
        );
    }
}