fallow-core 3.32.0

Internal detector backend for fallow-engine and fallow-api
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
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use rustc_hash::{FxHashMap, FxHashSet};

use fallow_config::{IgnoreDependencyMatcher, PackageJson, ResolvedConfig};

use crate::discover::FileId;
use crate::extract::ModuleInfo;
use crate::graph::ModuleGraph;
use crate::resolve::ResolvedModule;
use crate::results::{
    DependencyLocation, DevDependencyInProduction, ImportSite, TestOnlyDependency,
    TypeOnlyDependency, UnlistedDependency, UnresolvedImport, UnusedDependency,
};
use crate::suppress::{IssueKind, SuppressionContext};

use super::bundle_externalization::source_sets_packages_external;
use super::gitignored_targets::GitignoredTargets;
use super::package_json_utils::{find_dep_line_in_json, read_pkg_json_content};
use super::predicates::{
    is_builtin_module, is_config_file, is_implicit_dependency, is_path_alias, is_virtual_module,
};
use super::{LineOffsetsMap, byte_offset_to_line_col};

use crate::plugins::{CompiledPathRule, ProvidedDependencyRule};

/// Return `true` if a virtual-module `prefix` from the active plugin set covers
/// `spec`. Two shapes are recognised:
///
/// - **Plain prefix match** (`@docusaurus/`, `@theme/`, `#imports`, `$app/`):
///   any specifier that `starts_with(prefix)` is covered. This handles the
///   common case where a plugin registers an entire namespace.
/// - **Trailing-slash exact-bare match** (`ember/`): the bare specifier `ember`
///   also matches (via the second branch's `strip_suffix('/')` shortcut),
///   while real npm packages like `ember-cli` and `ember-data` deliberately
///   do not. A no-slash entry would prefix-match them and silence legitimate
///   missing-dep reports.
///
/// Centralised here so the `unresolved-import` and `unlisted-dependency`
/// suppression sites use the same matcher as plugin test helpers (see
/// `Plugin::virtual_module_prefixes` consumers in `crates/core/src/plugins/`).
#[must_use]
pub fn matches_virtual_prefix(prefix: &str, spec: &str) -> bool {
    spec.starts_with(prefix) || prefix.strip_suffix('/').is_some_and(|base| spec == base)
}

/// Return `true` if a workspace `package.json` path is covered by `ignorePatterns`.
///
/// Mirrors the source-walker behavior in `fallow_core::discover::walk`: the glob
/// is matched against the project-root-relative path so relative patterns like
/// `**/dist/**` work as users expect. Without this check, workspace discovery
/// would include build-artifact `package.json` files (e.g., `dist/package.json`
/// generated by ng-packagr / tsc) and report their dependencies as unused.
/// See issue #124.
fn is_package_json_ignored(ws_pkg_path: &Path, config: &ResolvedConfig) -> bool {
    is_package_json_ignored_under(ws_pkg_path, &config.root, &config.ignore_patterns)
}

/// [`is_package_json_ignored`] for a caller that has the project root and the
/// ignore patterns but no [`ResolvedConfig`].
fn is_package_json_ignored_under(
    ws_pkg_path: &Path,
    root: &Path,
    ignore_patterns: &fallow_config::IgnorePatternSet,
) -> bool {
    let relative = ws_pkg_path.strip_prefix(root).unwrap_or(ws_pkg_path);
    ignore_patterns.is_match(relative)
}

/// Per-category configuration for unused dependency detection.
///
/// Each dependency category (prod, dev, optional) has slightly different
/// filter rules. This struct captures those differences so a single helper
/// can handle all three categories.
pub struct DepCategoryConfig {
    /// Which `DependencyLocation` variant to tag results with.
    pub location: DependencyLocation,
    /// Whether to check `is_implicit_dependency` (prod + optional = true, dev = false).
    pub check_implicit: bool,
    /// Whether to check `is_known_tooling_dependency` (dev = true, others = false).
    pub check_known_tooling: bool,
    /// Whether to check `plugin_tooling` set (prod + dev = true, optional = false).
    pub check_plugin_tooling: bool,
    /// Whether a plugin tooling dependency needs evidence that the project
    /// uses the plugin (dev = true): the plugin found its own config file, or
    /// a script, CI workflow or git hook invokes its tool. When true, the
    /// check reads `credited_plugin_tooling` instead of `plugin_tooling`.
    pub plugin_tooling_needs_evidence: bool,
}

/// Shared sets used by `collect_unused_for_category` to filter dependencies.
pub struct SharedDepSets<'a> {
    pub plugin_referenced: &'a FxHashSet<&'a str>,
    pub package_plugin_referenced: &'a FxHashSet<&'a str>,
    pub plugin_tooling: &'a FxHashSet<&'a str>,
    /// The plugin tooling dependencies whose plugin found evidence of use.
    pub credited_plugin_tooling: &'a FxHashSet<&'a str>,
    /// Every dependency name the project declares, in any manifest and any
    /// section. A declared `X` credits a `@types/X` devDependency.
    pub declared_packages: &'a FxHashSet<&'a str>,
    /// The project root, where a command-line tool's own config file may
    /// live for any package.
    pub project_root: &'a Path,
    pub script_used: &'a FxHashSet<&'a str>,
    pub ignore_deps: &'a IgnoreDependencyMatcher,
}

struct PeerDependencyResolver {
    cache: FxHashMap<(PathBuf, String), Vec<InstalledPeer>>,
}

/// One entry of an installed package's `peerDependencies`.
#[derive(Clone)]
struct InstalledPeer {
    name: String,
    /// `peerDependenciesMeta.<name>.optional` is set.
    optional: bool,
}

impl PeerDependencyResolver {
    fn new() -> Self {
        Self {
            cache: FxHashMap::default(),
        }
    }

    /// Every package that a seed package lists in `peerDependencies`, directly
    /// or through another credited peer, mapped to the packages that list it.
    ///
    /// Optional peers (`peerDependenciesMeta.<name>.optional`) count too: a
    /// project lists an optional peer of a package it uses to turn on a feature
    /// of that package, which loads the peer at runtime where the import graph
    /// does not see it. Only used packages seed the closure, so the peers of an
    /// unused package get no credit.
    ///
    /// A required peer always passes credit on to its own peers, because the
    /// host needs it. An optional peer passes credit on only when `listed`
    /// (the names that the root and workspace manifests declare) contains it.
    /// An optional peer that the project does not list is not turned on, so
    /// its peers get no credit through it.
    fn peer_dependency_closure<'b>(
        &mut self,
        package_root: &Path,
        seeds: impl IntoIterator<Item = &'b str>,
        listed: &FxHashSet<String>,
    ) -> FxHashMap<String, Vec<String>> {
        let mut hosts_by_peer: FxHashMap<String, Vec<String>> = FxHashMap::default();
        let mut expanded = FxHashSet::default();
        let mut queue: Vec<String> = seeds.into_iter().map(str::to_string).collect();

        while let Some(package_name) = queue.pop() {
            if !expanded.insert(package_name.clone()) {
                continue;
            }

            for peer in self.peer_dependencies_for(package_root, &package_name) {
                if !peer.optional || listed.contains(peer.name.as_str()) {
                    queue.push(peer.name.clone());
                }
                hosts_by_peer
                    .entry(peer.name)
                    .or_default()
                    .push(package_name.clone());
            }
        }

        hosts_by_peer
    }

    fn peer_dependencies_for(
        &mut self,
        package_root: &Path,
        package_name: &str,
    ) -> Vec<InstalledPeer> {
        let key = (package_root.to_path_buf(), package_name.to_string());
        if let Some(cached) = self.cache.get(&key) {
            return cached.clone();
        }

        let peer_dependencies: Vec<InstalledPeer> =
            find_installed_package_json(package_root, package_name)
                .and_then(|path| PackageJson::load(&path).ok())
                .map(|pkg| {
                    pkg.peer_dependency_names()
                        .into_iter()
                        .map(|name| InstalledPeer {
                            optional: pkg.peer_dependency_is_optional(&name),
                            name,
                        })
                        .collect()
                })
                .unwrap_or_default();

        self.cache.insert(key, peer_dependencies.clone());
        peer_dependencies
    }
}

/// The packages that give `package_name` peer-dependency credit in the
/// unused-dependency check: each one is used, or credited itself, and lists
/// `package_name` in its installed `peerDependencies`, required or optional.
///
/// The check runs one closure for the root manifest and one for each
/// workspace, and this function runs the same closures. The root closure
/// starts from every package that the import graph records and looks up the
/// installed manifests from `project_root` and its ancestors. A workspace
/// closure starts from the packages that the files of that workspace import
/// and looks up the installed manifests from the workspace root. In every
/// closure, an optional peer passes credit on only when the root
/// `package.json` or a workspace `package.json` lists it, as in the root and
/// workspace checks. A workspace `package.json` that `ignore_patterns` matches
/// or that does not load does not count and gets no closure, as in those
/// checks. The result is the union of the hosts, sorted, and empty when no
/// closure credits `package_name`.
pub fn peer_dependency_hosts(
    graph: &ModuleGraph,
    project_root: &Path,
    workspace_roots: &[&Path],
    ignore_patterns: &fallow_config::IgnorePatternSet,
    package_name: &str,
) -> Vec<String> {
    let root_declared = PackageJson::load(&project_root.join("package.json"))
        .map(|pkg| pkg.all_dependency_names())
        .unwrap_or_default();
    let workspace_manifests: Vec<(&Path, Vec<String>)> = workspace_roots
        .iter()
        .copied()
        .filter_map(|ws_root| {
            let pkg_path = ws_root.join("package.json");
            if is_package_json_ignored_under(&pkg_path, project_root, ignore_patterns) {
                return None;
            }
            let pkg = PackageJson::load(&pkg_path).ok()?;
            Some((ws_root, pkg.all_dependency_names()))
        })
        .collect();
    let listed = closure_listed_names(
        &root_declared,
        workspace_manifests
            .iter()
            .flat_map(|(_, declared)| declared.iter()),
    );
    let workspace_roots: Vec<&Path> = workspace_manifests
        .iter()
        .map(|(ws_root, _)| *ws_root)
        .collect();
    let mut resolver = PeerDependencyResolver::new();
    let mut hosts = resolver
        .peer_dependency_closure(
            project_root,
            graph.package_usage.keys().map(String::as_str),
            &listed,
        )
        .remove(package_name)
        .unwrap_or_default();
    let ownership = WorkspaceOwnershipIndex::new(graph, &workspace_roots);
    let used_by_workspace = collect_workspace_used_packages(graph, &workspace_roots, &ownership);
    for ws_root in &workspace_roots {
        let Some(used) = used_by_workspace.get(ws_root) else {
            continue;
        };
        if let Some(ws_hosts) = resolver
            .peer_dependency_closure(ws_root, used.iter().copied(), &listed)
            .remove(package_name)
        {
            hosts.extend(ws_hosts);
        }
    }
    hosts.sort_unstable();
    hosts.dedup();
    hosts
}

fn find_installed_package_json(package_root: &Path, package_name: &str) -> Option<PathBuf> {
    for base in package_root.ancestors() {
        let candidate = node_modules_package_json(base, package_name);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

fn node_modules_package_json(base: &Path, package_name: &str) -> PathBuf {
    let mut path = base.join("node_modules");
    for segment in package_name.split('/') {
        path.push(segment);
    }
    path.join("package.json")
}

/// Map graph files to their deepest matching workspace once per analysis.
///
/// Dependency detectors repeatedly need to answer which workspace owns a file.
/// Keeping the existing deepest-match semantics in one per-run index avoids
/// scanning every workspace for every package-usage entry or import site.
struct WorkspaceOwnershipIndex {
    workspace_by_file: Vec<Option<usize>>,
    /// For each workspace, the workspaces whose roots contain its root,
    /// nearest first. The root manifest is not a workspace and is not listed.
    ancestors_by_workspace: Vec<Vec<usize>>,
}

impl WorkspaceOwnershipIndex {
    fn new(graph: &ModuleGraph, workspace_roots: &[&Path]) -> Self {
        use rayon::prelude::*;

        let by_root: FxHashMap<&Path, usize> = workspace_roots
            .iter()
            .enumerate()
            .map(|(index, root)| (*root, index))
            .collect();
        let workspace_by_file = graph
            .modules
            .par_iter()
            .map(|module| {
                module
                    .path
                    .ancestors()
                    .find_map(|ancestor| by_root.get(ancestor).copied())
            })
            .collect();
        let ancestors_by_workspace = workspace_roots
            .iter()
            .map(|root| {
                root.ancestors()
                    .skip(1)
                    .filter_map(|ancestor| by_root.get(ancestor).copied())
                    .collect()
            })
            .collect();

        Self {
            workspace_by_file,
            ancestors_by_workspace,
        }
    }

    fn ancestors_of(&self, workspace_index: usize) -> &[usize] {
        self.ancestors_by_workspace
            .get(workspace_index)
            .map_or(&[], Vec::as_slice)
    }

    fn workspace_index_for_file(&self, file_id: FileId) -> Option<usize> {
        self.workspace_by_file
            .get(file_id.0 as usize)
            .copied()
            .flatten()
    }

    fn root_for_file<'a>(&self, file_id: FileId, workspace_roots: &[&'a Path]) -> Option<&'a Path> {
        self.workspace_index_for_file(file_id)
            .and_then(|index| workspace_roots.get(index).copied())
    }
}

