fix-engine-js-fix 0.0.1

JS/TS/JSX/TSX language-specific fix operations for the fix engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
//! JS/TS/JSX/TSX language-specific fix operations.
//!
//! Implements [`LanguageFixProvider`] for the JavaScript/TypeScript ecosystem:
//! - Skips `node_modules/` paths
//! - Deduplicates ES import specifiers after renames
//! - Removes JSX attributes (props) using syntax-aware regex
//! - Extracts matched text from JSX/React incident variables
//! - Manages `package.json` dependencies
//! - Resolves ecosystem dependency versions via npm registry
//! - Resolves transitive dependency conflicts from lockfiles

mod lockfile;

use fix_engine::language::LanguageFixProvider;
use fix_engine_core::*;
use konveyor_core::incident::Incident;
use std::path::{Path, PathBuf};

/// Language fix provider for JavaScript/TypeScript/JSX/TSX files.
pub struct JsFixProvider;

impl JsFixProvider {
    pub fn new() -> Self {
        Self
    }
}

impl Default for JsFixProvider {
    fn default() -> Self {
        Self::new()
    }
}

impl LanguageFixProvider for JsFixProvider {
    fn should_skip_path(&self, path: &Path) -> bool {
        // Skip node_modules — these are updated via package.json
        // version bumps, not by patching source directly.
        // Note: src/vendor/ is NOT skipped — vendored source code
        // (e.g., forked libraries) is compiled as part of the project
        // and needs migration alongside the rest of the codebase.
        path.components().any(|c| c.as_os_str() == "node_modules")
    }

    fn post_process_lines(&self, lines: &mut [String]) {
        dedup_import_specifiers(lines);
    }

    fn plan_remove_attribute(
        &self,
        rule_id: &str,
        incident: &Incident,
        file_path: &Path,
    ) -> Option<PlannedFix> {
        plan_remove_prop(rule_id, incident, file_path)
    }

    fn plan_ensure_dependency(
        &self,
        rule_id: &str,
        incident: &Incident,
        package: &str,
        new_version: &str,
        file_path: &Path,
    ) -> Vec<PlannedFix> {
        plan_ensure_npm_dependency(rule_id, incident, package, new_version, file_path)
    }

    fn get_matched_text(&self, incident: &Incident) -> String {
        get_matched_text_from_incident(incident)
    }

    fn get_matched_text_for_rename(
        &self,
        incident: &Incident,
        mappings: &[RenameMapping],
    ) -> String {
        get_matched_text_for_rename_from_incident(incident, mappings)
    }

    fn is_whole_file_rename(&self, incident: &Incident) -> bool {
        // Component/import renames (detected via importedName variable) need
        // whole-file scanning since JSX usage of the component appears on many
        // lines beyond the import: opening tags, closing tags, type references.
        incident.variables.contains_key("importedName")
    }

    fn pre_apply(&self, project_root: &Path) -> Option<Box<dyn std::any::Any>> {
        // For yarn projects, capture the baseline set of unmet peer dep names
        // BEFORE any edits are written. This lets post_apply diff against the
        // baseline and only install peers that are newly introduced by our
        // version updates — not pre-existing intentionally-unmet ones (e.g.,
        // host-provided shared modules like react-redux in console plugins).
        if !project_root.join("yarn.lock").exists() {
            return None;
        }

        tracing::info!("Capturing baseline peer dependency warnings before applying fixes");
        let baseline = capture_yarn_missing_peer_names(project_root);
        tracing::info!(
            count = baseline.len(),
            peers = ?baseline,
            "Baseline unmet peer dependencies captured"
        );
        Some(Box::new(baseline))
    }

    fn post_apply(
        &self,
        project_root: &Path,
        modified_files: &[std::path::PathBuf],
        pre_state: Option<Box<dyn std::any::Any>>,
    ) -> anyhow::Result<()> {
        // Check if any package.json was modified — if so, run install to
        // regenerate the lockfile and node_modules.
        let any_package_json = modified_files
            .iter()
            .any(|p| p.file_name().and_then(|f| f.to_str()) == Some("package.json"));

        if !any_package_json {
            return Ok(());
        }

        tracing::info!("package.json was modified, running install to sync lockfile");

        if project_root.join("yarn.lock").exists() {
            // Extract the baseline peer dep names captured by pre_apply
            let baseline = pre_state
                .and_then(|s| s.downcast::<std::collections::HashSet<String>>().ok())
                .map(|b| *b)
                .unwrap_or_default();
            run_yarn_install_and_resolve_peers(project_root, &baseline);
        } else if project_root.join("pnpm-lock.yaml").exists() {
            run_pnpm_install(project_root);
        } else {
            run_npm_install(project_root);
        }

        Ok(())
    }
}

// ── Post-apply install helpers ──────────────────────────────────────────

/// Run `yarn install` and return the set of missing peer dependency names
/// from YN0002 warnings. Used to capture a baseline before edits are
/// applied, so that post-apply can diff and only install newly-introduced peers.
fn capture_yarn_missing_peer_names(project_root: &Path) -> std::collections::HashSet<String> {
    let output = std::process::Command::new("yarn")
        .args(["install"])
        .env("YARN_ENABLE_SCRIPTS", "false")
        .current_dir(project_root)
        .output();

    match output {
        Ok(o) => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            parse_yarn_missing_peer_deps(&stdout)
                .into_iter()
                .map(|p| p.peer_name)
                .collect()
        }
        Err(e) => {
            tracing::warn!(
                "yarn install could not be executed for baseline capture: {}",
                e
            );
            std::collections::HashSet::new()
        }
    }
}

