aube-lockfile 1.20.0

Multi-format lockfile reader/writer for Aube (aube-lock, pnpm-lock, package-lock, yarn.lock, bun.lock)
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
use super::layout::package_name_from_install_path;
use super::source::local_git_source_from_resolved;
use super::*;
use crate::{DepType, DirectDep, Error, GitSource, LocalSource, LockedPackage, LockfileGraph};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

#[test]
fn test_package_name_from_install_path() {
    assert_eq!(
        package_name_from_install_path("node_modules/foo"),
        Some("foo".to_string())
    );
    assert_eq!(
        package_name_from_install_path("node_modules/@scope/pkg"),
        Some("@scope/pkg".to_string())
    );
    assert_eq!(
        package_name_from_install_path("node_modules/foo/node_modules/bar"),
        Some("bar".to_string())
    );
    assert_eq!(
        package_name_from_install_path("node_modules/foo/node_modules/@scope/pkg"),
        Some("@scope/pkg".to_string())
    );
}

#[test]
fn test_parse_simple() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": { "foo": "^1.0.0" },
                    "devDependencies": { "bar": "^2.0.0" }
                },
                "node_modules/foo": {
                    "version": "1.2.3",
                    "integrity": "sha512-aaa",
                    "dependencies": { "nested": "^3.0.0" }
                },
                "node_modules/nested": {
                    "version": "3.1.0",
                    "integrity": "sha512-bbb"
                },
                "node_modules/bar": {
                    "version": "2.5.0",
                    "integrity": "sha512-ccc",
                    "dev": true
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();

    assert_eq!(graph.packages.len(), 3);
    assert!(graph.packages.contains_key("foo@1.2.3"));
    assert!(graph.packages.contains_key("nested@3.1.0"));
    assert!(graph.packages.contains_key("bar@2.5.0"));

    let foo = &graph.packages["foo@1.2.3"];
    assert_eq!(foo.integrity.as_deref(), Some("sha512-aaa"));
    // `LockedPackage.dependencies` values are dep_path *tails* (the
    // substring after `<name>@`), not full dep_paths — matches the
    // pnpm parser and the linker's sibling-symlink builder.
    assert_eq!(
        foo.dependencies.get("nested").map(String::as_str),
        Some("3.1.0")
    );

    let root = graph.importers.get(".").unwrap();
    assert_eq!(root.len(), 2);
    assert!(
        root.iter()
            .any(|d| d.name == "foo" && d.dep_type == DepType::Production)
    );
    assert!(
        root.iter()
            .any(|d| d.name == "bar" && d.dep_type == DepType::Dev)
    );
}

#[test]
fn test_parse_git_resolved_package() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let sha = "abcdef1234567890abcdef1234567890abcdef12";
    let content = format!(
        r#"{{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 2,
            "packages": {{
                "": {{
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": {{ "git-only": "github:owner/repo#{sha}" }}
                }},
                "node_modules/git-only": {{
                    "version": "1.2.3",
                    "resolved": "git+ssh://git@github.com/owner/repo.git#{sha}",
                    "integrity": "sha512-aaa"
                }}
            }}
        }}"#
    );
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let root = &graph.importers["."];
    assert_eq!(root.len(), 1);
    assert_eq!(root[0].name, "git-only");
    assert!(!graph.packages.contains_key("git-only@1.2.3"));

    let pkg = &graph.packages[&root[0].dep_path];
    assert_eq!(pkg.name, "git-only");
    assert_eq!(pkg.version, "1.2.3");
    assert_eq!(pkg.integrity.as_deref(), Some("sha512-aaa"));
    assert!(pkg.tarball_url.is_none());

    let Some(LocalSource::Git(git)) = &pkg.local_source else {
        panic!("expected git local source, got {:?}", pkg.local_source);
    };
    assert_eq!(git.url, "ssh://git@github.com/owner/repo.git");
    assert_eq!(git.committish.as_deref(), Some(sha));
    assert_eq!(git.resolved, sha);
}

#[test]
fn test_unpinned_git_resolved_url_is_not_locked_git_source() {
    assert!(local_git_source_from_resolved("git+https://github.com/owner/repo.git").is_none());
}