/// One workspace manifest, read once for the whole unused-dependency pass.
///
/// The per-workspace pass reads `package.json` again to locate declaration
/// lines, but the cross-workspace indices need only the fields below, so they
/// are collected up front instead of inside the parallel per-workspace map.
struct WorkspaceManifest<'a> {
    /// Workspace root, the key every usage index is built against.
    root: &'a Path,
    /// Manifest `name`, falling back to the discovered workspace name. This is
    /// the string a sibling workspace writes in its own dependency map.
    name: String,
    /// `"private": true`. The offline, deterministic signal that a workspace is
    /// never published, so consumers inline its source instead of installing it
    /// from a registry.
    is_private: bool,
    /// Every declared dependency name, in any category. Used to follow edges to
    /// private siblings: a sibling's source reaches this workspace whether it is
    /// pulled in for the shipped build or only for the local one.
    declared: FxHashSet<String>,
    /// Names the package manager installs for this workspace: `dependencies`,
    /// `devDependencies` and `optionalDependencies`. A `peerDependencies`
    /// entry alone installs nothing, so a consumer or an ancestor manifest
    /// still has to provide the package.
    installed: FxHashSet<String>,
    /// Names declared in a category that travels with the package:
    /// `dependencies`, `optionalDependencies`, and `peerDependencies`.
    /// `devDependencies` are build-time needs of this workspace alone and are
    /// never inlined into a consumer, so they are deliberately excluded.
    shipped: FxHashSet<String>,
    /// A package script bundles with every package external
    /// (`bun build --packages=external`, `esbuild --packages=external`).
    externalizes_packages: bool,
    /// The program file arguments that the package scripts run with a node
    /// runner outside test mode, as written, for example `build.mjs` in
    /// `node build.mjs`. These files and their import closure are the build
    /// files for the esbuild `packages: 'external'` signal. The paths resolve
    /// only for a workspace with a file that imports esbuild.
    script_programs: Vec<String>,
}

/// The program file arguments that the scripts of `pkg` run with a node
/// runner outside test mode.
fn script_program_args(pkg: &PackageJson) -> Vec<String> {
    pkg.scripts
        .iter()
        .flat_map(|scripts| scripts.values())
        .flat_map(|script| crate::scripts::script_program_files(script))
        .collect()
}

/// Absolute paths of the program files of `manifest`, resolved against the
/// workspace root.
fn script_file_paths(manifest: &WorkspaceManifest<'_>) -> FxHashSet<PathBuf> {
    manifest
        .script_programs
        .iter()
        .map(|file| normalize_lexically(&resolve_script_file(&manifest.root.join(file))))
        .collect()
}

/// The file that a script file argument names. A runtime resolves an argument
/// without an extension in this order: the exact file, the argument with a
/// source extension, then the index file of the directory that it names. When
/// no candidate exists, the argument path stays as it is.
fn resolve_script_file(base: &Path) -> PathBuf {
    if base.is_file() {
        return base.to_path_buf();
    }
    let with_extension = crate::discover::SOURCE_EXTENSIONS
        .iter()
        .find_map(|extension| {
            let mut candidate = base.as_os_str().to_owned();
            candidate.push(".");
            candidate.push(extension);
            let candidate = PathBuf::from(candidate);
            candidate.is_file().then_some(candidate)
        });
    let index = || {
        crate::discover::SOURCE_EXTENSIONS
            .iter()
            .find_map(|extension| {
                let candidate = base.join(format!("index.{extension}"));
                candidate.is_file().then_some(candidate)
            })
    };
    with_extension
        .or_else(index)
        .unwrap_or_else(|| base.to_path_buf())
}

/// Remove `.` components and apply `..` components without a file system
/// lookup, so `./build.mjs` and `scripts/../build.mjs` compare equal to the
/// module path.
fn normalize_lexically(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                normalized.pop();
            }
            other => normalized.push(other),
        }
    }
    normalized
}

/// Names a workspace carries into anything that inlines its source.
///
/// `peerDependencies` count because a peer is by definition supplied by the
/// consumer, and `optionalDependencies` count because an optional package that
/// is present is loaded from the consumer's tree like any other.
fn shipped_dependency_names(pkg: &PackageJson) -> FxHashSet<String> {
    pkg.production_dependency_names()
        .into_iter()
        .chain(pkg.optional_dependency_names())
        .chain(
            pkg.peer_dependencies
                .iter()
                .flat_map(|peers| peers.keys().cloned()),
        )
        .collect()
}

/// Read every workspace manifest once, in parallel, dropping workspaces whose
/// `package.json` is missing, unparsable, or covered by `ignorePatterns`.
fn read_workspace_manifests<'a>(
    workspaces: &'a [fallow_config::WorkspaceInfo],
    config: &ResolvedConfig,
) -> Vec<WorkspaceManifest<'a>> {
    use rayon::prelude::*;
    workspaces
        .par_iter()
        .filter_map(|workspace| {
            let (_, _, pkg) = read_workspace_package(workspace, config)?;
            Some(WorkspaceManifest {
                root: workspace.root.as_path(),
                name: pkg.name.clone().unwrap_or_else(|| workspace.name.clone()),
                is_private: pkg.private == Some(true),
                declared: pkg.all_dependency_names().into_iter().collect(),
                installed: pkg
                    .production_dependency_names()
                    .into_iter()
                    .chain(pkg.dev_dependency_names())
                    .chain(pkg.optional_dependency_names())
                    .collect(),
                shipped: shipped_dependency_names(&pkg),
                externalizes_packages: pkg.scripts.as_ref().is_some_and(|scripts| {
                    scripts
                        .values()
                        .any(|script| crate::scripts::script_externalizes_packages(script))
                }),
                script_programs: script_program_args(&pkg),
            })
        })
        .collect()
}

fn dependency_owning_workspace_roots<'a>(manifests: &[WorkspaceManifest<'a>]) -> Vec<&'a Path> {
    manifests.iter().map(|manifest| manifest.root).collect()
}

/// Reverse index: workspace root -> third-party packages that workspace inherits
/// from the private siblings its build inlines.
///
/// A private, unpublished sibling is never installed from a registry, so a
/// consumer that depends on it bundles its source. The package manager then has
/// to resolve that sibling's own packages from the consumer's manifest, which is
/// why hoisting them into the consumer is correct rather than dead weight. See
/// discussion #2244.
///
/// The walk follows private siblings only, transitively, because a published
/// package brings its own dependency tree and needs no hoisting. Crediting a
/// published sibling's packages would suppress a genuine finding. Workspace
/// graphs can be cyclic, so each walk carries a visited set.
///
/// A consumer in `externalizing` leaves every package out of its bundle, so it
/// does not inline a sibling and gets no credit.
fn collect_bundled_workspace_usage<'a>(
    manifests: &[WorkspaceManifest<'a>],
    workspace_used_packages: &FxHashMap<&'a Path, FxHashSet<&'a str>>,
    externalizing: &FxHashSet<usize>,
) -> FxHashMap<&'a Path, FxHashSet<&'a str>> {
    let private_by_name: FxHashMap<&str, usize> = manifests
        .iter()
        .enumerate()
        .filter(|(_, manifest)| manifest.is_private)
        .map(|(index, manifest)| (manifest.name.as_str(), index))
        .collect();
    if private_by_name.is_empty() {
        return FxHashMap::default();
    }

    use rayon::prelude::*;
    manifests
        .par_iter()
        .enumerate()
        .filter(|(index, _)| !externalizing.contains(index))
        .map(|(index, consumer)| {
            let bundled = bundled_packages_for(
                index,
                consumer,
                manifests,
                &private_by_name,
                workspace_used_packages,
            );
            (consumer.root, bundled)
        })
        .filter(|(_, bundled)| !bundled.is_empty())
        .collect()
}

/// Walk the private-sibling closure reachable from one consumer workspace and
/// return the packages those siblings actually import.
///
/// A package is credited only when the sibling both imports it and declares it
/// in a shipped category, so a sibling's own unused declaration cannot mask a
/// finding in the consumer, and a sibling's `devDependencies` stay out.
fn bundled_packages_for<'a>(
    consumer_index: usize,
    consumer: &WorkspaceManifest<'a>,
    manifests: &[WorkspaceManifest<'a>],
    private_by_name: &FxHashMap<&str, usize>,
    workspace_used_packages: &FxHashMap<&'a Path, FxHashSet<&'a str>>,
) -> FxHashSet<&'a str> {
    let private_siblings = |manifest: &WorkspaceManifest<'a>| -> Vec<usize> {
        manifest
            .declared
            .iter()
            .filter_map(|dep| private_by_name.get(dep.as_str()).copied())
            .collect()
    };

    let mut bundled: FxHashSet<&str> = FxHashSet::default();
    let mut visited: FxHashSet<usize> = FxHashSet::default();
    visited.insert(consumer_index);
    let mut pending = private_siblings(consumer);

    while let Some(index) = pending.pop() {
        if !visited.insert(index) {
            continue;
        }
        let sibling = &manifests[index];
        if let Some(imported) = workspace_used_packages.get(&sibling.root) {
            bundled.extend(
                imported
                    .iter()
                    .copied()
                    .filter(|package| sibling.shipped.contains(*package)),
            );
        }
        pending.extend(private_siblings(sibling));
    }

    bundled
}