/// Run `yarn install`, parse peer dependency warnings (YN0002), and install
/// any missing peers that are *newly* introduced by our edits.
///
/// `baseline_peers` is the set of peer dep names that were already unmet
/// before any edits were applied. Only peers NOT in this baseline set are
/// installed, preventing accidental installation of host-provided packages
/// (like `react-redux` in OpenShift console plugins) or other pre-existing
/// intentionally-unmet peers.
///
/// Yarn berry does not auto-install peer dependencies and has no config to
/// enable it. We capture its output, parse the YN0002 warning lines to
/// extract the names of missing peer packages, then run `yarn add -D` for
/// the newly-introduced ones.
fn run_yarn_install_and_resolve_peers(
    project_root: &Path,
    baseline_peers: &std::collections::HashSet<String>,
) {
    tracing::info!("Running yarn install (scripts disabled)");

    // Yarn berry (v2+) doesn't support --ignore-scripts; use the env var instead.
    // Yarn classic (v1) supports both the flag and the env var.
    let output = std::process::Command::new("yarn")
        .args(["install"])
        .env("YARN_ENABLE_SCRIPTS", "false")
        .current_dir(project_root)
        .output();

    let output = match output {
        Ok(o) => o,
        Err(e) => {
            tracing::warn!("yarn install could not be executed: {}", e);
            return;
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        tracing::warn!("yarn install failed: {}", stderr.trim());
    }

    // Yarn berry writes warnings to stdout. Parse YN0002 lines for missing peers.
    let stdout = String::from_utf8_lossy(&output.stdout);
    let all_missing_peers = parse_yarn_missing_peer_deps(&stdout);

    // Filter to only peers that are NEW (not in the baseline). Pre-existing
    // unmet peers are intentionally absent (e.g., host-provided shared modules
    // like react-redux, redux, redux-thunk in OpenShift console plugins).
    let missing_peers: Vec<_> = all_missing_peers
        .into_iter()
        .filter(|p| !baseline_peers.contains(&p.peer_name))
        .collect();

    if missing_peers.is_empty() {
        tracing::info!("yarn install completed, no newly-introduced missing peer dependencies");
        return;
    }

    tracing::info!(
        new_count = missing_peers.len(),
        baseline_count = baseline_peers.len(),
        "Filtered peer deps: {} new (out of {} total warnings, {} were pre-existing)",
        missing_peers.len(),
        missing_peers.len() + baseline_peers.len(),
        baseline_peers.len(),
    );

    // Build version-qualified install specs by looking up each peer's
    // required version range from the requesting package's peerDependencies
    // in node_modules. This prevents installing incompatible latest versions.
    let mut install_specs: Vec<String> = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for peer in &missing_peers {
        if !seen.insert(peer.peer_name.clone()) {
            continue;
        }

        match lookup_peer_dep_version(project_root, &peer.requested_by, &peer.peer_name) {
            Some(version_range) => {
                tracing::info!(
                    peer = %peer.peer_name,
                    version = %version_range,
                    requested_by = %peer.requested_by,
                    "Resolved peer dep version range from requesting package"
                );
                install_specs.push(format!("{}@{}", peer.peer_name, version_range));
            }
            None => {
                tracing::warn!(
                    peer = %peer.peer_name,
                    requested_by = %peer.requested_by,
                    "Could not resolve peer dep version; skipping to avoid installing incompatible version"
                );
            }
        }
    }

    if install_specs.is_empty() {
        tracing::info!("No peer dependencies with resolved versions to install");
        return;
    }

    tracing::info!(
        count = install_specs.len(),
        specs = ?install_specs,
        "Installing missing peer dependencies with resolved versions"
    );

    // Use -D (--dev) so peer deps land in devDependencies, not dependencies.
    // These are transitive peer requirements from dev tooling packages
    // (e.g., @patternfly/react-component-groups needs react-drag-drop),
    // not production dependencies the consumer ships.
    let add_result = std::process::Command::new("yarn")
        .args(["add", "-D"])
        .args(&install_specs)
        .env("YARN_ENABLE_SCRIPTS", "false")
        .current_dir(project_root)
        .output();

    match add_result {
        Ok(o) if o.status.success() => {
            tracing::info!("Successfully installed missing peer dependencies");
        }
        Ok(o) => {
            let stderr = String::from_utf8_lossy(&o.stderr);
            tracing::warn!("yarn add for peer dependencies failed: {}", stderr.trim());
        }
        Err(e) => {
            tracing::warn!("yarn add could not be executed: {}", e);
        }
    }
}

/// A missing peer dependency detected from yarn's YN0002 warnings.
#[derive(Debug, Clone)]
struct MissingPeerDep {
    /// The missing peer package name (e.g., "victory")
    peer_name: String,
    /// The package that requires it (e.g., "@patternfly/react-charts")
    requested_by: String,
}

/// Parse yarn berry output for YN0002 (missing peer dependency) warnings.
///
/// Yarn berry emits lines like:
/// ```text
/// ➤ YN0002: @patternfly/react-charts@npm:8.4.1 doesn't provide victory (p1a2b3), requested by ...
/// ```
///
/// The output contains ANSI escape codes which are stripped before matching.
/// Returns a list of `MissingPeerDep` with both the peer name and the
/// requesting package, so the caller can look up the required version range.
fn parse_yarn_missing_peer_deps(output: &str) -> Vec<MissingPeerDep> {
    // Strip ANSI escape codes: ESC[ followed by parameters and a letter
    let ansi_re = regex::Regex::new(r"\x1b\[[0-9;]*[a-zA-Z]").expect("valid regex");
    let stripped = ansi_re.replace_all(output, "");

    // Match YN0002 lines. Two formats exist:
    //   Package-level: YN0002: <pkg>@npm:<ver> doesn't provide <peer> (<hash>), requested by <requester>.
    //   Workspace-level: YN0002: │ <workspace>@workspace:. doesn't provide <peer> (<hash>), requested by <requester>.
    // Both requester and peer name can be scoped (e.g., @scope/pkg).
    // Yarn 4.6.0 uses a "│ " (box-drawing vertical bar) separator after the
    // warning code in some output formats (e.g., workspace peer dep warnings).
    //
    // For workspace-level warnings, the first name is the workspace (e.g.,
    // "pipelines-console-plugin") which won't exist in node_modules. We also
    // capture the "requested by" package at the end of the line (group 3) so
    // `lookup_peer_dep_version` can find the actual package that declares the
    // peer dependency.
    let peer_re = regex::Regex::new(
        r"YN0002: (?:│ )?(@?[^@\s]+)@\S+ doesn't provide (@?[^\s(]+) \([^)]+\),? ?(?:requested by (@?[^\s.]+))?",
    )
    .expect("valid regex");

    let mut seen = std::collections::HashSet::new();
    peer_re
        .captures_iter(&stripped)
        .filter_map(|cap| {
            let provider = cap[1].to_string();
            let peer_name = cap[2].to_string();
            // Prefer the "requested by" package (group 3) when available,
            // since the provider field for workspace-level warnings is the
            // workspace name (not in node_modules). For package-level warnings,
            // the provider IS the requesting package, so fall back to it.
            let requested_by = cap
                .get(3)
                .map(|m| m.as_str().to_string())
                .unwrap_or(provider);
            // Deduplicate by peer_name — use the first requester encountered
            seen.insert(peer_name.clone()).then_some(MissingPeerDep {
                peer_name,
                requested_by,
            })
        })
        .collect()
}

/// Look up the required version range for a peer dependency from the
/// requesting package's `peerDependencies` in `node_modules`.
///
/// Returns the version range string (e.g., `"^37.3.6"`) if found.
fn lookup_peer_dep_version(
    project_root: &Path,
    requested_by: &str,
    peer_name: &str,
) -> Option<String> {
    let pkg_json_path = project_root
        .join("node_modules")
        .join(requested_by)
        .join("package.json");

    let content = std::fs::read_to_string(&pkg_json_path).ok()?;
    let parsed: serde_json::Value = serde_json::from_str(&content).ok()?;

    parsed
        .get("peerDependencies")?
        .get(peer_name)?
        .as_str()
        .map(|s| s.to_string())
}

/// Run `pnpm install` with auto-install-peers enabled via env var.
///
/// pnpm supports `auto-install-peers` (default true since v8) but we set
/// the env var explicitly to ensure it works on older pnpm versions too.
fn run_pnpm_install(project_root: &Path) {
    tracing::info!("Running pnpm install --ignore-scripts (with auto-install-peers)");

    let output = std::process::Command::new("pnpm")
        .args(["install", "--ignore-scripts"])
        .env("npm_config_auto_install_peers", "true")
        .current_dir(project_root)
        .output();

    match output {
        Ok(o) if o.status.success() => {
            tracing::info!("pnpm install completed successfully");
        }
        Ok(o) => {
            let stderr = String::from_utf8_lossy(&o.stderr);
            tracing::warn!("pnpm install failed: {}", stderr.trim());
        }
        Err(e) => {
            tracing::warn!("pnpm install could not be executed: {}", e);
        }
    }
}

/// Run `npm install`. npm v7+ auto-installs peer dependencies by default.
fn run_npm_install(project_root: &Path) {
    tracing::info!("Running npm install --ignore-scripts --no-audit --no-fund");

    let output = std::process::Command::new("npm")
        .args(["install", "--ignore-scripts", "--no-audit", "--no-fund"])
        .current_dir(project_root)
        .output();

    match output {
        Ok(o) if o.status.success() => {
            tracing::info!("npm install completed successfully");
        }
        Ok(o) => {
            let stderr = String::from_utf8_lossy(&o.stderr);
            tracing::warn!("npm install failed: {}", stderr.trim());
        }
        Err(e) => {
            tracing::warn!("npm install could not be executed: {}", e);
        }
    }
}

// -- JSX prop removal --

fn plan_remove_prop(rule_id: &str, incident: &Incident, file_path: &Path) -> Option<PlannedFix> {
    let line = incident.line_number?;
    let prop_name = incident
        .variables
        .get("propName")
        .and_then(|v| v.as_str())?;

    // Read the actual file line to construct a precise removal edit.
    let source = std::fs::read_to_string(file_path).ok()?;
    let all_lines: Vec<&str> = source.lines().collect();
    let line_idx = (line as usize).saturating_sub(1);
    let file_line = all_lines.get(line_idx)?;
    let trimmed = file_line.trim();

    // If the entire line is just the prop (common in formatted JSX), remove it.
    if trimmed.starts_with(prop_name) {
        let depth = bracket_depth(file_line);
        if depth == 0 {
            // Single-line prop -- safe to remove just this line
            Some(PlannedFix {
                edits: vec![TextEdit {
                    line,
                    old_text: file_line.to_string(),
                    new_text: String::new(),
                    rule_id: rule_id.to_string(),
                    description: format!("Remove prop '{}' (entire line)", prop_name),
                    replace_all: false,
                }],
                confidence: FixConfidence::High,
                source: FixSource::Pattern,
                rule_id: rule_id.to_string(),
                file_uri: incident.file_uri.clone(),
                line,
                description: format!("Remove prop '{}'", prop_name),
            })
        } else {
            // Multi-line prop value -- scan forward to find where brackets balance.
            let mut cumulative_depth = depth;
            let mut end_idx = line_idx;
            for (i, subsequent_line) in all_lines.iter().enumerate().skip(line_idx + 1) {
                cumulative_depth += bracket_depth(subsequent_line);
                end_idx = i;
                if cumulative_depth <= 0 {
                    break;
                }
            }

            if cumulative_depth > 0 {
                return Some(PlannedFix {
                    edits: vec![],
                    confidence: FixConfidence::Low,
                    source: FixSource::Pattern,
                    rule_id: rule_id.to_string(),
                    file_uri: incident.file_uri.clone(),
                    line,
                    description: format!(
                        "Remove prop '{}' (unbalanced brackets, manual)",
                        prop_name
                    ),
                });
            }

            // Remove all lines from prop start through closing bracket
            let mut edits = Vec::new();
            for i in line_idx..=end_idx {
                if let Some(l) = all_lines.get(i) {
                    edits.push(TextEdit {
                        line: (i + 1) as u32,
                        old_text: l.to_string(),
                        new_text: String::new(),
                        rule_id: rule_id.to_string(),
                        description: format!(
                            "Remove prop '{}' (line {} of multi-line)",
                            prop_name,
                            i - line_idx + 1
                        ),
                        replace_all: false,
                    });
                }
            }

            Some(PlannedFix {
                edits,
                confidence: FixConfidence::High,
                source: FixSource::Pattern,
                rule_id: rule_id.to_string(),
                file_uri: incident.file_uri.clone(),
                line,
                description: format!(
                    "Remove prop '{}' ({} lines)",
                    prop_name,
                    end_idx - line_idx + 1
                ),
            })
        }
    } else {
        // Prop is inline with other content -- try to remove just the prop fragment.
        let prop_re = regex::Regex::new(&format!(
            r#"\s+{prop_name}(?:=\{{[^}}]*\}}|="[^"]*"|='[^']*'|=\{{.*?\}})?"#
        ))
        .ok()?;

        if let Some(m) = prop_re.find(file_line) {
            if bracket_depth(m.as_str()) != 0 {
                return Some(PlannedFix {
                    edits: vec![],
                    confidence: FixConfidence::Low,
                    source: FixSource::Pattern,
                    rule_id: rule_id.to_string(),
                    file_uri: incident.file_uri.clone(),
                    line,
                    description: format!("Remove prop '{}' (multi-line inline, manual)", prop_name),
                });
            }

            Some(PlannedFix {
                edits: vec![TextEdit {
                    line,
                    old_text: m.as_str().to_string(),
                    new_text: String::new(),
                    rule_id: rule_id.to_string(),
                    description: format!("Remove prop '{}'", prop_name),
                    replace_all: false,
                }],
                confidence: FixConfidence::High,
                source: FixSource::Pattern,
                rule_id: rule_id.to_string(),
                file_uri: incident.file_uri.clone(),
                line,
                description: format!("Remove prop '{}'", prop_name),
            })
        } else {
            Some(PlannedFix {
                edits: vec![],
                confidence: FixConfidence::Low,
                source: FixSource::Pattern,
                rule_id: rule_id.to_string(),
                file_uri: incident.file_uri.clone(),
                line,
                description: format!("Remove prop '{}' (manual)", prop_name),
            })
        }
    }
}

// -- Import deduplication --

/// Deduplicate import specifiers on lines that look like ES import statements.
fn dedup_import_specifiers(lines: &mut [String]) {
    let import_re = regex::Regex::new(r"^(\s*import\s+\{)([^}]+)(\}\s*from\s+.*)$").unwrap();

    for line in lines.iter_mut() {
        if let Some(caps) = import_re.captures(line) {
            let prefix = caps.get(1).unwrap().as_str();
            let specifiers_str = caps.get(2).unwrap().as_str();
            let suffix = caps.get(3).unwrap().as_str();

            let specifiers: Vec<&str> = specifiers_str
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .collect();

            let mut seen = std::collections::HashSet::new();
            let deduped: Vec<&str> = specifiers
                .into_iter()
                .filter(|s| seen.insert(s.to_string()))
                .collect();

            let new_specifiers = format!(" {} ", deduped.join(", "));
            let new_line = format!("{}{}{}", prefix, new_specifiers, suffix);

            if new_line != *line {
                *line = new_line;
            }
        }
    }
}

// -- Bracket depth --

/// Count net bracket/brace depth change for a line.
fn bracket_depth(line: &str) -> i32 {
    let mut depth: i32 = 0;
    let mut in_single_quote = false;
    let mut in_double_quote = false;
    let mut in_backtick = false;
    let mut prev = '\0';
    for ch in line.chars() {
        match ch {
            '\'' if !in_double_quote && !in_backtick && prev != '\\' => {
                in_single_quote = !in_single_quote
            }
            '"' if !in_single_quote && !in_backtick && prev != '\\' => {
                in_double_quote = !in_double_quote
            }
            '`' if !in_single_quote && !in_double_quote && prev != '\\' => {
                in_backtick = !in_backtick
            }
            '(' | '{' | '[' if !in_single_quote && !in_double_quote && !in_backtick => depth += 1,
            ')' | '}' | ']' if !in_single_quote && !in_double_quote && !in_backtick => depth -= 1,
            _ => {}
        }
        prev = ch;
    }
    depth
}

// -- Incident variable extraction --

/// Extract the matched text from incident variables.
fn get_matched_text_from_incident(incident: &Incident) -> String {
    for key in &[
        "propName",
        "componentName",
        "importedName",
        "className",
        "variableName",
    ] {
        if let Some(serde_json::Value::String(s)) = incident.variables.get(*key) {
            return s.clone();
        }
    }
    String::new()
}

/// Get the matched text, considering both prop names and prop values.
fn get_matched_text_for_rename_from_incident(
    incident: &Incident,
    mappings: &[RenameMapping],
) -> String {
    let prop_name = get_matched_text_from_incident(incident);

    if mappings.iter().any(|m| m.old == prop_name) {
        return prop_name;
    }

    if let Some(serde_json::Value::String(val)) = incident.variables.get("propValue") {
        if mappings.iter().any(|m| m.old == val.as_str()) {
            return val.clone();
        }
    }

    if let Some(serde_json::Value::Array(vals)) = incident.variables.get("propObjectValues") {
        for v in vals {
            if let serde_json::Value::String(s) = v {
                if mappings.iter().any(|m| m.old == s.as_str()) {
                    return s.clone();
                }
            }
        }
    }

    prop_name
}

// -- npm dependency management (package.json) --

/// Walk up the directory tree from `path` to find the nearest `package.json`.
fn find_nearest_package_json(path: &Path) -> Option<PathBuf> {
    let mut dir = if path.is_file() { path.parent()? } else { path };
    loop {
        let candidate = dir.join("package.json");
        if candidate.exists() {
            return Some(candidate);
        }
        dir = dir.parent()?;
    }
}

/// Ensure a dependency exists at the correct version in `package.json`.
///
/// Three paths:
///
/// 1. **Lockfile incident** (URI points to a lockfile): The incident fired on a
///    transitive copy of the package. Parse the lockfile to find which direct
///    deps in `package.json` pull it in, resolve their latest compatible
///    versions from npm, and plan updates for those parent packages.
///
/// 2. **Dependent incident** (has `isDependentOf` variable): Legacy path for
///    transitive conflicts detected by the lockfile scanner in the provider.
///    Resolves the actual package from `dependencyName` via npm.
///
/// 3. **Direct incident** (URI points to `package.json` or source file): Update
///    or insert the package in `package.json` with the given version.
fn plan_ensure_npm_dependency(
    rule_id: &str,
    incident: &Incident,
    package: &str,
    new_version: &str,
    file_path: &Path,
) -> Vec<PlannedFix> {
    // ── Path 1: Lockfile incident ────────────────────────────────────
    //
    // When the incident URI points to a lockfile (yarn.lock, package-lock.json,
    // pnpm-lock.yaml), the rule fired on a transitive copy of `package` (e.g.,
    // a nested @patternfly/react-core@5.x pulled in by react-topology).
    //
    // Instead of redundantly updating the target package (the direct incident
    // handles that), we find which direct deps bring in the transitive copy
    // and update those parent packages to versions compatible with the new
    // major version of the target.
    if lockfile::is_lockfile(file_path) {
        tracing::info!(
            package = %package,
            lockfile = %file_path.display(),
            "Lockfile incident: resolving parent packages for transitive dependency"
        );

        // Find the sibling package.json
        let pkg_json = match find_nearest_package_json(file_path) {
            Some(p) => p,
            None => {
                tracing::warn!(
                    lockfile = %file_path.display(),
                    "No package.json found near lockfile; skipping"
                );
                return Vec::new();
            }
        };

        // Before resolving parents, check if the consumer's existing version
        // of the target package already satisfies the required range. If so,
        // there's nothing to do — the lockfile will sort itself out once the
        // direct deps are updated by their own (non-lockfile) incidents.
        //
        // This prevents spurious updates like bumping react-dom from ^17 to ^19
        // when the consumer has react@^17.0.1 and PF's peer dep is
        // "^17 || ^18 || ^19" (which ^17.0.1 already satisfies).
        if let Some(current_version) = read_dep_version_from_package_json(&pkg_json, package) {
            if is_range_already_compatible(&current_version, new_version) {
                tracing::info!(
                    package = %package,
                    current = %current_version,
                    required = %new_version,
                    "Lockfile path: consumer's version already satisfies required range; skipping parent resolution"
                );
                return Vec::new();
            }
        }

        // Get the set of direct dep names from package.json
        let direct_deps = lockfile::parse_direct_dep_names(&pkg_json);

        // Find which lockfile entries transitively depend on the target package.
        // This walks up the dependency chain: if A → B → C and C is the target,
        // both A and B are returned as ancestors.
        let all_parents = lockfile::find_transitive_ancestor_packages(file_path, package);

        // Filter to only direct deps (we can only update what's in package.json)
        let actionable_parents: Vec<&String> = all_parents
            .iter()
            .filter(|name| direct_deps.contains(name.as_str()))
            .collect();

        if actionable_parents.is_empty() {
            tracing::debug!(
                package = %package,
                "No direct-dep parents found for transitive lockfile dep; skipping"
            );
            return Vec::new();
        }

        let target_major = extract_major(new_version);
        let mut fixes = Vec::new();

        for parent in &actionable_parents {
            tracing::info!(
                parent = %parent,
                compatible_with = %package,
                target_major = target_major,
                "Resolving npm-compatible version for lockfile parent"
            );

            let resolved = resolve_npm_compatible_version(parent, package, target_major);

            match resolved {
                Some(ref ver) => {
                    tracing::info!(
                        parent = %parent,
                        resolved_version = %ver,
                        "Resolved npm-compatible version for lockfile parent"
                    );
                    if let Some(fix) =
                        plan_ensure_npm_dependency_inner(rule_id, &pkg_json, parent, ver)
                    {
                        fixes.push(fix);
                    }
                }
                None => {
                    tracing::warn!(
                        parent = %parent,
                        compatible_with = %package,
                        "Could not resolve compatible version from npm; skipping parent"
                    );
                }
            }
        }

        tracing::info!(
            package = %package,
            parents = actionable_parents.len(),
            fixes = fixes.len(),
            "Lockfile incident resolved"
        );

        return fixes;
    }

    // ── Path 2: Dependent incident (isDependentOf variable) ──────────
    //
    // Legacy path for transitive conflicts with explicit variables.
    if let Some(serde_json::Value::String(depends_on)) = incident.variables.get("isDependentOf") {
        let actual_package = match incident
            .variables
            .get("dependencyName")
            .and_then(|v| v.as_str())
        {
            Some(p) => p,
            None => return Vec::new(),
        };

        // If the consumer already has a compatible version of the dependency
        // that this package depends on, skip the transitive update.
        if let Some(current) = read_dep_version_from_package_json(file_path, depends_on) {
            if is_range_already_compatible(&current, new_version) {
                tracing::info!(
                    package = %depends_on,
                    current = %current,
                    required = %new_version,
                    "Dependent path: consumer's version already satisfies required range; skipping"
                );
                return Vec::new();
            }
        }

        let target_major = extract_major(new_version);

        tracing::info!(
            dependent = %actual_package,
            depends_on = %depends_on,
            target_major = target_major,
            "Resolving compatible version from npm for dependent package"
        );

        let resolved = resolve_npm_compatible_version(actual_package, depends_on, target_major);

        return match resolved {
            Some(ref ver) => {
                tracing::info!(
                    package = %actual_package,
                    resolved_version = %ver,
                    "Resolved npm-compatible version for dependent"
                );
                plan_ensure_npm_dependency_inner(rule_id, file_path, actual_package, ver)
                    .into_iter()
                    .collect()
            }
            None => {
                tracing::warn!(
                    package = %actual_package,
                    depends_on = %depends_on,
                    "Could not resolve compatible version from npm; skipping"
                );
                Vec::new()
            }
        };
    }

    // ── Path 3: Direct incident ──────────────────────────────────────
    plan_ensure_npm_dependency_inner(rule_id, file_path, package, new_version)
        .into_iter()
        .collect()
}

/// Inner implementation: update or insert a dependency in package.json.
fn plan_ensure_npm_dependency_inner(
    rule_id: &str,
    file_path: &Path,
    package: &str,
    new_version: &str,
) -> Option<PlannedFix> {
    // Resolve the target package.json
    let pkg_json = if file_path.file_name().is_some_and(|f| f == "package.json") {
        file_path.to_path_buf()
    } else {
        find_nearest_package_json(file_path)?
    };

    let source = std::fs::read_to_string(&pkg_json).ok()?;
    let pkg_json_uri = format!("file://{}", pkg_json.display());

    // --- Identify top-level dependency blocks ---
    // We need to distinguish top-level "dependencies" / "devDependencies" from
    // nested ones (e.g., "consolePlugin.dependencies"). Top-level blocks start
    // at JSON brace depth 1 (inside the root object).
    let lines: Vec<&str> = source.lines().collect();
    let top_level_dep_ranges = find_top_level_dep_blocks(&lines);

    // --- Try update: find the package in a top-level dep block and replace its version ---
    let package_quoted = format!("\"{}\"", package);
    let version_re = regex::Regex::new(r#"("[\^~><=]*[0-9][^"]*")"#).ok()?;

    for (idx, file_line) in source.lines().enumerate() {
        if !file_line.contains(&package_quoted) {
            continue;
        }
        // Only match if this line is inside a top-level dep block
        if !top_level_dep_ranges
            .iter()
            .any(|r| idx >= r.start && idx < r.end)
        {
            continue;
        }
        if let Some(m) = version_re.find(file_line) {
            let line = (idx + 1) as u32;
            let old_version = m.as_str();

            // Strip quotes to get raw version strings for comparison
            let old_ver_raw = old_version.trim_matches('"');

            // If the consumer's existing version range is already compatible
            // with the new required range, skip the update. This prevents
            // unnecessary version churn — e.g., when PF expands its react
            // peer dep from "^17 || ^18" to "^17 || ^18 || ^19", a consumer
            // with "^17.0.1" doesn't need to change anything.
            if is_range_already_compatible(old_ver_raw, new_version) {
                tracing::info!(
                    package = %package,
                    current = %old_ver_raw,
                    required = %new_version,
                    "Skipping update: consumer's version range already satisfies the required range"
                );
                return None;
            }

            let new_ver_quoted = format!("\"{}\"", new_version);

            return Some(PlannedFix {
                edits: vec![TextEdit {
                    line,
                    old_text: old_version.to_string(),
                    new_text: new_ver_quoted.clone(),
                    rule_id: rule_id.to_string(),
                    description: format!(
                        "Update {} from {} to {}",
                        package, old_version, new_ver_quoted
                    ),
                    replace_all: false,
                }],
                confidence: FixConfidence::Exact,
                source: FixSource::Pattern,
                rule_id: rule_id.to_string(),
                file_uri: pkg_json_uri,
                line,
                description: format!("Update {} to {}", package, new_version),
            });
        }
    }

    // --- Insert: package not found, add it to a top-level dep block ---
    // Prefer "devDependencies" if it exists (most PF consumer deps live there),
    // fall back to "dependencies".
    let target_block = top_level_dep_ranges
        .iter()
        .find(|r| r.name == "devDependencies")
        .or_else(|| {
            top_level_dep_ranges
                .iter()
                .find(|r| r.name == "dependencies")
        });

    let target_block = target_block?;
    let mut last_entry_line: Option<usize> = None;
    let mut closing_brace_line: Option<usize> = None;

    for (idx, line) in lines
        .iter()
        .enumerate()
        .take(target_block.end)
        .skip(target_block.start)
    {
        let trimmed = line.trim();
        if trimmed == "}" || trimmed == "}," {
            closing_brace_line = Some(idx);
            break;
        }
        if !trimmed.is_empty()
            && !trimmed.starts_with("\"dependencies\"")
            && !trimmed.starts_with("\"devDependencies\"")
            && trimmed != "{"
        {
            last_entry_line = Some(idx);
        }
    }

    let closing_idx = closing_brace_line?;
    let closing_line_num = (closing_idx + 1) as u32;

    let entry_indent = if let Some(last_idx) = last_entry_line {
        let last = lines[last_idx];
        let indent_len = last.len() - last.trim_start().len();
        &last[..indent_len]
    } else {
        "    "
    };

    let mut edits = Vec::new();

    if let Some(last_idx) = last_entry_line {
        let last = lines[last_idx];
        if !last.trim_end().ends_with(',') {
            let last_line_num = (last_idx + 1) as u32;
            let trimmed_last = last.trim_end().to_string();
            edits.push(TextEdit {
                line: last_line_num,
                old_text: trimmed_last.clone(),
                new_text: format!("{},", trimmed_last),
                rule_id: rule_id.to_string(),
                description: format!("Add trailing comma before new dependency {}", package),
                replace_all: false,
            });
        }
    }

    let closing_line_text = lines[closing_idx].to_string();
    let new_entry = format!(
        "{}\"{}\": \"{}\"\n{}",
        entry_indent, package, new_version, closing_line_text
    );
    edits.push(TextEdit {
        line: closing_line_num,
        old_text: closing_line_text,
        new_text: new_entry,
        rule_id: rule_id.to_string(),
        description: format!("Add {} {} to dependencies", package, new_version),
        replace_all: false,
    });

    Some(PlannedFix {
        edits,
        confidence: FixConfidence::Exact,
        source: FixSource::Pattern,
        rule_id: rule_id.to_string(),
        file_uri: pkg_json_uri,
        line: closing_line_num,
        description: format!("Add {} {} to dependencies", package, new_version),
    })
}

// -- Top-level dependency block detection --

/// A range of lines in package.json belonging to a top-level dependency block.
struct DepBlockRange {
    /// "dependencies" or "devDependencies"
    name: &'static str,
    /// Start line index (inclusive, the key line)
    start: usize,
    /// End line index (exclusive, after the closing brace)
    end: usize,
}

/// Find top-level "dependencies" and "devDependencies" blocks in package.json.
///
/// Top-level means at JSON depth 1 (direct children of the root object).
/// Nested blocks like "consolePlugin.dependencies" are at depth >= 2 and
/// are excluded.
fn find_top_level_dep_blocks(lines: &[&str]) -> Vec<DepBlockRange> {
    let mut results = Vec::new();
    let mut root_depth: i32 = 0;

    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim();

        // Track root-level brace depth (outside any dep block scan)
        for ch in trimmed.chars() {
            match ch {
                '{' => root_depth += 1,
                '}' => root_depth -= 1,
                _ => {}
            }
        }

        // Only match dep block keys at depth 1 (just entered the root object)
        // After processing braces above, a line like `"dependencies": {` will
        // have bumped root_depth to 2. So we check for depth == 2 for a
        // combined key+brace line, or depth == 1 for key-only lines.
        let is_dep_key = (root_depth == 2 || root_depth == 1)
            && (trimmed.starts_with("\"dependencies\"")
                || trimmed.starts_with("\"devDependencies\""));

        if !is_dep_key {
            i += 1;
            continue;
        }

        let name = if trimmed.starts_with("\"devDependencies\"") {
            "devDependencies"
        } else {
            "dependencies"
        };

        let start = i;
        // Find the matching closing brace for this block
        let mut block_depth: i32 = 0;
        for ch in trimmed.chars() {
            match ch {
                '{' => block_depth += 1,
                '}' => block_depth -= 1,
                _ => {}
            }
        }

        i += 1;
        while i < lines.len() && block_depth > 0 {
            let t = lines[i].trim();
            for ch in t.chars() {
                match ch {
                    '{' => {
                        block_depth += 1;
                        root_depth += 1;
                    }
                    '}' => {
                        block_depth -= 1;
                        root_depth -= 1;
                    }
                    _ => {}
                }
            }
            i += 1;
        }

        results.push(DepBlockRange {
            name,
            start,
            end: i,
        });
    }

    results
}

// -- package.json version lookup --

/// Read the version of a specific dependency from package.json.
///
/// Searches both `dependencies` and `devDependencies` (top-level only).
/// Returns the raw version string (e.g., `"^17.0.1"`) if found.
fn read_dep_version_from_package_json(pkg_json: &Path, package: &str) -> Option<String> {
    let pkg_json = if pkg_json.file_name().is_some_and(|f| f == "package.json") {
        pkg_json.to_path_buf()
    } else {
        find_nearest_package_json(pkg_json)?
    };

    let source = std::fs::read_to_string(&pkg_json).ok()?;
    let parsed: serde_json::Value = serde_json::from_str(&source).ok()?;

    // Check both dependency sections
    for section in ["dependencies", "devDependencies"] {
        if let Some(version) = parsed
            .get(section)
            .and_then(|deps| deps.get(package))
            .and_then(|v| v.as_str())
        {
            return Some(version.to_string());
        }
    }

    None
}

// -- npm semver range compatibility --

/// Check if the consumer's existing version range is already compatible with
/// the required range from a peer dependency or dependency update rule.
///
/// Returns `true` if every version matched by `consumer_range` is also
/// accepted by `required_range` — meaning the consumer doesn't need to
/// change their version.
///
/// Examples:
///   - `is_range_already_compatible("^17.0.1", "^17 || ^18 || ^19")` → true
///     (^17.0.1 is a subset of ^17)
///   - `is_range_already_compatible("^11.7.3", "^17.0.3")` → false
///     (^11 and ^17 don't overlap)
///   - `is_range_already_compatible("^6.4.1", "^6.4.1")` → true
///     (identical ranges)
///
/// If either range fails to parse (e.g., dist tags like "latest", git URLs),
/// returns `false` to allow the update to proceed.
fn is_range_already_compatible(consumer_range: &str, required_range: &str) -> bool {
    let consumer = match consumer_range.parse::<node_semver::Range>() {
        Ok(r) => r,
        Err(_) => return false,
    };
    let required = match required_range.parse::<node_semver::Range>() {
        Ok(r) => r,
        Err(_) => return false,
    };

    // "Does the required range accept every version that the consumer's range accepts?"
    // If yes, the consumer's current version is already within the acceptable set.
    required.allows_all(&consumer)
}

// -- npm registry resolution --

/// Extract the major version number from a version string.
/// `"^6.4.1"` → 6, `"6.4.1"` → 6, `"~5.0.0"` → 5
fn extract_major(version: &str) -> u64 {
    let stripped = version
        .trim()
        .trim_start_matches('^')
        .trim_start_matches('~')
        .trim_start_matches(">=")
        .trim_start_matches("<=")
        .trim_start_matches('>')
        .trim_start_matches('<')
        .trim_start_matches('=');
    stripped
        .split('.')
        .next()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
}

/// Query the npm registry to find the latest stable version of `package`
/// whose dependency on `compatible_with` uses major version `target_major`.
///
/// For example, for `resolve_npm_compatible_version("@patternfly/react-topology",
/// "@patternfly/react-core", 6)`, this finds the latest version of
/// `react-topology` that depends on `@patternfly/react-core@^6.x`.
///
/// Returns the version as `"^X.Y.Z"` or `None` if no compatible version
/// is found or the registry query fails.
fn resolve_npm_compatible_version(
    package: &str,
    compatible_with: &str,
    target_major: u64,
) -> Option<String> {
    let url = format!("https://registry.npmjs.org/{}", package);

    let mut response = match ureq::get(&url).call() {
        Ok(resp) => resp,
        Err(e) => {
            tracing::warn!(
                package = %package,
                error = %e,
                "npm registry query failed"
            );
            return None;
        }
    };

    let body: serde_json::Value = match response.body_mut().read_json() {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(
                package = %package,
                error = %e,
                "Failed to parse npm registry response"
            );
            return None;
        }
    };

    let versions = body.get("versions")?.as_object()?;

    // Find all stable versions whose dependency on `compatible_with`
    // has a major version >= target_major
    let mut candidates: Vec<(u64, u64, u64, &str)> = Vec::new();

    for (ver_str, ver_data) in versions {
        // Skip prereleases
        if ver_str.contains("alpha")
            || ver_str.contains("prerelease")
            || ver_str.contains("rc")
            || ver_str.contains("beta")
        {
            continue;
        }

        // Check if this version is compatible with the target major of
        // compatible_with. A version is compatible if:
        // 1. It declares compatible_with at target_major+ (explicit compat), OR
        // 2. It doesn't declare compatible_with at all (the dep was dropped,
        //    meaning no version constraint — implicitly compatible with any version)
        //
        // A version is INCOMPATIBLE only if it explicitly constrains
        // compatible_with to a major version below target_major.
        let dep_constraint = ["dependencies", "peerDependencies"]
            .iter()
            .find_map(|section| {
                ver_data
                    .get(*section)
                    .and_then(|deps| deps.get(compatible_with))
                    .and_then(|c| c.as_str())
            });

        let is_compatible = match dep_constraint {
            Some(c) => extract_major(c) >= target_major,
            None => true, // dep dropped — no constraint, implicitly compatible
        };

        if !is_compatible {
            continue;
        }

        // Parse version for sorting
        if let Some(parsed) = parse_semver_tuple(ver_str) {
            candidates.push((parsed.0, parsed.1, parsed.2, ver_str.as_str()));
        }
    }

    // Sort and take the latest
    candidates.sort();
    let latest = candidates.last()?;

    Some(format!("^{}", latest.3))
}

