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
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
use bun_collections::VecExt;
use core::mem;
use bun_collections::{ArrayHashMap, ArrayIdentityContext, MultiArrayList, StringSet};
use bun_core::strings;
use bun_core::{Global, Output};
use bun_paths::{self as path, AutoAbsPath, MAX_PATH_BYTES, PathBuffer, resolve_path};
use bun_resolver::fs::FileSystem;
use bun_semver::semver_query::Wildcard;
use bun_semver::version::VersionInt;
use bun_semver::{self as semver, ExternalString, String, Version as SemverVersion};
use crate::bun_json::{Expr, ExprData};
use crate::dependency::{Behavior, DependencyExt as _, TagExt as _};
use crate::repository::RepositoryExt as _;
use crate::{
self as install, Aligner, Bin, Dependency, ExternalStringList, ExternalStringMap, Features,
Npm, PackageID, PackageJSON, PackageManager, PackageNameHash, Repository,
TruncatedPackageNameHash, UpdateRequest, bin, default_trusted_dependencies, dependency,
initialize_store, invalid_package_id,
};
// `Package.rs` is mounted as `crate::lockfile_real::package`; the parent module
// (`super`) is the real `lockfile.rs`, distinct from the `crate::lockfile`
// stub that lib.rs exposes for downstream crates during the staged port.
// PORT NOTE: bare `use super as lockfile;` fails when this file is reached via
// `#[path]` from a non-module context (rust-lang/rust#48067). Name the parent
// module by its absolute crate path instead.
use crate::lockfile_real as lockfile;
use crate::lockfile_real::{
Cloner, DependencySlice, Lockfile, PackageIDSlice, PatchedDep, PendingResolution,
PositionalStream, Stream, StringBuilder, TrustedDependenciesSet,
};
use crate::resolution_real::{ResolutionType, Tag as ResolutionTag, TaggedValue};
use crate::versioned_url::VersionedURLType;
#[path = "Package/Meta.rs"]
pub mod meta;
#[path = "Package/Scripts.rs"]
pub mod scripts;
#[path = "Package/WorkspaceMap.rs"]
pub mod workspace_map;
pub use meta::Meta;
pub use scripts::Scripts;
pub use workspace_map as WorkspaceMap;
bun_output::declare_scope!(Lockfile, hidden);
trait ExprStr {
fn as_utf8<'b>(&self, bump: &'b bun_alloc::Arena) -> Option<&'b [u8]>;
}
impl ExprStr for Expr {
// Zig `Expr.asString` (expr.zig:477) — transparently transcodes UTF-16
// `EString`s. The earlier `is_utf8()` guard returned `None` for keys the
// lexer stored as UTF-16 (e.g. `\u`-escaped non-ASCII), tripping the
// `expect("unreachable")` callers below.
#[inline]
fn as_utf8<'b>(&self, bump: &'b bun_alloc::Arena) -> Option<&'b [u8]> {
if let ExprData::EString(s) = &self.data {
return Some(s.string(bump).expect("OOM"));
}
None
}
}
// Zig: `pub fn Package(comptime SemverIntType: type) type { return extern struct { ... } }`
// Defaulted to `u64` so bare `Package` matches Zig's primary `Package(u64)`
// instantiation (the only one the lockfile/PM call sites name unqualified).
//
// PORT NOTE: `` cannot be used here — the derive
// emits a `PackageField` enum with snake_case variants and an inherent
// `__MAL_SIZES` const that fail to const-eval through the defaulted
// `SemverIntType` param. The trait impl, field enum, and `PackageColumns` /
// `PackageColumns` accessor traits are therefore expanded by hand below
// (mirroring Zig's `MultiArrayList(Package).items(.field)`).
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Package<SemverIntType: VersionInt = u64> {
pub name: String,
pub name_hash: PackageNameHash,
/// How this package has been resolved
/// When .tag is uninitialized, that means the package is not resolved yet.
pub resolution: ResolutionType<SemverIntType>,
/// dependencies & resolutions must be the same length
/// resolutions[i] is the resolved package ID for dependencies[i]
/// if resolutions[i] is an invalid package ID, then dependencies[i] is not resolved
pub dependencies: DependencySlice,
/// The resolved package IDs for this package's dependencies. Instead of storing this
/// on the `Dependency` struct within `.dependencies`, it is stored on the package itself
/// so we can access it faster.
///
/// Each index in this array corresponds to the same index in dependencies.
/// Each value in this array corresponds to the resolved package ID for that dependency.
///
/// So this is how you say "what package ID for lodash does this package actually resolve to?"
///
/// By default, the underlying buffer is filled with "invalid_id" to indicate this package ID
/// was not resolved
pub resolutions: PackageIDSlice,
pub meta: Meta,
pub bin: Bin,
/// If any of these scripts run, they will run in order:
/// 1. preinstall
/// 2. install
/// 3. postinstall
/// 4. preprepare
/// 5. prepare
/// 6. postprepare
pub scripts: Scripts,
}
pub type Resolution<SemverIntType> = ResolutionType<SemverIntType>;
// ─── ResolverContext ─────────────────────────────────────────────────────────
//
// Zig used `comptime ResolverContext: type` for `parse`/`parseWithJSON` and
// branched on `ResolverContext == void` / `== PackageManager.GitResolver` at
// comptime. Rust models this as a trait with associated consts; concrete
// resolvers (folder/cache/git) override what they need. The `()` impl gives
// the `void` semantics.
pub trait ResolverContext {
/// Zig: `comptime ResolverContext == void`.
const IS_VOID: bool = false;
/// Zig: `comptime ResolverContext == PackageManager.GitResolver`.
const IS_GIT_RESOLVER: bool = false;
/// Zig: `ResolverContext.checkBundledDependencies()`.
fn check_bundled_dependencies() -> bool {
false
}
/// Zig: `resolver.count(builder, json)` — counts strings to be appended by
/// `resolve`. Default no-op for void/folder resolvers that don't need it.
fn count(&mut self, _builder: &mut StringBuilder<'_>, _json: &Expr) {}
/// Zig: `resolver.resolve(builder, json)` — produces the package's
/// `Resolution`. Only called when `!IS_VOID`.
///
/// No default body: Zig enforced this at comptime (a non-void resolver
/// without `resolve` failed to compile). Each concrete resolver supplies
/// its own body; `()` returns the zero-value `Resolution` to mirror Zig's
/// "void leaves `package.resolution` uninitialized" path.
///
/// Zig threaded `comptime IntType` through `parseWithJSON`, but the only
/// instantiation is `u64` (`Package.resolution: ResolutionType<u64>`), so
/// the trait method is monomorphic — keeps `CacheFolderResolver::resolve`
/// free of an identity `transmute`.
fn resolve(
&mut self,
builder: &mut StringBuilder<'_>,
json: &Expr,
) -> Result<ResolutionType<u64>, bun_core::Error>;
// ── GitResolver-only surface ────────────────────────────────────────────
// Zig accessed `resolver.resolved`, `resolver.new_name`, `resolver.dep_id`
// directly when `ResolverContext == GitResolver`. Trait methods so non-git
// resolvers don't need the fields; default impls are dead code (gated on
// `IS_GIT_RESOLVER`). The bodies here are never executed — calls are
// statically guarded by `if R::IS_GIT_RESOLVER` — so a debug assertion
// documents the invariant without panicking in release.
fn resolution(&self) -> &ResolutionType<u64> {
debug_assert!(
false,
"ResolverContext::resolution called on non-git resolver"
);
// SAFETY: unreachable in practice; never dereferenced when the
// `IS_GIT_RESOLVER` gate is false. `ZEROED` is an associated const on a
// trait-bounded generic impl, which Rust refuses to evaluate in `const`
// position; a `static` (with `Sync` POD payload) sidesteps that.
static EMPTY: ResolutionType<u64> = ResolutionType::<u64>::ZEROED;
&EMPTY
}
fn dep_id(&self) -> install::DependencyID {
debug_assert!(false, "ResolverContext::dep_id called on non-git resolver");
0
}
fn new_name(&self) -> &[u8] {
b""
}
fn set_new_name(&mut self, _name: Vec<u8>) {}
fn take_new_name(&mut self) -> Vec<u8> {
Vec::new()
}
}
impl ResolverContext for () {
const IS_VOID: bool = true;
fn resolve(
&mut self,
_builder: &mut StringBuilder<'_>,
_json: &Expr,
) -> Result<ResolutionType<u64>, bun_core::Error> {
// Zig: `if (comptime ResolverContext != void) { … }` — the void
// resolver never assigned `package.resolution`, so it kept its
// zero-initialized value. The call site still gates on `!IS_VOID`,
// but provide the equivalent behavior for trait completeness.
Ok(ResolutionType::default())
}
}
// ─── ResolverContextDyn ──────────────────────────────────────────────────────
//
// Object-safe projection of `ResolverContext` so the ~960-line body of
// `parse_with_json` is compiled exactly once instead of being re-stamped per
// `R` (six instantiations × ~49kB ≈ 292kB of identical machine code, plus a
// duplicate `<()>` copy across CGUs). The associated consts become `&self`
// predicates; everything else forwards 1:1. The generic `parse_with_json<R>`
// stays as a thin shim that erases `&mut R` → `&mut dyn ResolverContextDyn`
// and delegates to the non-generic `parse_with_json_impl`.
//
// `count`/`resolve` keep their `StringBuilder<'_>` borrow — lifetimes are
// permitted on object-safe trait methods, only type generics are not.
pub(crate) trait ResolverContextDyn {
fn is_void(&self) -> bool;
fn is_git(&self) -> bool;
fn check_bundled_dependencies(&self) -> bool;
fn count(&mut self, builder: &mut StringBuilder<'_>, json: &Expr);
fn resolve(
&mut self,
builder: &mut StringBuilder<'_>,
json: &Expr,
) -> Result<ResolutionType<u64>, bun_core::Error>;
fn resolution(&self) -> &ResolutionType<u64>;
fn dep_id(&self) -> install::DependencyID;
fn new_name(&self) -> &[u8];
fn set_new_name(&mut self, name: Vec<u8>);
fn take_new_name(&mut self) -> Vec<u8>;
}
impl<R: ResolverContext> ResolverContextDyn for R {
#[inline]
fn is_void(&self) -> bool {
R::IS_VOID
}
#[inline]
fn is_git(&self) -> bool {
R::IS_GIT_RESOLVER
}
#[inline]
fn check_bundled_dependencies(&self) -> bool {
R::check_bundled_dependencies()
}
#[inline]
fn count(&mut self, builder: &mut StringBuilder<'_>, json: &Expr) {
ResolverContext::count(self, builder, json)
}
#[inline]
fn resolve(
&mut self,
builder: &mut StringBuilder<'_>,
json: &Expr,
) -> Result<ResolutionType<u64>, bun_core::Error> {
ResolverContext::resolve(self, builder, json)
}
#[inline]
fn resolution(&self) -> &ResolutionType<u64> {
ResolverContext::resolution(self)
}
#[inline]
fn dep_id(&self) -> install::DependencyID {
ResolverContext::dep_id(self)
}
#[inline]
fn new_name(&self) -> &[u8] {
ResolverContext::new_name(self)
}
#[inline]
fn set_new_name(&mut self, name: Vec<u8>) {
ResolverContext::set_new_name(self, name)
}
#[inline]
fn take_new_name(&mut self) -> Vec<u8> {
ResolverContext::take_new_name(self)
}
}
/// Comparator for the post-build dependency sort. Hoisted out of
/// `parse_with_json_impl` so `<[Dependency]>::sort_by` is instantiated once
/// (the closure it wraps is zero-capture modulo `buf`, and the impl fn is
/// itself non-generic, so the 6.5kB pdqsort + 2.2kB drift is emitted exactly
/// once instead of per-`R`).
#[inline]
fn dep_sort_cmp(buf: &[u8], a: &Dependency, b: &Dependency) -> core::cmp::Ordering {
// Zig used `std.sort.pdq` with a `<` predicate. `slice::sort_by` requires
// a total order (and panics since 1.81 when violated), so derive
// `Ordering::Equal` from the predicate symmetrically.
if Dependency::is_less_than(buf, a, b) {
core::cmp::Ordering::Less
} else if Dependency::is_less_than(buf, b, a) {
core::cmp::Ordering::Greater
} else {
core::cmp::Ordering::Equal
}
}
/// Field tags for the binary lockfile serializer (`bun.lockb`). The
/// reflection-backed `MultiArrayList` no longer needs an enum, but the
/// serializer iterates fields by tag to write column blobs in a fixed order.
#[repr(usize)]
#[derive(Copy, Clone)]
pub(crate) enum PackageField {
Name = 0,
NameHash = 1,
Resolution = 2,
Dependencies = 3,
Resolutions = 4,
Meta = 5,
Bin = 6,
Scripts = 7,
}
impl PackageField {
pub(crate) const ALL: [PackageField; 8] = [
PackageField::Name,
PackageField::NameHash,
PackageField::Resolution,
PackageField::Dependencies,
PackageField::Resolutions,
PackageField::Meta,
PackageField::Bin,
PackageField::Scripts,
];
#[allow(dead_code)]
pub(crate) fn name(self) -> &'static [u8] {
match self {
PackageField::Name => b"name",
PackageField::NameHash => b"name_hash",
PackageField::Resolution => b"resolution",
PackageField::Dependencies => b"dependencies",
PackageField::Resolutions => b"resolutions",
PackageField::Meta => b"meta",
PackageField::Bin => b"bin",
PackageField::Scripts => b"scripts",
}
}
}
bun_collections::multi_array_columns! {
pub trait PackageColumns [SemverIntType: VersionInt] for Package<SemverIntType> {
name: String,
name_hash: PackageNameHash,
resolution: ResolutionType<SemverIntType>,
dependencies: DependencySlice,
resolutions: PackageIDSlice,
meta: Meta,
bin: Bin,
scripts: Scripts,
}
}
impl<SemverIntType: VersionInt> Default for Package<SemverIntType> {
fn default() -> Self {
Self {
name: String::default(),
name_hash: 0,
resolution: Resolution::<SemverIntType>::default(),
dependencies: DependencySlice::default(),
resolutions: PackageIDSlice::default(),
meta: Meta::init(),
bin: Bin::default(),
scripts: Scripts::default(),
}
}
}
pub use bun_install_types::DependencyGroup;
// Borrows into lockfile.packages SoA columns + string_bytes; `RawSlice`
// carries the outlives-holder invariant (the lockfile outlives every sort
// pass that constructs an Alphabetizer).
pub(crate) struct Alphabetizer<SemverIntType: VersionInt> {
pub names: bun_ptr::RawSlice<String>,
pub buf: bun_ptr::RawSlice<u8>,
pub resolutions: bun_ptr::RawSlice<Resolution<SemverIntType>>,
}
impl<SemverIntType: VersionInt> Alphabetizer<SemverIntType> {
pub(crate) fn order(&self, lhs: PackageID, rhs: PackageID) -> core::cmp::Ordering {
let (names, buf, resolutions) = (
self.names.slice(),
self.buf.slice(),
self.resolutions.slice(),
);
names[lhs as usize]
.order(names[rhs as usize], buf, buf)
.then_with(|| resolutions[lhs as usize].order(&resolutions[rhs as usize], buf, buf))
}
}
impl<SemverIntType: VersionInt> Package<SemverIntType> {
#[inline]
pub fn is_disabled(&self, cpu: Npm::Architecture, os: Npm::OperatingSystem) -> bool {
self.meta.is_disabled(cpu, os)
}
}
// PORT NOTE: `clone` / `from_package_json` / `from_npm` / `parse*` all interact
// with `Lockfile`, whose package list is concretely `MultiArrayList<Package<u64>>`.
// Zig's `Package(SemverIntType)` is only ever instantiated at `u64` for these
// paths (the `u32` instantiation is migration-only and routed through
// `Serializer::load`). Binding the impl to `u64` avoids spurious
// `Package<SemverIntType>` ≠ `Package<u64>` mismatches at every Lockfile call
// site.
impl Package<u64> {
pub fn clone(&self, cloner: &mut Cloner) -> Result<PackageID, bun_core::Error> {
// TODO(port): narrow error set
// PORT NOTE: Zig passes (`pm`, `old`, `new`, `package_id_mapping`,
// `cloner`) separately, but `cloner` already owns `&mut` to all four.
// Rust borrowck rejects the redundant aliasing at the call site, so
// route everything through `cloner`'s disjoint fields here instead.
// `old`/`new`/`mapping` are reborrowed for the whole body (disjoint
// from `cloner.clone_queue` / `.trees_count` / `.old_preinstall_state`);
// `manager` is accessed via `cloner.manager` at each use so the borrow
// doesn't span the `cloner.*` accesses below.
let old = &mut *cloner.old;
let new = &mut *cloner.lockfile;
let package_id_mapping = &mut *cloner.mapping;
let old_string_buf = old.buffers.string_bytes.as_slice();
let old_extern_string_buf = old.buffers.extern_strings.as_slice();
// PORT NOTE: `string_builder!` split-borrows only `new.buffers
// .string_bytes` + `new.string_pool`, leaving sibling buffer fields
// (`dependencies`, `resolutions`, `extern_strings`, `packages`) free
// for the disjoint borrows below.
let mut builder_ = crate::string_builder!(new);
let builder = &mut builder_;
bun_output::scoped_log!(
Lockfile,
"Clone: {}@{} ({:?}, {} dependencies)",
bstr::BStr::new(self.name.slice(old_string_buf)),
self.resolution
.fmt(old_string_buf, bun_core::fmt::PathSep::Auto),
self.resolution.tag,
self.dependencies.len,
);
builder.count(self.name.slice(old_string_buf));
self.resolution.count(old_string_buf, &mut *builder);
self.meta.count(old_string_buf, &mut *builder);
self.scripts.count(old_string_buf, &mut *builder);
for patched_dep in old.patched_dependencies.values() {
builder.count(patched_dep.path.slice(old.buffers.string_bytes.as_slice()));
}
let new_extern_string_count =
self.bin
.count(old_string_buf, old_extern_string_buf, &mut *builder) as usize;
let old_dependencies: &[Dependency] =
self.dependencies.get(old.buffers.dependencies.as_slice());
let old_resolutions: &[PackageID] =
self.resolutions.get(old.buffers.resolutions.as_slice());
for dependency in old_dependencies {
dependency.count(old_string_buf, &mut *builder);
}
builder.allocate()?;
// should be unnecessary, but Just In Case
new.buffers.dependencies.reserve(old_dependencies.len());
new.buffers.resolutions.reserve(old_dependencies.len());
new.buffers.extern_strings.reserve(new_extern_string_count);
let prev_len = new.buffers.dependencies.len() as u32;
let end = prev_len + (old_dependencies.len() as u32);
let max_package_id = old.packages.len() as PackageID;
// Grow both buffers by `old_dependencies.len()`, default-filling the
// new tail. The zip-loops further below overwrite each slot with the
// real cloned value; pre-filling avoids ever forming `&mut T` over
// uninitialized storage (the old `set_len`-then-assign dropped uninit).
bun_core::vec::extend_from_fn(
&mut new.buffers.dependencies,
old_dependencies.len(),
|_| Dependency::default(),
);
bun_core::vec::extend_from_fn(&mut new.buffers.resolutions, old_dependencies.len(), |_| {
invalid_package_id
});
debug_assert_eq!(new.buffers.dependencies.len(), end as usize);
debug_assert_eq!(new.buffers.resolutions.len(), end as usize);
let _extern_strings_old_len = new.buffers.extern_strings.len();
// Default-fill the tail so it is valid before `bin.clone` overwrites
// it (replaces `reserve` + raw `set_len`).
bun_core::vec::grow_default(&mut new.buffers.extern_strings, new_extern_string_count);
// PORT NOTE: Zig passes both `new.buffers.extern_strings.items` (full slice) and a
// tail subslice into `bin.clone`; the full slice is only used to compute the tail's
// offset for `ExternalStringList::init`. In Rust those two views would alias, so
// `Bin::clone_with_buffers` takes the precomputed offset directly.
let new_extern_strings_start = new.buffers.extern_strings.len() - new_extern_string_count;
let id = new.packages.len() as PackageID;
// PORT NOTE: Zig calls `appendPackageWithID` mid-body while still
// holding live slices into `new.buffers` and the `builder`. Rust can't
// express that (the method borrows `&mut Lockfile` whole), so build the
// `Package` value and clone the dependency strings *first* (only needs
// disjoint buffer fields), drop the builder, then append, then write
// resolutions. `appendPackageWithID` touches `packages` /
// `package_index` / `string_bytes` only — none of which the dependency
// pass mutates — so the reorder is observationally identical.
let pkg_value = Package {
name: builder
.append_with_hash::<String>(self.name.slice(old_string_buf), self.name_hash),
bin: self.bin.clone_with_buffers(
old_string_buf,
old_extern_string_buf,
new_extern_strings_start as u32,
&mut new.buffers.extern_strings[new_extern_strings_start..],
&mut *builder,
),
name_hash: self.name_hash,
meta: Meta::clone_into(&self.meta, id, old_string_buf, &mut *builder),
resolution: self.resolution.clone_into(old_string_buf, &mut *builder),
scripts: self.scripts.clone_into(old_string_buf, &mut *builder),
dependencies: DependencySlice::new(prev_len, end - prev_len),
resolutions: PackageIDSlice::new(prev_len, end - prev_len),
};
{
let dependencies: &mut [Dependency] =
&mut new.buffers.dependencies[prev_len as usize..end as usize];
debug_assert_eq!(old_dependencies.len(), dependencies.len());
for (old_dep, new_dep) in old_dependencies.iter().zip(dependencies.iter_mut()) {
*new_dep = old_dep.clone_in(cloner.manager, old_string_buf, &mut *builder)?;
}
}
builder.clamp();
let new_package = new.append_package_with_id(&pkg_value, id)?;
// `self.meta.id` is range-checked at load time (bun.lockb.rs), but
// defend here as well since an error returned from `clean_with_logger`
// is not recoverable — it aborts the install instead of re-resolving.
if self.meta.id as usize >= package_id_mapping.len() {
return Err(bun_core::err!("InvalidLockfile"));
}
package_id_mapping[self.meta.id as usize] = new_package.meta.id;
if cloner.manager.preinstall_state.len() > 0 {
cloner.manager.preinstall_state[new_package.meta.id as usize] =
cloner.old_preinstall_state[self.meta.id as usize];
}
cloner.trees_count += (old_resolutions.len() > 0) as u32;
let resolutions: &mut [PackageID] =
&mut new.buffers.resolutions[prev_len as usize..end as usize];
debug_assert_eq!(old_resolutions.len(), resolutions.len());
for (i, (old_resolution, resolution)) in old_resolutions
.iter()
.zip(resolutions.iter_mut())
.enumerate()
{
if *old_resolution >= max_package_id {
*resolution = invalid_package_id;
continue;
}
let mapped = package_id_mapping[*old_resolution as usize];
if mapped < max_package_id {
*resolution = mapped;
} else {
cloner.clone_queue.push(PendingResolution {
old_resolution: *old_resolution,
parent: new_package.meta.id,
resolve_id: new_package.resolutions.off
+ PackageID::try_from(i).expect("int cast"),
});
}
}
Ok(new_package.meta.id)
}
pub fn from_package_json(
lockfile: &mut Lockfile,
pm: &mut PackageManager,
package_json: &mut PackageJSON,
features: Features,
) -> Result<Self, bun_core::Error> {
#[allow(non_snake_case)]
let FEATURES = features;
// TODO(port): narrow error set
let mut package = Self::default();
// var string_buf = package_json;
// PORT NOTE: split-borrow `string_bytes`/`string_pool` so the disjoint
// `lockfile.buffers.dependencies/resolutions` borrows below pass.
let mut string_builder = crate::string_builder!(lockfile);
let mut total_dependencies_count: u32 = 0;
// var bin_extern_strings_count: u32 = 0;
// --- Counting
{
string_builder.count(&package_json.name);
string_builder.count(&package_json.version);
let dependencies = package_json.dependencies.map.values();
for dep in dependencies {
if dep.behavior.is_enabled(FEATURES) {
dep.count(package_json.dependencies.source_buf, &mut string_builder);
total_dependencies_count += 1;
}
}
}
// string_builder.count(manifest.str(&package_version_ptr.tarball_url));
string_builder.allocate()?;
// defer string_builder.clamp(); — handled at end of scope below
// var extern_strings_list = &lockfile.buffers.extern_strings;
let dependencies_list = &mut lockfile.buffers.dependencies;
let resolutions_list = &mut lockfile.buffers.resolutions;
dependencies_list.reserve(total_dependencies_count as usize);
resolutions_list.reserve(total_dependencies_count as usize);
// try extern_strings_list.ensureUnusedCapacity(lockfile.allocator, bin_extern_strings_count);
// extern_strings_list.items.len += bin_extern_strings_count;
// -- Cloning
{
let package_name: ExternalString =
string_builder.append::<ExternalString>(&package_json.name);
package.name_hash = package_name.hash;
package.name = package_name.value;
package.resolution = Resolution::<u64>::init(TaggedValue::Root);
let total_len = dependencies_list.len() + total_dependencies_count as usize;
if cfg!(debug_assertions) {
debug_assert!(dependencies_list.len() == resolutions_list.len());
}
let dep_start = dependencies_list.len();
// Zig: `@memset(items.ptr[len..total_len], .{})` then bump `.items.len`.
bun_core::vec::extend_from_fn(
dependencies_list,
total_dependencies_count as usize,
|_| Dependency::default(),
);
debug_assert_eq!(dependencies_list.len(), total_len);
let mut dependencies: &mut [Dependency] = &mut dependencies_list[dep_start..total_len];
let package_dependencies = package_json.dependencies.map.values();
let source_buf = package_json.dependencies.source_buf;
for dep in package_dependencies {
if !dep.behavior.is_enabled(FEATURES) {
continue;
}
dependencies[0] = dep.clone_in(pm, source_buf, &mut string_builder)?;
dependencies = &mut dependencies[1..];
if dependencies.is_empty() {
break;
}
}
// We lose the bin info here
// package.bin = package_version.bin.clone(string_buf, manifest.extern_strings_bin_entries, extern_strings_list.items, extern_strings_slice, @TypeOf(&string_builder), &string_builder);
// and the integriy hash
// package.meta.integrity = package_version.integrity;
package.meta.arch = package_json.arch;
package.meta.os = package_json.os;
package.dependencies.off = dep_start as u32;
package.dependencies.len = total_dependencies_count - (dependencies.len() as u32);
package.resolutions.off = package.dependencies.off;
package.resolutions.len = package.dependencies.len;
let new_length = package.dependencies.len as usize + dep_start;
debug_assert_eq!(resolutions_list.len(), dep_start);
bun_core::vec::extend_from_fn(
resolutions_list,
package.dependencies.len as usize,
|_| invalid_package_id,
);
debug_assert_eq!(resolutions_list.len(), new_length);
// Shrink off the unused default-initialized tail (`new_length <= total_len`).
dependencies_list.truncate(new_length);
string_builder.clamp();
return Ok(package);
}
}
pub fn from_npm(
pm: &mut PackageManager,
lockfile: &mut Lockfile,
log: &mut bun_ast::Log,
manifest: &Npm::PackageManifest,
version: SemverVersion,
package_version_ptr: &Npm::PackageVersion,
features: Features,
) -> Result<Self, bun_core::Error> {
#[allow(non_snake_case)]
let FEATURES = features;
// TODO(port): narrow error set
let mut package = Self::default();
let package_version = *package_version_ptr;
// PERF(port): was comptime-computed array — profile if hot.
let dependency_groups: &[DependencyGroup] = &{
let mut out: Vec<DependencyGroup> = Vec::with_capacity(4);
if FEATURES.dependencies {
out.push(DependencyGroup::DEPENDENCIES);
}
if FEATURES.dev_dependencies {
out.push(DependencyGroup::DEV);
}
if FEATURES.optional_dependencies {
out.push(DependencyGroup::OPTIONAL);
}
if FEATURES.peer_dependencies {
out.push(DependencyGroup::PEER);
}
out
};
// PORT NOTE: split-borrow so `lockfile.buffers.dependencies/resolutions
// /extern_strings` below are disjoint from the builder's `string_bytes`.
let mut string_builder = crate::string_builder!(lockfile);
let mut total_dependencies_count: u32 = 0;
let bin_extern_strings_count: u32;
// --- Counting
{
string_builder.count(manifest.name());
version.count(&manifest.string_buf, &mut string_builder);
// PERF(port): was `inline for` — profile if hot.
for group in dependency_groups {
// Zig uses `@field(package_version, group.field)` reflection;
// ported as `PackageVersion::dep_group(field) -> ExternalStringMap`.
let map: ExternalStringMap = package_version.dep_group(group.field);
let keys = map.name.get(&manifest.external_strings);
let version_strings = map.value.get(&manifest.external_strings_for_versions);
total_dependencies_count += map.value.len;
if cfg!(debug_assertions) {
debug_assert!(keys.len() == version_strings.len());
}
debug_assert_eq!(keys.len(), version_strings.len());
for (key, ver) in keys.iter().zip(version_strings.iter()) {
string_builder.count(key.slice(&manifest.string_buf));
string_builder.count(ver.slice(&manifest.string_buf));
}
}
bin_extern_strings_count = package_version.bin.count(
&manifest.string_buf,
&manifest.extern_strings_bin_entries,
&mut string_builder,
);
}
string_builder.count(manifest.str(&package_version_ptr.tarball_url));
string_builder.allocate()?;
// defer string_builder.clamp(); — handled at end of scope
let extern_strings_list = &mut lockfile.buffers.extern_strings;
let dependencies_list = &mut lockfile.buffers.dependencies;
let resolutions_list = &mut lockfile.buffers.resolutions;
dependencies_list.reserve(total_dependencies_count as usize);
resolutions_list.reserve(total_dependencies_count as usize);
let extern_old_len = extern_strings_list.len();
// Default-fill the tail so it is valid before `bin.clone` overwrites
// it (replaces `reserve` + raw `set_len`).
let extern_strings_slice =
bun_core::vec::grow_default(extern_strings_list, bin_extern_strings_count as usize);
// -- Cloning
{
let package_name: ExternalString = string_builder
.append_with_hash::<ExternalString>(manifest.name(), manifest.pkg.name.hash);
package.name_hash = package_name.hash;
package.name = package_name.value;
package.resolution =
Resolution::<u64>::init(TaggedValue::Npm(VersionedURLType::<u64> {
version: version.append(&manifest.string_buf, &mut string_builder),
url: string_builder
.append::<String>(manifest.str(&package_version_ptr.tarball_url)),
}));
let total_len = dependencies_list.len() + total_dependencies_count as usize;
if cfg!(debug_assertions) {
debug_assert!(dependencies_list.len() == resolutions_list.len());
}
let dep_start = dependencies_list.len();
// Zig: `@memset(items.ptr[len..total_len], .{})` then bump `.items.len`.
bun_core::vec::extend_from_fn(
dependencies_list,
total_dependencies_count as usize,
|_| Dependency::default(),
);
debug_assert_eq!(dependencies_list.len(), total_len);
let dependencies = &mut dependencies_list[dep_start..total_len];
total_dependencies_count = 0;
// PERF(port): was `inline for` — profile if hot.
for group in dependency_groups {
// TODO(port): @field reflection — see note above
let map: ExternalStringMap = package_version.dep_group(group.field);
let keys = map.name.get(&manifest.external_strings);
let version_strings = map.value.get(&manifest.external_strings_for_versions);
if cfg!(debug_assertions) {
debug_assert!(keys.len() == version_strings.len());
}
let is_peer = group.field == b"peer_dependencies";
debug_assert_eq!(keys.len(), version_strings.len());
'list: for (i, (key, version_string_)) in
keys.iter().zip(version_strings.iter()).enumerate()
{
// Duplicate peer & dev dependencies are promoted to whichever appeared first
// In practice, npm validates this so it shouldn't happen
let mut duplicate_at: Option<usize> = None;
if group.behavior.is_peer()
|| group.behavior.is_dev()
|| group.behavior.is_optional()
{
for (j, dependency) in dependencies[0..total_dependencies_count as usize]
.iter()
.enumerate()
{
if dependency.name_hash == key.hash {
if group.behavior.is_optional() {
duplicate_at = Some(j);
break;
}
continue 'list;
}
}
}
let name: ExternalString = string_builder.append_with_hash::<ExternalString>(
key.slice(&manifest.string_buf),
key.hash,
);
let dep_version = string_builder.append_with_hash::<String>(
version_string_.slice(&manifest.string_buf),
version_string_.hash,
);
// `string_builder` holds the `&mut string_bytes` borrow; read
// through it instead of `lockfile.buffers.string_bytes`.
let sliced = dep_version.sliced(string_builder.string_bytes.as_slice());
let mut behavior = group.behavior;
if is_peer {
behavior.set(
Behavior::OPTIONAL,
(i as u32) < package_version.non_optional_peer_dependencies_start,
);
}
if package_version_ptr.all_dependencies_bundled() {
behavior.insert(Behavior::BUNDLED);
} else {
for bundled_dep_name_hash in package_version
.bundled_dependencies
.get(&manifest.bundled_deps_buf)
{
if *bundled_dep_name_hash == name.hash {
behavior.insert(Behavior::BUNDLED);
break;
}
}
}
let dependency = Dependency {
name: name.value,
name_hash: name.hash,
behavior,
version: Dependency::parse(
name.value,
Some(name.hash),
sliced.slice,
&sliced,
Some(&mut *log),
Some(&mut *pm),
)
.unwrap_or_default(),
};
// If a dependency appears in both "dependencies" and "optionalDependencies", it is considered optional!
if group.behavior.is_optional() {
if let Some(j) = duplicate_at {
// need to shift dependencies after the duplicate to maintain sort order
// (in-place left-rotate by 1 over `[j .. total_dependencies_count)`)
dependencies[j..total_dependencies_count as usize].rotate_left(1);
// https://docs.npmjs.com/cli/v8/configuring-npm/package-json#optionaldependencies
// > Entries in optionalDependencies will override entries of the same name in dependencies, so it's usually best to only put in one place.
dependencies[total_dependencies_count as usize - 1] = dependency;
continue 'list;
}
}
dependencies[total_dependencies_count as usize] = dependency;
total_dependencies_count += 1;
}
}
package.bin = package_version.bin.clone_with_buffers(
&manifest.string_buf,
&manifest.extern_strings_bin_entries,
extern_old_len as u32,
extern_strings_slice,
&mut string_builder,
);
package.meta.arch = package_version.cpu;
package.meta.os = package_version.os;
package.meta.integrity = package_version.integrity;
package
.meta
.set_has_install_script(package_version.has_install_script);
package.dependencies.off = dep_start as u32;
package.dependencies.len = total_dependencies_count;
package.resolutions.off = package.dependencies.off;
package.resolutions.len = package.dependencies.len;
let new_length = package.dependencies.len as usize + dep_start;
debug_assert_eq!(resolutions_list.len(), dep_start);
bun_core::vec::extend_from_fn(
resolutions_list,
package.dependencies.len as usize,
|_| invalid_package_id,
);
debug_assert_eq!(resolutions_list.len(), new_length);
// Shrink off the unused default-initialized tail (`new_length <= total_len`).
dependencies_list.truncate(new_length);
#[cfg(debug_assertions)]
{
if package.resolution.npm().url.is_empty() {
Output::panic(format_args!(
"tarball_url is empty for package {}@{}",
bstr::BStr::new(manifest.name()),
version.fmt(&manifest.string_buf),
));
}
}
string_builder.clamp();
return Ok(package);
}
}
}
// ─── Diff ────────────────────────────────────────────────────────────────────
pub(crate) struct Diff;
/// A trusted dependency newly added by the current diff. `name` is the exact
/// byte string the truncated key hash was computed from.
pub struct AddedTrustedDependency {
/// Whether this dependency should be added to lockfile trusted
/// dependencies. It is false when the new trusted dependency is coming
/// from the default list.
pub add_to_lockfile: bool,
pub name: Box<[u8]>,
}
#[derive(Default)]
pub struct DiffSummary {
pub add: u32,
pub remove: u32,
pub update: u32,
pub overrides_changed: bool,
pub catalogs_changed: bool,
pub added_trusted_dependencies:
ArrayHashMap<TruncatedPackageNameHash, AddedTrustedDependency, ArrayIdentityContext>,
pub removed_trusted_dependencies: TrustedDependenciesSet,
pub patched_dependencies_changed: bool,
}
impl DiffSummary {
#[inline]
pub(crate) fn has_diffs(&self) -> bool {
self.add > 0
|| self.remove > 0
|| self.update > 0
|| self.overrides_changed
|| self.catalogs_changed
|| self.added_trusted_dependencies.count() > 0
|| self.removed_trusted_dependencies.count() > 0
|| self.patched_dependencies_changed
}
}
impl Diff {
// PORT NOTE: Zig's `Package` here is the canonical `Package(u64)` (the only
// instantiation `Lockfile` ever holds). Dropping the generic avoids a
// spurious `Package<I>` ≠ `Package<u64>` mismatch on the recursive call
// through `from_lockfile.packages.get(...)`.
pub(crate) fn generate(
pm: &mut PackageManager,
log: &mut bun_ast::Log,
from_lockfile: &mut Lockfile,
to_lockfile: &mut Lockfile,
from: &Package,
to: &Package,
update_requests: Option<&[UpdateRequest]>,
mut id_mapping: Option<&mut [PackageID]>,
) -> Result<DiffSummary, bun_core::Error> {
// TODO(port): narrow error set
let mut summary = DiffSummary::default();
let is_root = id_mapping.is_some();
// PORT NOTE: Zig held `to_deps` as a mutable slice binding and reassigned
// it after `parseWithJSON` (which may grow `to_lockfile.buffers
// .dependencies` and invalidate the old slice). Mirror that with raw fat
// pointers so the `&mut to_lockfile`/`&mut from_lockfile` reborrows below
// (sort, recursive `generate`) don't conflict with these read views; the
// recursive call only sorts `overrides`/`catalogs` and never reallocates
// either lockfile's `buffers.dependencies`/`resolutions`, so the raw
// pointers remain valid for the loop body.
let mut to_deps: bun_ptr::RawSlice<Dependency> = to
.dependencies
.get(to_lockfile.buffers.dependencies.as_slice())
.into();
macro_rules! to_deps {
() => {
to_deps.slice()
};
}
let from_deps: bun_ptr::RawSlice<Dependency> = from
.dependencies
.get(from_lockfile.buffers.dependencies.as_slice())
.into();
let from_resolutions: bun_ptr::RawSlice<PackageID> = from
.resolutions
.get(from_lockfile.buffers.resolutions.as_slice())
.into();
// See PORT NOTE above — `from_lockfile.buffers` is not reallocated for
// the lifetime of these references.
let (from_deps, from_resolutions) = (from_deps.slice(), from_resolutions.slice());
let mut to_i: usize = 0;
if from_lockfile.overrides.map.count() != to_lockfile.overrides.map.count() {
summary.overrides_changed = true;
if PackageManager::verbose_install() {
Output::pretty_errorln(format_args!("Overrides changed since last install"));
}
} else {
// PORT NOTE: reshaped for borrowck — Zig passed `from_lockfile`
// twice (once as `&mut self` via `.overrides`, once as `lockfile`).
// `OverrideMap::sort` only reads `lockfile.buffers.string_bytes`,
// so split the borrow at the field.
lockfile::OverrideMap::sort(
&mut from_lockfile.overrides,
from_lockfile.buffers.string_bytes.as_slice(),
);
lockfile::OverrideMap::sort(
&mut to_lockfile.overrides,
to_lockfile.buffers.string_bytes.as_slice(),
);
debug_assert_eq!(
from_lockfile.overrides.map.keys().len(),
to_lockfile.overrides.map.keys().len()
);
for (((from_k, from_override), to_k), to_override) in from_lockfile
.overrides
.map
.keys()
.iter()
.zip(from_lockfile.overrides.map.values())
.zip(to_lockfile.overrides.map.keys())
.zip(to_lockfile.overrides.map.values())
{
if (from_k != to_k)
|| (!Dependency::eql(
from_override,
to_override,
from_lockfile.buffers.string_bytes.as_slice(),
to_lockfile.buffers.string_bytes.as_slice(),
))
{
summary.overrides_changed = true;
if PackageManager::verbose_install() {
Output::pretty_errorln(format_args!(
"Overrides changed since last install"
));
}
break;
}
}
}
if is_root {
'catalogs: {
// don't sort if lengths are different
if from_lockfile.catalogs.default.count() != to_lockfile.catalogs.default.count() {
summary.catalogs_changed = true;
break 'catalogs;
}
if from_lockfile.catalogs.groups.count() != to_lockfile.catalogs.groups.count() {
summary.catalogs_changed = true;
break 'catalogs;
}
// PORT NOTE: reshaped for borrowck — see `overrides.sort` note above.
lockfile::CatalogMap::sort(&mut from_lockfile.catalogs, &from_lockfile.buffers);
lockfile::CatalogMap::sort(&mut to_lockfile.catalogs, &to_lockfile.buffers);
for (((from_dep_name, from_dep), to_dep_name), to_dep) in from_lockfile
.catalogs
.default
.keys()
.iter()
.zip(from_lockfile.catalogs.default.values())
.zip(to_lockfile.catalogs.default.keys())
.zip(to_lockfile.catalogs.default.values())
{
if !String::eql(
*from_dep_name,
*to_dep_name,
from_lockfile.buffers.string_bytes.as_slice(),
to_lockfile.buffers.string_bytes.as_slice(),
) {
summary.catalogs_changed = true;
break 'catalogs;
}
if !Dependency::eql(
from_dep,
to_dep,
from_lockfile.buffers.string_bytes.as_slice(),
to_lockfile.buffers.string_bytes.as_slice(),
) {
summary.catalogs_changed = true;
break 'catalogs;
}
}
for (((from_catalog_name, from_catalog_deps), to_catalog_name), to_catalog_deps) in
from_lockfile
.catalogs
.groups
.keys()
.iter()
.zip(from_lockfile.catalogs.groups.values())
.zip(to_lockfile.catalogs.groups.keys())
.zip(to_lockfile.catalogs.groups.values())
{
if !String::eql(
*from_catalog_name,
*to_catalog_name,
from_lockfile.buffers.string_bytes.as_slice(),
to_lockfile.buffers.string_bytes.as_slice(),
) {
summary.catalogs_changed = true;
break 'catalogs;
}
if from_catalog_deps.count() != to_catalog_deps.count() {
summary.catalogs_changed = true;
break 'catalogs;
}
for (((from_dep_name, from_dep), to_dep_name), to_dep) in from_catalog_deps
.keys()
.iter()
.zip(from_catalog_deps.values())
.zip(to_catalog_deps.keys())
.zip(to_catalog_deps.values())
{
if !String::eql(
*from_dep_name,
*to_dep_name,
from_lockfile.buffers.string_bytes.as_slice(),
to_lockfile.buffers.string_bytes.as_slice(),
) {
summary.catalogs_changed = true;
break 'catalogs;
}
if !Dependency::eql(
from_dep,
to_dep,
from_lockfile.buffers.string_bytes.as_slice(),
to_lockfile.buffers.string_bytes.as_slice(),
) {
summary.catalogs_changed = true;
break 'catalogs;
}
}
}
}
}
'trusted_dependencies: {
// trusted dependency diff
//
// situations:
// 1 - Both old lockfile and new lockfile use default trusted dependencies, no diffs
// 2 - Both exist, only diffs are from additions and removals
//
// 3 - Old lockfile has trusted dependencies, new lockfile does not. Added are dependencies
// from default list that didn't exist previously. We need to be careful not to add these
// to the new lockfile. Removed are dependencies from old list that
// don't exist in the default list.
//
// 4 - Old lockfile used the default list, new lockfile has trusted dependencies. Added
// are dependencies are all from the new lockfile. Removed is empty because the default
// list isn't appended to the lockfile.
// 1
if from_lockfile.trusted_dependencies.is_none()
&& to_lockfile.trusted_dependencies.is_none()
{
break 'trusted_dependencies;
}
// 2
if let (Some(from_trusted_dependencies), Some(to_trusted_dependencies)) = (
from_lockfile.trusted_dependencies.as_mut(),
to_lockfile.trusted_dependencies.as_ref(),
) {
// added
for (&to_trusted, to_name) in to_trusted_dependencies.iter() {
// Empty name = legacy bun.lockb hash-only sentinel.
let already_trusted = from_trusted_dependencies
.get_mut(&to_trusted)
.is_some_and(|from_name| {
if from_name.is_empty() && !to_name.is_empty() {
from_name.clone_from(to_name);
}
from_name.is_empty() || to_name.is_empty() || **from_name == **to_name
});
if !already_trusted {
summary.added_trusted_dependencies.put(
to_trusted,
AddedTrustedDependency {
add_to_lockfile: true,
name: to_name.clone(),
},
)?;
}
}
// removed
for (&from_trusted, from_name) in from_trusted_dependencies.iter() {
let still_trusted =
to_trusted_dependencies
.get(&from_trusted)
.is_some_and(|to_name| {
from_name.is_empty()
|| to_name.is_empty()
|| **to_name == **from_name
});
if !still_trusted {
summary
.removed_trusted_dependencies
.put(from_trusted, from_name.clone())?;
}
}
break 'trusted_dependencies;
}
// 3
if let (Some(from_trusted_dependencies), None) = (
from_lockfile.trusted_dependencies.as_ref(),
to_lockfile.trusted_dependencies.as_ref(),
) {
// added
for entry in default_trusted_dependencies::entries() {
if !from_trusted_dependencies
.contains(&(entry.hash as TruncatedPackageNameHash))
{
// although this is a new trusted dependency, it is from the default
// list so it shouldn't be added to the lockfile
summary.added_trusted_dependencies.put(
entry.hash as TruncatedPackageNameHash,
AddedTrustedDependency {
add_to_lockfile: false,
name: Box::from(entry.key),
},
)?;
}
}
// removed
for (&from_trusted, from_name) in from_trusted_dependencies.iter() {
if !default_trusted_dependencies::has_with_hash(u64::from(from_trusted)) {
summary
.removed_trusted_dependencies
.put(from_trusted, from_name.clone())?;
}
}
break 'trusted_dependencies;
}
// 4
if let (None, Some(to_trusted_dependencies)) = (
from_lockfile.trusted_dependencies.as_ref(),
to_lockfile.trusted_dependencies.as_ref(),
) {
// add all to trusted dependencies, even if they exist in default because they weren't in the
// lockfile originally
for (&to_trusted, to_name) in to_trusted_dependencies.iter() {
summary.added_trusted_dependencies.put(
to_trusted,
AddedTrustedDependency {
add_to_lockfile: true,
name: to_name.clone(),
},
)?;
}
{
// removed
// none
}
break 'trusted_dependencies;
}
}
summary.patched_dependencies_changed = 'patched_dependencies_changed: {
if from_lockfile.patched_dependencies.count()
!= to_lockfile.patched_dependencies.count()
{
break 'patched_dependencies_changed true;
}
let iter = to_lockfile.patched_dependencies.iterator();
for entry in iter {
if let Some(val) = from_lockfile.patched_dependencies.get(&*entry.key_ptr) {
if val
.path
.slice(from_lockfile.buffers.string_bytes.as_slice())
!= entry
.value_ptr
.path
.slice(to_lockfile.buffers.string_bytes.as_slice())
{
break 'patched_dependencies_changed true;
}
} else {
break 'patched_dependencies_changed true;
}
}
for key in from_lockfile.patched_dependencies.keys() {
if !to_lockfile.patched_dependencies.contains(key) {
break 'patched_dependencies_changed true;
}
}
false
};
for (i, from_dep) in from_deps.iter().enumerate() {
let found = 'found: {
let prev_i = to_i;
// common case, dependency is present in both versions:
// - in the same position
// - shifted by a constant offset
while to_i < to_deps!().len() {
if from_dep.name_hash == to_deps!()[to_i].name_hash {
let from_behavior = from_dep.behavior;
let to_behavior = to_deps!()[to_i].behavior;
if from_behavior != to_behavior {
to_i += 1;
continue;
}
break 'found true;
}
to_i += 1;
}
// less common, o(n^2) case
to_i = 0;
while to_i < prev_i {
if from_dep.name_hash == to_deps!()[to_i].name_hash {
let from_behavior = from_dep.behavior;
let to_behavior = to_deps!()[to_i].behavior;
if from_behavior != to_behavior {
to_i += 1;
continue;
}
break 'found true;
}
to_i += 1;
}
false
};
if !found {
// We found a removed dependency!
// We don't need to remove it
// It will be cleaned up later
summary.remove += 1;
continue;
}
// defer to_i += 1; — applied at end of iteration body
let cur_to_i = to_i;
to_i += 1;
if Dependency::eql(
&to_deps!()[cur_to_i],
from_dep,
to_lockfile.buffers.string_bytes.as_slice(),
from_lockfile.buffers.string_bytes.as_slice(),
) {
if let Some(updates) = update_requests {
if updates.is_empty()
|| 'brk: {
for request in updates {
if from_dep.name_hash == request.name_hash {
break 'brk true;
}
}
false
}
{
// Listed as to be updated
summary.update += 1;
continue;
}
}
if let Some(mapping) = id_mapping.as_deref_mut() {
let update_mapping = 'update_mapping: {
if !is_root || !from_dep.behavior.is_workspace() {
break 'update_mapping true;
}
let Some(workspace_path) = to_lockfile
.workspace_paths
.get(&from_dep.name_hash)
.copied()
else {
break 'update_mapping false;
};
let mut package_json_path: AutoAbsPath = AutoAbsPath::init_top_level_dir();
// defer package_json_path.deinit(); — Drop handles it
// OOM/capacity: Zig aborts; port keeps fire-and-forget
let _ = package_json_path.append(
workspace_path.slice(to_lockfile.buffers.string_bytes.as_slice()),
);
let _ = package_json_path.append(b"package.json"); // OOM/capacity: Zig aborts; port keeps fire-and-forget
// PORT NOTE: `bun.sys.File.toSource` was removed from
// T1 (`bun_sys`) because `bun_ast::Source` lives in T2.
// Route through the workspace cache's path-based getter
// instead, which both reads and parses.
let mut workspace_pkg = Package::default();
// The cache entry borrows `pm.workspace_package_json_cache`;
// capture a stable BACKREF to its `source` so the
// `&mut pm` reborrow below doesn't conflict. The entry
// lives in a `StringHashMap` whose backing storage is
// not touched by `parse_with_json`.
let (source_ref, json_root): (bun_ptr::ParentRef<bun_ast::Source>, Expr) =
match pm
.workspace_package_json_cache
.get_with_path(
&mut *log,
package_json_path.slice(),
Default::default(),
)
.unwrap()
{
Ok(entry) => (bun_ptr::ParentRef::new(&entry.source), entry.root),
Err(_) => break 'update_mapping false,
};
// BACKREF — entry storage is stable for the remainder
// of this block (see note above).
let source = source_ref.get();
let mut resolver: () = ();
workspace_pkg.parse_with_json::<()>(
to_lockfile,
pm,
log,
source,
json_root,
&mut resolver,
Features::WORKSPACE,
)?;
// `parse_with_json` may have grown `to_lockfile.buffers
// .dependencies` — re-derive the slice (Zig did the same).
to_deps = to
.dependencies
.get(to_lockfile.buffers.dependencies.as_slice())
.into();
let from_pkg = from_lockfile.packages.get(from_resolutions[i] as usize);
let diff = Self::generate(
pm,
log,
from_lockfile,
to_lockfile,
&from_pkg,
&workspace_pkg,
update_requests,
None,
)?;
if pm.options.log_level.is_verbose()
&& (diff.add + diff.remove + diff.update) > 0
{
Output::pretty_errorln(format_args!(
"Workspace package \"{}\" has added <green>{}<r> dependencies, removed <red>{}<r> dependencies, and updated <cyan>{}<r> dependencies",
bstr::BStr::new(
workspace_path
.slice(to_lockfile.buffers.string_bytes.as_slice())
),
diff.add,
diff.remove,
diff.update,
));
}
!diff.has_diffs()
};
if update_mapping {
mapping[cur_to_i] = i as PackageID;
continue;
}
} else {
continue;
}
}
// We found a changed dependency!
//
// If only the *version literal* changed and the previously-resolved
// package still satisfies the new range, keep the existing
// resolution. Otherwise widening a range (e.g. `"4.0.0"` → `"*"`)
// re-resolves to latest on the next `bun add <unrelated>`, which
// surprises migrations from npm/pnpm lockfiles whose package.json
// range diverged from the locked version. This matches npm's
// sticky-lockfile behaviour and lets `Lockfile::get_package_id`
// apply its order-independence guard without overriding a locked
// pin.
//
// Skipped when the dependency is an explicit update target
// (`bun update <pkg>` or bare `bun update`): the user is asking
// for a fresh resolve and the old resolution must not be
// preserved. Same gate as the `Dependency::eql == true` branch
// above.
let is_explicit_update_target = matches!(update_requests, Some(updates)
if updates.is_empty()
|| updates.iter().any(|r| r.name_hash == from_dep.name_hash));
if !is_explicit_update_target {
if let Some(mapping) = id_mapping.as_deref_mut() {
let from_res_id = from_resolutions[i];
if (from_res_id as usize) < from_lockfile.packages.len() {
let from_pkg_resolution =
from_lockfile.packages.items_resolution()[from_res_id as usize];
let to_dep = &to_deps!()[cur_to_i];
if to_dep.version.tag == dependency::version::Tag::Npm
&& from_pkg_resolution.tag == ResolutionTag::Npm
&& to_dep.version.npm().version.satisfies(
from_pkg_resolution.npm().version,
to_lockfile.buffers.string_bytes.as_slice(),
from_lockfile.buffers.string_bytes.as_slice(),
)
{
mapping[cur_to_i] = i as PackageID;
// Still counted as an update so `had_any_diffs`
// triggers the rebuild path; we just preserved
// the resolved package.
}
}
}
}
summary.update += 1;
}
// Use saturating arithmetic here because a migrated
// package-lock.json could be out of sync with the package.json, so the
// number of from_deps could be greater than to_deps.
summary.add = (to_deps!()
.len()
.saturating_sub(from_deps.len().saturating_sub(summary.remove as usize)))
as u32;
if from.resolution.tag != ResolutionTag::Root {
// PERF(port): was `inline for` over Lockfile.Scripts.names — profile if hot.
for (to_hook, from_hook) in to.scripts.hooks().iter().zip(from.scripts.hooks().iter()) {
if !String::eql(
**to_hook,
**from_hook,
to_lockfile.buffers.string_bytes.as_slice(),
from_lockfile.buffers.string_bytes.as_slice(),
) {
// We found a changed life-cycle script
summary.update += 1;
}
}
}
Ok(summary)
}
}
impl Package<u64> {
pub fn hash(name: &[u8], version: SemverVersion) -> u64 {
let mut hasher = bun_wyhash::Wyhash::init(0);
hasher.update(name);
// SAFETY: Semver.Version is POD; reading its raw bytes is sound.
hasher.update(unsafe {
bun_core::ffi::slice(
(&raw const version).cast::<u8>(),
mem::size_of::<SemverVersion>(),
)
});
hasher.final_()
}
pub fn parse<R: ResolverContext>(
&mut self,
lockfile: &mut Lockfile,
pm: &mut PackageManager,
log: &mut bun_ast::Log,
source: &bun_ast::Source,
resolver: &mut R,
features: Features,
) -> Result<(), bun_core::Error> {
// TODO(port): narrow error set
initialize_store();
// Zig threaded `lockfile.allocator` for the JSON arena. The returned
// `Expr` tree only needs to live until `parse_with_json` finishes, so
// a function-local arena is sufficient (matches Scripts.rs / lockfile.rs
// call sites) and avoids leaking.
let bump = bun_alloc::Arena::new();
let json = match crate::bun_json::parse_package_json_utf8(source, log, &bump) {
Ok(j) => j,
Err(err) => {
let _ = log.print(std::ptr::from_mut(Output::error_writer()));
Output::pretty_errorln(format_args!(
"<r><red>{}<r> parsing package.json in <b>\"{}\"<r>",
err.name(),
bstr::BStr::new(source.path.pretty_dir()),
));
Global::crash();
}
};
self.parse_with_json::<R>(lockfile, pm, log, source, json, resolver, features)
}
/// Borrow-splitting bridge for `PackageManager` callers
/// (`processDependencyList`, `folder_resolver`). Zig passes
/// `manager.lockfile`, `manager`, `manager.log` as three separate args;
/// Rust borrowck rejects the overlap on `&mut self`, so split via raw
/// pointer here once instead of at every call site.
///
/// # Safety
/// `manager` must point to a live `PackageManager` for the duration of the
/// call, and its `lockfile` / `log` fields must point to live allocations
/// disjoint from `*manager` itself.
pub unsafe fn parse_from_real_manager<R: ResolverContext>(
&mut self,
manager: *mut crate::package_manager_real::PackageManager,
source: &bun_ast::Source,
resolver: &mut R,
features: Features,
) -> Result<(), bun_core::Error> {
// SAFETY: `manager` points to a live `PackageManager` for the duration
// of this call (caller passes `self as *mut _`); `lockfile` and `log`
// are disjoint fields, and `parse_with_json` only reaches `manager`
// through the `pm` argument it receives here — no re-entrancy.
let (lockfile, pm, log) = unsafe {
let m = &mut *manager;
let lockfile: *mut Lockfile = &raw mut *m.lockfile;
let log: *mut bun_ast::Log = m.log;
(&mut *lockfile, &mut *manager, &mut *log)
};
self.parse(lockfile, pm, log, source, resolver, features)
}
// Zig: `comptime group: DependencyGroup`, `comptime features: Features`, `comptime tag: ?Dependency.Version.Tag`
// PERF(port): was comptime monomorphization on `group`/`tag` — profile if hot.
//
// PORT NOTE: Zig took `lockfile: *Lockfile`, but the live `StringBuilder`
// (also passed) already holds `&mut lockfile.buffers.string_bytes`. The
// body only otherwise touches `workspace_paths` / `workspace_versions`,
// so accept those two maps directly and read `string_bytes` via the
// builder — caller can then split-borrow at the field level.
fn parse_dependency(
workspace_paths: &mut lockfile::NameHashMap,
workspace_versions: &mut lockfile::VersionHashMap,
duplicate_checker_map: &mut lockfile::DuplicateCheckerMap,
pm: &mut PackageManager,
log: &mut bun_ast::Log,
source: &bun_ast::Source,
group: &DependencyGroup,
string_builder: &mut StringBuilder<'_>,
features: Features,
package_dependencies: &mut [Dependency],
dependencies_count: u32,
tag: Option<dependency::version::Tag>,
workspace_ver: Option<SemverVersion>,
external_alias: ExternalString,
version: &[u8],
key_loc: bun_ast::Loc,
value_loc: bun_ast::Loc,
) -> Result<Option<Dependency>, bun_core::Error> {
// TODO(port): narrow error set
#[cfg(windows)]
let external_version = 'brk: {
match tag.unwrap_or_else(|| dependency::version::Tag::infer(version)) {
dependency::version::Tag::Workspace
| dependency::version::Tag::Folder
| dependency::version::Tag::Symlink
| dependency::version::Tag::Tarball => {
if String::can_inline(version) {
let mut copy = string_builder.append::<String>(version);
path::dangerously_convert_path_to_posix_in_place::<u8>(&mut copy.bytes);
break 'brk copy;
} else {
let str_ = string_builder.append::<String>(version);
let ptr = str_.ptr();
path::dangerously_convert_path_to_posix_in_place::<u8>(
&mut string_builder.string_bytes
[ptr.off as usize..(ptr.off + ptr.len) as usize],
);
break 'brk str_;
}
}
_ => string_builder.append::<String>(version),
}
};
#[cfg(not(windows))]
let external_version = string_builder.append::<String>(version);
// SAFETY: `buf` aliases `string_builder.string_bytes` while later
// `string_builder.append()` calls write into the *pre-reserved* tail
// (`allocate()` ran before this fn). No realloc occurs, so the detached
// borrow stays valid; a tracked `&[u8]` would needlessly lock the builder.
let buf: &[u8] =
unsafe { bun_ptr::detach_lifetime(string_builder.string_bytes.as_slice()) };
let sliced = external_version.sliced(buf);
let mut dependency_version = Dependency::parse_with_optional_tag(
external_alias.value,
Some(external_alias.hash),
sliced.slice,
tag,
&sliced,
Some(&mut *log),
Some(&mut *pm),
)
.unwrap_or_default();
let mut workspace_range: Option<semver::query::Group> = None;
#[allow(non_snake_case)]
let FEATURES = features;
let name_hash = match dependency_version.tag {
dependency::version::Tag::Npm => {
let npm_name = dependency_version.npm().name;
semver::string::Builder::string_hash(npm_name.slice(buf))
}
dependency::version::Tag::Workspace => {
if strings::has_prefix(sliced.slice, b"workspace:") {
'brk: {
let input = &sliced.slice[b"workspace:".len()..];
let trimmed = strings::trim(input, &strings::WHITESPACE_CHARS);
if trimmed.len() != 1
|| (trimmed[0] != b'*' && trimmed[0] != b'^' && trimmed[0] != b'~')
{
let at = strings::last_index_of_char(input, b'@').unwrap_or(0);
if at > 0 {
workspace_range = Some(
semver::query::parse(&input[at as usize + 1..], sliced)
.unwrap_or_else(|_| bun_core::out_of_memory()),
);
break 'brk semver::string::Builder::string_hash(
&input[0..at as usize],
);
}
workspace_range = Some(
semver::query::parse(input, sliced)
.unwrap_or_else(|_| bun_core::out_of_memory()),
);
}
external_alias.hash
}
} else {
external_alias.hash
}
}
_ => external_alias.hash,
};
let mut workspace_path: Option<String> = None;
let mut workspace_version = workspace_ver;
if tag.is_none() {
workspace_path = workspace_paths.get(&name_hash).copied();
workspace_version = workspace_versions.get(&name_hash).copied();
}
if tag.is_some() {
debug_assert!(
dependency_version.tag != dependency::version::Tag::Npm
&& dependency_version.tag != dependency::version::Tag::DistTag
);
}
match dependency_version.tag {
dependency::version::Tag::Folder => {
let folder = *dependency_version.folder();
let mut folder_buf = PathBuffer::uninit();
let Some(joined) = resolve_path::join_abs_string_buf_checked::<path::platform::Auto>(
FileSystem::instance().top_level_dir(),
&mut folder_buf.0,
&[source.path.name().dir, folder.slice(buf)],
) else {
log.add_error_fmt(
source,
value_loc,
format_args!(
"Dependency \"{}\" has an unsafe folder path",
bstr::BStr::new(external_alias.slice(buf)),
),
);
return Err(bun_core::err!("InstallFailed"));
};
let relative =
resolve_path::relative(FileSystem::instance().top_level_dir(), joined);
// if relative is empty, we are linking the package to itself
dependency_version.value.folder = string_builder
.append::<String>(if relative.is_empty() { b"." } else { relative });
}
dependency::version::Tag::Npm => {
if let Some(workspace_version) = workspace_version {
let satisfies =
dependency_version
.npm()
.version
.satisfies(workspace_version, buf, buf);
if pm.options.link_workspace_packages && satisfies {
// `String::sliced` takes `&'a self`; bind the unwrapped
// value so the borrow outlives the parse call.
let wp = workspace_path.unwrap();
let path = wp.sliced(buf);
if let Some(mut dep) = dependency::parse_with_tag(
external_alias.value,
Some(external_alias.hash),
path.slice,
dependency::version::Tag::Workspace,
&path,
Some(&mut *log),
Some(&mut *pm),
) {
// Whole-struct move so `Drop` frees the old npm
// chain; keep the existing `literal` (Zig parity).
dep.literal = dependency_version.literal;
dependency_version = dep;
}
} else {
// It doesn't satisfy, but a workspace shares the same name. Override the workspace with the other dependency
for dep in &mut package_dependencies[0..dependencies_count as usize] {
if dep.name_hash == name_hash && dep.behavior.is_workspace() {
*dep = Dependency {
behavior: group.behavior,
name: external_alias.value,
name_hash: external_alias.hash,
version: dependency_version,
};
return Ok(None);
}
}
}
}
}
dependency::version::Tag::Workspace => 'workspace: {
if let Some(path) = workspace_path {
if let Some(range) = &workspace_range {
if let Some(ver) = workspace_version {
if range.satisfies(ver, buf, buf) {
dependency_version.value.workspace = path;
break 'workspace;
}
}
// important to trim before len == 0 check. `workspace:foo@ ` should install successfully
// SAFETY: `range.input` borrows `lockfile.buffers.string_bytes`
// (set by `semver::query::parse` above), which is live here.
let version_literal =
strings::trim(unsafe { &*range.input }, &strings::WHITESPACE_CHARS);
if version_literal.is_empty()
|| range.is_star()
|| SemverVersion::is_tagged_version_only(version_literal)
{
dependency_version.value.workspace = path;
break 'workspace;
}
// workspace is not required to have a version, but if it does
// and this version doesn't match it, fail to install
log.add_error_fmt(
source,
bun_ast::Loc::EMPTY,
format_args!(
"No matching version for workspace dependency \"{}\". Version: \"{}\"",
bstr::BStr::new(external_alias.slice(buf)),
bstr::BStr::new(dependency_version.literal.slice(buf)),
),
);
return Err(bun_core::err!("InstallFailed"));
}
dependency_version.value.workspace = path;
} else {
// SAFETY: tag == Workspace selects the `workspace` union member.
// Bind the (Copy) union field first so `slice()`'s `&self`
// borrow has a named place to point at.
let workspace_str = *dependency_version.workspace();
let workspace = workspace_str.slice(buf);
let path =
string_builder.append::<String>(if workspace == b"*" {
b"*"
} else {
'brk: {
let mut buf2 = PathBuffer::uninit();
let rel =
resolve_path::relative_platform::<path::platform::Auto, false>(
FileSystem::instance().top_level_dir(),
resolve_path::join_abs_string_buf::<path::platform::Auto>(
FileSystem::instance().top_level_dir(),
&mut buf2.0,
&[source.path.name().dir, workspace],
),
);
#[cfg(windows)]
{
// Zig spec (Package.zig:1175-1178) converts
// `relative_to_common_path_buf()[0..rel.len]` in place but then
// returns `rel`. With ALWAYS_COPY=false, `rel` may instead borrow
// RELATIVE_TO_BUF (resolve_path.rs early returns at L450/457/500/
// 522) or be `b""`. Re-deriving a slice of the common-path buf
// would yield stale bytes in those cases. Copy `rel` into the
// common-path scratch when it isn't already there, then convert
// and return that — preserving the spec's "return `rel`'s bytes"
// contract while avoiding aliasing UB.
let len = rel.len();
let common_raw = path::relative_to_common_path_buf();
// `PathBuffer` is `repr(transparent)` over `[u8; N]`, so the
// struct pointer equals `(&*common_raw).as_ptr()`.
let rel_is_common =
core::ptr::eq(rel.as_ptr(), common_raw.cast::<u8>());
// SAFETY: thread-local scratch; sole live mut borrow on this
// thread for the remainder of this block. When `rel` aliased
// it, its last use was the `.as_ptr()` above (NLL-dead);
// otherwise `rel` borrows a disjoint allocation.
let common = unsafe { &mut *common_raw };
if !rel_is_common {
// `rel` is into a disjoint thread-local (RELATIVE_TO_BUF)
// or `b""` (len==0 → no read).
common[..len].copy_from_slice(rel);
}
let s: &mut [u8] = &mut common[..len];
path::dangerously_convert_path_to_posix_in_place::<u8>(s);
break 'brk &*s;
}
#[cfg(not(windows))]
break 'brk rel;
}
});
if cfg!(debug_assertions) {
debug_assert!(path.len() > 0);
debug_assert!(!bun_paths::is_absolute(path.slice(buf)));
}
dependency_version.value.workspace = path;
let workspace_entry = workspace_paths.get_or_put(name_hash)?;
let found_matching_workspace = workspace_entry.found_existing;
if let Some(ver) = workspace_version {
workspace_versions.put(name_hash, ver)?;
for package_dep in &mut package_dependencies[0..dependencies_count as usize]
{
if match package_dep.version.tag {
// `dependencies` & `workspaces` defined within the same `package.json`
dependency::version::Tag::Npm => {
semver::string::Builder::string_hash(
package_dep.realname().slice(buf),
) == name_hash
// SAFETY: tag == Npm selects the `npm` union member.
&& unsafe {
package_dep
.version
.value
.npm
.version
.satisfies(ver, buf, buf)
}
}
// `workspace:*`
dependency::version::Tag::Workspace => {
found_matching_workspace
&& semver::string::Builder::string_hash(
package_dep.realname().slice(buf),
) == name_hash
}
_ => false,
} {
package_dep.version = dependency_version;
*workspace_entry.value_ptr = path;
return Ok(None);
}
}
} else if workspace_entry.found_existing {
for package_dep in &mut package_dependencies[0..dependencies_count as usize]
{
if package_dep.version.tag == dependency::version::Tag::Workspace
&& semver::string::Builder::string_hash(
package_dep.realname().slice(buf),
) == name_hash
{
package_dep.version = dependency_version;
return Ok(None);
}
}
return Err(bun_core::err!("InstallFailed"));
}
*workspace_entry.value_ptr = path;
}
}
_ => {}
}
let this_dep = Dependency {
behavior: group.behavior,
name: external_alias.value,
name_hash: external_alias.hash,
version: dependency_version,
};
// `peerDependencies` may be specified on existing dependencies. Packages in `workspaces` are deduplicated when
// the array is processed
if FEATURES.check_for_duplicate_dependencies
&& !group.behavior.is_peer()
&& !group.behavior.is_workspace()
{
// PERF(port): was assume_capacity
let entry = duplicate_checker_map.get_or_put(external_alias.hash)?;
if entry.found_existing {
// duplicate dependencies are allowed in optionalDependencies
if group.behavior.is_optional() {
for package_dep in &mut package_dependencies[0..dependencies_count as usize] {
if package_dep.name_hash == this_dep.name_hash {
*package_dep = this_dep;
break;
}
}
return Ok(None);
} else {
let mut notes: Vec<bun_ast::Data> = Vec::with_capacity(1);
let mut text = Vec::new();
{
use std::io::Write;
let _ = write!(
&mut text,
"\"{}\" originally specified here",
bstr::BStr::new(external_alias.slice(buf))
);
}
notes.push(bun_ast::Data {
text: text.into(),
location: bun_ast::Location::init_or_null(
Some(source),
source.range_of_string(*entry.value_ptr),
),
..Default::default()
});
log.add_range_warning_fmt_with_notes(
Some(source),
source.range_of_string(key_loc),
notes.into(),
format_args!(
"Duplicate dependency: \"{}\" specified in package.json",
bstr::BStr::new(external_alias.slice(buf))
),
);
}
}
*entry.value_ptr = value_loc;
}
Ok(Some(this_dep))
}
pub fn parse_with_json<R: ResolverContext>(
&mut self,
lockfile: &mut Lockfile,
pm: &mut PackageManager,
log: &mut bun_ast::Log,
source: &bun_ast::Source,
json: Expr,
resolver: &mut R,
features: Features,
) -> Result<(), bun_core::Error> {
// Thin monomorphic shim: erase `R` to `dyn ResolverContextDyn` so the
// ~960-line body below is codegen'd once. The half-dozen vtable calls
// are noise next to the JSON walking / string-building this does.
self.parse_with_json_impl(lockfile, pm, log, source, json, resolver, features)
}
#[inline(never)]
fn parse_with_json_impl(
&mut self,
lockfile: &mut Lockfile,
pm: &mut PackageManager,
log: &mut bun_ast::Log,
source: &bun_ast::Source,
json: Expr,
resolver: &mut dyn ResolverContextDyn,
features: Features,
) -> Result<(), bun_core::Error> {
#[allow(non_snake_case)]
let FEATURES = features;
// TODO(port): narrow error set
// Zig threads `allocator` for `asString` transcoding; the Rust signature
// dropped it, so use a function-local arena (transcoded strings are only
// borrowed until `string_builder.append` copies them).
let bump = bun_alloc::Arena::new();
// PORT NOTE: split-borrow `string_bytes`/`string_pool` so the dozens of
// disjoint `lockfile.{buffers.*, overrides, catalogs, workspace_*, …}`
// accesses below pass borrowck. Reads of `lockfile.buffers.string_bytes`
// must go through `string_builder.string_bytes` while it's live.
let mut string_builder = crate::string_builder!(lockfile);
let mut total_dependencies_count: u32 = 0;
self.meta.origin = if FEATURES.is_main {
install::Origin::Local
} else {
install::Origin::Npm
};
self.name = String::default();
self.name_hash = 0;
// -- Count the sizes
'name: {
if let Some(name_q) = json.as_property(b"name") {
if let Some(name) = name_q.expr.as_utf8(&bump) {
if !name.is_empty() {
string_builder.count(name);
break 'name;
}
}
}
// name is not validated by npm, so fallback to creating a new from the version literal
if resolver.is_git() {
let resolution: &Resolution<u64> = resolver.resolution();
let repo = match resolution.tag {
ResolutionTag::Git => *resolution.git(),
ResolutionTag::Github => *resolution.github(),
_ => break 'name,
};
resolver.set_new_name(Repository::create_dependency_name_from_version_literal(
&repo,
string_builder.string_bytes.as_slice(),
&lockfile.buffers.dependencies[resolver.dep_id() as usize],
));
string_builder.count(resolver.new_name());
}
}
if let Some(patched_deps) = json.as_property(b"patchedDependencies") {
if let ExprData::EObject(obj) = &patched_deps.expr.data {
for prop in obj.properties.slice() {
let key = prop.key.expect("infallible: prop has key");
let value = prop.value.expect("infallible: prop has value");
if key.is_string() && value.is_string() {
string_builder.count(value.as_utf8(&bump).unwrap());
}
}
}
}
if !FEATURES.is_main {
if let Some(version_q) = json.as_property(b"version") {
if let Some(version_str) = version_q.expr.as_utf8(&bump) {
string_builder.count(version_str);
}
}
}
'bin: {
if let Some(bin) = json.as_property(b"bin") {
match &bin.expr.data {
ExprData::EObject(obj) => {
for bin_prop in obj.properties.slice() {
let Some(k) = bin_prop
.key
.expect("infallible: prop has key")
.as_utf8(&bump)
else {
break 'bin;
};
string_builder.count(k);
let Some(v) = bin_prop
.value
.expect("infallible: prop has value")
.as_utf8(&bump)
else {
break 'bin;
};
string_builder.count(v);
}
break 'bin;
}
ExprData::EString(_) => {
if let Some(str_) = bin.expr.as_utf8(&bump) {
string_builder.count(str_);
break 'bin;
}
}
_ => {}
}
}
if let Some(dirs) = json.as_property(b"directories") {
if let Some(bin_prop) = dirs.expr.as_property(b"bin") {
if let Some(str_) = bin_prop.expr.as_utf8(&bump) {
string_builder.count(str_);
break 'bin;
}
}
}
}
Scripts::parse_count(&mut string_builder, json);
if !resolver.is_void() {
resolver.count(&mut string_builder, &json);
}
// PERF(port): was comptime-computed array — profile if hot.
let dependency_groups: Vec<DependencyGroup> = {
let mut out: Vec<DependencyGroup> = Vec::with_capacity(5);
if FEATURES.workspaces {
out.push(DependencyGroup::WORKSPACES);
}
if FEATURES.dependencies {
out.push(DependencyGroup::DEPENDENCIES);
}
if FEATURES.dev_dependencies {
out.push(DependencyGroup::DEV);
}
if FEATURES.optional_dependencies {
out.push(DependencyGroup::OPTIONAL);
}
if FEATURES.peer_dependencies {
out.push(DependencyGroup::PEER);
}
out
};
let mut workspace_names = workspace_map::WorkspaceMap::init();
// defer workspace_names.deinit(); — Drop handles it
// pnpm/yarn synthesise an implicit `"*"` optional peer for entries
// that appear in `peerDependenciesMeta` but not in
// `peerDependencies`. Track the original key string so the
// post-build pass can emit a real `Dependency` for any meta-only
// names that nothing in the build loop consumed.
let mut optional_peer_dependencies: ArrayHashMap<
PackageNameHash,
&[u8],
bun_collections::identity_context::U64,
> = ArrayHashMap::default();
// defer optional_peer_dependencies.deinit(); — Drop handles it
if FEATURES.peer_dependencies {
if let Some(peer_dependencies_meta) = json.as_property(b"peerDependenciesMeta") {
if let ExprData::EObject(obj) = &peer_dependencies_meta.expr.data {
let props = obj.properties.slice();
optional_peer_dependencies.ensure_unused_capacity(props.len())?;
for prop in props {
if let Some(optional) = prop
.value
.expect("infallible: prop has value")
.as_property(b"optional")
{
if !matches!(
&optional.expr.data,
ExprData::EBoolean(b) if b.value
) {
continue;
}
let key = prop
.key
.expect("infallible: prop has key")
.as_utf8(&bump)
.expect("unreachable");
// PERF(port): was assume_capacity
optional_peer_dependencies.put_assume_capacity(
semver::string::Builder::string_hash(key),
key,
);
// Reserve space for a synthesised entry. If the
// matching name later appears in `peerDependencies`
// the slot just goes unused.
string_builder.count(key);
string_builder.count(b"*");
total_dependencies_count += 1;
}
}
}
}
}
// PERF(port): was `inline for` — profile if hot.
for group in &dependency_groups {
if let Some(dependencies_q) = json.as_property(group.prop) {
'brk: {
match &dependencies_q.expr.data {
ExprData::EArray(arr) => {
if !group.behavior.is_workspace() {
let _ = bun_ast::add_error_pretty!(
log,
source,
dependencies_q.loc,
"{0} expects a map of specifiers, e.g.\n <r><green>\"{0}\"<r>: {{\n <green>\"bun\"<r>: <green>\"latest\"<r>\n }}",
bstr::BStr::new(group.prop)
);
return Err(bun_core::err!("InvalidPackageJSON"));
}
total_dependencies_count += workspace_names.process_names_array(
&mut pm.workspace_package_json_cache,
log,
&**arr,
source,
dependencies_q.loc,
Some(&mut string_builder),
)?;
}
ExprData::EObject(obj) => {
if group.behavior.is_workspace() {
// yarn workspaces expects a "workspaces" property shaped like this:
//
// "workspaces": {
// "packages": [
// "path/to/package"
// ]
// }
//
if let Some(packages_query) = obj.as_property(b"packages") {
let packages_expr = packages_query.expr;
if !matches!(packages_expr.data, ExprData::EArray(_)) {
let _ = log.add_error_fmt(
source,
packages_expr.loc,
// TODO: what if we could comptime call the syntax highlighter
format_args!(
"\"workspaces.packages\" expects an array of strings, e.g.\n \"workspaces\": {{\n \"packages\": [\n \"path/to/package\"\n ]\n }}"
),
);
return Err(bun_core::err!("InvalidPackageJSON"));
}
let ExprData::EArray(packages_arr) = &packages_expr.data else {
unreachable!()
};
total_dependencies_count += workspace_names
.process_names_array(
&mut pm.workspace_package_json_cache,
log,
&**packages_arr,
source,
packages_expr.loc,
Some(&mut string_builder),
)?;
}
break 'brk;
}
for item in obj.properties.slice() {
let key = item
.key
.expect("infallible: prop has key")
.as_utf8(&bump)
.unwrap();
let Some(value) = item
.value
.expect("infallible: prop has value")
.as_utf8(&bump)
else {
let _ = bun_ast::add_error_pretty!(
log,
source,
item.value.expect("infallible: prop has value").loc,
// TODO: what if we could comptime call the syntax highlighter
"{0} expects a map of specifiers, e.g.\n <r><green>\"{0}\"<r>: {{\n <green>\"bun\"<r>: <green>\"latest\"<r>\n }}",
bstr::BStr::new(group.prop)
);
return Err(bun_core::err!("InvalidPackageJSON"));
};
string_builder.count(key);
string_builder.count(value);
// If it's a folder or workspace, pessimistically assume we will need a maximum path
match dependency::version::Tag::infer(value) {
dependency::version::Tag::Folder
| dependency::version::Tag::Workspace => {
string_builder.cap += MAX_PATH_BYTES;
}
_ => {}
}
}
total_dependencies_count += obj.properties.len_u32();
}
_ => {
if group.behavior.is_workspace() {
let _ = bun_ast::add_error_pretty!(
log,
source,
dependencies_q.loc,
// TODO: what if we could comptime call the syntax highlighter
"\"workspaces\" expects an array of strings, e.g.\n <r><green>\"workspaces\"<r>: [\n <green>\"path/to/package\"<r>\n ]"
);
} else {
let _ = bun_ast::add_error_pretty!(
log,
source,
dependencies_q.loc,
"{0} expects a map of specifiers, e.g.\n <r><green>\"{0}\"<r>: {{\n <green>\"bun\"<r>: <green>\"latest\"<r>\n }}",
bstr::BStr::new(group.prop)
);
}
return Err(bun_core::err!("InvalidPackageJSON"));
}
}
}
}
}
if FEATURES.trusted_dependencies {
if let Some(q) = json.as_property(b"trustedDependencies") {
match &q.expr.data {
ExprData::EArray(arr) => {
if lockfile.trusted_dependencies.is_none() {
lockfile.trusted_dependencies = Some(Default::default());
}
lockfile
.trusted_dependencies
.as_mut()
.unwrap()
.ensure_unused_capacity(arr.items.len_u32() as usize)?;
for item in arr.slice() {
let Some(name) = item.as_utf8(&bump) else {
let _ = log.add_error_fmt(
source,
q.loc,
format_args!(
"trustedDependencies expects an array of strings, e.g.\n <r><green>\"trustedDependencies\"<r>: [\n <green>\"package_name\"<r>\n ]"
),
);
return Err(bun_core::err!("InvalidPackageJSON"));
};
// PERF(port): was assume_capacity
lockfile
.trusted_dependencies
.as_mut()
.unwrap()
.put_assume_capacity(
semver::string::Builder::string_hash(name)
as TruncatedPackageNameHash,
Box::<[u8]>::from(name),
);
}
}
_ => {
let _ = log.add_error_fmt(
source,
q.loc,
format_args!(
"trustedDependencies expects an array of strings, e.g.\n <r><green>\"trustedDependencies\"<r>: [\n <green>\"package_name\"<r>\n ]"
),
);
return Err(bun_core::err!("InvalidPackageJSON"));
}
}
}
}
if FEATURES.is_main {
lockfile.overrides.parse_count(json, &mut string_builder);
if let Some(workspaces_expr) = json.get(b"workspaces") {
lockfile
.catalogs
.parse_count(workspaces_expr, &mut string_builder);
}
// Count catalog strings in top-level package.json as well, since parseAppend
// might process them later if no catalogs were found in workspaces
lockfile.catalogs.parse_count(json, &mut string_builder);
install::postinstall_optimizer::PostinstallOptimizer::from_package_json(
&mut pm.postinstall_optimizer,
&json,
)?;
}
string_builder.allocate()?;
lockfile
.buffers
.dependencies
.reserve(total_dependencies_count as usize);
lockfile
.buffers
.resolutions
.reserve(total_dependencies_count as usize);
let off = lockfile.buffers.dependencies.len();
let total_len = off + total_dependencies_count as usize;
if cfg!(debug_assertions) {
debug_assert!(
lockfile.buffers.dependencies.len() == lockfile.buffers.resolutions.len()
);
}
// PORT NOTE: Zig slices `lockfile.buffers.dependencies.items.ptr[off..total_len]`
// — i.e. into reserved-but-uncommitted capacity *without* bumping `items.len`.
// Mirroring that here matters: `parse_dependency` can return early with an error
// (e.g. `InstallFailed` for a non-matching `workspace:` range), and the caller
// may swallow it and re-enter for the next package. If we eagerly grow
// `dependencies` and then bail, `dependencies.len() != resolutions.len()` on the
// next call and the debug_assert above trips.
//
// Rather than `from_raw_parts_mut` over spare capacity (which yields a `&mut [T]`
// to uninitialized memory — UB, and `Dependency` is not `Copy` so indexed
// assignment would drop garbage), build into a local `Vec` and `append` into the
// lockfile buffer once all `?`-points are past. On early error the local vec is
// dropped and `lockfile.buffers.dependencies.len()` is left untouched, preserving
// the `== resolutions.len()` invariant exactly as the Zig spare-capacity write
// did. Capacity for the final `append` was reserved above so it does not realloc.
let mut package_dependencies: Vec<Dependency> = Vec::with_capacity(total_len - off);
'name: {
if resolver.is_git() {
if !resolver.new_name().is_empty() {
let new_name = resolver.take_new_name();
let external_string = string_builder.append::<ExternalString>(&new_name);
self.name = external_string.value;
self.name_hash = external_string.hash;
break 'name;
}
}
if let Some(name_q) = json.as_property(b"name") {
if let Some(name) = name_q.expr.as_utf8(&bump) {
if !name.is_empty() {
let external_string = string_builder.append::<ExternalString>(name);
self.name = external_string.value;
self.name_hash = external_string.hash;
break 'name;
}
}
}
}
if !FEATURES.is_main {
if !resolver.is_void() {
self.resolution = resolver.resolve(&mut string_builder, &json)?;
}
} else {
self.resolution = Resolution::<u64>::init(TaggedValue::Root);
}
if let Some(patched_deps) = json.as_property(b"patchedDependencies") {
if let ExprData::EObject(obj) = &patched_deps.expr.data {
lockfile
.patched_dependencies
.ensure_total_capacity(obj.properties.len_u32() as usize)
.expect("unreachable");
for prop in obj.properties.slice() {
let key = prop.key.expect("infallible: prop has key");
let value = prop.value.expect("infallible: prop has value");
if key.is_string() && value.is_string() {
// PERF(port): was stack-fallback
let keyhash =
semver::string::Builder::string_hash(key.as_utf8(&bump).unwrap());
let patch_path =
string_builder.append::<String>(value.as_utf8(&bump).unwrap());
lockfile
.patched_dependencies
.put(
keyhash,
PatchedDep {
path: patch_path,
..Default::default()
},
)
.expect("unreachable");
}
}
}
}
'bin: {
if let Some(bin) = json.as_property(b"bin") {
match &bin.expr.data {
ExprData::EObject(obj) => {
match obj.properties.len_u32() {
0 => {}
1 => {
let first = &obj.properties.slice()[0];
let Some(bin_name) = first.key.unwrap().as_utf8(&bump) else {
break 'bin;
};
let Some(value) = first.value.unwrap().as_utf8(&bump) else {
break 'bin;
};
self.bin = Bin {
tag: bin::Tag::NamedFile,
value: bin::Value::init_named_file([
string_builder.append::<String>(bin_name),
string_builder.append::<String>(value),
]),
..Default::default()
};
}
_ => {
let current_len = lockfile.buffers.extern_strings.len();
let count = obj.properties.len_u32() as usize * 2;
lockfile.buffers.extern_strings.reserve_exact(count);
// Default-fill the tail; the loop below
// overwrites each slot. Keeps every exposed
// `ExternalString` valid even if `break 'bin`
// fires partway through (replaces raw
// `set_len`).
let extern_strings = bun_core::vec::grow_default(
&mut lockfile.buffers.extern_strings,
count,
);
let mut i: usize = 0;
for bin_prop in obj.properties.slice() {
let Some(k) = bin_prop
.key
.expect("infallible: prop has key")
.as_utf8(&bump)
else {
break 'bin;
};
extern_strings[i] = string_builder.append::<ExternalString>(k);
i += 1;
let Some(v) = bin_prop
.value
.expect("infallible: prop has value")
.as_utf8(&bump)
else {
break 'bin;
};
extern_strings[i] = string_builder.append::<ExternalString>(v);
i += 1;
}
if cfg!(debug_assertions) {
debug_assert!(i == extern_strings.len());
}
// PORT NOTE: Zig passed the full extern_strings
// buffer + tail subslice; `init` only needs the
// tail's offset, so construct directly to avoid
// the aliasing borrow.
self.bin = Bin {
tag: bin::Tag::Map,
value: bin::Value {
map: ExternalStringList::new(
current_len as u32,
extern_strings.len() as u32,
),
},
..Default::default()
};
}
}
break 'bin;
}
ExprData::EString(stri) => {
if !stri.data.is_empty() {
self.bin = Bin {
tag: bin::Tag::File,
value: bin::Value {
file: string_builder.append::<String>(&stri.data),
},
..Default::default()
};
break 'bin;
}
}
_ => {}
}
}
if let Some(dirs) = json.as_property(b"directories") {
// https://docs.npmjs.com/cli/v8/configuring-npm/package-json#directoriesbin
// Because of the way the bin directive works,
// specifying both a bin path and setting
// directories.bin is an error. If you want to
// specify individual files, use bin, and for all
// the files in an existing bin directory, use
// directories.bin.
if let Some(bin_prop) = dirs.expr.as_property(b"bin") {
if let Some(str_) = bin_prop.expr.as_utf8(&bump) {
if !str_.is_empty() {
self.bin = Bin {
tag: bin::Tag::Dir,
value: bin::Value {
dir: string_builder.append::<String>(str_),
},
..Default::default()
};
break 'bin;
}
}
}
}
}
self.scripts.parse_alloc(&mut string_builder, json);
self.scripts.filled = true;
// It is allowed for duplicate dependencies to exist in optionalDependencies and regular dependencies
if FEATURES.check_for_duplicate_dependencies {
lockfile.scratch.duplicate_checker_map.clear();
lockfile
.scratch
.duplicate_checker_map
.reserve(total_dependencies_count as usize);
}
let mut bundled_deps = StringSet::init();
// defer bundled_deps.deinit(); — Drop handles it
let mut bundle_all_deps = false;
if !resolver.is_void() && resolver.check_bundled_dependencies() {
if let Some(bundled_deps_expr) = json
.get(b"bundleDependencies")
.or_else(|| json.get(b"bundledDependencies"))
{
match &bundled_deps_expr.data {
ExprData::EBoolean(boolean) => {
bundle_all_deps = boolean.value;
}
ExprData::EArray(arr) => {
for item in arr.slice() {
let Some(s) = item.as_utf8(&bump) else {
continue;
};
bundled_deps.insert(s)?;
}
}
_ => {}
}
}
}
total_dependencies_count = 0;
// PERF(port): was `inline for` — profile if hot.
for group in &dependency_groups {
if group.behavior.is_workspace() {
let mut seen_workspace_names: ArrayHashMap<
TruncatedPackageNameHash,
(),
ArrayIdentityContext,
> = ArrayHashMap::default();
// defer seen_workspace_names.deinit(allocator); — Drop handles it
for (entry, path_) in workspace_names
.values()
.iter()
.zip(workspace_names.keys().iter())
{
// workspace names from their package jsons. duplicates not allowed
let gop = seen_workspace_names
.get_or_put(semver::string::Builder::string_hash(&entry.name)
as TruncatedPackageNameHash)?;
if gop.found_existing {
// this path does alot of extra work to format the error message
// but this is ok because the install is going to fail anyways, so this
// has zero effect on the happy path.
let mut cwd_buf = PathBuffer::uninit();
// Zig `bun.getcwd` returned the slice; Rust port returns
// the byte length — slice the buffer ourselves.
let cwd_len = bun_sys::getcwd(&mut cwd_buf.0[..])?;
let cwd: &[u8] = &cwd_buf.0[..cwd_len];
let num_notes = 'count: {
let mut i: usize = 0;
for value in workspace_names.values() {
if strings::eql_long(&value.name, &entry.name, true) {
i += 1;
}
}
break 'count i;
};
let notes = 'notes: {
let mut notes: Vec<bun_ast::Data> = Vec::with_capacity(num_notes);
let mut i: usize = 0;
for (value, note_path) in workspace_names
.values()
.iter()
.zip(workspace_names.keys().iter())
{
if note_path.as_ptr() == path_.as_ptr() {
continue;
}
if strings::eql_long(&value.name, &entry.name, true) {
let note_abs_path = bun_core::ZBox::from_bytes(
resolve_path::join_abs_string_z::<path::platform::Auto>(
cwd,
&[note_path, b"package.json"],
)
.as_bytes(),
);
let note_src = match bun_ast::to_source(
¬e_abs_path,
Default::default(),
) {
Ok(s) => s,
Err(_) => bun_ast::Source::init_empty_file_interned(
note_abs_path.as_bytes(),
),
};
// `Location::init_or_null` borrows `file` from
// `note_src.path.text`, which itself borrows
// `note_abs_path`; both drop before the log is
// printed. `Location::clone` deep-copies `file`
// into a `Cow::Owned`, matching the Zig
// `allocator.dupeZ` lifetime.
notes.push(bun_ast::Data {
text: b"Package name is also declared here".to_vec().into(),
location: bun_ast::Location::init_or_null(
Some(¬e_src),
note_src.range_of_string(value.name_loc),
)
.as_ref()
.cloned(),
..Default::default()
});
i += 1;
}
}
notes.truncate(i);
break 'notes notes;
};
let abs_path = bun_core::ZBox::from_bytes(
resolve_path::join_abs_string_z::<path::platform::Auto>(
cwd,
&[path_, b"package.json"],
)
.as_bytes(),
);
let src = match bun_ast::to_source(&abs_path, Default::default()) {
Ok(s) => s,
Err(_) => bun_ast::Source::init_empty_file_interned(abs_path.as_bytes()),
};
let _ = log.add_range_error_fmt_with_notes(
Some(&src),
src.range_of_string(entry.name_loc),
notes.into(),
format_args!(
"Workspace name \"{}\" already exists",
bstr::BStr::new(&entry.name),
),
);
return Err(bun_core::err!("InstallFailed"));
}
let external_name = string_builder.append::<ExternalString>(&entry.name);
let workspace_version = 'brk: {
if let Some(version_string) = &entry.version {
let external_version =
string_builder.append::<ExternalString>(version_string);
// allocator.free(version_string); — Drop handles it (Box<[u8]>)
let sliced = external_version
.value
.sliced(string_builder.string_bytes.as_slice());
let result = SemverVersion::parse(sliced);
if result.valid && result.wildcard == Wildcard::None {
break 'brk Some(result.version.min());
}
}
None
};
if let Some(dep_) = Self::parse_dependency(
&mut lockfile.workspace_paths,
&mut lockfile.workspace_versions,
&mut lockfile.scratch.duplicate_checker_map,
pm,
log,
source,
group,
&mut string_builder,
FEATURES,
package_dependencies.as_mut_slice(),
total_dependencies_count,
Some(dependency::version::Tag::Workspace),
workspace_version,
external_name,
path_,
bun_ast::Loc::EMPTY,
bun_ast::Loc::EMPTY,
)? {
let mut dep = dep_;
if group.behavior.is_peer()
&& optional_peer_dependencies.swap_remove(&external_name.hash)
{
dep.behavior = dep.behavior.add(Behavior::OPTIONAL);
}
// `parse_dependency` was called with `Tag::Workspace`,
// so the workspace accessor's tag-check holds.
let ws_path = *dep.version.workspace();
package_dependencies.push(dep);
total_dependencies_count += 1;
lockfile.workspace_paths.put(external_name.hash, ws_path)?;
if let Some(version) = workspace_version {
lockfile
.workspace_versions
.put(external_name.hash, version)?;
}
}
}
} else {
if let Some(dependencies_q) = json.as_property(group.prop) {
match &dependencies_q.expr.data {
ExprData::EObject(obj) => {
for item in obj.properties.slice() {
let key = item.key.expect("infallible: prop has key");
let value = item.value.expect("infallible: prop has value");
let external_name = string_builder
.append::<ExternalString>(key.as_utf8(&bump).unwrap());
let version = value.as_utf8(&bump).unwrap_or(b"");
if let Some(dep_) = Self::parse_dependency(
&mut lockfile.workspace_paths,
&mut lockfile.workspace_versions,
&mut lockfile.scratch.duplicate_checker_map,
pm,
log,
source,
group,
&mut string_builder,
FEATURES,
package_dependencies.as_mut_slice(),
total_dependencies_count,
None,
None,
external_name,
version,
key.loc,
value.loc,
)? {
let mut dep = dep_;
// swapRemove (not contains): drain names that
// have a real `peerDependencies` entry so the
// meta-only synthesis pass below only sees
// names that appear *only* in
// `peerDependenciesMeta`.
if group.behavior.is_peer()
&& optional_peer_dependencies
.swap_remove(&external_name.hash)
{
dep.behavior.insert(Behavior::OPTIONAL);
}
if bundle_all_deps
|| bundled_deps.contains(
dep.name.slice(string_builder.string_bytes.as_slice()),
)
{
dep.behavior.insert(Behavior::BUNDLED);
}
package_dependencies.push(dep);
total_dependencies_count += 1;
}
}
}
_ => unreachable!(),
}
}
}
}
// Anything left in `optional_peer_dependencies` was listed only in
// `peerDependenciesMeta`. Synthesise an optional peer dep with
// version `"*"` so resolution can pick up a sibling install when
// one exists (matching pnpm/yarn). Webpack relies on this for
// `webpack-cli`, which it lists in meta but not in
// `peerDependencies`.
let meta_only = optional_peer_dependencies.iterator();
for entry in meta_only {
let external_name = string_builder.append::<ExternalString>(*entry.value_ptr);
if let Some(dep_) = Self::parse_dependency(
&mut lockfile.workspace_paths,
&mut lockfile.workspace_versions,
&mut lockfile.scratch.duplicate_checker_map,
pm,
log,
source,
&DependencyGroup::PEER,
&mut string_builder,
FEATURES,
package_dependencies.as_mut_slice(),
total_dependencies_count,
None,
None,
external_name,
b"*",
bun_ast::Loc::EMPTY,
bun_ast::Loc::EMPTY,
)? {
let mut dep = dep_;
dep.behavior.insert(Behavior::OPTIONAL);
package_dependencies.push(dep);
total_dependencies_count += 1;
}
}
debug_assert_eq!(
package_dependencies.len(),
total_dependencies_count as usize
);
{
let buf = string_builder.string_bytes.as_slice();
package_dependencies.sort_by(|a, b| dep_sort_cmp(buf, a, b));
}
self.dependencies.off = off as u32;
self.dependencies.len = total_dependencies_count;
// PackageIDSlice and DependencySlice are both `ExternalSlice<_>` — same
// `{off: u32, len: u32}` window into different backing buffers.
self.resolutions =
lockfile::PackageIDSlice::new(self.dependencies.off, self.dependencies.len);
// Prior len == `off` (asserted above), so `resize` fills exactly
// `[off..total_len]` — equivalent to the old `set_len` + `fill`.
lockfile
.buffers
.resolutions
.resize(total_len, invalid_package_id);
let new_len = off + total_dependencies_count as usize;
// Capacity for `[off..total_len]` was reserved above; `append` is a
// single memcpy into it (no realloc). All `?`-points are past, so the
// `dependencies.len() == resolutions.len()` invariant is committed
// together with the `resolutions` resize/truncate that brackets this.
debug_assert_eq!(lockfile.buffers.dependencies.len(), off);
lockfile
.buffers
.dependencies
.append(&mut package_dependencies);
debug_assert_eq!(lockfile.buffers.dependencies.len(), new_len);
lockfile.buffers.resolutions.truncate(new_len);
// This function depends on package.dependencies being set, so it is done at the very end.
if FEATURES.is_main {
lockfile.overrides.parse_append(
pm,
lockfile.buffers.dependencies.as_slice(),
self,
log,
source,
json,
&mut string_builder,
)?;
let mut found_any_catalog_or_catalog_object = false;
let mut has_workspaces = false;
if let Some(workspaces_expr) = json.get(b"workspaces") {
found_any_catalog_or_catalog_object = lockfile.catalogs.parse_append(
pm,
log,
source,
workspaces_expr,
&mut string_builder,
)?;
has_workspaces = true;
}
// `"workspaces"` being an object instead of an array is sometimes
// unexpected to people. therefore if you also are using workspaces,
// allow "catalog" and "catalogs" in top-level "package.json"
// so it's easier to guess.
if !found_any_catalog_or_catalog_object && has_workspaces {
let _ =
lockfile
.catalogs
.parse_append(pm, log, source, json, &mut string_builder)?;
}
}
string_builder.clamp();
Ok(())
}
}
pub type List<SemverIntType> = MultiArrayList<Package<SemverIntType>>;
// ─── Serializer ──────────────────────────────────────────────────────────────
pub mod serializer {
use super::*;
/// Number of columns in the on-disk package table. Zig: `sizes.Types.len`.
pub(crate) const FIELD_COUNT: usize = PackageField::ALL.len();
// which is unused on the load/save paths we port.)
pub struct Sizes {
pub bytes: [usize; FIELD_COUNT],
pub fields: [usize; FIELD_COUNT],
}
// Zig: `const FieldsEnum = @typeInfo(List.Field).@"enum";`
// → `PackageField::ALL` (declaration order, same as the MultiArrayList
// field enum Zig reflects over).
// Zig: `const AlignmentType = sizes.Types[sizes.fields[0]];`
// Unused by save/load (the live aligner uses `@TypeOf(list.bytes)`), so
// it is intentionally not ported.
pub fn save<SemverIntType: VersionInt, S>(
list: &List<SemverIntType>,
stream: &mut S,
) -> Result<(), bun_core::Error>
where
// PORT NOTE: Zig threaded a separate `stream` (anytype) and `writer` over
// the same buffer. Two `&mut` to one object is UB in Rust regardless of
// access order, so the port collapses both roles onto one type —
// `Serializer::StreamType` impls both `PositionalStream` and
// `bun_io::Write`.
S: PositionalStream + bun_io::Write,
{
// TODO(port): narrow error set
stream.write_int_le::<u64>(list.len() as u64)?;
// TODO(port): @alignOf(@TypeOf(list.bytes)) — needs concrete type from MultiArrayList.
stream.write_int_le::<u64>(mem::align_of::<*mut u8>() as u64)?;
stream.write_int_le::<u64>(FIELD_COUNT as u64)?;
let begin_at = stream.get_pos()?;
stream.write_int_le::<u64>(0)?;
let end_at = stream.get_pos()?;
stream.write_int_le::<u64>(0)?;
// TODO(port): Aligner.write needs the bytes-pointer alignment type.
let pos = stream.get_pos()? as u64;
let _ = Aligner::write::<*mut u8, _>(&mut *stream, pos)?;
let really_begin_at = stream.get_pos()?;
let mut sliced = list.slice();
// PERF(port): was `inline for (FieldsEnum.fields)` — profile if hot.
for field in PackageField::ALL {
// SAFETY: each `PackageField` discriminant corresponds to a column
// whose element size matches `SIZES_BYTES[field as usize]`; we
// address the column as raw bytes for serialisation.
let bytes: &[u8] = unsafe {
let _n = list.len();
let sz =
bun_collections::multi_array_list::Slice::<Package<SemverIntType>>::field_size(
field as usize,
);
{
let _ = sz;
&*sliced.column_bytes_mut(field as usize)
}
};
#[cfg(debug_assertions)]
{
bun_output::scoped_log!(
Lockfile,
"save(\"{}\") = {} bytes",
bstr::BStr::new(field.name()),
bytes.len(),
);
}
// TODO(port): assert_no_uninitialized_padding once a typed accessor
// is exposed; for now `Package`'s field types are all `#[repr(C)]`
// with explicit padding zeroed by their `Default`/`init` paths.
if matches!(field, PackageField::Resolution) {
// copy each resolution to make sure the union is zero initialized
let resolutions: &[Resolution<SemverIntType>] =
sliced.items::<"resolution", Resolution<SemverIntType>>();
for val in resolutions {
// `ResolutionType::copy` builds a fresh zero-initialised
// `Resolution` and writes only the active union member,
// matching Zig `val.copy()`. A bare `*val` would serialise
// garbage in the inactive union bytes (non-deterministic
// lockfile output).
let copy = val.copy();
// SAFETY: Resolution is #[repr(C)] POD; reading raw bytes is sound.
stream.write_all(unsafe {
bun_core::ffi::slice(
(&raw const copy).cast::<u8>(),
mem::size_of_val(©),
)
})?;
}
} else {
stream.write_all(bytes)?;
}
}
let really_end_at = stream.get_pos()?;
let _ = stream.pwrite(&really_begin_at.to_ne_bytes(), begin_at);
let _ = stream.pwrite(&really_end_at.to_ne_bytes(), end_at);
Ok(())
}
#[derive(Default)]
pub(crate) struct PackagesLoadResult<SemverIntType: VersionInt> {
pub list: List<SemverIntType>,
pub needs_update: bool,
}
// PORT NOTE: Zig parameterised on `SemverIntType`, but the v2-migration arm
// below hard-codes `u32 → u64` (`VersionedURL.migrate()` returns `<u64>`).
// The only caller (`bun.lockb.rs`) instantiates at `u64`, so bind concretely
// instead of carrying a phantom generic that can't typecheck the migrate arm.
pub(crate) fn load(
stream: &mut Stream,
end: usize,
migrate_from_v2: bool,
) -> Result<PackagesLoadResult<u64>, bun_core::Error> {
type SemverIntType = u64;
// TODO(port): narrow error set
let reader = stream.reader();
let list_len = reader.read_int_le::<u64>()?;
if list_len > u32::MAX as u64 - 1 {
return Err(bun_core::err!(
"Lockfile validation failed: list is impossibly long"
));
}
let input_alignment = reader.read_int_le::<u64>()?;
let mut list = List::<SemverIntType>::default();
// TODO(port): @alignOf(@TypeOf(list.bytes)) — needs MultiArrayList bytes ptr type.
let expected_alignment = mem::align_of::<*mut u8>() as u64;
if expected_alignment != input_alignment {
return Err(bun_core::err!(
"Lockfile validation failed: alignment mismatch"
));
}
let field_count = reader.read_int_le::<u64>()? as usize;
match field_count {
FIELD_COUNT => {}
// "scripts" field is absent before v0.6.8
// we will back-fill from each package.json
n if n == FIELD_COUNT - 1 => {}
_ => {
return Err(bun_core::err!(
"Lockfile validation failed: unexpected number of package fields"
));
}
}
let begin_at = reader.read_int_le::<u64>()? as usize;
let end_at = reader.read_int_le::<u64>()? as usize;
if begin_at > end || end_at > end || begin_at > end_at {
return Err(bun_core::err!(
"Lockfile validation failed: invalid package list range"
));
}
stream.pos = begin_at;
list.ensure_total_capacity(list_len as usize)?;
let mut needs_update = false;
if migrate_from_v2 {
type OldPackageV2 = Package<u32>;
let mut list_for_migrating_from_v2 = <List<u32>>::default();
// defer list_for_migrating_from_v2.deinit(allocator); — Drop handles it
list_for_migrating_from_v2.ensure_total_capacity(list_len as usize)?;
// SAFETY: capacity reserved above; `load_fields` writes every column.
unsafe { list_for_migrating_from_v2.set_len(list_len as usize) };
load_fields::<u32>(
stream,
end_at as u64,
&mut list_for_migrating_from_v2,
&mut needs_update,
)?;
for pkg_id_ in 0..list_for_migrating_from_v2.len() {
let pkg_id: PackageID = PackageID::try_from(pkg_id_).expect("int cast");
let _ = pkg_id;
let old: OldPackageV2 = *list_for_migrating_from_v2.get(pkg_id_);
let new = Package::<SemverIntType> {
name: old.name,
name_hash: old.name_hash,
meta: old.meta,
bin: old.bin,
dependencies: old.dependencies,
resolutions: old.resolutions,
scripts: old.scripts,
resolution: match old.resolution.tag {
ResolutionTag::Uninitialized => {
Resolution::init(TaggedValue::Uninitialized)
}
ResolutionTag::Root => Resolution::init(TaggedValue::Root),
ResolutionTag::Npm => {
Resolution::init(TaggedValue::Npm(old.resolution.npm().migrate()))
}
ResolutionTag::Folder => {
Resolution::init(TaggedValue::Folder(*old.resolution.folder()))
}
ResolutionTag::LocalTarball => Resolution::init(TaggedValue::LocalTarball(
*old.resolution.local_tarball(),
)),
ResolutionTag::Github => {
Resolution::init(TaggedValue::Github(*old.resolution.github()))
}
ResolutionTag::Git => {
Resolution::init(TaggedValue::Git(*old.resolution.git()))
}
ResolutionTag::Symlink => {
Resolution::init(TaggedValue::Symlink(*old.resolution.symlink()))
}
ResolutionTag::Workspace => {
Resolution::init(TaggedValue::Workspace(*old.resolution.workspace()))
}
ResolutionTag::RemoteTarball => Resolution::init(
TaggedValue::RemoteTarball(*old.resolution.remote_tarball()),
),
ResolutionTag::SingleFileModule => Resolution::init(
TaggedValue::SingleFileModule(*old.resolution.single_file_module()),
),
_ => Resolution::init(TaggedValue::Uninitialized),
},
};
// PERF(port): was assume_capacity
list.append(new)?;
}
} else {
// SAFETY: capacity reserved above; `load_fields` writes every column.
unsafe { list.set_len(list_len as usize) };
load_fields::<SemverIntType>(stream, end_at as u64, &mut list, &mut needs_update)?;
}
Ok(PackagesLoadResult { list, needs_update })
}
fn load_fields<SemverIntType: VersionInt>(
stream: &mut Stream,
end_at: u64,
list: &mut List<SemverIntType>,
needs_update: &mut bool,
) -> Result<(), bun_core::Error> {
// TODO(port): narrow error set
let _n = list.len();
let mut sliced = list.slice();
// PERF(port): was `inline for (FieldsEnum.fields)` — profile if hot.
for field in PackageField::ALL {
let sz = bun_collections::multi_array_list::Slice::<Package<SemverIntType>>::field_size(
field as usize,
);
// SAFETY: `items_raw` returns a column pointer with `n` elements of
// `sz` bytes each; the byte view is used solely for memcpy from the
// serialised lockfile stream.
let bytes: &mut [u8] = unsafe {
{
let _ = sz;
sliced.column_bytes_mut(field as usize)
}
};
// TODO(port): assert_no_uninitialized_padding once a typed accessor lands.
let end_pos = stream.pos + bytes.len();
if end_pos as u64 <= end_at {
let src = &stream.buffer[stream.pos..stream.pos + bytes.len()];
if matches!(field, PackageField::Resolution) {
// Validate the tag discriminant on the *raw stream bytes*
// before they are copied into the typed column. `ResolutionTag`
// is a `#[repr(u8)]` enum with non-contiguous discriminants
// (0,1,2,4,8,16,32,64,72,80,100); copying an out-of-range byte
// into `ResolutionType.tag` and then reading it would be
// immediate UB, and a `matches!` over all 11 typed variants is
// provably exhaustive and would be optimized away. Check the
// raw u8 here. Layout: `ResolutionType` is `#[repr(C)]
// { tag: Tag, _padding: [u8; 7], value: ... }`, so the
// discriminant is the first byte of each element.
let stride = mem::size_of::<ResolutionType<SemverIntType>>();
debug_assert!(stride != 0 && src.len().is_multiple_of(stride));
for raw in src.chunks_exact(stride) {
if !matches!(raw[0], 0 | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 72 | 80 | 100) {
return Err(bun_core::err!(
"Lockfile validation failed: invalid resolution tag"
));
}
}
}
if matches!(field, PackageField::Meta) {
// Same hardening as `Resolution` above: `Meta` embeds two
// `#[repr(u8)]` enums (`Origin` = 0..=2 and
// `HasInstallScript` = 0..=2). Copying an out-of-range byte
// into either field and reading it back as the enum would
// be immediate UB, so check the raw stream bytes first.
let stride = mem::size_of::<Meta>();
let origin_at = mem::offset_of!(Meta, origin);
let install_script_at = mem::offset_of!(Meta, has_install_script);
debug_assert!(stride != 0 && src.len().is_multiple_of(stride));
for raw in src.chunks_exact(stride) {
if !matches!(raw[origin_at], 0..=2)
|| !matches!(raw[install_script_at], 0..=2)
{
return Err(bun_core::err!(
"Lockfile validation failed: invalid package meta"
));
}
}
}
if matches!(field, PackageField::Bin) {
// `Bin.tag` is a `#[repr(u8)]` enum with discriminants
// 0..=4; validate it the same way before the copy.
let stride = mem::size_of::<Bin>();
let tag_at = mem::offset_of!(Bin, tag);
debug_assert!(stride != 0 && src.len().is_multiple_of(stride));
for raw in src.chunks_exact(stride) {
if !matches!(raw[tag_at], 0..=4) {
return Err(bun_core::err!(
"Lockfile validation failed: invalid bin tag"
));
}
}
}
bytes.copy_from_slice(src);
stream.pos = end_pos;
if matches!(field, PackageField::Meta) {
// need to check if any values were created from an older version of bun
// (currently just `has_install_script`). If any are found, the values need
// to be updated before saving the lockfile.
let metas: &mut [Meta] = sliced.items_mut::<"meta", Meta>();
for meta in metas {
if meta.needs_update() {
*needs_update = true;
break;
}
}
}
} else if matches!(field, PackageField::Scripts) {
bytes.fill(0);
} else {
return Err(bun_core::err!(
"Lockfile validation failed: invalid package list range"
));
}
}
Ok(())
}
}
pub use serializer as Serializer;
// ported from: src/install/lockfile/Package.zig