/// Indices of the workspaces whose build leaves every package external.
///
/// The signal is explicit: a package script that runs
/// `bun build --packages=external` or `esbuild --packages=external`, or a build
/// file that imports `esbuild` and sets `packages: 'external'`. A build file is
/// a program file that a package script of the workspace runs with a node
/// runner outside test mode and that does not look like a test, or a module of
/// the same workspace that a build file imports (statically or dynamically). Other files, such as a test that calls esbuild, do
/// not change how the workspace is built.
/// Without a signal, a private sibling is assumed to be bundled.
fn collect_externalizing_workspaces(
    graph: &ModuleGraph,
    manifests: &[WorkspaceManifest<'_>],
    ownership: &WorkspaceOwnershipIndex,
) -> FxHashSet<usize> {
    let mut externalizing: FxHashSet<usize> = manifests
        .iter()
        .enumerate()
        .filter(|(_, manifest)| manifest.externalizes_packages)
        .map(|(index, _)| index)
        .collect();
    let Some(file_ids) = graph.package_usage.get("esbuild") else {
        return externalizing;
    };
    let candidates: FxHashSet<usize> = file_ids
        .iter()
        .filter_map(|id| ownership.workspace_index_for_file(*id))
        .filter(|index| !externalizing.contains(index))
        .collect();
    if candidates.is_empty() {
        return externalizing;
    }
    let build_files = collect_build_files(graph, manifests, ownership, &candidates);
    let mut checked: FxHashSet<FileId> = FxHashSet::default();
    for id in file_ids {
        let Some(index) = ownership.workspace_index_for_file(*id) else {
            continue;
        };
        if externalizing.contains(&index) || !checked.insert(*id) {
            continue;
        }
        if !build_files.contains(id) {
            continue;
        }
        let Some(module) = graph.modules.get(id.0 as usize) else {
            continue;
        };
        if std::fs::read_to_string(&module.path)
            .is_ok_and(|source| source_sets_packages_external(&source, &module.path))
        {
            externalizing.insert(index);
        }
    }
    externalizing
}

/// The build files of the `workspaces`: the program files that their package
/// scripts run, plus the import closure of those files within the same
/// workspace. The closure follows static and dynamic imports, but not
/// type-only imports. A build script can delegate the bundler call to a helper
/// module, as `build.mjs` does with `import "./lib/bundle.mjs"`.
fn collect_build_files(
    graph: &ModuleGraph,
    manifests: &[WorkspaceManifest<'_>],
    ownership: &WorkspaceOwnershipIndex,
    workspaces: &FxHashSet<usize>,
) -> FxHashSet<FileId> {
    let script_files: FxHashMap<usize, FxHashSet<PathBuf>> = workspaces
        .iter()
        .filter_map(|index| {
            let manifest = manifests.get(*index)?;
            (!manifest.script_programs.is_empty()).then(|| (*index, script_file_paths(manifest)))
        })
        .collect();
    if script_files.is_empty() {
        return FxHashSet::default();
    }
    let mut pending: Vec<FileId> = graph
        .modules
        .iter()
        .filter(|module| {
            ownership
                .workspace_index_for_file(module.file_id)
                .and_then(|index| script_files.get(&index))
                .is_some_and(|files| files.contains(&normalize_lexically(&module.path)))
        })
        .map(|module| module.file_id)
        .collect();
    let mut build_files: FxHashSet<FileId> = pending.iter().copied().collect();
    while let Some(id) = pending.pop() {
        let workspace = ownership.workspace_index_for_file(id);
        for (target, symbols) in graph.outgoing_edge_symbols(id) {
            let runs_target = symbols.is_empty()
                || symbols
                    .iter()
                    .any(|symbol| !symbol.is_type_only && symbol.loads_target());
            if runs_target
                && ownership.workspace_index_for_file(target) == workspace
                && build_files.insert(target)
            {
                pending.push(target);
            }
        }
    }
    build_files
}

/// Reverse index: workspace root -> packages with ANY file under that root using
/// them. Each module's deepest matching workspace root is pre-computed once in parallel so the
/// package_usage walk costs O(packages * avg_files_per_package) instead of
/// O(packages * files * workspaces).
fn collect_workspace_used_packages<'a>(
    graph: &'a ModuleGraph,
    workspace_roots: &[&'a Path],
    ownership: &WorkspaceOwnershipIndex,
) -> FxHashMap<&'a Path, FxHashSet<&'a str>> {
    let mut by_ws: FxHashMap<&Path, FxHashSet<&str>> = workspace_roots
        .iter()
        .map(|root| (*root, FxHashSet::default()))
        .collect();
    for (package_name, file_ids) in &graph.package_usage {
        for id in file_ids {
            if let Some(ws_path) = ownership.root_for_file(*id, workspace_roots) {
                by_ws
                    .entry(ws_path)
                    .or_default()
                    .insert(package_name.as_str());
            }
        }
    }
    by_ws
}

/// Reverse index: workspace root -> packages that a descendant workspace's files
/// import through that workspace's declaration.
///
/// A file whose own workspace does not install a package may use the first
/// ancestor workspace that does, under the rule of
/// [`accepts_ancestor_declaration`] that the unlisted-dependency check applies.
/// The import then counts as a use of that ancestor's declaration, so the two
/// results agree. The root manifest is credited project-wide elsewhere.
fn collect_ancestor_credited_packages<'a>(
    graph: &'a ModuleGraph,
    config: &ResolvedConfig,
    manifests: &[WorkspaceManifest<'a>],
    ownership: &WorkspaceOwnershipIndex,
) -> FxHashMap<&'a Path, FxHashSet<&'a str>> {
    let mut credited: FxHashMap<&Path, FxHashSet<&str>> = FxHashMap::default();
    for (package_name, file_ids) in &graph.package_usage {
        for id in file_ids {
            if let Some(ancestor) =
                ancestor_satisfying_import(graph, config, manifests, ownership, package_name, *id)
            {
                credited
                    .entry(ancestor.root)
                    .or_default()
                    .insert(package_name.as_str());
            }
        }
    }
    credited
}

/// The ancestor workspace whose declaration satisfies an import of
/// `package_name` in file `id`, or `None` when the owning workspace installs
/// the package itself, the file may not use an ancestor declaration, or no
/// ancestor workspace installs it.
///
/// The walk tests `installed`, as [`workspace_chain_installer`] does. A
/// `peerDependencies` entry alone installs nothing, so it does not stop the
/// walk before the ancestor that provides the package.
fn ancestor_satisfying_import<'m, 'a>(
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    manifests: &'m [WorkspaceManifest<'a>],
    ownership: &WorkspaceOwnershipIndex,
    package_name: &str,
    id: FileId,
) -> Option<&'m WorkspaceManifest<'a>> {
    let index = ownership.workspace_index_for_file(id)?;
    let owner = manifests.get(index)?;
    if owner.installed.contains(package_name) {
        return None;
    }
    let module = graph.modules.get(id.0 as usize)?;
    if !accepts_ancestor_declaration(owner.is_private, module, config) {
        return None;
    }
    ownership
        .ancestors_of(index)
        .iter()
        .filter_map(|ancestor| manifests.get(*ancestor))
        .find(|ancestor| ancestor.installed.contains(package_name))
}

/// Packages whose import in at least one file is attributed to the root
/// manifest.
///
/// Each import is attributed to the nearest manifest that installs the
/// package: the owning workspace, then its ancestor workspaces, then the root.
/// A root declaration is therefore used only when some importer lies outside
/// every workspace, or when no workspace in the importer's chain installs the
/// package. An importer whose own workspace or an ancestor workspace declares
/// the package does not keep the root declaration alive.
fn collect_root_credited_packages<'a>(
    graph: &'a ModuleGraph,
    manifests: &[WorkspaceManifest<'_>],
    ownership: &WorkspaceOwnershipIndex,
) -> FxHashSet<&'a str> {
    graph
        .package_usage
        .iter()
        .filter(|(package_name, file_ids)| {
            file_ids.iter().any(|id| {
                workspace_chain_installer(manifests, ownership, package_name, *id).is_none()
            })
        })
        .map(|(package_name, _)| package_name.as_str())
        .collect()
}

/// Reverse index: package name -> roots of the workspaces whose declaration an
/// import of the package uses instead of the root declaration.
///
/// A root finding reads this index to name the nearer manifests that keep the
/// package installed, so the finding does not look like "never imported".
fn collect_nearer_manifest_credit<'a>(
    graph: &'a ModuleGraph,
    manifests: &[WorkspaceManifest<'_>],
    ownership: &WorkspaceOwnershipIndex,
) -> FxHashMap<&'a str, Vec<PathBuf>> {
    let mut credit: FxHashMap<&str, Vec<PathBuf>> = FxHashMap::default();
    for (package_name, file_ids) in &graph.package_usage {
        let mut roots: Vec<PathBuf> = file_ids
            .iter()
            .filter_map(|id| workspace_chain_installer(manifests, ownership, package_name, *id))
            .map(Path::to_path_buf)
            .collect();
        if roots.is_empty() {
            continue;
        }
        roots.sort();
        roots.dedup();
        credit.insert(package_name.as_str(), roots);
    }
    credit
}

/// The root of the nearest workspace, the owner of file `id` or one of its
/// ancestor workspaces, that installs `package_name`. `None` when no
/// workspace in the chain installs it.
fn workspace_chain_installer<'a>(
    manifests: &[WorkspaceManifest<'a>],
    ownership: &WorkspaceOwnershipIndex,
    package_name: &str,
    id: FileId,
) -> Option<&'a Path> {
    let index = ownership.workspace_index_for_file(id)?;
    std::iter::once(index)
        .chain(ownership.ancestors_of(index).iter().copied())
        .filter_map(|workspace| manifests.get(workspace))
        .find(|manifest| manifest.installed.contains(package_name))
        .map(|manifest| manifest.root)
}

/// The importers of a package that the root manifest serves, under the same
/// nearest-manifest attribution as [`collect_root_credited_packages`].
///
/// The root test-only and type-only checks read only these importers. An
/// importer that a workspace chain installs the package for says nothing
/// about the root declaration.
struct RootImporters<'a> {
    graph: &'a ModuleGraph,
    manifests: Vec<WorkspaceManifest<'a>>,
    ownership: WorkspaceOwnershipIndex,
}

impl<'a> RootImporters<'a> {
    fn new(
        graph: &'a ModuleGraph,
        config: &ResolvedConfig,
        workspaces: &'a [fallow_config::WorkspaceInfo],
    ) -> Self {
        let manifests = read_workspace_manifests(workspaces, config);
        let ownership =
            WorkspaceOwnershipIndex::new(graph, &dependency_owning_workspace_roots(&manifests));
        Self {
            graph,
            manifests,
            ownership,
        }
    }

    /// Files that import `package_name` through the root declaration.
    fn of(&self, package_name: &str) -> Vec<FileId> {
        self.filter(self.graph.package_usage.get(package_name), package_name)
    }

    /// Files that import `package_name` only with `import type`, through the
    /// root declaration.
    fn type_only_of(&self, package_name: &str) -> Vec<FileId> {
        self.filter(
            self.graph.type_only_package_usage.get(package_name),
            package_name,
        )
    }

    fn filter(&self, file_ids: Option<&Vec<FileId>>, package_name: &str) -> Vec<FileId> {
        file_ids
            .into_iter()
            .flatten()
            .copied()
            .filter(|id| {
                workspace_chain_installer(&self.manifests, &self.ownership, package_name, *id)
                    .is_none()
            })
            .collect()
    }
}

fn shared_dep_sets<'a>(
    plugin_referenced: &'a FxHashSet<&'a str>,
    package_plugin_referenced: &'a FxHashSet<&'a str>,
    plugin_tooling: &'a PluginToolingSets<'a>,
    script_used: &'a FxHashSet<&'a str>,
    ignore_deps: &'a IgnoreDependencyMatcher,
    project_root: &'a Path,
) -> SharedDepSets<'a> {
    SharedDepSets {
        project_root,
        plugin_referenced,
        package_plugin_referenced,
        plugin_tooling: &plugin_tooling.declared,
        credited_plugin_tooling: &plugin_tooling.credited,
        declared_packages: &plugin_tooling.declared_packages,
        script_used,
        ignore_deps,
    }
}

/// The tooling dependencies of the active plugins: every declared one, and
/// the subset whose plugin found evidence that the project uses it.
///
/// It also carries every declared dependency name, which the `@types/X`
/// credit reads.
#[derive(Default)]
struct PluginToolingSets<'a> {
    declared: FxHashSet<&'a str>,
    credited: FxHashSet<&'a str>,
    declared_packages: FxHashSet<&'a str>,
}

/// Collect unused dependencies for a single category (prod, dev, or optional).
///
/// Filters `dep_names` against usage data and category-specific rules, returning
/// `UnusedDependency` entries for deps that are unused.
pub struct UnusedCategoryInput<'a> {
    pub dep_names: Vec<String>,
    pub category: &'a DepCategoryConfig,
    pub shared: &'a SharedDepSets<'a>,
    pub is_used: &'a dyn Fn(&str) -> bool,
    pub used_in_workspaces: &'a dyn Fn(&str) -> Vec<PathBuf>,
    pub pkg_path: &'a Path,
    pub pkg_content: Option<&'a str>,
}

pub fn collect_unused_for_category(input: UnusedCategoryInput<'_>) -> Vec<UnusedDependency> {
    input
        .dep_names
        .into_iter()
        // Checked first so every declared name reaches the matcher, which
        // lets it report a glob that matches no declared dependency.
        .filter(|dep| !input.shared.ignore_deps.is_declared_ignored(dep))
        .filter(|dep| !(input.is_used)(dep))
        .filter(|dep| !input.shared.script_used.contains(dep.as_str()))
        .filter(|dep| !input.category.check_implicit || !is_implicit_dependency(dep))
        .filter(|dep| {
            !input.category.check_known_tooling
                || !is_credited_known_tooling(
                    dep,
                    input.shared,
                    input.is_used,
                    input.pkg_path,
                    input.pkg_content,
                )
        })
        .filter(|dep| {
            let tooling = if input.category.plugin_tooling_needs_evidence {
                input.shared.credited_plugin_tooling
            } else {
                input.shared.plugin_tooling
            };
            !input.category.check_plugin_tooling || !tooling.contains(dep.as_str())
        })
        .filter(|dep| !input.shared.plugin_referenced.contains(dep.as_str()))
        .filter(|dep| {
            !input
                .shared
                .package_plugin_referenced
                .contains(dep.as_str())
        })
        .map(|dep| {
            let line = input
                .pkg_content
                .map_or(1, |c| find_dep_line_in_json(c, &dep));
            let used_in_workspaces = (input.used_in_workspaces)(&dep);
            UnusedDependency {
                package_name: dep,
                location: input.category.location.clone(),
                path: input.pkg_path.to_path_buf(),
                line,
                used_in_workspaces,
                declared_and_imported_in: Vec::new(),
            }
        })
        .collect()
}