/// Parse a semver string into (major, minor, patch) tuple.
fn parse_semver_tuple(s: &str) -> Option<(u64, u64, u64)> {
    let s = s.trim();
    let version_part = s.split('-').next().unwrap_or(s);
    let parts: Vec<&str> = version_part.split('.').collect();
    let major = parts.first()?.parse().ok()?;
    let minor = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
    let patch = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
    Some((major, minor, patch))
}

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

    /// Create a test Incident with just the fields the fix provider cares about.
    fn make_test_incident(
        uri: &str,
        line: u32,
        variables: BTreeMap<String, serde_json::Value>,
    ) -> Incident {
        Incident {
            file_uri: uri.to_string(),
            line_number: Some(line),
            code_location: None,
            message: String::new(),
            code_snip: None,
            variables,
            effort: None,
            links: Vec::new(),
            is_dependency_incident: false,
        }
    }

    // -- should_skip_path tests --

    #[test]
    fn test_skip_node_modules() {
        let provider = JsFixProvider::new();
        assert!(provider.should_skip_path(Path::new(
            "/project/node_modules/@patternfly/react-core/index.js"
        )));
    }

    #[test]
    fn test_skip_nested_node_modules() {
        let provider = JsFixProvider::new();
        assert!(
            provider.should_skip_path(Path::new("/project/packages/app/node_modules/foo/bar.ts"))
        );
    }

    #[test]
    fn test_does_not_skip_src() {
        let provider = JsFixProvider::new();
        assert!(!provider.should_skip_path(Path::new("/project/src/App.tsx")));
    }

    #[test]
    fn test_does_not_skip_vendor() {
        let provider = JsFixProvider::new();
        assert!(!provider.should_skip_path(Path::new("/project/src/vendor/lib.ts")));
    }

    // -- is_whole_file_rename tests --

    #[test]
    fn test_whole_file_rename_with_imported_name() {
        let provider = JsFixProvider::new();
        let mut vars = BTreeMap::new();
        vars.insert(
            "importedName".to_string(),
            serde_json::Value::String("Chip".to_string()),
        );
        let incident = make_test_incident("file:///test.tsx", 1, vars);
        assert!(provider.is_whole_file_rename(&incident));
    }

    #[test]
    fn test_not_whole_file_rename_without_imported_name() {
        let provider = JsFixProvider::new();
        let mut vars = BTreeMap::new();
        vars.insert(
            "propName".to_string(),
            serde_json::Value::String("isActive".to_string()),
        );
        let incident = make_test_incident("file:///test.tsx", 1, vars);
        assert!(!provider.is_whole_file_rename(&incident));
    }

    // -- bracket_depth tests --

    #[test]
    fn test_bracket_depth_balanced() {
        assert_eq!(bracket_depth("{ foo: bar }"), 0);
        assert_eq!(bracket_depth("foo()"), 0);
        assert_eq!(bracket_depth("[1, 2, 3]"), 0);
        assert_eq!(bracket_depth("{ foo: [1, 2] }"), 0);
    }

    #[test]
    fn test_bracket_depth_open() {
        assert_eq!(bracket_depth("actions={["), 2);
        assert_eq!(bracket_depth("  <Button"), 0);
        assert_eq!(bracket_depth("foo(bar, {"), 2);
    }

    #[test]
    fn test_bracket_depth_close() {
        assert_eq!(bracket_depth("]}"), -2);
        assert_eq!(bracket_depth(")"), -1);
    }

    #[test]
    fn test_bracket_depth_ignores_string_literals() {
        assert_eq!(bracket_depth(r#"  foo="{not a bracket}""#), 0);
        assert_eq!(bracket_depth("  foo='[still not]'"), 0);
    }

    // -- dedup_import_specifiers tests --

    #[test]
    fn test_dedup_import_removes_duplicates() {
        let mut lines =
            vec!["import { Content, Content, Content } from '@patternfly/react-core';".to_string()];
        dedup_import_specifiers(&mut lines);
        let count = lines[0].matches("Content").count();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_dedup_import_preserves_different_specifiers() {
        let mut lines = vec!["import { Foo, Bar, Foo, Baz, Bar } from '@pkg';".to_string()];
        dedup_import_specifiers(&mut lines);
        assert_eq!(lines[0].matches("Foo").count(), 1);
        assert_eq!(lines[0].matches("Bar").count(), 1);
        assert_eq!(lines[0].matches("Baz").count(), 1);
    }

    // -- get_matched_text tests --

    #[test]
    fn test_get_matched_text_prop_name_first() {
        let mut vars = BTreeMap::new();
        vars.insert(
            "propName".to_string(),
            serde_json::Value::String("isActive".to_string()),
        );
        vars.insert(
            "componentName".to_string(),
            serde_json::Value::String("Button".to_string()),
        );
        let incident = make_test_incident("file:///test.tsx", 1, vars);
        assert_eq!(get_matched_text_from_incident(&incident), "isActive");
    }

    #[test]
    fn test_get_matched_text_empty_when_no_known_vars() {
        let incident = make_test_incident("", 1, BTreeMap::new());
        assert_eq!(get_matched_text_from_incident(&incident), "");
    }

    // -- get_matched_text_for_rename tests --

    #[test]
    fn test_get_matched_text_for_rename_prefers_prop_name() {
        let mut vars = BTreeMap::new();
        vars.insert(
            "propName".into(),
            serde_json::Value::String("spaceItems".into()),
        );
        let incident = make_test_incident("file:///test.tsx", 1, vars);
        let mappings = vec![RenameMapping {
            old: "spaceItems".into(),
            new: "gap".into(),
        }];
        assert_eq!(
            get_matched_text_for_rename_from_incident(&incident, &mappings),
            "spaceItems"
        );
    }

    #[test]
    fn test_get_matched_text_for_rename_falls_back_to_prop_value() {
        let mut vars = BTreeMap::new();
        vars.insert(
            "propName".into(),
            serde_json::Value::String("variant".into()),
        );
        vars.insert(
            "propValue".into(),
            serde_json::Value::String("light".into()),
        );
        let incident = make_test_incident("file:///test.tsx", 1, vars);
        let mappings = vec![RenameMapping {
            old: "light".into(),
            new: "secondary".into(),
        }];
        assert_eq!(
            get_matched_text_for_rename_from_incident(&incident, &mappings),
            "light"
        );
    }

    // -- post_process_lines integration test --

    #[test]
    fn test_post_process_deduplicates_imports() {
        let provider = JsFixProvider::new();
        let mut lines = vec![
            "import { Content, Content } from '@patternfly/react-core';".to_string(),
            "const x = 1;".to_string(),
        ];
        provider.post_process_lines(&mut lines);
        assert_eq!(lines[0].matches("Content").count(), 1);
        assert_eq!(lines[1], "const x = 1;");
    }

    // -- npm resolution helper tests --

    #[test]
    fn test_extract_major() {
        assert_eq!(extract_major("^6.4.1"), 6);
        assert_eq!(extract_major("~5.0.0"), 5);
        assert_eq!(extract_major("6.4.1"), 6);
        assert_eq!(extract_major(">=7.0.0"), 7);
        assert_eq!(extract_major("^6.0.0-alpha.1"), 6);
    }

    #[test]
    fn test_parse_semver_tuple() {
        assert_eq!(parse_semver_tuple("6.4.1"), Some((6, 4, 1)));
        assert_eq!(parse_semver_tuple("5.0.0"), Some((5, 0, 0)));
        assert_eq!(parse_semver_tuple("6.0.0-alpha.1"), Some((6, 0, 0)));
    }

    // -- dependent incident detection test --

    #[test]
    fn test_dependent_incident_updates_correct_package() {
        let dir = tempfile::tempdir().unwrap();
        let pkg_json = dir.path().join("package.json");
        std::fs::write(
            &pkg_json,
            r#"{
  "devDependencies": {
    "@patternfly/react-core": "^6.4.1",
    "@patternfly/react-topology": "5.2.1"
  }
}"#,
        )
        .unwrap();

        // Create a dependent incident (as the frontend-analyzer-provider would)
        let mut vars = BTreeMap::new();
        vars.insert(
            "dependencyName".into(),
            serde_json::Value::String("@patternfly/react-topology".into()),
        );
        vars.insert(
            "dependencyVersion".into(),
            serde_json::Value::String("5.2.1".into()),
        );
        vars.insert(
            "dependencyType".into(),
            serde_json::Value::String("devDependencies".into()),
        );
        vars.insert(
            "isDependentOf".into(),
            serde_json::Value::String("@patternfly/react-core".into()),
        );
        vars.insert(
            "dependentConstraint".into(),
            serde_json::Value::String("^5.1.1".into()),
        );

        let incident = make_test_incident(&format!("file://{}", pkg_json.display()), 4, vars);

        // Call the function — it will try to query npm for react-topology.
        // In CI without network, the npm query may fail, but the function
        // should gracefully return None rather than panic.
        let result = plan_ensure_npm_dependency(
            "semver-dep-update-patternfly-react-core",
            &incident,
            "@patternfly/react-core",
            "^6.4.1",
            &pkg_json,
        );

        // If npm is reachable, we get a fix targeting react-topology (not react-core).
        // If npm is unreachable, we get an empty vec (graceful degradation).
        if let Some(fix) = result.first() {
            assert!(
                fix.description.contains("react-topology"),
                "Fix should target react-topology, got: {}",
                fix.description
            );
            assert!(
                !fix.description.contains("react-core"),
                "Fix should NOT mention react-core as the package to update"
            );
        }
        // Either way: no panic, no crash.
    }

    // -- non-dependent incident preserves existing behavior --

    #[test]
    fn test_non_dependent_incident_uses_provided_version() {
        let dir = tempfile::tempdir().unwrap();
        let pkg_json = dir.path().join("package.json");
        std::fs::write(
            &pkg_json,
            r#"{
  "dependencies": {
    "@patternfly/react-core": "5.3.4"
  }
}"#,
        )
        .unwrap();

        let vars = BTreeMap::new();
        let incident = make_test_incident(&format!("file://{}", pkg_json.display()), 3, vars);

        let result = plan_ensure_npm_dependency(
            "semver-dep-update-patternfly-react-core",
            &incident,
            "@patternfly/react-core",
            "^6.4.1",
            &pkg_json,
        );

        assert_eq!(
            result.len(),
            1,
            "Should produce exactly one fix for primary dep update"
        );
        let fix = &result[0];
        assert_eq!(fix.edits.len(), 1);
        assert!(fix.edits[0].new_text.contains("6.4.1"));
        assert!(fix.description.contains("react-core"));
    }

    #[test]
    fn parse_yarn_missing_peers_basic() {
        let output = "\
➤ YN0000: · Yarn 4.6.0
➤ YN0002: @patternfly/react-charts@npm:8.4.1 doesn't provide victory (p1a2b3), requested by @patternfly/react-charts.
➤ YN0002: @patternfly/react-charts@npm:8.4.1 doesn't provide victory-core (p4d5e6), requested by some-dep.
➤ YN0000: · Done in 1.5s
";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert_eq!(peers.len(), 2);
        assert_eq!(peers[0].peer_name, "victory");
        // "requested by" trailer matches the provider here
        assert_eq!(peers[0].requested_by, "@patternfly/react-charts");
        assert_eq!(peers[1].peer_name, "victory-core");
        // "requested by" trailer names a different package than the provider
        assert_eq!(peers[1].requested_by, "some-dep");
    }

    #[test]
    fn parse_yarn_missing_peers_with_ansi() {
        // Simulate ANSI color codes wrapping the warning code
        let output = "\x1b[33m➤\x1b[0m \x1b[33mYN0002\x1b[0m: \x1b[38;5;173mfoo@npm:1.0.0\x1b[0m doesn't provide \x1b[38;5;111mbar\x1b[0m (p7g8h9), requested by baz.\n";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert_eq!(peers.len(), 1);
        assert_eq!(peers[0].peer_name, "bar");
        // "requested by" trailer takes precedence over provider
        assert_eq!(peers[0].requested_by, "baz");
    }

    #[test]
    fn parse_yarn_missing_peers_scoped_package() {
        let output = "➤ YN0002: @scope/some-pkg@npm:2.0.0 doesn't provide @scope/peer-pkg (pabcde), requested by other-dep.\n";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert_eq!(peers.len(), 1);
        assert_eq!(peers[0].peer_name, "@scope/peer-pkg");
        // "requested by" trailer takes precedence
        assert_eq!(peers[0].requested_by, "other-dep");
    }

    #[test]
    fn parse_yarn_missing_peers_deduplicates() {
        let output = "\
➤ YN0002: pkg-a@npm:1.0.0 doesn't provide victory (p11111), requested by dep-a.
➤ YN0002: pkg-b@npm:2.0.0 doesn't provide victory (p22222), requested by dep-b.
➤ YN0002: pkg-c@npm:3.0.0 doesn't provide victory (p33333), requested by dep-c.
";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert_eq!(peers.len(), 1);
        assert_eq!(peers[0].peer_name, "victory");
        // First requester wins for deduplication; uses "requested by" trailer
        assert_eq!(peers[0].requested_by, "dep-a");
    }

    #[test]
    fn parse_yarn_missing_peers_workspace_box_separator() {
        // Yarn 4.6.0 uses "│ " (box-drawing vertical bar) separator for
        // workspace-level peer dep warnings. This is the actual format
        // observed when a workspace doesn't provide a peer dep required
        // by one of its dependencies. The "requested by" package at the
        // end of each line should be used as requested_by (not the workspace name).
        let output = "\
➤ YN0000: · Yarn 4.6.0
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed
➤ YN0000: ┌ Post-resolution validation
➤ YN0002: │ pipelines-console-plugin@workspace:. doesn't provide @patternfly/react-drag-drop (pccfa6), requested by @patternfly/react-component-groups.
➤ YN0002: │ pipelines-console-plugin@workspace:. doesn't provide axe-core (p27d9e), requested by cypress-axe.
➤ YN0002: │ pipelines-console-plugin@workspace:. doesn't provide i18next (p374d5), requested by react-i18next.
➤ YN0086: │ Some peer dependencies are incorrectly met by your project; run yarn explain peer-requirements <hash> for details, where <hash> is the six-letter p-prefixed code.
➤ YN0000: └ Completed
➤ YN0000: · Done with warnings in 1s 4ms
";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert_eq!(peers.len(), 3);
        assert_eq!(peers[0].peer_name, "@patternfly/react-drag-drop");
        assert_eq!(peers[0].requested_by, "@patternfly/react-component-groups");
        assert_eq!(peers[1].peer_name, "axe-core");
        assert_eq!(peers[1].requested_by, "cypress-axe");
        assert_eq!(peers[2].peer_name, "i18next");
        assert_eq!(peers[2].requested_by, "react-i18next");
    }

    #[test]
    fn parse_yarn_missing_peers_mixed_formats() {
        // Mix of workspace-level (with │) and package-level (without │) warnings.
        // Workspace-level uses "requested by" for requested_by; package-level
        // also uses "requested by" when available, falling back to the provider.
        let output = "\
➤ YN0002: │ my-app@workspace:. doesn't provide @patternfly/react-drag-drop (pccfa6), requested by @patternfly/react-component-groups.
➤ YN0002: @patternfly/react-charts@npm:8.4.1 doesn't provide victory (p1a2b3), requested by @patternfly/react-charts.
";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert_eq!(peers.len(), 2);
        assert_eq!(peers[0].peer_name, "@patternfly/react-drag-drop");
        assert_eq!(peers[0].requested_by, "@patternfly/react-component-groups");
        assert_eq!(peers[1].peer_name, "victory");
        assert_eq!(peers[1].requested_by, "@patternfly/react-charts");
    }

    #[test]
    fn parse_yarn_missing_peers_no_warnings() {
        let output = "➤ YN0000: · Yarn 4.6.0\n➤ YN0000: · Done in 0.5s\n";
        let peers = super::parse_yarn_missing_peer_deps(output);
        assert!(peers.is_empty());
    }

    #[test]
    fn lookup_peer_dep_version_finds_version() {
        let dir = tempfile::tempdir().unwrap();
        let pkg_dir = dir.path().join("node_modules/@patternfly/react-charts");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(
            pkg_dir.join("package.json"),
            r#"{
  "name": "@patternfly/react-charts",
  "peerDependencies": {
    "victory-core": "^37.3.6",
    "echarts": "^5.6.0 || ^6.0.0"
  }
}"#,
        )
        .unwrap();

        assert_eq!(
            super::lookup_peer_dep_version(dir.path(), "@patternfly/react-charts", "victory-core"),
            Some("^37.3.6".to_string())
        );
        assert_eq!(
            super::lookup_peer_dep_version(dir.path(), "@patternfly/react-charts", "echarts"),
            Some("^5.6.0 || ^6.0.0".to_string())
        );
        assert_eq!(
            super::lookup_peer_dep_version(dir.path(), "@patternfly/react-charts", "nonexistent"),
            None
        );
    }

    #[test]
    fn lookup_peer_dep_version_missing_package() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(
            super::lookup_peer_dep_version(dir.path(), "nonexistent-pkg", "some-peer"),
            None
        );
    }

    // ── semver range compatibility tests ──

    #[test]
    fn range_compatible_caret_subset_of_or_range() {
        // ^17.0.1 is a subset of ^17 || ^18 || ^19
        assert!(super::is_range_already_compatible(
            "^17.0.1",
            "^17 || ^18 || ^19"
        ));
    }

    #[test]
    fn range_compatible_identical_ranges() {
        assert!(super::is_range_already_compatible("^6.4.1", "^6.4.1"));
    }

    #[test]
    fn range_incompatible_different_majors() {
        // ^11.7.3 does NOT satisfy ^17.0.3
        assert!(!super::is_range_already_compatible("^11.7.3", "^17.0.3"));
    }

    #[test]
    fn range_compatible_exact_within_caret() {
        // 1.2.3 is within ^1.0.0
        assert!(super::is_range_already_compatible("1.2.3", "^1.0.0"));
    }

    #[test]
    fn range_compatible_tilde_within_caret() {
        // ~1.2.3 (>=1.2.3 <1.3.0) is within ^1.0.0 (>=1.0.0 <2.0.0)
        assert!(super::is_range_already_compatible("~1.2.3", "^1.0.0"));
    }

    #[test]
    fn range_incompatible_caret_not_in_tilde() {
        // ^1.0.0 (>=1.0.0 <2.0.0) is NOT within ~1.2.3 (>=1.2.3 <1.3.0)
        assert!(!super::is_range_already_compatible("^1.0.0", "~1.2.3"));
    }

    #[test]
    fn range_compatible_or_range_within_star() {
        // ^17 || ^18 is within * (any version)
        assert!(super::is_range_already_compatible("^17 || ^18", ">=0.0.0"));
    }

    #[test]
    fn range_unparseable_returns_false() {
        // Dist tags, git URLs, etc. should return false (allow update)
        assert!(!super::is_range_already_compatible("latest", "^1.0.0"));
        assert!(!super::is_range_already_compatible(
            "^1.0.0",
            "git+ssh://foo"
        ));
    }

    #[test]
    fn range_compatible_prerelease() {
        // ^6.30.3-pre-v6.0 should be within ^6.0.0
        assert!(super::is_range_already_compatible(
            "^6.30.3-pre-v6.0",
            "^6.0.0"
        ));
    }

    #[test]
    fn range_compatible_higher_patch_not_downgraded() {
        // Consumer has ^6.4.2, rule wants ^6.4.1. The consumer's range is
        // already within the required range, so no update should occur.
        // This prevents version specifier downgrades.
        assert!(super::is_range_already_compatible("^6.4.2", "^6.4.1"));
    }

    #[test]
    fn range_compatible_higher_minor_not_downgraded() {
        // Consumer has ^6.5.0, rule wants ^6.4.1. Same principle.
        assert!(super::is_range_already_compatible("^6.5.0", "^6.4.1"));
    }

    #[test]
    fn baseline_diff_filters_preexisting_peers() {
        // Simulate the before/after diff logic used in run_yarn_install_and_resolve_peers.
        // Baseline (before fixes): these peers were already unmet
        let baseline: std::collections::HashSet<String> = [
            "@patternfly/react-styles",
            "axe-core",
            "i18next",
            "mocha",
            "react-redux",
            "react-router",
            "react-router-dom",
            "redux",
            "redux-thunk",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();

        // After fixes: some are still unmet, plus one new one
        let after_output = "\
➤ YN0002: │ my-app@workspace:. doesn't provide @patternfly/react-drag-drop (pccfa6), requested by @patternfly/react-component-groups.
➤ YN0002: │ my-app@workspace:. doesn't provide axe-core (p27d9e), requested by cypress-axe.
➤ YN0002: │ my-app@workspace:. doesn't provide i18next (p374d5), requested by react-i18next.
➤ YN0002: │ my-app@workspace:. doesn't provide mocha (p7ec1d), requested by cypress-multi-reporters and other dependencies.
➤ YN0002: │ my-app@workspace:. doesn't provide react-redux (pa391f), requested by @openshift/dynamic-plugin-sdk-extensions and other dependencies.
➤ YN0002: │ my-app@workspace:. doesn't provide react-router-dom (p7d47e), requested by react-router-dom-v5-compat.
➤ YN0002: │ my-app@workspace:. doesn't provide redux (pd1d52), requested by @openshift/dynamic-plugin-sdk-extensions and other dependencies.
➤ YN0002: │ my-app@workspace:. doesn't provide redux-thunk (pd9e06), requested by @openshift/dynamic-plugin-sdk-utils.
";
        let all_missing = super::parse_yarn_missing_peer_deps(after_output);

        // Filter: only peers NOT in the baseline should remain
        let new_peers: Vec<_> = all_missing
            .into_iter()
            .filter(|p| !baseline.contains(&p.peer_name))
            .collect();

        // Only @patternfly/react-drag-drop is new
        assert_eq!(new_peers.len(), 1);
        assert_eq!(new_peers[0].peer_name, "@patternfly/react-drag-drop");
        assert_eq!(
            new_peers[0].requested_by,
            "@patternfly/react-component-groups"
        );
    }

    #[test]
    fn baseline_diff_installs_nothing_when_no_new_peers() {
        // If no new peers are introduced, nothing should be installed
        let baseline: std::collections::HashSet<String> = ["react-redux", "redux"]
            .iter()
            .map(|s| s.to_string())
            .collect();

        let after_output = "\
➤ YN0002: │ my-app@workspace:. doesn't provide react-redux (pa391f), requested by some-pkg.
➤ YN0002: │ my-app@workspace:. doesn't provide redux (pd1d52), requested by some-pkg.
";
        let all_missing = super::parse_yarn_missing_peer_deps(after_output);
        let new_peers: Vec<_> = all_missing
            .into_iter()
            .filter(|p| !baseline.contains(&p.peer_name))
            .collect();

        assert!(new_peers.is_empty());
    }
}