#[test]
fn test_write_preserves_git_resolved_url() {
    let sha = "abcdef1234567890abcdef1234567890abcdef12";
    let mut graph = LockfileGraph::default();
    let local = LocalSource::Git(GitSource {
        url: "ssh://git@github.com/owner/repo.git".to_string(),
        committish: Some(sha.to_string()),
        resolved: sha.to_string(),
        integrity: None,
        subpath: None,
    });
    let dep_path = local.dep_path("git-only");
    graph.packages.insert(
        dep_path.clone(),
        LockedPackage {
            name: "git-only".to_string(),
            version: "1.2.3".to_string(),
            dep_path: dep_path.clone(),
            local_source: Some(local),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![DirectDep {
            name: "git-only".to_string(),
            dep_path,
            dep_type: DepType::Production,
            specifier: Some(format!("github:owner/repo#{sha}")),
        }],
    );

    let manifest = aube_manifest::PackageJson {
        name: Some("test".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [("git-only".to_string(), format!("github:owner/repo#{sha}"))]
            .into_iter()
            .collect(),
        ..Default::default()
    };
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let body = std::fs::read_to_string(out.path()).unwrap();
    assert!(
        body.contains(&format!(
            "\"resolved\": \"git+ssh://git@github.com/owner/repo.git#{sha}\""
        )),
        "expected git resolved URL emitted; got:\n{body}"
    );

    let reparsed = parse(out.path()).unwrap();
    let pkg = &reparsed.packages[&graph.importers["."][0].dep_path];
    assert!(matches!(pkg.local_source, Some(LocalSource::Git(_))));
}

#[test]
fn test_write_skips_non_git_local_sources() {
    let local = LocalSource::Directory(PathBuf::from("vendor/local-dir"));
    let dep_path = local.dep_path("local-dir");
    let mut graph = LockfileGraph::default();
    graph.packages.insert(
        dep_path.clone(),
        LockedPackage {
            name: "local-dir".to_string(),
            version: "1.0.0".to_string(),
            dep_path: dep_path.clone(),
            local_source: Some(local),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![DirectDep {
            name: "local-dir".to_string(),
            dep_path,
            dep_type: DepType::Production,
            specifier: Some("file:vendor/local-dir".to_string()),
        }],
    );

    let manifest = aube_manifest::PackageJson {
        name: Some("test".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [("local-dir".to_string(), "file:vendor/local-dir".to_string())]
            .into_iter()
            .collect(),
        ..Default::default()
    };
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let body = std::fs::read_to_string(out.path()).unwrap();
    assert!(!body.contains("\"node_modules/local-dir\""));
}

#[test]
fn test_parse_file_resolved_without_link() {
    // npm writes `resolved: "file:..."` without `link: true` for
    // local tarball deps (`npm install file:../foo-1.0.0.tgz`) and
    // for some directory deps. Both shapes must surface as a
    // LocalSource so the resolver dispatches the local-source
    // branch and doesn't fall through to a registry fetch.
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "dependencies": {
                        "tar-dep": "file:../utils/tar-dep-1.0.0.tgz",
                        "dir-dep": "file:../utils"
                    }
                },
                "node_modules/tar-dep": {
                    "version": "1.0.0",
                    "resolved": "file:../utils/tar-dep-1.0.0.tgz",
                    "integrity": "sha512-aaa"
                },
                "node_modules/dir-dep": {
                    "version": "1.0.0",
                    "resolved": "file:../utils"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();

    let tar_pkg = graph
        .packages
        .values()
        .find(|p| p.name == "tar-dep")
        .expect("tar-dep entry");
    assert!(
        matches!(&tar_pkg.local_source, Some(LocalSource::Tarball(p)) if p == Path::new("../utils/tar-dep-1.0.0.tgz")),
        "expected Tarball source, got {:?}",
        tar_pkg.local_source,
    );
    assert!(
        tar_pkg.dep_path.starts_with("tar-dep@file+"),
        "tarball dep_path should be local-source-keyed, got {}",
        tar_pkg.dep_path,
    );

    let dir_pkg = graph
        .packages
        .values()
        .find(|p| p.name == "dir-dep")
        .expect("dir-dep entry");
    assert!(
        matches!(&dir_pkg.local_source, Some(LocalSource::Directory(p)) if p == Path::new("../utils")),
        "expected Directory source, got {:?}",
        dir_pkg.local_source,
    );
    assert!(
        dir_pkg.dep_path.starts_with("dir-dep@file+"),
        "directory dep_path should be local-source-keyed, got {}",
        dir_pkg.dep_path,
    );

    let root = graph.importers.get(".").unwrap();
    let tar_direct = root.iter().find(|d| d.name == "tar-dep").unwrap();
    assert_eq!(tar_direct.dep_path, tar_pkg.dep_path);
    let dir_direct = root.iter().find(|d| d.name == "dir-dep").unwrap();
    assert_eq!(dir_direct.dep_path, dir_pkg.dep_path);
}

#[test]
fn test_parse_scoped_package() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "dependencies": { "@scope/pkg": "^1.0.0" }
                },
                "node_modules/@scope/pkg": {
                    "version": "1.0.0",
                    "integrity": "sha512-zzz"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    assert!(graph.packages.contains_key("@scope/pkg@1.0.0"));
    let root = graph.importers.get(".").unwrap();
    assert_eq!(root[0].name, "@scope/pkg");
    assert_eq!(root[0].dep_path, "@scope/pkg@1.0.0");
}

#[test]
fn test_parse_multi_version_nested() {
    // bar exists at two versions: 2.0.0 hoisted to root, 1.0.0 nested under foo.
    // foo's transitive dep on bar must resolve to 1.0.0, not 2.0.0.
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "dependencies": { "foo": "^1.0.0", "bar": "^2.0.0" }
                },
                "node_modules/bar": {
                    "version": "2.0.0",
                    "integrity": "sha512-top-bar"
                },
                "node_modules/foo": {
                    "version": "1.0.0",
                    "integrity": "sha512-foo",
                    "dependencies": { "bar": "^1.0.0" }
                },
                "node_modules/foo/node_modules/bar": {
                    "version": "1.0.0",
                    "integrity": "sha512-nested-bar"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    // Both versions of bar should be present.
    assert!(graph.packages.contains_key("bar@2.0.0"));
    assert!(graph.packages.contains_key("bar@1.0.0"));
    assert!(graph.packages.contains_key("foo@1.0.0"));

    // foo's transitive dep must point to the nested (1.0.0), not the hoisted (2.0.0).
    // Value is the dep_path tail (version) — see the `LockedPackage.dependencies` doc.
    let foo = &graph.packages["foo@1.0.0"];
    assert_eq!(
        foo.dependencies.get("bar").map(String::as_str),
        Some("1.0.0")
    );

    // Root's direct bar dep points to the hoisted 2.0.0.
    let root = graph.importers.get(".").unwrap();
    let root_bar = root.iter().find(|d| d.name == "bar").unwrap();
    assert_eq!(root_bar.dep_path, "bar@2.0.0");
}

/// Regression: a package reachable from both a dev root and
/// an optional root (but *not* from any production root) must
/// be written with `devOptional: true`, not with both `dev: true`
/// and `optional: true`. Emitting both trips `npm install
/// --omit=dev` (and `--omit=optional`) into dropping a package
/// the other chain still needs.
#[test]
fn test_write_dev_and_optional_reachable_uses_dev_optional() {
    let mut graph = LockfileGraph::default();
    let mk = |name: &str| LockedPackage {
        name: name.to_string(),
        version: "1.0.0".to_string(),
        integrity: Some(format!("sha512-{name}")),
        dep_path: format!("{name}@1.0.0"),
        dependencies: [("shared".to_string(), "1.0.0".to_string())]
            .into_iter()
            .collect(),
        ..Default::default()
    };
    graph
        .packages
        .insert("dev-root@1.0.0".to_string(), mk("dev-root"));
    graph
        .packages
        .insert("opt-root@1.0.0".to_string(), mk("opt-root"));
    graph.packages.insert(
        "shared@1.0.0".to_string(),
        LockedPackage {
            name: "shared".to_string(),
            version: "1.0.0".to_string(),
            integrity: Some("sha512-shared".to_string()),
            dep_path: "shared@1.0.0".to_string(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![
            DirectDep {
                name: "dev-root".to_string(),
                dep_path: "dev-root@1.0.0".to_string(),
                dep_type: DepType::Dev,
                specifier: None,
            },
            DirectDep {
                name: "opt-root".to_string(),
                dep_path: "opt-root@1.0.0".to_string(),
                dep_type: DepType::Optional,
                specifier: None,
            },
        ],
    );

    let manifest = aube_manifest::PackageJson {
        name: Some("test".to_string()),
        version: Some("1.0.0".to_string()),
        dev_dependencies: [("dev-root".to_string(), "^1.0.0".to_string())]
            .into_iter()
            .collect(),
        optional_dependencies: [("opt-root".to_string(), "^1.0.0".to_string())]
            .into_iter()
            .collect(),
        ..Default::default()
    };

    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();
    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(out.path()).unwrap()).unwrap();

    let shared = &json["packages"]["node_modules/shared"];
    assert_eq!(shared["devOptional"], true, "expected devOptional flag");
    assert!(
        shared.get("dev").is_none(),
        "must not emit dev: true alongside devOptional",
    );
    assert!(
        shared.get("optional").is_none(),
        "must not emit optional: true alongside devOptional",
    );

    // Roots themselves retain their specific flag.
    assert_eq!(json["packages"]["node_modules/dev-root"]["dev"], true);
    assert_eq!(json["packages"]["node_modules/opt-root"]["optional"], true);
}

/// Regression: the npm writer must drop `dependencies` entries
/// whose target isn't in the canonical map. Platform-filtered
/// optionals and `ignoredOptionalDependencies` leave the parent's
/// declared `dependencies` map pointing at packages the resolver
/// already removed; emitting them anyway produces a lockfile
/// where `npm ci` sees a reference with no matching `packages`
/// entry and refuses to install. Must match the bun/yarn
/// writers, which already filter this way.
#[test]
fn test_write_filters_missing_canonical_deps() {
    let mut graph = LockfileGraph::default();
    // Root has one real package, `foo`, which declares a dep on
    // `ghost@1.0.0` — but `ghost` was filtered out of the graph
    // (e.g. a platform-gated optional). The canonical map won't
    // contain it.
    graph.packages.insert(
        "foo@1.0.0".to_string(),
        LockedPackage {
            name: "foo".to_string(),
            version: "1.0.0".to_string(),
            integrity: Some("sha512-foo".to_string()),
            dep_path: "foo@1.0.0".to_string(),
            dependencies: [("ghost".to_string(), "1.0.0".to_string())]
                .into_iter()
                .collect(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![DirectDep {
            name: "foo".to_string(),
            dep_path: "foo@1.0.0".to_string(),
            dep_type: DepType::Production,
            specifier: None,
        }],
    );

    let manifest = test_manifest();
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    // Parse the raw JSON directly — the aube reparser tolerates
    // dangling references so we assert on the serialized shape.
    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(out.path()).unwrap()).unwrap();
    let foo_entry = &json["packages"]["node_modules/foo"];
    assert!(
        foo_entry
            .get("dependencies")
            .and_then(|d| d.get("ghost"))
            .is_none(),
        "writer emitted a ghost dep that has no packages entry: {foo_entry}",
    );
    // And there should be no node_modules/ghost entry at all.
    assert!(
        json["packages"].get("node_modules/ghost").is_none(),
        "writer hallucinated a ghost entry",
    );
}

/// Regression for the shadow-nesting bug: if an intermediate
/// ancestor carries the *wrong* version of a dep, Node's
/// runtime walk stops there and never reaches a correct entry
/// at root. The writer must nest a fresh entry inside the
/// current parent's own `node_modules` instead of assuming
/// hoisting is fine just because root happens to have the
/// right version.
///
/// Shape:
///   root → foo → baz, baz depends on bar@2.0.0
///   foo already pulled in bar@1.0.0 for a sibling, so bar@1.0.0
///     lives at node_modules/foo/node_modules/bar
///   root has bar@2.0.0 at node_modules/bar
///
///   When we walk baz's deps and get to bar@2.0.0, the nearest
///   ancestor hit is bar@1.0.0 (shadowing), not root. We must
///   place a fresh entry at
///   `node_modules/foo/node_modules/baz/node_modules/bar` so
///   Node resolves the right version.
#[test]
fn test_nested_shadow_forces_nested_placement() {
    // Build a graph by hand to control the dep order deterministically.
    let mut graph = LockfileGraph::default();
    let mk = |name: &str, version: &str, deps: &[(&str, &str)]| LockedPackage {
        name: name.to_string(),
        version: version.to_string(),
        integrity: Some(format!("sha512-{name}-{version}")),
        dep_path: format!("{name}@{version}"),
        dependencies: deps
            .iter()
            .map(|(n, v)| (n.to_string(), (*v).to_string()))
            .collect(),
        ..Default::default()
    };
    graph.packages.insert(
        "foo@1.0.0".to_string(),
        mk(
            "foo",
            "1.0.0",
            &[
                // foo pulls in bar@1.0.0 and baz@1.0.0 as siblings.
                ("bar", "1.0.0"),
                ("baz", "1.0.0"),
            ],
        ),
    );
    graph.packages.insert(
        "baz@1.0.0".to_string(),
        // baz wants bar@2.0.0, which matches the root version.
        mk("baz", "1.0.0", &[("bar", "2.0.0")]),
    );
    graph
        .packages
        .insert("bar@1.0.0".to_string(), mk("bar", "1.0.0", &[]));
    graph
        .packages
        .insert("bar@2.0.0".to_string(), mk("bar", "2.0.0", &[]));
    graph.importers.insert(
        ".".to_string(),
        vec![
            DirectDep {
                name: "foo".to_string(),
                dep_path: "foo@1.0.0".to_string(),
                dep_type: DepType::Production,
                specifier: None,
            },
            DirectDep {
                name: "bar".to_string(),
                dep_path: "bar@2.0.0".to_string(),
                dep_type: DepType::Production,
                specifier: None,
            },
        ],
    );

    let manifest = test_manifest();
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();
    let reparsed = parse(out.path()).unwrap();

    // baz's transitive dep must resolve to bar@2.0.0, not the
    // shadowing bar@1.0.0 under foo. Value is the dep_path tail
    // (version) so the linker can recombine it with the dep name.
    let baz = &reparsed.packages["baz@1.0.0"];
    assert_eq!(
        baz.dependencies.get("bar").map(String::as_str),
        Some("2.0.0"),
        "baz's bar dep was shadowed by foo/bar@1.0.0 — shadow-nest fix regressed",
    );
}

#[test]
fn test_parse_npm_preserves_platform_optional_metadata() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "platform-optional-root",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "platform-optional-root",
                    "version": "1.0.0",
                    "dependencies": { "host": "file:host" }
                },
                "node_modules/host": {
                    "resolved": "host",
                    "link": true
                },
                "host": {
                    "name": "host",
                    "version": "1.0.0",
                    "optionalDependencies": { "native-win": "1.0.0" }
                },
                "node_modules/native-win": {
                    "version": "1.0.0",
                    "resolved": "https://registry.npmjs.org/native-win/-/native-win-1.0.0.tgz",
                    "integrity": "sha512-native",
                    "optional": true,
                    "os": ["win32"],
                    "cpu": ["x64"],
                    "libc": ["glibc"]
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let host_dep_path = &graph.importers["."][0].dep_path;
    let host = &graph.packages[host_dep_path];
    assert_eq!(
        host.dependencies.get("native-win").map(String::as_str),
        Some("1.0.0")
    );
    assert_eq!(
        host.optional_dependencies
            .get("native-win")
            .map(String::as_str),
        Some("1.0.0")
    );

    let native = &graph.packages["native-win@1.0.0"];
    assert_eq!(
        native.os.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["win32"]
    );
    assert_eq!(
        native.cpu.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["x64"]
    );
    assert_eq!(
        native.libc.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["glibc"]
    );
}

/// npm sometimes emits `os` / `cpu` / `libc` as scalar strings instead
/// of arrays (e.g. `sass-embedded-linux-arm@1.99.0` ships
/// `"libc": "glibc"`). Verbatim-roundtripped into package-lock.json,
/// the field stays scalar — accept both shapes the same way the
/// pnpm + bun parsers already do.
#[test]
fn parse_npm_package_platform_fields_accept_scalar_strings() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "scalar-platform-root",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "scalar-platform-root",
                    "version": "1.0.0",
                    "dependencies": { "sass-embedded-linux-arm": "1.99.0" }
                },
                "node_modules/sass-embedded-linux-arm": {
                    "version": "1.99.0",
                    "resolved": "https://registry.npmjs.org/sass-embedded-linux-arm/-/sass-embedded-linux-arm-1.99.0.tgz",
                    "integrity": "sha512-native",
                    "cpu": "arm",
                    "os": "linux",
                    "libc": "glibc"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let pkg = &graph.packages["sass-embedded-linux-arm@1.99.0"];
    assert_eq!(
        pkg.os.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["linux"]
    );
    assert_eq!(
        pkg.cpu.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["arm"]
    );
    assert_eq!(
        pkg.libc.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["glibc"]
    );
}

#[test]
fn test_write_npm_preserves_platform_optional_metadata() {
    let mut graph = LockfileGraph::default();
    graph.packages.insert(
        "host@1.0.0".to_string(),
        LockedPackage {
            name: "host".to_string(),
            version: "1.0.0".to_string(),
            integrity: Some("sha512-host".to_string()),
            dep_path: "host@1.0.0".to_string(),
            dependencies: [("native-win".to_string(), "1.0.0".to_string())]
                .into_iter()
                .collect(),
            optional_dependencies: [("native-win".to_string(), "1.0.0".to_string())]
                .into_iter()
                .collect(),
            declared_dependencies: [("native-win".to_string(), "1.0.0".to_string())]
                .into_iter()
                .collect(),
            ..Default::default()
        },
    );
    graph.packages.insert(
        "native-win@1.0.0".to_string(),
        LockedPackage {
            name: "native-win".to_string(),
            version: "1.0.0".to_string(),
            integrity: Some("sha512-native".to_string()),
            dep_path: "native-win@1.0.0".to_string(),
            os: vec!["win32".to_string()].into(),
            cpu: vec!["x64".to_string()].into(),
            libc: vec!["glibc".to_string()].into(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![DirectDep {
            name: "host".to_string(),
            dep_path: "host@1.0.0".to_string(),
            dep_type: DepType::Production,
            specifier: Some("1.0.0".to_string()),
        }],
    );
    let manifest = aube_manifest::PackageJson {
        name: Some("platform-optional-root".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [("host".to_string(), "1.0.0".to_string())]
            .into_iter()
            .collect(),
        ..Default::default()
    };

    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();
    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(out.path()).unwrap()).unwrap();

    let host = &json["packages"]["node_modules/host"];
    assert_eq!(host["optionalDependencies"]["native-win"], "1.0.0");
    assert!(
        host.get("dependencies")
            .and_then(|deps| deps.get("native-win"))
            .is_none(),
        "optional child must not be duplicated as a required dependency: {host}",
    );

    let native = &json["packages"]["node_modules/native-win"];
    assert_eq!(native["os"], serde_json::json!(["win32"]));
    assert_eq!(native["cpu"], serde_json::json!(["x64"]));
    assert_eq!(native["libc"], serde_json::json!(["glibc"]));

    let reparsed = parse(out.path()).unwrap();
    let host = &reparsed.packages["host@1.0.0"];
    assert_eq!(
        host.optional_dependencies
            .get("native-win")
            .map(String::as_str),
        Some("1.0.0")
    );
    assert_eq!(
        host.dependencies.get("native-win").map(String::as_str),
        Some("1.0.0")
    );
    let native = &reparsed.packages["native-win@1.0.0"];
    assert_eq!(
        native.os.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["win32"]
    );
    assert_eq!(
        native.cpu.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["x64"]
    );
    assert_eq!(
        native.libc.iter().map(String::as_str).collect::<Vec<_>>(),
        vec!["glibc"]
    );
}

/// Regression: `canonical_key_from_dep_path` must strip the
/// `(peer@ver)` suffix *before* splitting on `@`. A naive
/// `rfind('@')` lands inside the peer suffix and returns the
/// input unchanged, which silently drops every peer-contextualized
/// root dep from the written lockfile. Hashed suffixes use the
/// same canonical identity; otherwise long peer suffixes drop
/// out of npm package-lock output.
#[test]
fn test_canonical_key_strips_peer_suffix() {
    assert_eq!(canonical_key_from_dep_path("foo@1.0.0"), "foo@1.0.0");
    assert_eq!(
        canonical_key_from_dep_path("styled-components@6.1.0(react@18.2.0)"),
        "styled-components@6.1.0"
    );
    assert_eq!(
        canonical_key_from_dep_path("@scope/pkg@2.0.0(peer@1.0.0)"),
        "@scope/pkg@2.0.0"
    );
    assert_eq!(
        canonical_key_from_dep_path("expo-router@4.0.22_94c00fd028"),
        "expo-router@4.0.22"
    );
    assert_eq!(
        child_canonical_key("expo-router", "4.0.22_94c00fd028"),
        "expo-router@4.0.22"
    );
    assert_eq!(
        dep_value_as_version("expo-router", "expo-router@4.0.22_94c00fd028"),
        "4.0.22"
    );
    assert_eq!(
        canonical_key_from_dep_path("expo-router@4.0.22_94C00FD028"),
        "expo-router@4.0.22"
    );
}

fn test_manifest() -> aube_manifest::PackageJson {
    aube_manifest::PackageJson {
        name: Some("test".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [
            ("foo".to_string(), "^1.0.0".to_string()),
            ("bar".to_string(), "^2.0.0".to_string()),
        ]
        .into_iter()
        .collect(),
        ..Default::default()
    }
}

/// Parse a fixture, write it back, re-parse: the resulting graph
/// must have the same packages, direct deps, and integrity hashes.
/// Catches silent data loss in the hoist/nest walk.
#[test]
fn test_write_roundtrip_multi_version() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": { "foo": "^1.0.0", "bar": "^2.0.0" }
                },
                "node_modules/bar": {
                    "version": "2.0.0",
                    "integrity": "sha512-top-bar"
                },
                "node_modules/foo": {
                    "version": "1.0.0",
                    "integrity": "sha512-foo",
                    "dependencies": { "bar": "^1.0.0" }
                },
                "node_modules/foo/node_modules/bar": {
                    "version": "1.0.0",
                    "integrity": "sha512-nested-bar"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let manifest = test_manifest();

    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();
    let reparsed = parse(out.path()).unwrap();

    // Both versions of bar survived the round-trip.
    assert!(reparsed.packages.contains_key("bar@1.0.0"));
    assert!(reparsed.packages.contains_key("bar@2.0.0"));
    assert!(reparsed.packages.contains_key("foo@1.0.0"));
    assert_eq!(
        reparsed.packages["bar@2.0.0"].integrity.as_deref(),
        Some("sha512-top-bar")
    );
    assert_eq!(
        reparsed.packages["bar@1.0.0"].integrity.as_deref(),
        Some("sha512-nested-bar")
    );
    // foo's nested bar dep still resolves to 1.0.0, not the
    // hoisted 2.0.0. If the writer failed to nest, reparse would
    // snap this to bar@2.0.0. Value is the dep_path tail.
    assert_eq!(
        reparsed.packages["foo@1.0.0"]
            .dependencies
            .get("bar")
            .map(String::as_str),
        Some("1.0.0")
    );
}

/// Dev-only and optional-only packages get the right flags after
/// round-trip so `npm install --omit=dev` on the written file
/// does the right thing.
#[test]
fn test_write_dev_optional_flags() {
    let mut graph = LockfileGraph::default();
    graph.packages.insert(
        "foo@1.0.0".to_string(),
        LockedPackage {
            name: "foo".to_string(),
            version: "1.0.0".to_string(),
            integrity: Some("sha512-foo".to_string()),
            dep_path: "foo@1.0.0".to_string(),
            ..Default::default()
        },
    );
    graph.packages.insert(
        "devdep@1.0.0".to_string(),
        LockedPackage {
            name: "devdep".to_string(),
            version: "1.0.0".to_string(),
            integrity: Some("sha512-dev".to_string()),
            dep_path: "devdep@1.0.0".to_string(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![
            DirectDep {
                name: "foo".to_string(),
                dep_path: "foo@1.0.0".to_string(),
                dep_type: DepType::Production,
                specifier: None,
            },
            DirectDep {
                name: "devdep".to_string(),
                dep_path: "devdep@1.0.0".to_string(),
                dep_type: DepType::Dev,
                specifier: None,
            },
        ],
    );

    let manifest = aube_manifest::PackageJson {
        name: Some("test".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [("foo".to_string(), "^1.0.0".to_string())]
            .into_iter()
            .collect(),
        dev_dependencies: [("devdep".to_string(), "^1.0.0".to_string())]
            .into_iter()
            .collect(),
        ..Default::default()
    };

    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(out.path()).unwrap()).unwrap();
    let packages = &json["packages"];
    assert_eq!(packages["node_modules/devdep"]["dev"], true);
    // Prod dep should have no dev field (skipped when false).
    assert!(packages["node_modules/foo"].get("dev").is_none());
}

#[test]
fn test_reject_v1() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "lockfileVersion": 1,
            "dependencies": {}
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let err = parse(tmp.path()).unwrap_err();
    assert!(matches!(err, Error::Parse(_, msg) if msg.contains("lockfileVersion 1")));
}

/// Pre-npm-2.x packages (e.g. `ansi-html-community@0.0.8`) ship
/// `"engines": ["node >= 0.8.0"]` as an array; npm preserves that
/// shape verbatim in v2/v3 lockfiles. Without tolerant parsing, a
/// single such entry blows up the whole `aube ci`. Normalize to an
/// empty map (matches what modern npm does for engine-strict on
/// the array shape) so the install proceeds.
#[test]
fn test_parse_legacy_array_engines() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": { "ansi-html-community": "0.0.8" }
                },
                "node_modules/ansi-html-community": {
                    "version": "0.0.8",
                    "integrity": "sha512-aaa",
                    "engines": ["node >= 0.8.0"]
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let pkg = &graph.packages["ansi-html-community@0.0.8"];
    // Array shape gets normalized to an empty map — same as the
    // manifest parser, and same as what modern npm honors for the
    // engine-strict check on the array form.
    assert!(pkg.engines.is_empty());
}

/// npm writes `"h3-v2": "npm:h3@..."` aliases as a packages entry
/// at `node_modules/h3-v2` with `name: "h3"` and the real registry
/// `resolved:` URL. Aube keys the graph on the *alias* (so
/// `node_modules/h3-v2` ends up at `.aube/h3-v2@.../node_modules/h3-v2`)
/// but remembers the real package name in `alias_of` so fetches
/// and store-index lookups use the URL that actually exists.
#[test]
fn test_parse_npm_alias_dependency() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": { "h3-v2": "npm:h3@2.0.1-rc.20" }
                },
                "node_modules/h3-v2": {
                    "name": "h3",
                    "version": "2.0.1-rc.20",
                    "resolved": "https://registry.npmjs.org/h3/-/h3-2.0.1-rc.20.tgz",
                    "integrity": "sha512-aliased"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    assert_eq!(graph.packages.len(), 1);
    // Graph key and LockedPackage.name both carry the alias —
    // that's what consumers (and the linker's folder-name logic)
    // refer to when they say "h3-v2".
    let pkg = graph
        .packages
        .get("h3-v2@2.0.1-rc.20")
        .expect("aliased entry should be keyed by the alias dep_path");
    assert_eq!(pkg.name, "h3-v2");
    assert_eq!(pkg.version, "2.0.1-rc.20");
    assert_eq!(pkg.alias_of.as_deref(), Some("h3"));
    assert_eq!(pkg.registry_name(), "h3");
    // `resolved:` round-trips into `tarball_url` so the fetcher
    // skips re-deriving from the alias-qualified name (which
    // would 404 the registry).
    assert_eq!(
        pkg.tarball_url.as_deref(),
        Some("https://registry.npmjs.org/h3/-/h3-2.0.1-rc.20.tgz")
    );

    let root = graph.importers.get(".").unwrap();
    assert_eq!(root.len(), 1);
    assert_eq!(root[0].name, "h3-v2");
    assert_eq!(root[0].dep_path, "h3-v2@2.0.1-rc.20");
}

/// Non-aliased entries (the common case) leave `alias_of` unset
/// and `registry_name()` degenerates to `name`. Regression guard
/// against over-aggressive alias detection that would flag every
/// entry carrying an explicit `name:` field (npm sometimes emits
/// one for non-aliased roots too).
#[test]
fn test_parse_non_alias_preserves_empty_alias_of() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": { "foo": "^1.0.0" }
                },
                "node_modules/foo": {
                    "name": "foo",
                    "version": "1.2.3",
                    "integrity": "sha512-foo"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let pkg = &graph.packages["foo@1.2.3"];
    assert_eq!(pkg.name, "foo");
    assert!(pkg.alias_of.is_none());
    assert_eq!(pkg.registry_name(), "foo");
    assert!(pkg.tarball_url.is_none());
}

/// Round-trip: writer must emit `name:` and `resolved:` for the
/// aliased entry so a subsequent `parse()` still recognizes it as
/// an alias. Without both fields the re-parser would see
/// `node_modules/h3-v2` with no `name:` and treat it as a plain
/// package called `h3-v2` — which doesn't exist on the registry.
#[test]
fn test_write_roundtrip_npm_alias() {
    let mut graph = LockfileGraph::default();
    graph.packages.insert(
        "h3-v2@2.0.1-rc.20".to_string(),
        LockedPackage {
            name: "h3-v2".to_string(),
            version: "2.0.1-rc.20".to_string(),
            integrity: Some("sha512-aliased".to_string()),
            dep_path: "h3-v2@2.0.1-rc.20".to_string(),
            alias_of: Some("h3".to_string()),
            tarball_url: Some("https://registry.npmjs.org/h3/-/h3-2.0.1-rc.20.tgz".to_string()),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![DirectDep {
            name: "h3-v2".to_string(),
            dep_path: "h3-v2@2.0.1-rc.20".to_string(),
            dep_type: DepType::Production,
            specifier: Some("npm:h3@2.0.1-rc.20".to_string()),
        }],
    );

    let manifest = test_manifest();
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let body = std::fs::read_to_string(out.path()).unwrap();
    assert!(
        body.contains("\"name\": \"h3\""),
        "expected `name: h3` emitted for aliased entry; got:\n{body}"
    );
    assert!(
        body.contains("\"resolved\": \"https://registry.npmjs.org/h3/-/h3-2.0.1-rc.20.tgz\""),
        "expected `resolved:` URL emitted for aliased entry; got:\n{body}"
    );

    let reparsed = parse(out.path()).unwrap();
    let pkg = &reparsed.packages["h3-v2@2.0.1-rc.20"];
    assert_eq!(pkg.alias_of.as_deref(), Some("h3"));
    assert_eq!(pkg.registry_name(), "h3");
}

/// npm v7+ writes `peerDependencies` / `peerDependenciesMeta` onto
/// every package entry. The parser must populate the matching
/// `LockedPackage` fields so the resolver's `apply_peer_contexts`
/// pass (run on npm-lockfile installs to wire peer siblings in the
/// isolated virtual store) actually has peer info to work with.
/// Before this parser change, peer-dependent packages like
/// `@tanstack/devtools-vite` would install without a sibling
/// `vite` link and die at runtime.
#[test]
fn test_parse_peer_dependencies() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "peer-test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "peer-test",
                    "version": "1.0.0",
                    "dependencies": { "devtools-vite": "0.6.0", "vite": "8.0.0" }
                },
                "node_modules/devtools-vite": {
                    "version": "0.6.0",
                    "integrity": "sha512-a",
                    "peerDependencies": {
                        "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
                    },
                    "peerDependenciesMeta": {
                        "vite": { "optional": false }
                    }
                },
                "node_modules/vite": {
                    "version": "8.0.0",
                    "integrity": "sha512-b"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let devtools = &graph.packages["devtools-vite@0.6.0"];
    assert_eq!(
        devtools.peer_dependencies.get("vite").map(String::as_str),
        Some("^6.0.0 || ^7.0.0 || ^8.0.0")
    );
    assert_eq!(
        devtools
            .peer_dependencies_meta
            .get("vite")
            .map(|m| m.optional),
        Some(false)
    );
}

/// Packages without peer fields keep both maps empty — guard
/// against accidental defaulting to `optional: true` or spurious
/// keys showing up in the LockedPackage from serde leak paths.
#[test]
fn test_parse_no_peer_fields_stays_empty() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "no-peers",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": { "name": "no-peers", "version": "1.0.0", "dependencies": { "foo": "1.0.0" } },
                "node_modules/foo": { "version": "1.0.0", "integrity": "sha512-x" }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let foo = &graph.packages["foo@1.0.0"];
    assert!(foo.peer_dependencies.is_empty());
    assert!(foo.peer_dependencies_meta.is_empty());
}

/// Writer round-trips `peerDependencies` so a second `parse()` on
/// the rewritten lockfile still feeds the peer-context pass. The
/// install path writes out the lockfile after every install; if
/// peers vanished on the first write-back, the *next* install
/// would ship without peer siblings again.
#[test]
fn test_write_roundtrip_peer_dependencies() {
    let mut graph = LockfileGraph::default();
    let mut peer_deps = BTreeMap::new();
    peer_deps.insert("vite".to_string(), "^6.0.0 || ^7.0.0 || ^8.0.0".to_string());
    // Include an `optional: true` entry so the round-trip covers
    // `peerDependenciesMeta` — without it, the writer's meta
    // block isn't exercised and the round-trip would silently
    // re-flag the peer as required on every subsequent install
    // (see `hoist_auto_installed_peers` + `detect_unmet_peers`,
    // which key off `optional`).
    let mut peer_deps_meta = BTreeMap::new();
    peer_deps_meta.insert("vite".to_string(), crate::PeerDepMeta { optional: true });
    graph.packages.insert(
        "devtools-vite@0.6.0".to_string(),
        LockedPackage {
            name: "devtools-vite".to_string(),
            version: "0.6.0".to_string(),
            integrity: Some("sha512-a".to_string()),
            dep_path: "devtools-vite@0.6.0".to_string(),
            peer_dependencies: peer_deps,
            peer_dependencies_meta: peer_deps_meta,
            ..Default::default()
        },
    );
    graph.packages.insert(
        "vite@8.0.0".to_string(),
        LockedPackage {
            name: "vite".to_string(),
            version: "8.0.0".to_string(),
            integrity: Some("sha512-b".to_string()),
            dep_path: "vite@8.0.0".to_string(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![
            DirectDep {
                name: "devtools-vite".to_string(),
                dep_path: "devtools-vite@0.6.0".to_string(),
                dep_type: DepType::Production,
                specifier: None,
            },
            DirectDep {
                name: "vite".to_string(),
                dep_path: "vite@8.0.0".to_string(),
                dep_type: DepType::Production,
                specifier: None,
            },
        ],
    );

    let manifest = test_manifest();
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let body = std::fs::read_to_string(out.path()).unwrap();
    assert!(
        body.contains("\"peerDependencies\""),
        "expected peerDependencies block to round-trip; got:\n{body}"
    );
    assert!(
        body.contains("\"peerDependenciesMeta\""),
        "expected peerDependenciesMeta block to round-trip; got:\n{body}"
    );

    let reparsed = parse(out.path()).unwrap();
    let devtools = &reparsed.packages["devtools-vite@0.6.0"];
    assert_eq!(
        devtools.peer_dependencies.get("vite").map(String::as_str),
        Some("^6.0.0 || ^7.0.0 || ^8.0.0")
    );
    assert_eq!(
        devtools
            .peer_dependencies_meta
            .get("vite")
            .map(|m| m.optional),
        Some(true),
        "peerDependenciesMeta.optional must survive write → parse round-trip"
    );
}

#[test]
fn test_parse_npm_workspace_importers() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "workspace-root",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "workspace-root",
                    "version": "1.0.0",
                    "workspaces": ["web"]
                },
                "node_modules/mise-versions-web": {
                    "resolved": "web",
                    "link": true
                },
                "web": {
                    "name": "mise-versions-web",
                    "version": "0.0.1",
                    "dependencies": { "astro": "^6.0.0" },
                    "devDependencies": { "vite": "^7.3.2" }
                },
                "web/node_modules/astro": {
                    "version": "6.2.1",
                    "integrity": "sha512-astro"
                },
                "web/node_modules/vite": {
                    "version": "7.3.2",
                    "integrity": "sha512-vite"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let root = graph.importers.get(".").expect("root importer");
    assert_eq!(root.len(), 1);
    assert_eq!(root[0].name, "mise-versions-web");
    assert!(matches!(
        graph.packages[&root[0].dep_path].local_source,
        Some(LocalSource::Link(_))
    ));

    let web = graph.importers.get("web").expect("web importer");
    assert_eq!(web.len(), 2);
    assert!(web.iter().any(|dep| {
        dep.name == "astro"
            && dep.dep_type == DepType::Production
            && dep.specifier.as_deref() == Some("^6.0.0")
    }));
    assert!(web.iter().any(|dep| {
        dep.name == "vite"
            && dep.dep_type == DepType::Dev
            && dep.specifier.as_deref() == Some("^7.3.2")
    }));
}

#[test]
fn test_write_npm_workspace_importers() {
    let mut graph = LockfileGraph::default();
    let web_link = LocalSource::Link(PathBuf::from("web"));
    let web_dep_path = web_link.dep_path("mise-versions-web");
    graph.packages.insert(
        web_dep_path.clone(),
        LockedPackage {
            name: "mise-versions-web".to_string(),
            version: "0.0.1".to_string(),
            dep_path: web_dep_path.clone(),
            local_source: Some(web_link),
            ..Default::default()
        },
    );
    graph.packages.insert(
        "astro@6.2.1".to_string(),
        LockedPackage {
            name: "astro".to_string(),
            version: "6.2.1".to_string(),
            integrity: Some("sha512-astro".to_string()),
            dep_path: "astro@6.2.1".to_string(),
            ..Default::default()
        },
    );
    graph.packages.insert(
        "vite@7.3.2".to_string(),
        LockedPackage {
            name: "vite".to_string(),
            version: "7.3.2".to_string(),
            integrity: Some("sha512-vite".to_string()),
            dep_path: "vite@7.3.2".to_string(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![DirectDep {
            name: "mise-versions-web".to_string(),
            dep_path: web_dep_path.clone(),
            dep_type: DepType::Production,
            specifier: None,
        }],
    );
    graph.importers.insert(
        "web".to_string(),
        vec![
            DirectDep {
                name: "astro".to_string(),
                dep_path: "astro@6.2.1".to_string(),
                dep_type: DepType::Production,
                specifier: Some("^6.0.0".to_string()),
            },
            DirectDep {
                name: "vite".to_string(),
                dep_path: "vite@7.3.2".to_string(),
                dep_type: DepType::Dev,
                specifier: Some("^7.3.2".to_string()),
            },
        ],
    );

    let manifest = aube_manifest::PackageJson {
        name: Some("workspace-root".to_string()),
        version: Some("1.0.0".to_string()),
        ..Default::default()
    };
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(out.path()).unwrap()).unwrap();
    assert_eq!(
        json["packages"]["node_modules/mise-versions-web"]["link"],
        true
    );
    assert_eq!(
        json["packages"]["node_modules/mise-versions-web"]["resolved"],
        "web"
    );
    assert_eq!(json["packages"]["web"]["dependencies"]["astro"], "^6.0.0");
    assert_eq!(json["packages"]["web"]["devDependencies"]["vite"], "^7.3.2");
    assert_eq!(
        json["packages"]["web/node_modules/astro"]["version"],
        "6.2.1"
    );
    assert_eq!(
        json["packages"]["web/node_modules/vite"]["version"],
        "7.3.2"
    );

    let reparsed = parse(out.path()).unwrap();
    assert!(reparsed.importers.contains_key("web"));
}

/// When the root tree already hoists a package to
/// `node_modules/<name>`, the workspace tree must NOT emit a
/// redundant `<workspace>/node_modules/<name>` for the same
/// version — Node's upward `node_modules` walk resolves the root
/// copy. Real `npm install` omits the redundant entry, and
/// emitting it produces a diff on every round-trip.
#[test]
fn test_write_npm_workspace_skips_root_hoisted_dups() {
    let mut graph = LockfileGraph::default();
    let web_link = LocalSource::Link(PathBuf::from("web"));
    let web_dep_path = web_link.dep_path("workspace-web");
    graph.packages.insert(
        web_dep_path.clone(),
        LockedPackage {
            name: "workspace-web".to_string(),
            version: "0.0.1".to_string(),
            dep_path: web_dep_path.clone(),
            local_source: Some(web_link),
            ..Default::default()
        },
    );
    graph.packages.insert(
        "astro@6.2.1".to_string(),
        LockedPackage {
            name: "astro".to_string(),
            version: "6.2.1".to_string(),
            integrity: Some("sha512-astro".to_string()),
            dep_path: "astro@6.2.1".to_string(),
            ..Default::default()
        },
    );
    graph.importers.insert(
        ".".to_string(),
        vec![
            DirectDep {
                name: "astro".to_string(),
                dep_path: "astro@6.2.1".to_string(),
                dep_type: DepType::Production,
                specifier: Some("^6.0.0".to_string()),
            },
            DirectDep {
                name: "workspace-web".to_string(),
                dep_path: web_dep_path.clone(),
                dep_type: DepType::Production,
                specifier: None,
            },
        ],
    );
    graph.importers.insert(
        "web".to_string(),
        vec![DirectDep {
            name: "astro".to_string(),
            dep_path: "astro@6.2.1".to_string(),
            dep_type: DepType::Production,
            specifier: Some("^6.0.0".to_string()),
        }],
    );

    let manifest = aube_manifest::PackageJson {
        name: Some("workspace-root".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [("astro".to_string(), "^6.0.0".to_string())]
            .into_iter()
            .collect(),
        ..Default::default()
    };
    let out = tempfile::NamedTempFile::new().unwrap();
    write(out.path(), &graph, &manifest).unwrap();

    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(out.path()).unwrap()).unwrap();
    assert_eq!(json["packages"]["node_modules/astro"]["version"], "6.2.1");
    assert!(
        json["packages"].get("web/node_modules/astro").is_none(),
        "redundant workspace-nested astro should not be emitted"
    );
}

/// Byte-parity with a real `npm install`-generated lockfile. The
/// fixture at `tests/fixtures/npm-native.json` was produced by
/// `npm install` (v11) against a `{ chalk, picocolors, semver }`
/// manifest. A parse → write round-trip must reproduce the exact
/// bytes. Covers `resolved:` on every entry, `license:` /
/// `engines:` / `bin:` / `funding:` field preservation, and the
/// sibling declared-range preservation that rides on
/// `declared_dependencies`.
#[test]
fn test_write_byte_identical_to_native_npm() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/npm-native.json");
    // Same LF normalization as the pnpm / bun byte-parity tests —
    // Windows' `core.autocrlf=true` rewrites the checked-out
    // fixture to CRLF even with `.gitattributes eol=lf`.
    let original = std::fs::read_to_string(&fixture)
        .unwrap()
        .replace("\r\n", "\n");
    let graph = parse(&fixture).unwrap();
    let manifest = aube_manifest::PackageJson {
        name: Some("aube-lockfile-stability".to_string()),
        version: Some("1.0.0".to_string()),
        dependencies: [
            ("chalk".to_string(), "^4.1.2".to_string()),
            ("picocolors".to_string(), "^1.1.1".to_string()),
            ("semver".to_string(), "^7.6.3".to_string()),
        ]
        .into_iter()
        .collect(),
        ..Default::default()
    };

    let tmp = tempfile::NamedTempFile::new().unwrap();
    write(tmp.path(), &graph, &manifest).unwrap();
    let written = std::fs::read_to_string(tmp.path()).unwrap();

    if written != original {
        panic!(
            "npm writer drifted from native npm output.\n\n--- expected ---\n{original}\n--- got ---\n{written}"
        );
    }
}

#[test]
fn test_parse_workspace_links() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "workspace-root",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "workspace-root",
                    "version": "1.0.0",
                    "dependencies": { "@scope/app": "file:packages/app" }
                },
                "node_modules/@scope/app": {
                    "resolved": "packages/app",
                    "link": true
                },
                "node_modules/chalk": {
                    "version": "5.4.1",
                    "integrity": "sha512-chalk"
                },
                "packages/app": {
                    "name": "@scope/app",
                    "version": "0.68.1",
                    "dependencies": {
                        "chalk": "^5.4.1"
                    }
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let dep_path = LocalSource::Link(PathBuf::from("packages/app")).dep_path("@scope/app");

    let importer = &graph.importers["."];
    assert_eq!(importer.len(), 1);
    assert_eq!(importer[0].name, "@scope/app");
    assert_eq!(importer[0].dep_path, dep_path);
    assert!(matches!(importer[0].dep_type, DepType::Production));
    assert!(importer[0].specifier.is_none());

    let app = &graph.packages[&importer[0].dep_path];
    assert_eq!(app.version, "0.68.1");
    assert_eq!(
        app.local_source,
        Some(LocalSource::Link(PathBuf::from("packages/app")))
    );
    assert_eq!(
        app.dependencies.get("chalk").map(String::as_str),
        Some("5.4.1")
    );
    assert!(!graph.packages.contains_key("@scope/app@0.68.1"));
}

/// npm workspaces that aren't listed in the root manifest's
/// `dependencies`/`devDependencies` still get a `node_modules/<name>`
/// link entry in the lockfile — npm symlinks every workspace member
/// at the workspace root regardless. The siemens/element repo
/// (https://github.com/siemens/element) hits this: its 11 workspace
/// projects under `projects/*` aren't declared as deps of the root
/// `package.json`, so the linker had nothing to link at the root and
/// `node_modules/@siemens/element-ng` (and friends) silently went
/// missing — breaking Angular CLI builds that resolve workspace
/// libraries from the repo root.
#[test]
fn test_parse_workspace_links_undeclared_in_root_deps() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "workspace-root",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "workspace-root",
                    "version": "1.0.0",
                    "workspaces": ["projects/element-ng", "projects/charts-ng"],
                    "dependencies": { "chalk": "^5.4.1" }
                },
                "node_modules/@siemens/element-ng": {
                    "resolved": "projects/element-ng",
                    "link": true
                },
                "node_modules/@siemens/charts-ng": {
                    "resolved": "projects/charts-ng",
                    "link": true
                },
                "node_modules/chalk": {
                    "version": "5.4.1",
                    "integrity": "sha512-chalk"
                },
                "projects/element-ng": {
                    "name": "@siemens/element-ng",
                    "version": "21.0.0"
                },
                "projects/charts-ng": {
                    "name": "@siemens/charts-ng",
                    "version": "21.0.0"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    let importer = &graph.importers["."];

    let names: Vec<&str> = importer.iter().map(|d| d.name.as_str()).collect();
    assert!(names.contains(&"chalk"));
    assert!(
        names.contains(&"@siemens/element-ng"),
        "workspace package `@siemens/element-ng` should be a direct dep of root \
             so the linker creates `node_modules/@siemens/element-ng`, even though \
             the root manifest doesn't list it; got importer deps {names:?}"
    );
    assert!(
        names.contains(&"@siemens/charts-ng"),
        "workspace package `@siemens/charts-ng` should be a direct dep of root; \
             got importer deps {names:?}"
    );

    // Each workspace dep_path round-trips through LocalSource::Link.
    let element_ng = importer
        .iter()
        .find(|d| d.name == "@siemens/element-ng")
        .unwrap();
    assert_eq!(
        graph.packages[&element_ng.dep_path].local_source,
        Some(LocalSource::Link(PathBuf::from("projects/element-ng")))
    );
}

/// npm copies `funding:` verbatim from each package's
/// `package.json`, so all three registry-permitted shapes (bare
/// string, `{url}` object, mixed array of either) appear in real
/// lockfiles. The pre-fix parser only accepted the object form
/// and would hard-fail on any project pulling in `htmlparser2`,
/// `@csstools/*`, etc. Aube only carries one URL per package, so
/// the contract is "first URL wins, no shape rejected".
#[test]
fn test_parse_funding_all_shapes() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": {
                        "string-funding": "1.0.0",
                        "object-funding": "1.0.0",
                        "array-funding": "1.0.0",
                        "mixed-array-funding": "1.0.0",
                        "no-funding": "1.0.0"
                    }
                },
                "node_modules/string-funding": {
                    "version": "1.0.0",
                    "integrity": "sha512-aaa",
                    "funding": "https://example.com/sponsor"
                },
                "node_modules/object-funding": {
                    "version": "1.0.0",
                    "integrity": "sha512-bbb",
                    "funding": { "type": "github", "url": "https://github.com/sponsors/foo" }
                },
                "node_modules/array-funding": {
                    "version": "1.0.0",
                    "integrity": "sha512-ccc",
                    "funding": [
                        { "type": "github", "url": "https://github.com/sponsors/csstools" },
                        { "type": "opencollective", "url": "https://opencollective.com/csstools" }
                    ]
                },
                "node_modules/mixed-array-funding": {
                    "version": "1.0.0",
                    "integrity": "sha512-ddd",
                    "funding": [
                        "https://github.com/fb55/htmlparser2?sponsor=1",
                        { "type": "github", "url": "https://github.com/sponsors/fb55" }
                    ]
                },
                "node_modules/no-funding": {
                    "version": "1.0.0",
                    "integrity": "sha512-eee"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    assert_eq!(
        graph.packages["string-funding@1.0.0"]
            .funding_url
            .as_deref(),
        Some("https://example.com/sponsor"),
    );
    assert_eq!(
        graph.packages["object-funding@1.0.0"]
            .funding_url
            .as_deref(),
        Some("https://github.com/sponsors/foo"),
    );
    // Array form: aube collapses to the first URL.
    assert_eq!(
        graph.packages["array-funding@1.0.0"].funding_url.as_deref(),
        Some("https://github.com/sponsors/csstools"),
    );
    // Mixed array (bare string + object): first element is a
    // string, so its value is the URL.
    assert_eq!(
        graph.packages["mixed-array-funding@1.0.0"]
            .funding_url
            .as_deref(),
        Some("https://github.com/fb55/htmlparser2?sponsor=1"),
    );
    assert!(graph.packages["no-funding@1.0.0"].funding_url.is_none());
}