/// Whether the unused devDependency check credits `dep` as known tooling.
///
/// An ambient global type package (`@types/node`, `bun-types`) is always
/// credited. Any other `@types/X` package is credited only when the project
/// declares `X` or uses `X` where `is_used` looks. A tsconfig `types` entry
/// credits it through the plugin-referenced set. A command-line tool from the
/// catalogue is credited here only when its own config file exists; a
/// script, CI workflow or git hook reference credits it through the
/// script-used set. Every other name falls back to the tooling catalogue.
fn is_credited_known_tooling(
    dep: &str,
    shared: &SharedDepSets<'_>,
    is_used: &dyn Fn(&str) -> bool,
    pkg_path: &Path,
    pkg_content: Option<&str>,
) -> bool {
    if crate::plugins::is_ambient_types_package(dep) {
        return true;
    }
    if let Some(target) = crate::plugins::types_package_target(dep) {
        return shared.declared_packages.contains(target.as_str()) || is_used(&target);
    }
    if let Some(config) = crate::plugins::cli_tooling_config_patterns(dep) {
        let manifest =
            pkg_content.and_then(|content| serde_json::from_str::<serde_json::Value>(content).ok());
        return cli_tool_own_config(
            dep,
            config,
            shared.project_root,
            pkg_path,
            manifest.as_ref(),
        )
        .is_some();
    }
    crate::plugins::is_known_tooling_dependency(dep)
}

/// The own config of a command-line tool that the manifest at `pkg_path`
/// declares: the declaring package.json when it has a key named after the
/// tool, else a config file next to that package.json or at the project
/// root. A config in a sibling workspace does not count.
pub fn cli_tool_own_config(
    dep: &str,
    config: &[String],
    project_root: &Path,
    pkg_path: &Path,
    manifest: Option<&serde_json::Value>,
) -> Option<PathBuf> {
    if manifest.is_some_and(|manifest| manifest.get(dep).is_some()) {
        return Some(pkg_path.to_path_buf());
    }
    if config.is_empty() {
        return None;
    }
    let package_root = pkg_path.parent().unwrap_or(project_root);
    let roots: &[&Path] = if package_root == project_root {
        &[project_root]
    } else {
        &[package_root, project_root]
    };
    crate::plugins::registry::find_config_file(config.iter().map(String::as_str), roots)
}

/// Build a reverse index from package name to workspace roots that import it.
fn collect_package_workspace_usage(
    graph: &ModuleGraph,
    workspace_roots: &[&Path],
    ownership: &WorkspaceOwnershipIndex,
) -> FxHashMap<String, Vec<PathBuf>> {
    let mut usage: FxHashMap<String, Vec<PathBuf>> = FxHashMap::default();

    for (package_name, file_ids) in &graph.package_usage {
        for id in file_ids {
            let Some(ws_root) = ownership.root_for_file(*id, workspace_roots) else {
                continue;
            };
            usage
                .entry(package_name.clone())
                .or_default()
                .push(ws_root.to_path_buf());
        }
    }

    for roots in usage.values_mut() {
        roots.sort();
        roots.dedup();
    }

    usage
}

fn used_in_other_workspaces(
    package_workspace_usage: &FxHashMap<String, Vec<PathBuf>>,
    dep: &str,
    declaring_workspace_root: &Path,
) -> Vec<PathBuf> {
    package_workspace_usage
        .get(dep)
        .map_or_else(Vec::new, |roots| {
            roots
                .iter()
                .filter(|root| root.as_path() != declaring_workspace_root)
                .cloned()
                .collect()
        })
}

/// Category configs for the three dependency types.
const fn prod_category() -> DepCategoryConfig {
    DepCategoryConfig {
        location: DependencyLocation::Dependencies,
        check_implicit: true,
        check_known_tooling: false,
        check_plugin_tooling: true,
        plugin_tooling_needs_evidence: false,
    }
}

const fn dev_category() -> DepCategoryConfig {
    DepCategoryConfig {
        location: DependencyLocation::DevDependencies,
        check_implicit: false,
        check_known_tooling: true,
        check_plugin_tooling: true,
        plugin_tooling_needs_evidence: true,
    }
}

const fn optional_category() -> DepCategoryConfig {
    DepCategoryConfig {
        location: DependencyLocation::OptionalDependencies,
        check_implicit: true,
        check_known_tooling: false,
        check_plugin_tooling: false,
        plugin_tooling_needs_evidence: false,
    }
}

/// Names a manifest lists in `peerDependencies`, required or optional.
///
/// A devDependency with one of these names is the package's own peer,
/// installed for local build and test. Its consumer supplies it at runtime, so
/// it is neither an unused devDependency nor a devDependency in production.
fn own_peer_dependency_names(pkg: &PackageJson) -> FxHashSet<&str> {
    pkg.peer_dependencies
        .as_ref()
        .into_iter()
        .flat_map(|deps| deps.keys().map(String::as_str))
        .collect()
}

fn package_referenced_dependencies_by_path(
    plugin_result: &crate::plugins::AggregatedPluginResult,
) -> FxHashMap<PathBuf, FxHashSet<&str>> {
    let mut by_path: FxHashMap<PathBuf, FxHashSet<&str>> = FxHashMap::default();
    for (pkg_path, dep) in &plugin_result.package_referenced_dependencies {
        by_path
            .entry(pkg_path.clone())
            .or_default()
            .insert(dep.as_str());
    }
    by_path
}

fn plugin_referenced_set(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> FxHashSet<&str> {
    plugin_result
        .map(|pr| {
            pr.referenced_dependencies
                .iter()
                .map(String::as_str)
                .collect()
        })
        .unwrap_or_default()
}

fn plugin_tooling_set(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> FxHashSet<&str> {
    plugin_result
        .map(|pr| pr.tooling_dependencies.iter().map(String::as_str).collect())
        .unwrap_or_default()
}

/// The plugin tooling sets for the unused-dependency check.
///
/// A plugin's tooling dependencies are credited for devDependencies only when
/// the plugin found its own config file, or when a package.json script, a CI
/// workflow or a git hook invokes one of its reference packages.
fn plugin_tooling_sets<'a>(
    plugin_result: Option<&'a crate::plugins::AggregatedPluginResult>,
    root_declared: &'a [String],
) -> PluginToolingSets<'a> {
    let Some(plugin_result) = plugin_result else {
        return PluginToolingSets {
            declared_packages: root_declared.iter().map(String::as_str).collect(),
            ..PluginToolingSets::default()
        };
    };
    let declared_packages = plugin_result
        .dependency_binaries
        .declared_packages()
        .iter()
        .map(String::as_str)
        .chain(root_declared.iter().map(String::as_str))
        .collect();
    let credited = plugin_result
        .plugin_tooling
        .iter()
        .filter(|entry| {
            entry
                .evidence(&plugin_result.script_used_packages)
                .is_some()
        })
        .flat_map(|entry| entry.dependencies.iter().map(String::as_str))
        .collect();
    PluginToolingSets {
        declared: plugin_tooling_set(Some(plugin_result)),
        credited,
        declared_packages,
    }
}

fn script_used_set(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> FxHashSet<&str> {
    plugin_result
        .map(|pr| pr.script_used_packages.iter().map(String::as_str).collect())
        .unwrap_or_default()
}

/// Find dependencies in package.json that are never imported.
///
/// Checks both the root package.json and each workspace's package.json.
/// For workspace deps, only files within that workspace are considered when
/// determining whether a dependency is used (mirroring `find_unlisted_dependencies`).
pub fn find_unused_dependencies(
    graph: &ModuleGraph,
    pkg: &PackageJson,
    config: &ResolvedConfig,
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> (
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
) {
    let root_declared = pkg.all_dependency_names();
    let scan =
        build_unused_dependency_scan(graph, config, plugin_result, workspaces, &root_declared);
    let shared = scan.root_shared(config);

    let linked_workspaces = fallow_config::link_only_workspace_dependencies(
        &config.root,
        &config.ignore_patterns,
        workspaces,
    );
    let (mut unused_deps, mut unused_dev_deps, mut unused_optional_deps) =
        collect_root_unused_dependencies(pkg, config, &shared, &scan.usage, &linked_workspaces);
    let root_flagged = root_flagged_dependencies(
        &unused_deps,
        &unused_dev_deps,
        &unused_optional_deps,
        &scan.usage.used_packages,
    );

    let inputs = scan.workspace_inputs(config, &root_flagged);
    append_workspace_unused_dependencies(
        workspaces,
        &inputs,
        &mut unused_deps,
        &mut unused_dev_deps,
        &mut unused_optional_deps,
    );

    (unused_deps, unused_dev_deps, unused_optional_deps)
}

struct UnusedDependencyScan<'a> {
    plugin_referenced: FxHashSet<&'a str>,
    plugin_tooling: PluginToolingSets<'a>,
    script_used: FxHashSet<&'a str>,
    package_referenced: FxHashMap<PathBuf, FxHashSet<&'a str>>,
    empty_package_referenced: FxHashSet<&'a str>,
    ignore_deps: &'a IgnoreDependencyMatcher,
    usage: DependencyUsageIndices<'a>,
}

impl<'a> UnusedDependencyScan<'a> {
    fn root_shared(&'a self, config: &'a ResolvedConfig) -> SharedDepSets<'a> {
        shared_dep_sets(
            &self.plugin_referenced,
            self.package_referenced
                .get(&config.root.join("package.json"))
                .unwrap_or(&self.empty_package_referenced),
            &self.plugin_tooling,
            &self.script_used,
            self.ignore_deps,
            &config.root,
        )
    }

    fn workspace_inputs(
        &'a self,
        config: &'a ResolvedConfig,
        root_flagged: &'a FxHashSet<String>,
    ) -> WorkspaceUnusedDependencyInputs<'a> {
        WorkspaceUnusedDependencyInputs {
            config,
            package_referenced: &self.package_referenced,
            empty_package_referenced: &self.empty_package_referenced,
            plugin_referenced: &self.plugin_referenced,
            plugin_tooling: &self.plugin_tooling,
            script_used: &self.script_used,
            ignore_deps: self.ignore_deps,
            workspace_used_packages: &self.usage.workspace_used_packages,
            bundled_workspace_usage: &self.usage.bundled_workspace_usage,
            ancestor_credited_packages: &self.usage.ancestor_credited_packages,
            package_workspace_usage: &self.usage.package_workspace_usage,
            root_flagged,
            closure_listed: &self.usage.closure_listed,
        }
    }
}

fn build_unused_dependency_scan<'a>(
    graph: &'a ModuleGraph,
    config: &'a ResolvedConfig,
    plugin_result: Option<&'a crate::plugins::AggregatedPluginResult>,
    workspaces: &'a [fallow_config::WorkspaceInfo],
    root_declared: &'a [String],
) -> UnusedDependencyScan<'a> {
    UnusedDependencyScan {
        plugin_referenced: plugin_referenced_set(plugin_result),
        plugin_tooling: plugin_tooling_sets(plugin_result, root_declared),
        script_used: script_used_set(plugin_result),
        package_referenced: plugin_result
            .map(package_referenced_dependencies_by_path)
            .unwrap_or_default(),
        empty_package_referenced: FxHashSet::default(),
        ignore_deps: &config.ignore_dependencies,
        usage: collect_dependency_usage_indices(graph, config, workspaces, root_declared),
    }
}

fn append_workspace_unused_dependencies(
    workspaces: &[fallow_config::WorkspaceInfo],
    inputs: &WorkspaceUnusedDependencyInputs<'_>,
    unused_deps: &mut Vec<UnusedDependency>,
    unused_dev_deps: &mut Vec<UnusedDependency>,
    unused_optional_deps: &mut Vec<UnusedDependency>,
) {
    for (prod, dev, optional) in collect_workspaces_unused_dependencies(workspaces, inputs) {
        unused_deps.extend(prod);
        unused_dev_deps.extend(dev);
        unused_optional_deps.extend(optional);
    }
}

type UnusedDependencyTriple = (
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
);

/// Package-usage indices shared by the root and per-workspace unused-dependency passes.
struct DependencyUsageIndices<'a> {
    used_packages: FxHashSet<&'a str>,
    /// Packages with at least one import attributed to the root manifest, see
    /// [`collect_root_credited_packages`].
    root_credited_packages: FxHashSet<&'a str>,
    /// See [`collect_nearer_manifest_credit`].
    nearer_manifest_credit: FxHashMap<&'a str, Vec<PathBuf>>,
    package_workspace_usage: FxHashMap<String, Vec<PathBuf>>,
    workspace_used_packages: FxHashMap<&'a Path, FxHashSet<&'a str>>,
    bundled_workspace_usage: FxHashMap<&'a Path, FxHashSet<&'a str>>,
    ancestor_credited_packages: FxHashMap<&'a Path, FxHashSet<&'a str>>,
    root_peer_used: FxHashMap<String, Vec<String>>,
    /// Names that turn on an optional peer, see [`closure_listed_names`].
    closure_listed: FxHashSet<String>,
}

/// Names that turn on an optional peer in a peer closure.
///
/// The project has one shared install. The root `package.json` or any
/// workspace `package.json` that lists an optional peer turns it on for that
/// install. Thus the root closure, every workspace closure and
/// [`peer_dependency_hosts`] use the root names together with the names of
/// every workspace manifest that `ignorePatterns` does not hide.
///
/// A manifest lists a name when it declares it in any dependency field, peers
/// included. A package that declares the optional peer of a used package as
/// its own peer expects the consumer to install it, so that peer counts as
/// turned on.
fn closure_listed_names<'a>(
    root_declared: &'a [String],
    workspace_declared: impl IntoIterator<Item = &'a String>,
) -> FxHashSet<String> {
    root_declared
        .iter()
        .chain(workspace_declared)
        .cloned()
        .collect()
}

/// Compute the package-usage indices used to decide whether a dependency is used.
fn collect_dependency_usage_indices<'a>(
    graph: &'a ModuleGraph,
    config: &ResolvedConfig,
    workspaces: &'a [fallow_config::WorkspaceInfo],
    root_declared: &[String],
) -> DependencyUsageIndices<'a> {
    let used_packages: FxHashSet<&str> = graph.package_usage.keys().map(String::as_str).collect();
    let manifests = read_workspace_manifests(workspaces, config);
    let closure_listed = closure_listed_names(
        root_declared,
        manifests
            .iter()
            .flat_map(|manifest| manifest.declared.iter()),
    );
    let root_peer_used = PeerDependencyResolver::new().peer_dependency_closure(
        &config.root,
        used_packages.iter().copied(),
        &closure_listed,
    );
    let workspace_roots = dependency_owning_workspace_roots(&manifests);
    let ownership = WorkspaceOwnershipIndex::new(graph, &workspace_roots);
    let workspace_used_packages =
        collect_workspace_used_packages(graph, &workspace_roots, &ownership);
    let externalizing = collect_externalizing_workspaces(graph, &manifests, &ownership);
    let bundled_workspace_usage =
        collect_bundled_workspace_usage(&manifests, &workspace_used_packages, &externalizing);
    let ancestor_credited_packages =
        collect_ancestor_credited_packages(graph, config, &manifests, &ownership);
    let root_credited_packages = collect_root_credited_packages(graph, &manifests, &ownership);
    let nearer_manifest_credit = collect_nearer_manifest_credit(graph, &manifests, &ownership);
    DependencyUsageIndices {
        root_credited_packages,
        nearer_manifest_credit,
        package_workspace_usage: collect_package_workspace_usage(
            graph,
            &workspace_roots,
            &ownership,
        ),
        workspace_used_packages,
        bundled_workspace_usage,
        ancestor_credited_packages,
        used_packages,
        root_peer_used,
        closure_listed,
    }
}

fn collect_root_unused_dependencies(
    pkg: &PackageJson,
    config: &ResolvedConfig,
    shared: &SharedDepSets<'_>,
    usage: &DependencyUsageIndices<'_>,
    linked_workspaces: &FxHashSet<String>,
) -> UnusedDependencyTriple {
    let root_pkg_path = config.root.join("package.json");
    let root_pkg_content = read_pkg_json_content(&root_pkg_path);
    let is_used_globally = |dep: &str| {
        usage.root_credited_packages.contains(dep)
            || usage.root_peer_used.contains_key(dep)
            || linked_workspaces.contains(dep)
    };

    let mut triple = collect_root_unused_categories(
        pkg,
        shared,
        &is_used_globally,
        &root_pkg_path,
        root_pkg_content.as_deref(),
    );
    let (prod, dev, optional) = &mut triple;
    for dep in prod
        .iter_mut()
        .chain(dev.iter_mut())
        .chain(optional.iter_mut())
    {
        if let Some(roots) = usage.nearer_manifest_credit.get(dep.package_name.as_str()) {
            dep.declared_and_imported_in.clone_from(roots);
        }
    }
    triple
}

/// Root findings for packages that nothing in the project imports.
///
/// A workspace does not repeat such a finding for its own declaration. A root
/// finding for a package that a workspace imports through a nearer manifest is
/// left out, so the workspace declarations of that package are still checked.
fn root_flagged_dependencies(
    unused_deps: &[UnusedDependency],
    unused_dev_deps: &[UnusedDependency],
    unused_optional_deps: &[UnusedDependency],
    used_packages: &FxHashSet<&str>,
) -> FxHashSet<String> {
    unused_deps
        .iter()
        .chain(unused_dev_deps)
        .chain(unused_optional_deps)
        .filter(|d| !used_packages.contains(d.package_name.as_str()))
        .map(|d| d.package_name.clone())
        .collect()
}

/// Collect unused prod/dev/optional dependencies for the root package.json.
fn collect_root_unused_categories(
    pkg: &PackageJson,
    shared: &SharedDepSets<'_>,
    is_used_globally: &dyn Fn(&str) -> bool,
    root_pkg_path: &Path,
    root_pkg_content: Option<&str>,
) -> UnusedDependencyTriple {
    let no_workspace_context = |_dep: &str| Vec::new();
    let category =
        |dep_names: Vec<String>, category: &DepCategoryConfig, is_used: &dyn Fn(&str) -> bool| {
            collect_unused_for_category(UnusedCategoryInput {
                dep_names,
                category,
                shared,
                is_used,
                used_in_workspaces: &no_workspace_context,
                pkg_path: root_pkg_path,
                pkg_content: root_pkg_content,
            })
        };
    let own_peers = own_peer_dependency_names(pkg);
    let is_dev_used = |dep: &str| own_peers.contains(dep) || is_used_globally(dep);

    let unused_deps = category(
        pkg.production_dependency_names(),
        &prod_category(),
        is_used_globally,
    );
    let unused_dev_deps = category(pkg.dev_dependency_names(), &dev_category(), &is_dev_used);
    let unused_optional_deps = category(
        pkg.optional_dependency_names(),
        &optional_category(),
        is_used_globally,
    );
    (unused_deps, unused_dev_deps, unused_optional_deps)
}

/// Run the per-workspace unused-dependency pass in parallel.
fn collect_workspaces_unused_dependencies(
    workspaces: &[fallow_config::WorkspaceInfo],
    inputs: &WorkspaceUnusedDependencyInputs<'_>,
) -> Vec<UnusedDependencyTriple> {
    use rayon::prelude::*;
    workspaces
        .par_iter()
        .map(|ws| collect_workspace_unused_dependencies(ws, inputs))
        .collect()
}

struct WorkspaceUnusedDependencyInputs<'a> {
    config: &'a ResolvedConfig,
    package_referenced: &'a FxHashMap<PathBuf, FxHashSet<&'a str>>,
    empty_package_referenced: &'a FxHashSet<&'a str>,
    plugin_referenced: &'a FxHashSet<&'a str>,
    plugin_tooling: &'a PluginToolingSets<'a>,
    script_used: &'a FxHashSet<&'a str>,
    ignore_deps: &'a IgnoreDependencyMatcher,
    workspace_used_packages: &'a FxHashMap<&'a Path, FxHashSet<&'a str>>,
    bundled_workspace_usage: &'a FxHashMap<&'a Path, FxHashSet<&'a str>>,
    ancestor_credited_packages: &'a FxHashMap<&'a Path, FxHashSet<&'a str>>,
    package_workspace_usage: &'a FxHashMap<String, Vec<PathBuf>>,
    root_flagged: &'a FxHashSet<String>,
    closure_listed: &'a FxHashSet<String>,
}

fn collect_workspace_unused_dependencies<'a>(
    ws: &'a fallow_config::WorkspaceInfo,
    inputs: &WorkspaceUnusedDependencyInputs<'a>,
) -> (
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
) {
    let Some((ws_pkg_path, ws_pkg_content, ws_pkg)) = read_workspace_package(ws, inputs.config)
    else {
        return (Vec::new(), Vec::new(), Vec::new());
    };
    let ws_package_referenced = inputs
        .package_referenced
        .get(&ws_pkg_path)
        .unwrap_or(inputs.empty_package_referenced);
    let ws_shared = shared_dep_sets(
        inputs.plugin_referenced,
        ws_package_referenced,
        inputs.plugin_tooling,
        inputs.script_used,
        inputs.ignore_deps,
        &inputs.config.root,
    );

    let ws_root = ws.root.as_path();
    let ancestor_credited = inputs.ancestor_credited_packages.get(&ws_root);
    let ws_used_packages: FxHashSet<&str> = inputs
        .workspace_used_packages
        .get(&ws_root)
        .into_iter()
        .chain(ancestor_credited)
        .flatten()
        .copied()
        .collect();
    let ws_peer_used = PeerDependencyResolver::new().peer_dependency_closure(
        ws_root,
        ws_used_packages.iter().copied(),
        inputs.closure_listed,
    );
    let usage = workspace_dependency_usage(
        ws_root,
        ws_peer_used,
        inputs.package_workspace_usage,
        inputs.bundled_workspace_usage.get(&ws_root),
        ancestor_credited,
        inputs.root_flagged,
    );

    collect_workspace_unused_categories(&ws_pkg, &ws_shared, &usage, &ws_pkg_path, &ws_pkg_content)
}

fn read_workspace_package(
    ws: &fallow_config::WorkspaceInfo,
    config: &ResolvedConfig,
) -> Option<(PathBuf, String, PackageJson)> {
    let ws_pkg_path = ws.root.join("package.json");
    if is_package_json_ignored(&ws_pkg_path, config) {
        return None;
    }
    let ws_pkg_content = std::fs::read_to_string(&ws_pkg_path).ok()?;
    let ws_pkg = serde_json::from_str::<PackageJson>(&ws_pkg_content).ok()?;
    Some((ws_pkg_path, ws_pkg_content, ws_pkg))
}

struct WorkspaceDependencyUsage<'a> {
    ws_root: &'a Path,
    ws_peer_used: FxHashMap<String, Vec<String>>,
    /// Packages this workspace inherits from the private siblings it bundles,
    /// absent when the workspace bundles no private sibling.
    bundled_used: Option<&'a FxHashSet<&'a str>>,
    /// Packages that descendant workspace files import through this
    /// workspace's declaration, absent when there are none.
    ancestor_credited: Option<&'a FxHashSet<&'a str>>,
    package_workspace_usage: &'a FxHashMap<String, Vec<PathBuf>>,
    root_flagged: &'a FxHashSet<String>,
}

impl WorkspaceDependencyUsage<'_> {
    fn is_used_in_workspace(&self, dep: &str) -> bool {
        self.root_flagged.contains(dep)
            || self.ws_peer_used.contains_key(dep)
            || self
                .bundled_used
                .is_some_and(|bundled| bundled.contains(dep))
            || self
                .ancestor_credited
                .is_some_and(|credited| credited.contains(dep))
            || self
                .package_workspace_usage
                .get(dep)
                .is_some_and(|roots| roots.iter().any(|root| root == self.ws_root))
    }

    fn used_in_other_workspaces(&self, dep: &str) -> Vec<PathBuf> {
        used_in_other_workspaces(self.package_workspace_usage, dep, self.ws_root)
    }
}

fn workspace_dependency_usage<'a>(
    ws_root: &'a Path,
    ws_peer_used: FxHashMap<String, Vec<String>>,
    package_workspace_usage: &'a FxHashMap<String, Vec<PathBuf>>,
    bundled_used: Option<&'a FxHashSet<&'a str>>,
    ancestor_credited: Option<&'a FxHashSet<&'a str>>,
    root_flagged: &'a FxHashSet<String>,
) -> WorkspaceDependencyUsage<'a> {
    WorkspaceDependencyUsage {
        ws_root,
        ws_peer_used,
        bundled_used,
        ancestor_credited,
        package_workspace_usage,
        root_flagged,
    }
}