/// Real-world `package-lock.json` entries can carry the legacy
/// object / array-of-objects shapes for `license:` (npm copies
/// whatever's in the package's `package.json` verbatim, and older
/// packages like `tv4` still ship the deprecated forms). Regression
/// guard for https://github.com/jdx/aube/discussions/510.
#[test]
fn test_parse_license_all_shapes() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let content = r#"{
            "name": "test",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "packages": {
                "": {
                    "name": "test",
                    "version": "1.0.0",
                    "dependencies": {
                        "string-license": "1.0.0",
                        "object-license": "1.0.0",
                        "array-license": "1.0.0",
                        "mixed-array-license": "1.0.0",
                        "no-license": "1.0.0"
                    }
                },
                "node_modules/string-license": {
                    "version": "1.0.0",
                    "integrity": "sha512-aaa",
                    "license": "MIT"
                },
                "node_modules/object-license": {
                    "version": "1.0.0",
                    "integrity": "sha512-bbb",
                    "license": { "type": "ISC", "url": "https://example.com/ISC" }
                },
                "node_modules/array-license": {
                    "version": "1.0.0",
                    "integrity": "sha512-ccc",
                    "license": [
                        { "type": "Public Domain", "url": "http://geraintluff.github.io/tv4/LICENSE.txt" },
                        { "type": "MIT", "url": "http://jsonary.com/LICENSE.txt" }
                    ]
                },
                "node_modules/mixed-array-license": {
                    "version": "1.0.0",
                    "integrity": "sha512-ddd",
                    "license": [
                        "MIT",
                        { "type": "Apache-2.0", "url": "https://example.com/apache" }
                    ]
                },
                "node_modules/no-license": {
                    "version": "1.0.0",
                    "integrity": "sha512-eee"
                }
            }
        }"#;
    std::fs::write(tmp.path(), content).unwrap();

    let graph = parse(tmp.path()).unwrap();
    assert_eq!(
        graph.packages["string-license@1.0.0"].license.as_deref(),
        Some("MIT"),
    );
    assert_eq!(
        graph.packages["object-license@1.0.0"].license.as_deref(),
        Some("ISC"),
    );
    // Array form: aube collapses to the first license type.
    assert_eq!(
        graph.packages["array-license@1.0.0"].license.as_deref(),
        Some("Public Domain"),
    );
    // Mixed array (bare string + object): first element is a
    // string, so its value is the license.
    assert_eq!(
        graph.packages["mixed-array-license@1.0.0"]
            .license
            .as_deref(),
        Some("MIT"),
    );
    assert!(graph.packages["no-license@1.0.0"].license.is_none());
}