fn collect_workspace_unused_categories(
    ws_pkg: &PackageJson,
    ws_shared: &SharedDepSets<'_>,
    usage: &WorkspaceDependencyUsage<'_>,
    ws_pkg_path: &Path,
    ws_pkg_content: &str,
) -> (
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
    Vec<UnusedDependency>,
) {
    let is_used_in_workspace = |dep: &str| usage.is_used_in_workspace(dep);
    let used_in_workspaces = |dep: &str| usage.used_in_other_workspaces(dep);
    let own_peers = own_peer_dependency_names(ws_pkg);
    let is_dev_used = |dep: &str| own_peers.contains(dep) || is_used_in_workspace(dep);

    let prod = collect_unused_for_category(UnusedCategoryInput {
        dep_names: ws_pkg.production_dependency_names(),
        category: &prod_category(),
        shared: ws_shared,
        is_used: &is_used_in_workspace,
        used_in_workspaces: &used_in_workspaces,
        pkg_path: ws_pkg_path,
        pkg_content: Some(ws_pkg_content),
    });
    let dev = collect_unused_for_category(UnusedCategoryInput {
        dep_names: ws_pkg.dev_dependency_names(),
        category: &dev_category(),
        shared: ws_shared,
        is_used: &is_dev_used,
        used_in_workspaces: &used_in_workspaces,
        pkg_path: ws_pkg_path,
        pkg_content: Some(ws_pkg_content),
    });
    let optional = collect_unused_for_category(UnusedCategoryInput {
        dep_names: ws_pkg.optional_dependency_names(),
        category: &optional_category(),
        shared: ws_shared,
        is_used: &is_used_in_workspace,
        used_in_workspaces: &used_in_workspaces,
        pkg_path: ws_pkg_path,
        pkg_content: Some(ws_pkg_content),
    });

    (prod, dev, optional)
}

/// Find production dependencies that are only imported via type-only imports.
///
/// In production mode, `import type { Foo } from 'pkg'` is erased at compile time,
/// meaning the dependency is not needed at runtime. Such dependencies should be
/// moved to devDependencies.
///
/// Only importers that reach the package through the root declaration count,
/// see [`RootImporters`]. A root entry without such an importer is an unused
/// dependency, not a type-only one.
pub fn find_type_only_dependencies(
    graph: &ModuleGraph,
    pkg: &PackageJson,
    config: &ResolvedConfig,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> Vec<TypeOnlyDependency> {
    let root_pkg_path = config.root.join("package.json");
    let root_pkg_content = read_pkg_json_content(&root_pkg_path);
    let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
    let root_importers = RootImporters::new(graph, config, workspaces);

    let mut type_only_deps = Vec::new();

    for dep in pkg.production_dependency_names() {
        if workspace_names.contains(dep.as_str()) {
            continue;
        }
        if config.ignore_dependencies.is_ignored(&dep) {
            continue;
        }

        let total_count = root_importers.of(&dep).len();
        let type_only_count = root_importers.type_only_of(&dep).len();

        if total_count > 0 && type_only_count == total_count {
            let line = root_pkg_content
                .as_deref()
                .map_or(1, |c| find_dep_line_in_json(c, &dep));
            type_only_deps.push(TypeOnlyDependency {
                package_name: dep,
                path: root_pkg_path.clone(),
                line,
            });
        }
    }

    type_only_deps
}

/// Return the process-wide glob set matching production-excluded test/story files.
///
/// Returns `None` when the glob set fails to compile, mirroring the original
/// early-return-empty behavior of both dependency detectors. The `Option` is
/// cached too, so a failed compilation is never replaced with an empty matcher.
fn production_exclude_globset() -> Option<&'static globset::GlobSet> {
    static SET: OnceLock<Option<globset::GlobSet>> = OnceLock::new();
    SET.get_or_init(|| {
        let mut builder = globset::GlobSetBuilder::new();
        for pattern in crate::discover::PRODUCTION_EXCLUDE_PATTERNS {
            if let Ok(glob) = globset::GlobBuilder::new(pattern)
                .literal_separator(true)
                .build()
            {
                builder.add(glob);
            }
        }
        builder.build().ok()
    })
    .as_ref()
}

/// Return `true` when `module` is production code: reachable from a runtime
/// entry point, not a test or story file, and not a config file.
///
/// Repo tooling the test globs do not cover (`scripts/`, `benchmarks/`,
/// playgrounds, anything reachable only through a config-file support entry)
/// is not runtime reachable, so it is not production code either.
fn is_production_module(module: &crate::graph::ModuleNode, config: &ResolvedConfig) -> bool {
    if !module.is_runtime_reachable() || is_config_file(&module.path) {
        return false;
    }
    let relative = module
        .path
        .strip_prefix(&config.root)
        .unwrap_or(&module.path);
    !production_exclude_globset().is_some_and(|test_globs| test_globs.is_match(relative))
}

/// Return `true` when a workspace file may use a package that only an
/// ancestor manifest declares (an ancestor workspace or the root).
///
/// A private workspace is never published, so it always runs inside the
/// monorepo where the ancestor's install is present. A file that is not
/// production code (a test, config or build script) also runs only inside the
/// monorepo. A production file of a publishable workspace must declare its
/// packages itself, because consumers of the published package do not get the
/// ancestor's dependency.
fn accepts_ancestor_declaration(
    owner_is_private: bool,
    module: &crate::graph::ModuleNode,
    config: &ResolvedConfig,
) -> bool {
    owner_is_private || !is_production_module(module, config)
}

/// Return `true` when every file that imports `dep` through the root
/// declaration is a test/story or config file, and the dependency is not
/// exclusively type-only imported.
fn dependency_is_test_only(
    dep: &str,
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    test_globs: &globset::GlobSet,
    root_importers: &RootImporters<'_>,
) -> bool {
    let file_ids = root_importers.of(dep);
    if file_ids.is_empty() {
        return false;
    }

    let total_count = file_ids.len();
    let type_only_count = root_importers.type_only_of(dep).len();
    if type_only_count == total_count {
        return false;
    }

    file_ids.iter().all(|id| {
        graph.modules.get(id.0 as usize).is_some_and(|module| {
            let relative = module
                .path
                .strip_prefix(&config.root)
                .unwrap_or(&module.path);
            test_globs.is_match(relative) || is_config_file(&module.path)
        })
    })
}

/// Find production dependencies that are only imported by test/dev files.
///
/// When NOT in production mode (where test files are still discovered), a dep
/// that appears exclusively in test/story/config files should be a devDependency.
///
/// Like [`find_type_only_dependencies`], this reads only the importers that
/// reach the package through the root declaration.
pub fn find_test_only_dependencies(
    graph: &ModuleGraph,
    pkg: &PackageJson,
    config: &ResolvedConfig,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> Vec<TestOnlyDependency> {
    let Some(test_globs) = production_exclude_globset() else {
        return Vec::new();
    };

    let root_pkg_path = config.root.join("package.json");
    let root_pkg_content = read_pkg_json_content(&root_pkg_path);
    let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
    let ignore_deps = &config.ignore_dependencies;
    let root_importers = RootImporters::new(graph, config, workspaces);

    let mut test_only_deps = Vec::new();

    for dep in pkg.production_dependency_names() {
        if workspace_names.contains(dep.as_str()) {
            continue;
        }
        if ignore_deps.is_ignored(&dep) {
            continue;
        }

        if dependency_is_test_only(&dep, graph, config, test_globs, &root_importers) {
            let line = root_pkg_content
                .as_deref()
                .map_or(1, |c| find_dep_line_in_json(c, &dep));
            test_only_deps.push(TestOnlyDependency {
                package_name: dep,
                path: root_pkg_path.clone(),
                line,
            });
        }
    }

    test_only_deps
}

/// Return `true` when at least one PRODUCTION (non-test, non-config) file
/// imports `dep` via a runtime/value import.
///
/// `package_usage` records one entry per import statement,
/// `type_only_package_usage` one entry per `import type` statement and
/// `asset_package_usage` one entry per import through a webpack asset loader
/// (`raw-loader!pkg/file.txt`, read at build time). So for a given file the
/// count of runtime value imports is `total - type_only - asset`. A file with
/// a value import of `dep` is therefore one whose `total` occurrences exceed
/// its build-time occurrences. This mirrors the per-statement granularity the
/// `type-only-dependency` / `test-only-dependency` detectors rely on, so a
/// production file that imports `dep` ONLY via `import type` or through an
/// asset loader is not flagged.
///
/// Files owned by a workspace package are skipped: this rule reasons about the
/// ROOT manifest only, and a workspace file's runtime resolution is governed by
/// the workspace's own `package.json` (a package hoisted into root
/// `devDependencies` but declared in the workspace's `dependencies` would
/// otherwise be a false positive). Per-workspace detection is the shared
/// follow-up with the sibling dependency-family detectors.
///
/// Only files reachable from a RUNTIME entry point count as production
/// evidence (`is_runtime_reachable`, the graph's production scope). Repo
/// tooling the test globs do not cover (`scripts/`, `benchmarks/`, `.github/`,
/// playgrounds, and anything reachable only through a config-file support
/// entry such as a rollup config chain) is not part of the shipped artifact,
/// so a devDependency imported only there must not be promoted. The rule lives
/// in [`is_production_module`].
fn dependency_has_prod_value_import(
    dep: &str,
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    workspaces: &[fallow_config::WorkspaceInfo],
) -> bool {
    let Some(file_ids) = graph.package_usage.get(dep) else {
        return false;
    };

    let mut per_file: FxHashMap<FileId, (u32, u32)> = FxHashMap::default();
    for id in file_ids {
        per_file.entry(*id).or_default().0 += 1;
    }
    let build_time_ids = graph
        .type_only_package_usage
        .get(dep)
        .into_iter()
        .chain(graph.asset_package_usage.get(dep))
        .flatten();
    for id in build_time_ids {
        per_file.entry(*id).or_default().1 += 1;
    }

    per_file.iter().any(|(id, (total, build_time))| {
        // No runtime value import in this file: every occurrence was
        // `import type` or a read through an asset loader.
        if total <= build_time {
            return false;
        }
        graph.modules.get(id.0 as usize).is_some_and(|module| {
            is_production_module(module, config)
                && !workspaces
                    .iter()
                    .any(|ws| module.path.starts_with(&ws.root))
        })
    })
}

/// Find `devDependencies` imported by production code with a runtime/value
/// import.
///
/// The promote-side mirror of [`find_test_only_dependencies`]: where the
/// test-only rule demotes a production dependency imported only from tests, this
/// rule promotes a dev dependency imported at runtime from production code.
/// A production-only install (`pnpm install --prod`) omits `devDependencies`, so
/// such a package would break at runtime and belongs in `dependencies`.
///
/// A dev dependency is NOT flagged when its only production imports are
/// type-only (types are erased at build time, mirroring the
/// `type-only-dependency` import-kind analysis) or reads through a webpack
/// asset loader (the bundle holds the file content), when it is also listed in
/// `dependencies` / `peerDependencies` / `optionalDependencies` (runtime is
/// provided by another manifest section), when it is a known tooling package
/// (`@types/*`, `typescript`, ...), a workspace package, or config-ignored via
/// `ignoreDependencies`.
///
/// This checks the root `package.json` against the project-wide import graph;
/// per-workspace `package.json` parity is a shared follow-up with the sibling
/// dependency-family detectors.
pub fn find_dev_dependencies_in_production(
    graph: &ModuleGraph,
    pkg: &PackageJson,
    config: &ResolvedConfig,
    workspaces: &[fallow_config::WorkspaceInfo],
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> Vec<DevDependencyInProduction> {
    if production_exclude_globset().is_none() {
        return Vec::new();
    }

    let root_pkg_path = config.root.join("package.json");
    let root_pkg_content = read_pkg_json_content(&root_pkg_path);
    let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
    let ignore_deps = &config.ignore_dependencies;

    // Packages resolvable at runtime through another manifest section: a
    // devDependency that is also a prod/peer/optional dependency is legitimately
    // value-imported in production, so it must not be flagged.
    let prod_names = pkg.production_dependency_names();
    let optional_names = pkg.optional_dependency_names();
    let runtime_provided: FxHashSet<&str> = prod_names
        .iter()
        .chain(optional_names.iter())
        .map(String::as_str)
        .chain(own_peer_dependency_names(pkg))
        .collect();

    let plugin_tooling = plugin_tooling_set(plugin_result);
    let mut findings = Vec::new();

    for dep in pkg.dev_dependency_names() {
        if workspace_names.contains(dep.as_str()) {
            continue;
        }
        if ignore_deps.is_ignored(&dep) {
            continue;
        }
        if runtime_provided.contains(dep.as_str()) {
            continue;
        }
        // `@types/*`, `typescript`, `prettier`, ... are genuine dev tooling and
        // are never promoted, matching the dev category of unused-dep detection.
        if crate::plugins::is_known_tooling_dependency(&dep) {
            continue;
        }
        // A framework's own packages are build-time tooling the same way, and
        // the plugin that recognizes the framework already says which they are.
        // Every sibling dependency rule reads that declaration; this one used
        // to skip it, so a scaffold that keeps its framework in devDependencies
        // was told to promote it.
        if plugin_tooling.contains(dep.as_str()) {
            continue;
        }

        if dependency_has_prod_value_import(&dep, graph, config, workspaces) {
            let line = root_pkg_content
                .as_deref()
                .map_or(1, |c| find_dep_line_in_json(c, &dep));
            findings.push(DevDependencyInProduction {
                package_name: dep,
                path: root_pkg_path.clone(),
                line,
            });
        }
    }

    findings
}

/// Check if a corresponding `@types/<package>` is listed in dependencies.
///
/// When `@types/X` is installed but `X` itself is not, the dependency is used for types
/// only (e.g., `@types/geojson` for `import { Feature } from 'geojson'`). TypeScript
/// resolves types from `@types/X` automatically, and the import is erased at compile time
/// regardless of whether it uses the `import type` syntax.
///
/// For scoped packages like `@scope/pkg`, the DefinitelyTyped convention is `@types/scope__pkg`.
fn types_package_name(package_name: &str) -> String {
    package_name.strip_prefix('@').map_or_else(
        || format!("@types/{package_name}"),
        |scoped| format!("@types/{}", scoped.replacen('/', "__", 1)),
    )
}

fn relative_module_path(module_path: &Path, root: &Path) -> String {
    module_path
        .strip_prefix(root)
        .unwrap_or(module_path)
        .to_string_lossy()
        .into_owned()
}

struct CompiledProvidedDependencyRule<'a> {
    rule: &'a ProvidedDependencyRule,
    path_matcher: CompiledPathRule,
}

fn compile_provided_dependency_rules(
    rules: &[ProvidedDependencyRule],
) -> Vec<CompiledProvidedDependencyRule<'_>> {
    rules
        .iter()
        .filter_map(|rule| {
            CompiledPathRule::for_used_export_rule(&rule.path, "provided dependency")
                .map(|path_matcher| CompiledProvidedDependencyRule { rule, path_matcher })
        })
        .collect()
}

fn import_is_provided(
    rules: &[CompiledProvidedDependencyRule<'_>],
    relative_path: &str,
    source_specifier: &str,
) -> bool {
    rules.iter().any(|rule| {
        rule.path_matcher.matches(relative_path) && rule.rule.covers_specifier(source_specifier)
    })
}

fn package_has_file_scoped_provider(rules: &[ProvidedDependencyRule], package_name: &str) -> bool {
    rules
        .iter()
        .any(|rule| rule.may_cover_package(package_name))
}

fn find_unprovided_import_location(
    import_spans_by_file: &FxHashMap<FileId, Vec<(&str, &str, u32)>>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    provided_rules: &[CompiledProvidedDependencyRule<'_>],
    relative_path: &str,
    file_id: FileId,
    package_name: &str,
) -> Option<(u32, u32)> {
    import_spans_by_file.get(&file_id).and_then(|spans| {
        spans
            .iter()
            .filter(|(name, _, _)| *name == package_name)
            .find(|(_, source, _)| {
                !is_builtin_module(source)
                    && !import_is_provided(provided_rules, relative_path, source)
            })
            .or_else(|| {
                spans.iter().find(|(name, source, _)| {
                    *name == package_name
                        && !import_is_provided(provided_rules, relative_path, source)
                })
            })
            .map(|(_, _, span_start)| {
                byte_offset_to_line_col(line_offsets_by_file, file_id, *span_start)
            })
    })
}

fn package_imports_are_all_builtin(
    import_spans_by_file: &FxHashMap<FileId, Vec<(&str, &str, u32)>>,
    file_id: FileId,
    package_name: &str,
) -> bool {
    let Some(imports) = import_spans_by_file.get(&file_id) else {
        return false;
    };

    let mut saw_package = false;
    for (name, source, _) in imports {
        if *name == package_name {
            saw_package = true;
            if !is_builtin_module(source) {
                return false;
            }
        }
    }

    saw_package
}

/// A package whose every import in this file used the Deno `npm:` scheme is
/// self-declaring: Supabase Edge Functions and Deno deliberately inline the
/// dependency in the specifier instead of listing it in package.json, so it
/// must not surface as an unlisted dependency. Mirrors the per-file `bun:`
/// carve-out (`package_imports_are_all_builtin`) and stays conservative: a
/// package also imported via a bare specifier (e.g. `import 'foo'` in a Node
/// file) is NOT all-`npm:`, so the genuine missing-dependency report survives.
/// The resolver normalizes `npm:<pkg>` to its package name for usage crediting
/// but leaves the original `npm:` prefix on `ImportInfo.source`, which is the
/// string compared here. See issue #624.
fn package_imports_are_all_npm_scheme(
    import_spans_by_file: &FxHashMap<FileId, Vec<(&str, &str, u32)>>,
    file_id: FileId,
    package_name: &str,
) -> bool {
    let Some(imports) = import_spans_by_file.get(&file_id) else {
        return false;
    };

    let mut saw_package = false;
    for (name, source, _) in imports {
        if *name == package_name {
            saw_package = true;
            if !source.starts_with("npm:") {
                return false;
            }
        }
    }

    saw_package
}

/// The names one workspace manifest makes resolvable for its own files.
struct WorkspaceDependencies {
    root: PathBuf,
    /// Every declared dependency name, the workspace's own name, and for a
    /// Deno member the ambient names of the other Deno members.
    deps: FxHashSet<String>,
    /// `"private": true` in the manifest.
    is_private: bool,
}

fn workspace_dependency_map(
    workspaces: &[fallow_config::WorkspaceInfo],
    config: &ResolvedConfig,
) -> Vec<WorkspaceDependencies> {
    let ambient_workspace_names: FxHashSet<String> = workspaces
        .iter()
        .filter(|ws| fallow_config::dir_has_deno_json(&ws.root))
        .map(|ws| ws.name.clone())
        .collect();

    let mut ws_dep_map = Vec::new();
    for ws in workspaces {
        let ws_pkg_path = ws.root.join("package.json");
        if ws_pkg_path.is_file() && is_package_json_ignored(&ws_pkg_path, config) {
            continue;
        }

        let Ok(Some((_name, ws_pkg, _deps))) =
            fallow_config::load_member_package_manifest(&ws.root)
        else {
            continue;
        };

        let mut ws_deps: FxHashSet<String> = ws_pkg.all_dependency_names().into_iter().collect();
        ws_deps.insert(ws.name.clone());
        if fallow_config::dir_has_deno_json(&ws.root) {
            ws_deps.extend(ambient_workspace_names.iter().cloned());
        }
        ws_dep_map.push(WorkspaceDependencies {
            root: ws.root.clone(),
            deps: ws_deps,
            is_private: ws_pkg.private == Some(true),
        });
    }
    ws_dep_map
}

fn import_spans_by_file<'a>(
    resolved_modules: &'a [ResolvedModule],
    modules: &'a [ModuleInfo],
) -> FxHashMap<FileId, Vec<(&'a str, &'a str, u32)>> {
    let mut import_spans_by_file: FxHashMap<FileId, Vec<(&str, &str, u32)>> = FxHashMap::default();
    for rm in resolved_modules {
        for edge in rm.all_resolved_source_edges() {
            if let Some(name) = edge.target().package_usage_name() {
                import_spans_by_file.entry(rm.file_id).or_default().push((
                    name,
                    edge.source_specifier(),
                    edge.span().start,
                ));
            }
        }
    }
    // A direct `require.resolve('pkg')` call names the package at a known
    // location, so it is an unlisted-dependency site like an import. The
    // package name stands in for the specifier.
    for module in modules {
        for (package_name, span_start) in &module.package_resolve_sites {
            import_spans_by_file
                .entry(module.file_id)
                .or_default()
                .push((package_name.as_str(), package_name.as_str(), *span_start));
        }
    }
    import_spans_by_file
}

#[derive(Clone, Copy)]
pub struct UnlistedDependencyInput<'a> {
    pub graph: &'a ModuleGraph,
    pub pkg: &'a PackageJson,
    pub config: &'a ResolvedConfig,
    pub workspaces: &'a [fallow_config::WorkspaceInfo],
    pub plugin_result: Option<&'a crate::plugins::AggregatedPluginResult>,
    pub resolved_modules: &'a [ResolvedModule],
    pub modules: &'a [ModuleInfo],
    pub line_offsets_by_file: &'a LineOffsetsMap<'a>,
}

/// Find dependencies used in imports but not listed in package.json.
pub fn find_unlisted_dependencies(input: UnlistedDependencyInput<'_>) -> Vec<UnlistedDependency> {
    let parts = build_unlisted_dependency_context_parts(&input);
    let workspace_roots: Vec<&Path> = parts
        .ws_dep_map
        .iter()
        .map(|ws| ws.root.as_path())
        .collect();
    let workspace_ownership = WorkspaceOwnershipIndex::new(input.graph, &workspace_roots);
    let ctx = UnlistedDependencyContext {
        graph: input.graph,
        config: input.config,
        all_deps: &parts.all_deps,
        ws_dep_map: &parts.ws_dep_map,
        virtual_prefixes: &parts.virtual_prefixes,
        virtual_suffixes: &parts.virtual_suffixes,
        plugin_tooling: &parts.plugin_tooling,
        provided_dependency_rules: parts.provided_dependency_rules,
        compiled_provided_dependency_rules: &parts.compiled_provided_dependency_rules,
        import_spans_by_file: &parts.import_spans_by_file,
        ignore_deps: parts.ignore_deps,
        line_offsets_by_file: input.line_offsets_by_file,
        workspace_ownership: &workspace_ownership,
    };

    collect_unlisted_dependencies(&ctx)
}

struct UnlistedDependencyContextParts<'a> {
    all_deps: FxHashSet<String>,
    ws_dep_map: Vec<WorkspaceDependencies>,
    virtual_prefixes: Vec<&'a str>,
    virtual_suffixes: Vec<&'a str>,
    plugin_tooling: FxHashSet<&'a str>,
    provided_dependency_rules: &'a [ProvidedDependencyRule],
    compiled_provided_dependency_rules: Vec<CompiledProvidedDependencyRule<'a>>,
    import_spans_by_file: FxHashMap<FileId, Vec<(&'a str, &'a str, u32)>>,
    ignore_deps: &'a IgnoreDependencyMatcher,
}

struct UnlistedDependencyPluginParts<'a> {
    virtual_prefixes: Vec<&'a str>,
    virtual_suffixes: Vec<&'a str>,
    plugin_tooling: FxHashSet<&'a str>,
    provided_dependency_rules: &'a [ProvidedDependencyRule],
    compiled_provided_dependency_rules: Vec<CompiledProvidedDependencyRule<'a>>,
}

fn build_unlisted_dependency_plugin_parts(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> UnlistedDependencyPluginParts<'_> {
    let virtual_prefixes = plugin_result
        .map(|pr| {
            pr.virtual_module_prefixes
                .iter()
                .map(String::as_str)
                .collect()
        })
        .unwrap_or_default();

    let virtual_suffixes = plugin_result
        .map(|pr| {
            pr.virtual_package_suffixes
                .iter()
                .map(String::as_str)
                .collect()
        })
        .unwrap_or_default();

    let plugin_tooling = plugin_result
        .map(|pr| pr.tooling_dependencies.iter().map(String::as_str).collect())
        .unwrap_or_default();
    let provided_dependency_rules: &[ProvidedDependencyRule] =
        plugin_result.map_or(&[], |pr| pr.provided_dependencies.as_slice());
    let compiled_provided_dependency_rules =
        compile_provided_dependency_rules(provided_dependency_rules);

    UnlistedDependencyPluginParts {
        virtual_prefixes,
        virtual_suffixes,
        plugin_tooling,
        provided_dependency_rules,
        compiled_provided_dependency_rules,
    }
}

fn build_unlisted_dependency_context_parts<'a>(
    input: &UnlistedDependencyInput<'a>,
) -> UnlistedDependencyContextParts<'a> {
    let mut all_deps: FxHashSet<String> = input.pkg.all_dependency_names().into_iter().collect();
    if let Some(root_name) = &input.pkg.name {
        all_deps.insert(root_name.clone());
    }

    // Deno workspaces expose member packages without package.json dependency
    // entries. Treat discovered workspace names as listed at the root too so
    // files outside a member directory do not false-positive as unlisted.
    if fallow_config::dir_has_deno_json(&input.config.root) {
        all_deps.extend(
            input
                .workspaces
                .iter()
                .filter(|ws| fallow_config::dir_has_deno_json(&ws.root))
                .map(|ws| ws.name.clone()),
        );
    }

    let ws_dep_map = workspace_dependency_map(input.workspaces, input.config);

    let plugin_parts = build_unlisted_dependency_plugin_parts(input.plugin_result);
    let import_spans_by_file = import_spans_by_file(input.resolved_modules, input.modules);

    let ignore_deps = &input.config.ignore_dependencies;

    UnlistedDependencyContextParts {
        all_deps,
        ws_dep_map,
        virtual_prefixes: plugin_parts.virtual_prefixes,
        virtual_suffixes: plugin_parts.virtual_suffixes,
        plugin_tooling: plugin_parts.plugin_tooling,
        provided_dependency_rules: plugin_parts.provided_dependency_rules,
        compiled_provided_dependency_rules: plugin_parts.compiled_provided_dependency_rules,
        import_spans_by_file,
        ignore_deps,
    }
}

/// Walk `package_usage`, gathering per-package import sites into findings.
fn collect_unlisted_dependencies(ctx: &UnlistedDependencyContext<'_>) -> Vec<UnlistedDependency> {
    let mut unlisted: FxHashMap<String, Vec<ImportSite>> = FxHashMap::default();

    for (package_name, file_ids) in &ctx.graph.package_usage {
        if should_skip_unlisted_package(package_name, ctx) {
            continue;
        }
        let mut unlisted_sites = collect_unlisted_import_sites(package_name, file_ids, ctx);
        if !unlisted_sites.is_empty() {
            unlisted_sites.sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
            unlisted_sites.dedup_by(|a, b| a.path == b.path);
            unlisted.insert(package_name.clone(), unlisted_sites);
        }
    }

    unlisted
        .into_iter()
        .map(|(name, sites)| UnlistedDependency {
            package_name: name,
            imported_from: sites,
        })
        .collect()
}

struct UnlistedDependencyContext<'a> {
    graph: &'a ModuleGraph,
    config: &'a ResolvedConfig,
    all_deps: &'a FxHashSet<String>,
    ws_dep_map: &'a [WorkspaceDependencies],
    virtual_prefixes: &'a [&'a str],
    virtual_suffixes: &'a [&'a str],
    plugin_tooling: &'a FxHashSet<&'a str>,
    provided_dependency_rules: &'a [ProvidedDependencyRule],
    compiled_provided_dependency_rules: &'a [CompiledProvidedDependencyRule<'a>],
    import_spans_by_file: &'a FxHashMap<FileId, Vec<(&'a str, &'a str, u32)>>,
    ignore_deps: &'a IgnoreDependencyMatcher,
    line_offsets_by_file: &'a LineOffsetsMap<'a>,
    workspace_ownership: &'a WorkspaceOwnershipIndex,
}

fn should_skip_unlisted_package(package_name: &str, ctx: &UnlistedDependencyContext<'_>) -> bool {
    ((package_name != "bun" && is_builtin_module(package_name)) || is_path_alias(package_name))
        || is_virtual_module(package_name)
        || ctx.ignore_deps.is_ignored(package_name)
        || (ctx.plugin_tooling.contains(package_name)
            && !package_has_file_scoped_provider(ctx.provided_dependency_rules, package_name))
        || ctx
            .virtual_prefixes
            .iter()
            .any(|prefix| matches_virtual_prefix(prefix, package_name))
        || ctx
            .virtual_suffixes
            .iter()
            .any(|suffix| package_name.ends_with(suffix))
}

fn collect_unlisted_import_sites(
    package_name: &str,
    file_ids: &[FileId],
    ctx: &UnlistedDependencyContext<'_>,
) -> Vec<ImportSite> {
    file_ids
        .iter()
        .filter_map(|id| collect_unlisted_import_site(package_name, *id, ctx))
        .collect()
}

fn collect_unlisted_import_site(
    package_name: &str,
    id: FileId,
    ctx: &UnlistedDependencyContext<'_>,
) -> Option<ImportSite> {
    let module = ctx.graph.modules.get(id.0 as usize)?;
    if package_name == "bun"
        && package_imports_are_all_builtin(ctx.import_spans_by_file, id, package_name)
    {
        return None;
    }
    if package_imports_are_all_npm_scheme(ctx.import_spans_by_file, id, package_name) {
        return None;
    }
    if import_is_declared(package_name, id, module, ctx) {
        return None;
    }
    let relative_path = relative_module_path(&module.path, &ctx.config.root);
    let (line, col) = find_unprovided_import_location(
        ctx.import_spans_by_file,
        ctx.line_offsets_by_file,
        ctx.compiled_provided_dependency_rules,
        &relative_path,
        id,
        package_name,
    )?;
    Some(ImportSite {
        path: module.path.clone(),
        line,
        col,
    })
}

/// Return `true` when a manifest that the importing file may use declares
/// `package_name` or its `@types` package.
///
/// A file outside every workspace uses the root manifest. A workspace file
/// uses its own manifest first. When that manifest does not declare the
/// package, the walk goes up through the ancestor workspaces to the root
/// manifest, but only when [`accepts_ancestor_declaration`] allows it. Sibling
/// workspaces are never consulted.
fn import_is_declared(
    package_name: &str,
    id: FileId,
    module: &crate::graph::ModuleNode,
    ctx: &UnlistedDependencyContext<'_>,
) -> bool {
    manifest_chain_declares(
        package_name,
        id,
        ctx.ws_dep_map,
        ctx.workspace_ownership,
        ctx.all_deps,
        |owner_is_private| accepts_ancestor_declaration(owner_is_private, module, ctx.config),
    )
}

/// The manifest walk behind [`import_is_declared`]. `accepts_ancestor`
/// receives whether the owning workspace is private and decides whether the
/// walk may continue past the owning workspace's own manifest.
fn manifest_chain_declares(
    package_name: &str,
    id: FileId,
    ws_dep_map: &[WorkspaceDependencies],
    ownership: &WorkspaceOwnershipIndex,
    root_deps: &FxHashSet<String>,
    accepts_ancestor: impl FnOnce(bool) -> bool,
) -> bool {
    let types_name = types_package_name(package_name);
    let declares =
        |deps: &FxHashSet<String>| deps.contains(package_name) || deps.contains(&types_name);
    let Some((index, owner)) = ownership
        .workspace_index_for_file(id)
        .and_then(|index| ws_dep_map.get(index).map(|owner| (index, owner)))
    else {
        return declares(root_deps);
    };
    if declares(&owner.deps) {
        return true;
    }
    if !accepts_ancestor(owner.is_private) {
        return false;
    }
    ownership
        .ancestors_of(index)
        .iter()
        .filter_map(|ancestor| ws_dep_map.get(*ancestor))
        .any(|ancestor| declares(&ancestor.deps))
        || declares(root_deps)
}

/// Plumbing for the per-spec skip checks in `find_unresolved_imports`.
struct UnresolvedImportFilters<'a> {
    config: &'a ResolvedConfig,
    virtual_prefixes: &'a [&'a str],
    generated_patterns: &'a [&'a str],
    generated_type_prefixes: &'a [&'a str],
}

/// Return `true` when an unresolvable specifier should be silenced (builtin,
/// virtual, generated artifact, type-only generated prefix, or config-ignored).
fn unresolved_spec_is_silenced(
    spec: &str,
    is_type_only: bool,
    filters: &UnresolvedImportFilters<'_>,
) -> bool {
    if is_builtin_module(spec) || is_virtual_module(spec) {
        return true;
    }
    if filters
        .virtual_prefixes
        .iter()
        .any(|prefix| matches_virtual_prefix(prefix, spec))
    {
        return true;
    }
    if !filters.generated_patterns.is_empty() {
        let bare = spec
            .strip_suffix(".js")
            .or_else(|| spec.strip_suffix(".ts"))
            .unwrap_or(spec);
        if filters
            .generated_patterns
            .iter()
            .any(|pat| bare.ends_with(pat))
        {
            return true;
        }
    }
    if is_type_only
        && filters
            .generated_type_prefixes
            .iter()
            .any(|prefix| spec.starts_with(prefix))
    {
        return true;
    }
    // Config compilation strips a single leading "./" from
    // ignoreUnresolvedImports globs (see #1385), so the specifier must be
    // stripped the same way or exact-path entries like "./generated/x.js"
    // never match. The raw form is still tried so wildcard patterns that
    // count the "./" segment keep matching.
    let normalized_spec = spec.strip_prefix("./").unwrap_or(spec);
    filters
        .config
        .ignore_unresolved_imports
        .iter()
        .any(|matcher| matcher.is_match(spec) || matcher.is_match(normalized_spec))
}

/// Resolve the anchor `(line, col)` plus the specifier column for an edge.
///
/// The finding anchors on the source specifier (the string the user must
/// edit) when the extractor recorded its span. A multi-line statement
/// extracts one edge per binding line, so anchoring on the declaration span
/// would point at an arbitrary binding instead of the specifier. When the
/// specifier sits on the declaration line, the declaration column is kept so
/// single-line reporting is unchanged.
fn unresolved_import_location(
    edge: &crate::resolve::ResolvedSourceEdge<'_>,
    file_id: FileId,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> (u32, u32, u32) {
    let (line, col) = byte_offset_to_line_col(line_offsets_by_file, file_id, edge.span().start);

    let source_span = edge.source_span();
    if source_span.end > source_span.start {
        let (specifier_line, specifier_col) =
            byte_offset_to_line_col(line_offsets_by_file, file_id, source_span.start);
        if specifier_line == line {
            (line, col, specifier_col)
        } else {
            (specifier_line, specifier_col, specifier_col)
        }
    } else {
        (line, col, col)
    }
}

/// Check whether a suppression covers the statement that owns this edge.
///
/// The finding anchors on the specifier line, but a suppression comment
/// above the statement targets the statement's first line, and pre-anchor
/// suppressions may sit on any binding line in between. Probing every
/// statement line keeps all three placements working and consumes the
/// matched suppression so it is not reported stale.
fn unresolved_import_suppressed(
    suppressions: &SuppressionContext<'_>,
    edge: &crate::resolve::ResolvedSourceEdge<'_>,
    file_id: FileId,
    anchor_line: u32,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> bool {
    let statement_span = edge.statement_span();
    let statement_line = if statement_span.end > statement_span.start {
        byte_offset_to_line_col(line_offsets_by_file, file_id, statement_span.start).0
    } else {
        byte_offset_to_line_col(line_offsets_by_file, file_id, edge.span().start).0
    };

    let first = statement_line.min(anchor_line);
    let last = statement_line.max(anchor_line);
    (first..=last)
        .any(|line| suppressions.is_suppressed(file_id, line, IssueKind::UnresolvedImport))
}

/// Find imports that could not be resolved.
#[expect(
    clippy::too_many_arguments,
    reason = "each analysis input stays a separate borrowed argument"
)]
pub fn find_unresolved_imports(
    resolved_modules: &[ResolvedModule],
    config: &ResolvedConfig,
    suppressions: &SuppressionContext<'_>,
    virtual_prefixes: &[&str],
    generated_patterns: &[&str],
    generated_type_prefixes: &[&str],
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<UnresolvedImport> {
    let filters = UnresolvedImportFilters {
        config,
        virtual_prefixes,
        generated_patterns,
        generated_type_prefixes,
    };
    let mut gitignored = GitignoredTargets::new(&config.root);
    let mut unresolved = Vec::new();

    for module in resolved_modules {
        // A multi-binding re-export statement yields one edge per binding, all
        // with the same unresolvable specifier. Report each specifier once per
        // module, anchored on the first edge in source order. The dedup key is
        // claimed before the suppression check so one suppression on the
        // anchored statement retires the whole specifier instead of moving the
        // finding to the next binding or statement.
        let mut reported_specs: FxHashSet<String> = FxHashSet::default();
        for edge in module.all_resolved_source_edges() {
            let crate::resolve::ResolveResult::Unresolvable(spec) = edge.target() else {
                continue;
            };
            if reported_specs.contains(spec.as_str()) {
                continue;
            }
            if unresolved_spec_is_silenced(spec, edge.is_type_only(), &filters) {
                continue;
            }
            if gitignored.ignores_missing_target(&module.path, spec) {
                continue;
            }
            if module
                .missing_export_targets
                .iter()
                .find(|target| target.specifier == *spec)
                .is_some_and(|target| gitignored.ignores_missing_paths(&target.paths))
            {
                continue;
            }
            let (line, col, specifier_col) =
                unresolved_import_location(&edge, module.file_id, line_offsets_by_file);
            reported_specs.insert(spec.clone());
            if unresolved_import_suppressed(
                suppressions,
                &edge,
                module.file_id,
                line,
                line_offsets_by_file,
            ) {
                continue;
            }
            unresolved.push(UnresolvedImport {
                path: module.path.clone(),
                specifier: spec.clone(),
                line,
                col,
                specifier_col,
            });
        }
    }

    unresolved
}

#[cfg(test)]
#[path = "unused_deps_tests/mod.rs"]
mod tests;