aboutsummaryrefslogtreecommitdiff
path: root/src/resolver/resolver.zig
blob: b104823b0a72bed04cd84dcade737821b04ab794 (plain) (blame)
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
usingnamespace @import("../global.zig");
const ast = @import("../import_record.zig");
const logger = @import("../logger.zig");
const options = @import("../options.zig");
const Fs = @import("../fs.zig");
const std = @import("std");
const cache = @import("../cache.zig");
const sync = @import("../sync.zig");
const TSConfigJSON = @import("./tsconfig_json.zig").TSConfigJSON;
const PackageJSON = @import("./package_json.zig").PackageJSON;
usingnamespace @import("./data_url.zig");
pub const DirInfo = @import("./dir_info.zig");
const Expr = @import("../js_ast.zig").Expr;
const HTTPWatcher = @import("../http.zig").Watcher;
const Wyhash = std.hash.Wyhash;

const hash_map_v2 = @import("../hash_map_v2.zig");
const Mutex = @import("../lock.zig").Lock;
const StringBoolMap = std.StringHashMap(bool);

const allocators = @import("../allocators.zig");

const Path = Fs.Path;
const NodeModuleBundle = @import("../node_module_bundle.zig").NodeModuleBundle;

pub fn isPackagePath(path: string) bool {
    // this could probably be flattened into something more optimized
    return path[0] != '/' and !strings.startsWith(path, "./") and !strings.startsWith(path, "../") and !strings.eql(path, ".") and !strings.eql(path, "..");
}

pub const SideEffectsData = struct {
    source: *logger.Source,
    range: logger.Range,

    // If true, "sideEffects" was an array. If false, "sideEffects" was false.
    is_side_effects_array_in_json: bool = false,
};

pub const TemporaryBuffer = struct {
    pub threadlocal var ExtensionPathBuf: [512]u8 = undefined;
    pub threadlocal var TSConfigMatchStarBuf: [512]u8 = undefined;
    pub threadlocal var TSConfigMatchPathBuf: [512]u8 = undefined;
    pub threadlocal var TSConfigMatchFullBuf: [512]u8 = undefined;
};

pub const PathPair = struct {
    primary: Path,
    secondary: ?Path = null,

    pub const Iter = struct {
        index: u2,
        ctx: *PathPair,
        pub fn next(i: *Iter) ?*Path {
            const ind = i.index;
            i.index += 1;

            switch (ind) {
                0 => return &i.ctx.primary,
                1 => return if (i.ctx.secondary) |*sec| sec else null,
                else => return null,
            }
        }
    };

    pub fn iter(p: *PathPair) Iter {
        return Iter{ .ctx = p, .index = 0 };
    }
};

pub const Result = struct {
    path_pair: PathPair,

    jsx: options.JSX.Pragma = options.JSX.Pragma{},

    package_json: ?*PackageJSON = null,

    is_external: bool = false,

    // This is true when the package was loaded from within the node_modules directory.
    is_from_node_modules: bool = false,

    diff_case: ?Fs.FileSystem.Entry.Lookup.DifferentCase = null,

    // If present, any ES6 imports to this file can be considered to have no side
    // effects. This means they should be removed if unused.
    primary_side_effects_data: ?SideEffectsData = null,

    // If true, the class field transform should use Object.defineProperty().
    use_define_for_class_fields_ts: ?bool = null,

    // If true, unused imports are retained in TypeScript code. This matches the
    // behavior of the "importsNotUsedAsValues" field in "tsconfig.json" when the
    // value is not "remove".
    preserve_unused_imports_ts: bool = false,

    // This is the "type" field from "package.json"
    module_type: options.ModuleType = options.ModuleType.unknown,

    debug_meta: ?DebugMeta = null,

    dirname_fd: StoredFileDescriptorType = 0,
    file_fd: StoredFileDescriptorType = 0,
    import_kind: ast.ImportKind = undefined,

    // remember: non-node_modules can have package.json
    // checking package.json may not be relevant
    pub fn isLikelyNodeModule(this: *const Result) bool {
        const dir = this.path_pair.primary.name.dirWithTrailingSlash();
        return strings.indexOf(dir, "/node_modules/") != null;
    }

    // Most NPM modules are CommonJS
    // If unspecified, assume CommonJS.
    // If internal app code, assume ESM.
    pub fn shouldAssumeCommonJS(r: *const Result, import_record: *const ast.ImportRecord) bool {
        if (import_record.kind == .require or import_record.kind == .require_resolve or r.module_type == .cjs) {
            return true;
        }

        if (r.module_type == .esm) {
            return false;
        }

        // If we rely just on isPackagePath, we mess up tsconfig.json baseUrl paths.
        return r.isLikelyNodeModule();
    }

    pub const DebugMeta = struct {
        notes: std.ArrayList(logger.Data),
        suggestion_text: string = "",
        suggestion_message: string = "",

        pub fn init(allocator: *std.mem.Allocator) DebugMeta {
            return DebugMeta{ .notes = std.ArrayList(logger.Data).init(allocator) };
        }

        pub fn logErrorMsg(m: *DebugMeta, log: *logger.Log, _source: ?*const logger.Source, r: logger.Range, comptime fmt: string, args: anytype) !void {
            if (_source != null and m.suggestion_message.len > 0) {
                const data = logger.rangeData(_source.?, r, m.suggestion_message);
                data.location.?.suggestion = m.suggestion_text;
                try m.notes.append(data);
            }

            try log.addMsg(Msg{
                .kind = .err,
                .data = logger.rangeData(_source, r, std.fmt.allocPrint(m.notes.allocator, fmt, args)),
                .notes = m.toOwnedSlice(),
            });
        }
    };
};

pub const DirEntryResolveQueueItem = struct {
    result: allocators.Result,
    unsafe_path: string,
    safe_path: string = "",
    fd: StoredFileDescriptorType = 0,
};
threadlocal var _dir_entry_paths_to_resolve: [256]DirEntryResolveQueueItem = undefined;
threadlocal var _open_dirs: [256]std.fs.Dir = undefined;
threadlocal var resolve_without_remapping_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var index_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var dir_info_uncached_filename_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var tsconfig_base_url_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var relative_abs_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var load_as_file_or_directory_via_tsconfig_base_path: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var node_modules_check_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var field_abs_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
threadlocal var tsconfig_path_abs_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;

pub const DebugLogs = struct {
    what: string = "",
    indent: MutableString,
    notes: std.ArrayList(logger.Data),

    pub const FlushMode = enum { fail, success };

    pub fn init(allocator: *std.mem.Allocator) !DebugLogs {
        var mutable = try MutableString.init(allocator, 0);
        return DebugLogs{
            .indent = mutable,
            .notes = std.ArrayList(logger.Data).init(allocator),
        };
    }

    pub fn deinit(d: DebugLogs) void {
        var allocator = d.notes.allocator;
        d.notes.deinit();
        // d.indent.deinit();
    }

    pub fn increaseIndent(d: *DebugLogs) !void {
        try d.indent.append(" ");
    }

    pub fn decreaseIndent(d: *DebugLogs) !void {
        d.indent.list.shrinkRetainingCapacity(d.indent.list.items.len - 1);
    }

    pub fn addNote(d: *DebugLogs, _text: string) !void {
        var text = _text;
        const len = d.indent.len();
        if (len > 0) {
            var __text = try d.notes.allocator.alloc(u8, text.len + len);
            std.mem.copy(u8, __text, d.indent.list.items);
            std.mem.copy(u8, __text[len..__text.len], _text);
            d.notes.allocator.free(_text);
        }

        try d.notes.append(logger.rangeData(null, logger.Range.None, text));
    }

    pub fn addNoteFmt(d: *DebugLogs, comptime fmt: string, args: anytype) !void {
        return try d.addNote(try std.fmt.allocPrint(d.notes.allocator, fmt, args));
    }
};

pub const TSConfigExtender = struct {
    visited: *StringBoolMap,
    file_dir: string,
    r: *ThisResolver,

    pub fn extends(ctx: *TSConfigExtender, ext: String, range: logger.Range) ?*TSConfigJSON {
        unreachable;
        // if (isPackagePath(extends)) {
        //     // // If this is a package path, try to resolve it to a "node_modules"
        //     // // folder. This doesn't use the normal node module resolution algorithm
        //     // // both because it's different (e.g. we don't want to match a directory)
        //     // // and because it would deadlock since we're currently in the middle of
        //     // // populating the directory info cache.
        //     // var current = ctx.file_dir;
        //     // while (true) {
        //     //     // Skip "node_modules" folders
        //     //     if (!strings.eql(std.fs.path.basename(current), "node_modules")) {
        //     //         var paths1 = [_]string{ current, "node_modules", extends };
        //     //         var join1 = r.fs.absAlloc(ctx.r.allocator, &paths1) catch unreachable;
        //     //         const res = ctx.r.parseTSConfig(join1, ctx.1) catch |err| {
        //     //             if (err == error.ENOENT) {
        //     //                 continue;
        //     //             } else if (err == error.ParseErrorImportCycle) {} else if (err != error.ParseErrorAlreadyLogged) {}
        //     //             return null;
        //     //         };
        //     //         return res;

        //     //     }
        //     // }
        // }
    }
};

pub const MatchResult = struct {
    path_pair: PathPair,
    dirname_fd: StoredFileDescriptorType = 0,
    file_fd: StoredFileDescriptorType = 0,
    is_node_module: bool = false,
    package_json: ?*PackageJSON = null,
    diff_case: ?Fs.FileSystem.Entry.Lookup.DifferentCase = null,
};

pub const LoadResult = struct {
    path: string,
    diff_case: ?Fs.FileSystem.Entry.Lookup.DifferentCase,
    dirname_fd: StoredFileDescriptorType = 0,
};

// This is a global so even if multiple resolvers are created, the mutex will still work
var resolver_Mutex: Mutex = undefined;
var resolver_Mutex_loaded: bool = false;
// TODO:
// - Fix "browser" field mapping
// - Consider removing the string list abstraction?
pub fn NewResolver(cache_files: bool) type {
    const CacheSet = if (cache_files) cache.Cache.Set else cache.ServeCache.Set;

    return struct {
        const ThisResolver = @This();
        opts: options.BundleOptions,
        fs: *Fs.FileSystem,
        log: *logger.Log,
        allocator: *std.mem.Allocator,
        node_module_bundle: ?*NodeModuleBundle,

        debug_logs: ?DebugLogs = null,
        elapsed: i128 = 0, // tracing

        onStartWatchingDirectory: ?fn (*HTTPWatcher, dir_path: string, dir_fd: StoredFileDescriptorType) void = null,
        onStartWatchingDirectoryCtx: ?*HTTPWatcher = null,

        caches: CacheSet,

        // These are sets that represent various conditions for the "exports" field
        // in package.json.
        // esm_conditions_default: std.StringHashMap(bool),
        // esm_conditions_import: std.StringHashMap(bool),
        // esm_conditions_require: std.StringHashMap(bool),

        // A special filtered import order for CSS "@import" imports.
        //
        // The "resolve extensions" setting determines the order of implicit
        // extensions to try when resolving imports with the extension omitted.
        // Sometimes people create a JavaScript/TypeScript file and a CSS file with
        // the same name when they create a component. At a high level, users expect
        // implicit extensions to resolve to the JS file when being imported from JS
        // and to resolve to the CSS file when being imported from CSS.
        //
        // Different bundlers handle this in different ways. Parcel handles this by
        // having the resolver prefer the same extension as the importing file in
        // front of the configured "resolve extensions" order. Webpack's "css-loader"
        // plugin just explicitly configures a special "resolve extensions" order
        // consisting of only ".css" for CSS files.
        //
        // It's unclear what behavior is best here. What we currently do is to create
        // a special filtered version of the configured "resolve extensions" order
        // for CSS files that filters out any extension that has been explicitly
        // configured with a non-CSS loader. This still gives users control over the
        // order but avoids the scenario where we match an import in a CSS file to a
        // JavaScript-related file. It's probably not perfect with plugins in the
        // picture but it's better than some alternatives and probably pretty good.
        // atImportExtensionOrder []string

        // This mutex serves two purposes. First of all, it guards access to "dirCache"
        // which is potentially mutated during path resolution. But this mutex is also
        // necessary for performance. The "React admin" benchmark mysteriously runs
        // twice as fast when this mutex is locked around the whole resolve operation
        // instead of around individual accesses to "dirCache". For some reason,
        // reducing parallelism in the resolver helps the rest of the bundler go
        // faster. I'm not sure why this is but please don't change this unless you
        // do a lot of testing with various benchmarks and there aren't any regressions.
        mutex: *Mutex,

        // This cache maps a directory path to information about that directory and
        // all parent directories
        dir_cache: *DirInfo.HashMap,

        pub fn init1(
            allocator: *std.mem.Allocator,
            log: *logger.Log,
            _fs: *Fs.FileSystem,
            opts: options.BundleOptions,
        ) ThisResolver {
            if (!resolver_Mutex_loaded) {
                resolver_Mutex = Mutex.init();
                resolver_Mutex_loaded = true;
            }
            return ThisResolver{
                .allocator = allocator,
                .dir_cache = DirInfo.HashMap.init(allocator),
                .mutex = &resolver_Mutex,
                .caches = CacheSet.init(allocator),
                .opts = opts,
                .fs = _fs,
                .node_module_bundle = opts.node_modules_bundle,
                .log = log,
            };
        }

        pub fn isExternalPattern(r: *ThisResolver, import_path: string) bool {
            for (r.opts.external.patterns) |pattern| {
                if (import_path.len >= pattern.prefix.len + pattern.suffix.len and (strings.startsWith(
                    import_path,
                    pattern.prefix,
                ) and strings.endsWith(
                    import_path,
                    pattern.suffix,
                ))) {
                    return true;
                }
            }
            return false;
        }

        pub fn flushDebugLogs(r: *ThisResolver, flush_mode: DebugLogs.FlushMode) !void {
            if (r.debug_logs) |*debug| {
                if (flush_mode == DebugLogs.FlushMode.fail) {
                    try r.log.addRangeDebugWithNotes(null, logger.Range{ .loc = logger.Loc{} }, debug.what, debug.notes.toOwnedSlice());
                } else if (@enumToInt(r.log.level) <= @enumToInt(logger.Log.Level.verbose)) {
                    try r.log.addVerboseWithNotes(null, logger.Loc.Empty, debug.what, debug.notes.toOwnedSlice());
                }
            }
        }
        var tracing_start: i128 = if (FeatureFlags.tracing) 0 else undefined;

        pub const bunFrameworkPackagePrefix = "bun-framework-";
        pub fn resolveFramework(
            r: *ThisResolver,
            package: string,
            pair: *PackageJSON.FrameworkRouterPair,
            comptime preference: PackageJSON.LoadFramework,
            comptime load_defines: bool,
        ) !void {

            // We want to enable developers to integrate frameworks without waiting on official support.
            // But, we still want the command to do the actual framework integration to be succint
            // This lets users type "--use next" instead of "--use bun-framework-next"
            // If they're using a local file path, we skip this.
            if (isPackagePath(package)) {
                var prefixed_package_buf: [512]u8 = undefined;
                // Prevent the extra lookup if the package is already prefixed, i.e. avoid "bun-framework-next-bun-framework-next"
                if (strings.startsWith(package, bunFrameworkPackagePrefix) or package.len + bunFrameworkPackagePrefix.len >= prefixed_package_buf.len) {
                    return try r._resolveFramework(package, pair, preference, load_defines);
                }

                prefixed_package_buf[0..bunFrameworkPackagePrefix.len].* = bunFrameworkPackagePrefix.*;
                std.mem.copy(u8, prefixed_package_buf[bunFrameworkPackagePrefix.len..], package);
                return r._resolveFramework(prefixed_package_buf[0 .. bunFrameworkPackagePrefix.len + package.len], pair, preference, load_defines) catch |err| {
                    switch (err) {
                        error.ModuleNotFound => {
                            return try r._resolveFramework(package, pair, preference, load_defines);
                        },
                        else => {
                            return err;
                        },
                    }
                };
            }

            return try r._resolveFramework(package, pair, preference, load_defines);
        }

        fn _resolveFramework(
            r: *ThisResolver,
            package: string,
            pair: *PackageJSON.FrameworkRouterPair,
            comptime preference: PackageJSON.LoadFramework,
            comptime load_defines: bool,
        ) !void {

            // TODO: make this only parse package.json once
            var result = try r.resolve(r.fs.top_level_dir, package, .internal);
            // support passing a package.json or path to a package
            const pkg: *const PackageJSON = result.package_json orelse r.packageJSONForResolvedNodeModuleWithIgnoreMissingName(&result, true) orelse return error.MissingPackageJSON;

            const json: Expr = (try r.caches.json.parseJSON(r.log, pkg.source, r.allocator)) orelse return error.JSONParseError;
            pkg.loadFrameworkWithPreference(pair, json, r.allocator, load_defines, preference);
            const dir = pkg.source.path.name.dirWithTrailingSlash();
            var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
            if (pair.framework.client.len > 0) {
                var parts = [_]string{ dir, pair.framework.client };
                const abs = r.fs.abs(&parts);
                pair.framework.client = try r.allocator.dupe(u8, try std.os.realpath(abs, &buf));
                pair.framework.resolved = true;
            }

            if (pair.framework.server.len > 0) {
                var parts = [_]string{ dir, pair.framework.server };
                const abs = r.fs.abs(&parts);
                pair.framework.server = try r.allocator.dupe(u8, try std.os.realpath(abs, &buf));
                pair.framework.resolved = true;
            }

            if (pair.loaded_routes) {
                const chosen_dir: string = brk: {
                    if (pair.router.possible_dirs.len > 0) {
                        for (pair.router.possible_dirs) |route_dir| {
                            var parts = [_]string{ r.fs.top_level_dir, std.fs.path.sep_str, route_dir };
                            const abs = r.fs.join(&parts);
                            // must end in trailing slash
                            break :brk (std.os.realpath(abs, &buf) catch continue);
                        }
                        return error.MissingRouteDir;
                    } else {
                        var parts = [_]string{ r.fs.top_level_dir, std.fs.path.sep_str, pair.router.dir };
                        const abs = r.fs.join(&parts);
                        // must end in trailing slash
                        break :brk std.os.realpath(abs, &buf) catch return error.MissingRouteDir;
                    }
                };

                var out = try r.allocator.alloc(u8, chosen_dir.len + 1);
                std.mem.copy(u8, out, chosen_dir);
                out[out.len - 1] = '/';
                pair.router.dir = out;
                pair.router.routes_enabled = true;
            }
        }

        pub fn resolve(r: *ThisResolver, source_dir: string, import_path: string, kind: ast.ImportKind) !Result {
            if (FeatureFlags.tracing) {
                tracing_start = std.time.nanoTimestamp();
            }
            defer {
                if (FeatureFlags.tracing) {
                    r.elapsed += std.time.nanoTimestamp() - tracing_start;
                }
            }
            if (r.log.level == .verbose) {
                if (r.debug_logs != null) {
                    r.debug_logs.?.deinit();
                }

                r.debug_logs = try DebugLogs.init(r.allocator);
            }

            if (import_path.len == 0) return error.ModuleNotFound;

            // Certain types of URLs default to being external for convenience
            if (r.isExternalPattern(import_path) or
                // "fill: url(#filter);"
                (kind.isFromCSS() and strings.startsWith(import_path, "#")) or

                // "background: url(http://example.com/images/image.png);"
                strings.startsWith(import_path, "http://") or

                // "background: url(https://example.com/images/image.png);"
                strings.startsWith(import_path, "https://") or

                // "background: url(//example.com/images/image.png);"
                strings.startsWith(import_path, "//"))
            {
                if (r.debug_logs) |*debug| {
                    try debug.addNote("Marking this path as implicitly external");
                }
                r.flushDebugLogs(.success) catch {};
                return Result{
                    .import_kind = kind,
                    .path_pair = PathPair{
                        .primary = Path.init(import_path),
                    },
                    .is_external = true,
                    .module_type = .esm,
                };
            }

            if (DataURL.parse(import_path)) |_data_url| {
                const data_url: DataURL = _data_url;
                // "import 'data:text/javascript,console.log(123)';"
                // "@import 'data:text/css,body{background:white}';"
                if (data_url.decode_mime_type() != .Unsupported) {
                    if (r.debug_logs) |*debug| {
                        debug.addNote("Putting this path in the \"dataurl\" namespace") catch {};
                    }
                    r.flushDebugLogs(.success) catch {};
                    return Result{ .path_pair = PathPair{ .primary = Path.initWithNamespace(import_path, "dataurl") } };
                }

                // "background: url(data:image/png;base64,iVBORw0KGgo=);"
                if (r.debug_logs) |*debug| {
                    debug.addNote("Marking this \"dataurl\" as external") catch {};
                }
                r.flushDebugLogs(.success) catch {};
                return Result{
                    .path_pair = PathPair{ .primary = Path.initWithNamespace(import_path, "dataurl") },
                    .is_external = true,
                };
            }

            // Fail now if there is no directory to resolve in. This can happen for
            // virtual modules (e.g. stdin) if a resolve directory is not specified.
            if (source_dir.len == 0) {
                if (r.debug_logs) |*debug| {
                    debug.addNote("Cannot resolve this path without a directory") catch {};
                }
                r.flushDebugLogs(.fail) catch {};
                return error.MissingResolveDir;
            }

            r.mutex.lock();
            defer r.mutex.unlock();
            errdefer (r.flushDebugLogs(.fail) catch {});
            var result = (try r.resolveWithoutSymlinks(source_dir, import_path, kind)) orelse {
                r.flushDebugLogs(.fail) catch {};
                return error.ModuleNotFound;
            };

            try r.finalizeResult(&result);
            r.flushDebugLogs(.success) catch {};
            result.import_kind = kind;
            return result;
        }

        pub fn finalizeResult(r: *ThisResolver, result: *Result) !void {
            if (result.is_external) return;

            if (result.package_json) |package_json| {
                result.module_type = switch (package_json.module_type) {
                    .esm, .cjs => package_json.module_type,
                    .unknown => result.module_type,
                };
            }

            var iter = result.path_pair.iter();
            while (iter.next()) |path| {
                var dir: *DirInfo = (r.readDirInfo(path.name.dir) catch continue) orelse continue;
                if (dir.getEntries()) |entries| {
                    if (entries.get(path.name.filename)) |query| {
                        const symlink_path = query.entry.symlink(&r.fs.fs);
                        if (symlink_path.len > 0) {
                            path.non_symlink = path.text;
                            // Is this entry itself a symlink?
                            path.text = symlink_path;
                            path.name = Fs.PathName.init(path.text);

                            if (r.debug_logs) |*debug| {
                                debug.addNoteFmt("Resolved symlink \"{s}\" to \"{s}\"", .{ path.non_symlink, path.text }) catch {};
                            }
                        } else if (dir.abs_real_path.len > 0) {
                            path.non_symlink = path.text;
                            var parts = [_]string{ dir.abs_real_path, query.entry.base() };
                            var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
                            var out = r.fs.absBuf(&parts, &buf);
                            const symlink = try Fs.FileSystem.FilenameStore.instance.append(@TypeOf(out), out);
                            if (r.debug_logs) |*debug| {
                                debug.addNoteFmt("Resolved symlink \"{s}\" to \"{s}\"", .{ symlink, path.text }) catch {};
                            }
                            query.entry.cache.symlink = symlink;

                            path.name = Fs.PathName.init(path.text);
                        }
                    }
                }
            }
        }

        pub fn resolveWithoutSymlinks(r: *ThisResolver, source_dir: string, import_path: string, kind: ast.ImportKind) !?Result {
            // This implements the module resolution algorithm from node.js, which is
            // described here: https://nodejs.org/api/modules.html#modules_all_together
            var result: Result = Result{ .path_pair = PathPair{ .primary = Path.init("") } };

            // Return early if this is already an absolute path. In addition to asking
            // the file system whether this is an absolute path, we also explicitly check
            // whether it starts with a "/" and consider that an absolute path too. This
            // is because relative paths can technically start with a "/" on Windows
            // because it's not an absolute path on Windows. Then people might write code
            // with imports that start with a "/" that works fine on Windows only to
            // experience unexpected build failures later on other operating systems.
            // Treating these paths as absolute paths on all platforms means Windows
            // users will not be able to accidentally make use of these paths.
            if (strings.startsWith(import_path, "/") or std.fs.path.isAbsolutePosix(import_path)) {
                if (r.debug_logs) |*debug| {
                    debug.addNoteFmt("The import \"{s}\" is being treated as an absolute path", .{import_path}) catch {};
                }

                // First, check path overrides from the nearest enclosing TypeScript "tsconfig.json" file
                if ((r.dirInfoCached(source_dir) catch null)) |_dir_info| {
                    const dir_info: *DirInfo = _dir_info;
                    if (dir_info.tsconfig_json) |tsconfig| {
                        if (tsconfig.paths.count() > 0) {
                            if (r.matchTSConfigPaths(tsconfig, import_path, kind)) |res| {
                                return Result{
                                    .path_pair = res.path_pair,
                                    .diff_case = res.diff_case,
                                    .dirname_fd = dir_info.getFileDescriptor(),
                                    .is_from_node_modules = res.is_node_module,
                                    .package_json = res.package_json,
                                };
                            }
                        }
                    }
                }

                if (r.opts.external.abs_paths.count() > 0 and r.opts.external.abs_paths.contains(import_path)) {
                    // If the string literal in the source text is an absolute path and has
                    // been marked as an external module, mark it as *not* an absolute path.
                    // That way we preserve the literal text in the output and don't generate
                    // a relative path from the output directory to that path.
                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("The path \"{s}\" is marked as external by the user", .{import_path}) catch {};
                    }

                    return Result{
                        .path_pair = .{ .primary = Path.init(import_path) },
                        .is_external = true,
                    };
                }

                // Run node's resolution rules (e.g. adding ".js")
                if (r.loadAsFileOrDirectory(import_path, kind)) |entry| {
                    return Result{
                        .dirname_fd = entry.dirname_fd,
                        .path_pair = entry.path_pair,
                        .diff_case = entry.diff_case,
                        .is_from_node_modules = entry.is_node_module,
                        .package_json = entry.package_json,
                    };
                }

                return null;
            }

            // Check both relative and package paths for CSS URL tokens, with relative
            // paths taking precedence over package paths to match Webpack behavior.
            const is_package_path = isPackagePath(import_path);
            var check_relative = !is_package_path or kind == .url;
            var check_package = is_package_path;

            if (check_relative) {
                const parts = [_]string{ source_dir, import_path };
                const abs_path = r.fs.absBuf(&parts, &relative_abs_path_buf);

                if (r.opts.external.abs_paths.count() > 0 and r.opts.external.abs_paths.contains(abs_path)) {
                    // If the string literal in the source text is an absolute path and has
                    // been marked as an external module, mark it as *not* an absolute path.
                    // That way we preserve the literal text in the output and don't generate
                    // a relative path from the output directory to that path.
                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("The path \"{s}\" is marked as external by the user", .{abs_path}) catch {};
                    }

                    return Result{
                        .path_pair = .{ .primary = Path.init(r.fs.dirname_store.append(@TypeOf(abs_path), abs_path) catch unreachable) },
                        .is_external = true,
                    };
                }

                // Check the "browser" map for the first time (1 out of 2)
                if (r.dirInfoCached(std.fs.path.dirname(abs_path) orelse unreachable) catch null) |_import_dir_info| {
                    if (_import_dir_info.getEnclosingBrowserScope()) |import_dir_info| {
                        if (import_dir_info.package_json) |pkg| {
                            const pkg_json_dir = std.fs.path.dirname(pkg.source.key_path.text) orelse unreachable;

                            const rel_path = r.fs.relative(pkg_json_dir, abs_path);
                            if (r.checkBrowserMap(pkg, rel_path)) |remap| {
                                // Is the path disabled?
                                if (remap.len == 0) {
                                    var _path = Path.init(r.fs.dirname_store.append(string, abs_path) catch unreachable);
                                    _path.is_disabled = true;
                                    return Result{
                                        .path_pair = PathPair{
                                            .primary = _path,
                                        },
                                    };
                                }

                                if (r.resolveWithoutRemapping(import_dir_info, remap, kind)) |_result| {
                                    result = Result{
                                        .path_pair = _result.path_pair,
                                        .diff_case = _result.diff_case,
                                        .is_from_node_modules = _result.is_node_module,
                                        .module_type = pkg.module_type,
                                        .dirname_fd = _result.dirname_fd,
                                        .package_json = pkg,
                                    };
                                    check_relative = false;
                                    check_package = false;
                                }
                            }
                        }
                    }
                }

                if (check_relative) {
                    if (r.loadAsFileOrDirectory(abs_path, kind)) |res| {
                        check_package = false;
                        result = Result{
                            .path_pair = res.path_pair,
                            .diff_case = res.diff_case,
                            .is_from_node_modules = res.is_node_module,
                            .dirname_fd = res.dirname_fd,
                            .package_json = res.package_json,
                        };
                    } else if (!check_package) {
                        return null;
                    }
                }
            }

            if (check_package) {
                // Check for external packages first
                if (r.opts.external.node_modules.count() > 0) {
                    var query = import_path;
                    while (true) {
                        if (r.opts.external.node_modules.contains(query)) {
                            if (r.debug_logs) |*debug| {
                                debug.addNoteFmt("The path \"{s}\" was marked as external by the user", .{query}) catch {};
                            }
                            return Result{
                                .path_pair = .{ .primary = Path.init(query) },
                                .is_external = true,
                            };
                        }

                        // If the module "foo" has been marked as external, we also want to treat
                        // paths into that module such as "foo/bar" as external too.
                        var slash = strings.lastIndexOfChar(query, '/') orelse break;
                        query = query[0..slash];
                    }
                }

                const source_dir_info = (r.dirInfoCached(source_dir) catch null) orelse return null;

                // Support remapping one package path to another via the "browser" field
                if (source_dir_info.getEnclosingBrowserScope()) |browser_scope| {
                    if (browser_scope.package_json) |package_json| {
                        if (r.checkBrowserMap(package_json, import_path)) |remapped| {
                            if (remapped.len == 0) {
                                // "browser": {"module": false}
                                if (r.loadNodeModules(import_path, kind, source_dir_info)) |node_module| {
                                    var pair = node_module.path_pair;
                                    pair.primary.is_disabled = true;
                                    if (pair.secondary != null) {
                                        pair.secondary.?.is_disabled = true;
                                    }
                                    return Result{
                                        .path_pair = pair,
                                        .dirname_fd = node_module.dirname_fd,
                                        .diff_case = node_module.diff_case,
                                        .is_from_node_modules = true,
                                        .package_json = package_json,
                                    };
                                }
                            } else {
                                var primary = Path.init(import_path);
                                primary.is_disabled = true;
                                return Result{
                                    .path_pair = PathPair{ .primary = primary },
                                    // this might not be null? i think it is
                                    .diff_case = null,
                                };
                            }
                        }
                    }
                }

                if (r.resolveWithoutRemapping(source_dir_info, import_path, kind)) |res| {
                    result = Result{
                        .path_pair = res.path_pair,
                        .diff_case = res.diff_case,
                        .is_from_node_modules = res.is_node_module,
                        .dirname_fd = res.dirname_fd,
                        .package_json = res.package_json,
                    };
                } else {
                    // Note: node's "self references" are not currently supported
                    return null;
                }
            }

            var iter = result.path_pair.iter();
            while (iter.next()) |path| {
                const dirname = std.fs.path.dirname(path.text) orelse continue;
                const base_dir_info = ((r.dirInfoCached(dirname) catch null)) orelse continue;
                const dir_info = base_dir_info.getEnclosingBrowserScope() orelse continue;
                const pkg_json = dir_info.package_json orelse continue;
                const rel_path = r.fs.relative(pkg_json.source.key_path.text, path.text);
                result.module_type = pkg_json.module_type;
                result.package_json = result.package_json orelse pkg_json;
                if (r.checkBrowserMap(pkg_json, rel_path)) |remapped| {
                    if (remapped.len == 0) {
                        path.is_disabled = true;
                    } else if (r.resolveWithoutRemapping(dir_info, remapped, kind)) |remapped_result| {
                        switch (iter.index) {
                            0 => {
                                result.path_pair.primary = remapped_result.path_pair.primary;
                                result.dirname_fd = remapped_result.dirname_fd;
                            },
                            else => {
                                result.path_pair.secondary = remapped_result.path_pair.primary;
                            },
                        }
                    }
                }
            }

            return result;
        }

        pub fn packageJSONForResolvedNodeModule(
            r: *ThisResolver,
            result: *const Result,
        ) ?*const PackageJSON {
            return @call(.{ .modifier = .always_inline }, packageJSONForResolvedNodeModuleWithIgnoreMissingName, .{ r, result, true });
        }

        // This is a fallback, hopefully not called often. It should be relatively quick because everything should be in the cache.
        fn packageJSONForResolvedNodeModuleWithIgnoreMissingName(
            r: *ThisResolver,
            result: *const Result,
            comptime ignore_missing_name: bool,
        ) ?*const PackageJSON {
            var dir_info = (r.dirInfoCached(result.path_pair.primary.name.dir) catch null) orelse return null;
            while (true) {
                if (dir_info.package_json) |pkg| {
                    // if it doesn't have a name, assume it's something just for adjusting the main fields (react-bootstrap does this)
                    // In that case, we really would like the top-level package that you download from NPM
                    // so we ignore any unnamed packages
                    if (comptime !ignore_missing_name) {
                        if (pkg.name.len > 0) {
                            return pkg;
                        }
                    } else {
                        return pkg;
                    }
                }

                dir_info = dir_info.getParent() orelse return null;
            }

            unreachable;
        }
        const node_module_root_string = std.fs.path.sep_str ++ "node_modules" ++ std.fs.path.sep_str;

        pub fn rootNodeModulePackageJSON(
            r: *ThisResolver,
            result: *const Result,
        ) ?*const PackageJSON {
            const absolute = result.path_pair.primary.text;
            var end = strings.lastIndexOf(absolute, node_module_root_string) orelse return null;
            end += node_module_root_string.len;
            end += strings.indexOfChar(absolute[end..], std.fs.path.sep) orelse return null;

            const dir_info = (r.dirInfoCached(absolute[0 .. end + 1]) catch null) orelse return null;
            return dir_info.package_json;
        }

        pub fn loadNodeModules(r: *ThisResolver, import_path: string, kind: ast.ImportKind, _dir_info: *DirInfo) ?MatchResult {
            var res = _loadNodeModules(r, import_path, kind, _dir_info) orelse return null;
            res.is_node_module = true;
            return res;
        }

        inline fn _loadNodeModules(r: *ThisResolver, import_path: string, kind: ast.ImportKind, _dir_info: *DirInfo) ?MatchResult {
            var dir_info = _dir_info;
            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Searching for {s} in \"node_modules\" directories starting from \"{s}\"", .{ import_path, dir_info.abs_path }) catch {};
                debug.increaseIndent() catch {};
            }

            defer {
                if (r.debug_logs) |*debug| {
                    debug.decreaseIndent() catch {};
                }
            }

            // First, check path overrides from the nearest enclosing TypeScript "tsconfig.json" file

            if (dir_info.tsconfig_json) |tsconfig| {
                // Try path substitutions first
                if (tsconfig.paths.count() > 0) {
                    if (r.matchTSConfigPaths(tsconfig, import_path, kind)) |res| {
                        return res;
                    }
                }

                // Try looking up the path relative to the base URL
                if (tsconfig.hasBaseURL()) {
                    const base = tsconfig.base_url;
                    const paths = [_]string{ base, import_path };
                    const abs = r.fs.absBuf(&paths, &load_as_file_or_directory_via_tsconfig_base_path);

                    if (r.loadAsFileOrDirectory(abs, kind)) |res| {
                        return res;
                    }
                    // r.allocator.free(abs);
                }
            }

            // Then check for the package in any enclosing "node_modules" directories
            while (true) {
                // Skip directories that are themselves called "node_modules", since we
                // don't ever want to search for "node_modules/node_modules"
                if (dir_info.has_node_modules) {
                    var _paths = [_]string{ dir_info.abs_path, "node_modules", import_path };
                    const abs_path = r.fs.absBuf(&_paths, &node_modules_check_buf);
                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("Checking for a package in the directory \"{s}\"", .{abs_path}) catch {};
                    }

                    // TODO: esm "exports" field goes here!!! Here!!

                    if (r.loadAsFileOrDirectory(abs_path, kind)) |res| {
                        return res;
                    }
                    // r.allocator.free(abs_path);
                }

                dir_info = dir_info.getParent() orelse break;
            }

            // Mostly to cut scope, we don't resolve `NODE_PATH` environment variable.
            // But also: https://github.com/nodejs/node/issues/38128#issuecomment-814969356

            return null;
        }

        pub fn resolveWithoutRemapping(r: *ThisResolver, source_dir_info: *DirInfo, import_path: string, kind: ast.ImportKind) ?MatchResult {
            if (isPackagePath(import_path)) {
                return r.loadNodeModules(import_path, kind, source_dir_info);
            } else {
                const paths = [_]string{ source_dir_info.abs_path, import_path };
                var resolved = r.fs.absBuf(&paths, &resolve_without_remapping_buf);
                return r.loadAsFileOrDirectory(resolved, kind);
            }
        }

        pub fn parseTSConfig(
            r: *ThisResolver,
            file: string,
            dirname_fd: StoredFileDescriptorType,
        ) !?*TSConfigJSON {
            const entry = try r.caches.fs.readFile(
                r.fs,
                file,
                dirname_fd,
                false,
                null,
            );
            const key_path = Path.init(file);

            const source = logger.Source.initPathString(key_path.text, entry.contents);
            const file_dir = std.fs.path.dirname(file) orelse return null;

            var result = (try TSConfigJSON.parse(r.allocator, r.log, source, @TypeOf(r.caches.json), &r.caches.json)) orelse return null;

            if (result.hasBaseURL()) {
                // this might leak
                if (!std.fs.path.isAbsolute(result.base_url)) {
                    const paths = [_]string{ file_dir, result.base_url };
                    result.base_url = r.fs.dirname_store.append(string, r.fs.absBuf(&paths, &tsconfig_base_url_buf)) catch unreachable;
                }
            }

            if (result.paths.count() > 0 and (result.base_url_for_paths.len == 0 or !std.fs.path.isAbsolute(result.base_url_for_paths))) {
                // this might leak
                const paths = [_]string{ file_dir, result.base_url };
                result.base_url_for_paths = r.fs.dirname_store.append(string, r.fs.absBuf(&paths, &tsconfig_base_url_buf)) catch unreachable;
            }

            return result;
        }

        // TODO:
        pub fn prettyPath(r: *ThisResolver, path: Path) string {
            return path.text;
        }

        pub fn parsePackageJSON(r: *ThisResolver, file: string, dirname_fd: StoredFileDescriptorType) !?*PackageJSON {
            if (!cache_files or r.opts.node_modules_bundle != null) {
                const pkg = PackageJSON.parse(ThisResolver, r, file, dirname_fd, true) orelse return null;
                var _pkg = try r.allocator.create(PackageJSON);
                _pkg.* = pkg;
                return _pkg;
            } else {
                const pkg = PackageJSON.parse(ThisResolver, r, file, dirname_fd, false) orelse return null;
                var _pkg = try r.allocator.create(PackageJSON);
                _pkg.* = pkg;
                return _pkg;
            }
        }

        fn dirInfoCached(
            r: *ThisResolver,
            path: string,
        ) !?*DirInfo {
            return try r.dirInfoCachedMaybeLog(path, true, true);
        }

        pub fn readDirInfo(
            r: *ThisResolver,
            path: string,
        ) !?*DirInfo {
            return try r.dirInfoCachedMaybeLog(path, false, true);
        }

        pub fn readDirInfoIgnoreError(
            r: *ThisResolver,
            path: string,
        ) ?*const DirInfo {
            return r.dirInfoCachedMaybeLog(path, false, true) catch null;
        }

        pub inline fn readDirInfoCacheOnly(
            r: *ThisResolver,
            path: string,
        ) ?*DirInfo {
            return r.dir_cache.get(path);
        }

        inline fn dirInfoCachedMaybeLog(r: *ThisResolver, path: string, comptime enable_logging: bool, comptime follow_symlinks: bool) !?*DirInfo {
            const top_result = try r.dir_cache.getOrPut(path);
            if (top_result.status != .unknown) {
                return r.dir_cache.atIndex(top_result.index);
            }

            var i: i32 = 1;
            _dir_entry_paths_to_resolve[0] = (DirEntryResolveQueueItem{ .result = top_result, .unsafe_path = path, .safe_path = "" });
            var top = Dirname.dirname(path);

            var top_parent: allocators.Result = allocators.Result{
                .index = allocators.NotFound,
                .hash = 0,
                .status = .not_found,
            };
            const root_path = if (isWindows) std.fs.path.diskDesignator(path) else "/";
            var rfs: *Fs.FileSystem.RealFS = &r.fs.fs;

            rfs.entries_mutex.lock();
            defer rfs.entries_mutex.unlock();

            while (!strings.eql(top, root_path)) : (top = Dirname.dirname(top)) {
                var result = try r.dir_cache.getOrPut(top);
                if (result.status != .unknown) {
                    top_parent = result;
                    break;
                }
                _dir_entry_paths_to_resolve[@intCast(usize, i)] = DirEntryResolveQueueItem{
                    .unsafe_path = top,
                    .result = result,
                    .fd = 0,
                };

                if (rfs.entries.get(top)) |top_entry| {
                    _dir_entry_paths_to_resolve[@intCast(usize, i)].safe_path = top_entry.entries.dir;
                    _dir_entry_paths_to_resolve[@intCast(usize, i)].fd = top_entry.entries.fd;
                }
                i += 1;
            }

            if (strings.eql(top, root_path)) {
                var result = try r.dir_cache.getOrPut(root_path);
                if (result.status != .unknown) {
                    top_parent = result;
                } else {
                    _dir_entry_paths_to_resolve[@intCast(usize, i)] = DirEntryResolveQueueItem{
                        .unsafe_path = root_path,
                        .result = result,
                        .fd = 0,
                    };
                    if (rfs.entries.get(top)) |top_entry| {
                        _dir_entry_paths_to_resolve[@intCast(usize, i)].safe_path = top_entry.entries.dir;
                        _dir_entry_paths_to_resolve[@intCast(usize, i)].fd = top_entry.entries.fd;
                    }

                    i += 1;
                }
            }

            var queue_slice: []DirEntryResolveQueueItem = _dir_entry_paths_to_resolve[0..@intCast(usize, i)];
            std.debug.assert(queue_slice.len > 0);
            var open_dir_count: usize = 0;

            // When this function halts, any item not processed means it's not found.
            defer {

                // Anything
                if (open_dir_count > 0 and r.fs.fs.needToCloseFiles()) {
                    var open_dirs: []std.fs.Dir = _open_dirs[0..open_dir_count];
                    for (open_dirs) |*open_dir| {
                        open_dir.close();
                    }
                }
            }

            // We want to walk in a straight line from the topmost directory to the desired directory
            // For each directory we visit, we get the entries, but not traverse into child directories
            // (unless those child directores are in the queue)
            // Going top-down rather than bottom-up should have best performance because we can use
            // the file handle from the parent directory to open the child directory
            // It's important that we walk in precisely a straight line
            // For example
            // "/home/jarred/Code/node_modules/react/cjs/react.development.js"
            //       ^
            // If we start there, we will traverse all of /home/jarred, including e.g. /home/jarred/Downloads
            // which is completely irrelevant.

            // After much experimentation, fts_open is not the fastest way. fts actually just uses readdir!!
            var _safe_path: ?string = null;

            // Start at the top.
            while (queue_slice.len > 0) {
                var queue_top = queue_slice[queue_slice.len - 1];
                defer top_parent = queue_top.result;
                queue_slice.len -= 1;

                var _open_dir: anyerror!std.fs.Dir = undefined;
                if (queue_top.fd == 0) {
                    if (open_dir_count > 0) {
                        _open_dir = _open_dirs[open_dir_count - 1].openDir(
                            std.fs.path.basename(queue_top.unsafe_path),
                            .{ .iterate = true, .no_follow = !follow_symlinks },
                        );
                    } else {
                        _open_dir = std.fs.openDirAbsolute(
                            queue_top.unsafe_path,
                            .{
                                .iterate = true,
                                .no_follow = !follow_symlinks,
                            },
                        );
                    }
                }

                const open_dir = if (queue_top.fd != 0) std.fs.Dir{ .fd = queue_top.fd } else (_open_dir catch |err| {
                    switch (err) {
                        error.EACCESS => {},

                        // Ignore "ENOTDIR" here so that calling "ReadDirectory" on a file behaves
                        // as if there is nothing there at all instead of causing an error due to
                        // the directory actually being a file. This is a workaround for situations
                        // where people try to import from a path containing a file as a parent
                        // directory. The "pnpm" package manager generates a faulty "NODE_PATH"
                        // list which contains such paths and treating them as missing means we just
                        // ignore them during path resolution.
                        error.ENOENT,
                        error.ENOTDIR,
                        error.IsDir,
                        error.NotDir,
                        error.FileNotFound,
                        => {
                            return null;
                        },

                        else => {
                            var cached_dir_entry_result = rfs.entries.getOrPut(queue_top.unsafe_path) catch unreachable;
                            r.dir_cache.markNotFound(queue_top.result);
                            rfs.entries.markNotFound(cached_dir_entry_result);
                            if (comptime enable_logging) {
                                const pretty = r.prettyPath(Path.init(queue_top.unsafe_path));

                                r.log.addErrorFmt(
                                    null,
                                    logger.Loc{},
                                    r.allocator,
                                    "Cannot read directory \"{s}\": {s}",
                                    .{
                                        pretty,
                                        @errorName(err),
                                    },
                                ) catch {};
                            }
                        },
                    }

                    return null;
                });

                if (queue_top.fd == 0) {
                    Fs.FileSystem.setMaxFd(open_dir.fd);
                    // these objects mostly just wrap the file descriptor, so it's fine to keep it.
                    _open_dirs[open_dir_count] = open_dir;
                    open_dir_count += 1;
                }

                const dir_path = if (queue_top.safe_path.len > 0) queue_top.safe_path else brk: {

                    // ensure trailing slash
                    if (_safe_path == null) {
                        // Now that we've opened the topmost directory successfully, it's reasonable to store the slice.
                        if (path[path.len - 1] != std.fs.path.sep) {
                            var parts = [_]string{ path, std.fs.path.sep_str };
                            _safe_path = try r.fs.dirname_store.append(@TypeOf(parts), parts);
                        } else {
                            _safe_path = try r.fs.dirname_store.append(string, path);
                        }
                    }

                    const safe_path = _safe_path.?;

                    var dir_path_i = std.mem.indexOf(u8, safe_path, queue_top.unsafe_path) orelse unreachable;
                    var end = dir_path_i +
                        queue_top.unsafe_path.len;

                    // Directories must always end in a trailing slash or else various bugs can occur.
                    // This covers "what happens when the trailing"
                    end += @intCast(usize, @boolToInt(safe_path.len > end and end > 0 and safe_path[end - 1] != std.fs.path.sep and safe_path[end] == std.fs.path.sep));
                    break :brk safe_path[dir_path_i..end];
                };

                var cached_dir_entry_result = rfs.entries.getOrPut(dir_path) catch unreachable;

                var dir_entries_option: *Fs.FileSystem.RealFS.EntriesOption = undefined;
                var needs_iter: bool = true;

                if (rfs.entries.atIndex(cached_dir_entry_result.index)) |cached_entry| {
                    if (cached_entry.* == .entries) {
                        dir_entries_option = cached_entry;
                        needs_iter = false;
                    }
                }

                if (needs_iter) {
                    dir_entries_option = try rfs.entries.put(&cached_dir_entry_result, .{
                        .entries = Fs.FileSystem.DirEntry.init(dir_path, r.fs.allocator),
                    });

                    if (FeatureFlags.store_file_descriptors) {
                        Fs.FileSystem.setMaxFd(open_dir.fd);
                        dir_entries_option.entries.fd = open_dir.fd;
                    }
                    var dir_iterator = open_dir.iterate();
                    while (try dir_iterator.next()) |_value| {
                        dir_entries_option.entries.addEntry(_value) catch unreachable;
                    }
                }

                const dir_info = try r.dirInfoUncached(
                    dir_path,
                    dir_entries_option,
                    queue_top.result,
                    cached_dir_entry_result.index,
                    r.dir_cache.atIndex(top_parent.index),
                    top_parent.index,
                    open_dir.fd,
                );

                var dir_info_ptr = try r.dir_cache.put(&queue_top.result, dir_info);

                if (queue_slice.len == 0) {
                    return dir_info_ptr;

                    // Is the directory we're searching for actually a file?
                } else if (queue_slice.len == 1) {
                    // const next_in_queue = queue_slice[0];
                    // const next_basename = std.fs.path.basename(next_in_queue.unsafe_path);
                    // if (dir_info_ptr.getEntries()) |entries| {
                    //     if (entries.get(next_basename) != null) {
                    //         return null;
                    //     }
                    // }
                }
            }

            unreachable;
        }

        // This closely follows the behavior of "tryLoadModuleUsingPaths()" in the
        // official TypeScript compiler
        pub fn matchTSConfigPaths(r: *ThisResolver, tsconfig: *TSConfigJSON, path: string, kind: ast.ImportKind) ?MatchResult {
            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Matching \"{s}\" against \"paths\" in \"{s}\"", .{ path, tsconfig.abs_path }) catch unreachable;
            }

            var abs_base_url = tsconfig.base_url_for_paths;

            // The explicit base URL should take precedence over the implicit base URL
            // if present. This matters when a tsconfig.json file overrides "baseUrl"
            // from another extended tsconfig.json file but doesn't override "paths".
            if (tsconfig.hasBaseURL()) {
                abs_base_url = tsconfig.base_url;
            }

            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Using \"{s}\" as \"baseURL\"", .{abs_base_url}) catch unreachable;
            }

            // Check for exact matches first
            {
                var iter = tsconfig.paths.iterator();
                while (iter.next()) |entry| {
                    const key = entry.key_ptr.*;

                    if (strings.eql(key, path)) {
                        for (entry.value_ptr.*) |original_path| {
                            var absolute_original_path = original_path;
                            var was_alloc = false;

                            if (!std.fs.path.isAbsolute(absolute_original_path)) {
                                const parts = [_]string{ abs_base_url, original_path };
                                absolute_original_path = r.fs.absBuf(&parts, &tsconfig_path_abs_buf);
                            }

                            if (r.loadAsFileOrDirectory(absolute_original_path, kind)) |res| {
                                return res;
                            }
                        }

                        return null;
                    }
                }
            }

            const TSConfigMatch = struct {
                prefix: string,
                suffix: string,
                original_paths: []string,
            };

            var longest_match: TSConfigMatch = undefined;
            var longest_match_prefix_length: i32 = -1;
            var longest_match_suffix_length: i32 = -1;

            var iter = tsconfig.paths.iterator();
            while (iter.next()) |entry| {
                const key = entry.key_ptr.*;
                const original_paths = entry.value_ptr.*;

                if (strings.indexOfChar(key, '*')) |star_index| {
                    const prefix = key[0..star_index];
                    const suffix = key[star_index..key.len];

                    // Find the match with the longest prefix. If two matches have the same
                    // prefix length, pick the one with the longest suffix. This second edge
                    // case isn't handled by the TypeScript compiler, but we handle it
                    // because we want the output to always be deterministic and Go map
                    // iteration order is deliberately non-deterministic.
                    if (strings.startsWith(path, prefix) and strings.endsWith(path, suffix) and (prefix.len > longest_match_prefix_length or (prefix.len == longest_match_prefix_length and suffix.len > longest_match_suffix_length))) {
                        longest_match_prefix_length = @intCast(i32, prefix.len);
                        longest_match_suffix_length = @intCast(i32, suffix.len);
                        longest_match = TSConfigMatch{ .prefix = prefix, .suffix = suffix, .original_paths = original_paths };
                    }
                }
            }

            // If there is at least one match, only consider the one with the longest
            // prefix. This matches the behavior of the TypeScript compiler.
            if (longest_match_prefix_length > -1) {
                if (r.debug_logs) |*debug| {
                    debug.addNoteFmt("Found a fuzzy match for \"{s}*{s}\" in \"paths\"", .{ longest_match.prefix, longest_match.suffix }) catch unreachable;
                }

                for (longest_match.original_paths) |original_path| {
                    // Swap out the "*" in the original path for whatever the "*" matched
                    const matched_text = path[longest_match.prefix.len .. path.len - longest_match.suffix.len];

                    std.mem.copy(
                        u8,
                        &TemporaryBuffer.TSConfigMatchPathBuf,
                        original_path,
                    );
                    var start: usize = 0;
                    var total_length: usize = 0;
                    const star = std.mem.indexOfScalar(u8, original_path, '*') orelse unreachable;
                    total_length = star;
                    std.mem.copy(u8, &TemporaryBuffer.TSConfigMatchPathBuf, original_path[0..total_length]);
                    start = total_length;
                    total_length += matched_text.len;
                    std.mem.copy(u8, TemporaryBuffer.TSConfigMatchPathBuf[start..total_length], matched_text);
                    start = total_length;

                    total_length += original_path.len - star + 1; // this might be an off by one.
                    std.mem.copy(u8, TemporaryBuffer.TSConfigMatchPathBuf[start..TemporaryBuffer.TSConfigMatchPathBuf.len], original_path[star..original_path.len]);
                    const region = TemporaryBuffer.TSConfigMatchPathBuf[0..total_length];

                    // Load the original path relative to the "baseUrl" from tsconfig.json
                    var absolute_original_path: string = region;

                    var did_allocate = false;
                    if (!std.fs.path.isAbsolute(region)) {
                        var paths = [_]string{ abs_base_url, original_path };
                        absolute_original_path = r.fs.absAlloc(r.allocator, &paths) catch unreachable;
                        did_allocate = true;
                    } else {
                        absolute_original_path = std.mem.dupe(r.allocator, u8, region) catch unreachable;
                    }

                    if (r.loadAsFileOrDirectory(absolute_original_path, kind)) |res| {
                        return res;
                    }
                }
            }

            return null;
        }

        pub fn checkBrowserMap(r: *ThisResolver, pkg: *PackageJSON, input_path: string) ?string {
            // Normalize the path so we can compare against it without getting confused by "./"
            var cleaned = r.fs.normalize(input_path);
            const original_cleaned = cleaned;

            if (cleaned.len == 1 and cleaned[0] == '.') {
                // No bundler supports remapping ".", so we don't either
                return null;
            }

            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Checking for \"{s}\" in the \"browser\" map in \"{s}\"", .{ input_path, pkg.source.path.text }) catch {};
            }

            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Checking for \"{s}\" ", .{cleaned}) catch {};
            }
            var remapped = pkg.browser_map.get(cleaned);
            if (remapped == null) {
                for (r.opts.extension_order) |ext| {
                    std.mem.copy(u8, &TemporaryBuffer.ExtensionPathBuf, cleaned);
                    std.mem.copy(u8, TemporaryBuffer.ExtensionPathBuf[cleaned.len .. cleaned.len + ext.len], ext);
                    const new_path = TemporaryBuffer.ExtensionPathBuf[0 .. cleaned.len + ext.len];
                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("Checking for \"{s}\" ", .{new_path}) catch {};
                    }
                    if (pkg.browser_map.get(new_path)) |_remapped| {
                        remapped = _remapped;
                        cleaned = new_path;
                        break;
                    }
                }
            }

            if (remapped) |remap| {
                // "" == disabled, {"browser": { "file.js": false }}
                if (remap.len == 0 or (remap.len == 1 and remap[0] == '.')) {
                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("Found \"{s}\" marked as disabled", .{remap}) catch {};
                    }
                    return remap;
                }

                if (r.debug_logs) |*debug| {
                    debug.addNoteFmt("Found \"{s}\" remapped to \"{s}\"", .{ original_cleaned, remap }) catch {};
                }

                // Only allocate on successful remapping.
                return r.allocator.dupe(u8, remap) catch unreachable;
            }

            return null;
        }

        pub fn loadFromMainField(r: *ThisResolver, path: string, dir_info: *DirInfo, _field_rel_path: string, field: string, extension_order: []const string) ?MatchResult {
            var field_rel_path = _field_rel_path;
            // Is this a directory?
            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Found main field \"{s}\" with path \"{s}\"", .{ field, field_rel_path }) catch {};
                debug.increaseIndent() catch {};
            }

            defer {
                if (r.debug_logs) |*debug| {
                    debug.decreaseIndent() catch {};
                }
            }

            // Potentially remap using the "browser" field
            if (dir_info.getEnclosingBrowserScope()) |browser_scope| {
                if (browser_scope.package_json) |browser_json| {
                    if (r.checkBrowserMap(browser_json, field_rel_path)) |remap| {
                        // Is the path disabled?
                        if (remap.len == 0) {
                            const paths = [_]string{ path, field_rel_path };
                            const new_path = r.fs.absAlloc(r.allocator, &paths) catch unreachable;
                            var _path = Path.init(new_path);
                            _path.is_disabled = true;
                            return MatchResult{
                                .path_pair = PathPair{
                                    .primary = _path,
                                },
                                .package_json = browser_json,
                            };
                        }

                        field_rel_path = remap;
                    }
                }
            }
            const _paths = [_]string{ path, field_rel_path };
            const field_abs_path = r.fs.absBuf(&_paths, &field_abs_path_buf);

            // Is this a file?
            if (r.loadAsFile(field_abs_path, extension_order)) |result| {
                if (dir_info.package_json) |package_json| {
                    return MatchResult{
                        .path_pair = PathPair{ .primary = Fs.Path.init(result.path) },
                        .package_json = package_json,
                        .dirname_fd = result.dirname_fd,
                    };
                }

                return MatchResult{
                    .path_pair = PathPair{ .primary = Fs.Path.init(result.path) },
                    .dirname_fd = result.dirname_fd,
                    .diff_case = result.diff_case,
                };
            }

            // Is it a directory with an index?
            const field_dir_info = (r.dirInfoCached(field_abs_path) catch null) orelse {
                return null;
            };

            return r.loadAsIndexWithBrowserRemapping(field_dir_info, field_abs_path, extension_order) orelse {
                return null;
            };
        }

        pub fn loadAsIndex(r: *ThisResolver, dir_info: *DirInfo, path: string, extension_order: []const string) ?MatchResult {
            var rfs = &r.fs.fs;
            // Try the "index" file with extensions
            for (extension_order) |ext| {
                var base = TemporaryBuffer.ExtensionPathBuf[0 .. "index".len + ext.len];
                base[0.."index".len].* = "index".*;
                std.mem.copy(u8, base["index".len..base.len], ext);

                if (dir_info.getEntries()) |entries| {
                    if (entries.get(base)) |lookup| {
                        if (lookup.entry.kind(rfs) == .file) {
                            const parts = [_]string{ path, base };
                            const out_buf_ = r.fs.absBuf(&parts, &index_buf);
                            const out_buf = r.fs.dirname_store.append(@TypeOf(out_buf_), out_buf_) catch unreachable;
                            if (r.debug_logs) |*debug| {
                                debug.addNoteFmt("Found file: \"{s}\"", .{out_buf}) catch unreachable;
                            }

                            if (dir_info.package_json) |package_json| {
                                return MatchResult{
                                    .path_pair = .{ .primary = Path.init(out_buf) },
                                    .diff_case = lookup.diff_case,
                                    .package_json = package_json,
                                    .dirname_fd = dir_info.getFileDescriptor(),
                                };
                            }

                            return MatchResult{
                                .path_pair = .{ .primary = Path.init(out_buf) },
                                .diff_case = lookup.diff_case,

                                .dirname_fd = dir_info.getFileDescriptor(),
                            };
                        }
                    }
                }

                if (r.debug_logs) |*debug| {
                    debug.addNoteFmt("Failed to find file: \"{s}/{s}\"", .{ path, base }) catch unreachable;
                }
            }

            return null;
        }

        pub fn loadAsIndexWithBrowserRemapping(r: *ThisResolver, dir_info: *DirInfo, path: string, extension_order: []const string) ?MatchResult {
            if (dir_info.getEnclosingBrowserScope()) |browser_scope| {
                const field_rel_path = comptime "index";
                if (browser_scope.package_json) |browser_json| {
                    if (r.checkBrowserMap(browser_json, field_rel_path)) |remap| {
                        // Is the path disabled?
                        // This doesn't really make sense to me.
                        if (remap.len == 0) {
                            const paths = [_]string{ path, field_rel_path };
                            const new_path = r.fs.absAlloc(r.allocator, &paths) catch unreachable;
                            var _path = Path.init(new_path);
                            _path.is_disabled = true;
                            return MatchResult{
                                .path_pair = PathPair{
                                    .primary = _path,
                                },
                                .package_json = browser_json,
                            };
                        }

                        const new_paths = [_]string{ path, remap };
                        const remapped_abs = r.fs.absAlloc(r.allocator, &new_paths) catch unreachable;

                        // Is this a file
                        if (r.loadAsFile(remapped_abs, extension_order)) |file_result| {
                            return MatchResult{ .dirname_fd = file_result.dirname_fd, .path_pair = .{ .primary = Path.init(file_result.path) }, .diff_case = file_result.diff_case };
                        }

                        // Is it a directory with an index?
                        if (r.dirInfoCached(remapped_abs) catch null) |new_dir| {
                            if (r.loadAsIndex(new_dir, remapped_abs, extension_order)) |absolute| {
                                return absolute;
                            }
                        }

                        return null;
                    }
                }
            }

            return r.loadAsIndex(dir_info, path, extension_order);
        }

        pub fn loadAsFileOrDirectory(r: *ThisResolver, path: string, kind: ast.ImportKind) ?MatchResult {
            const extension_order = r.opts.extension_order;

            // Is this a file?
            if (r.loadAsFile(path, extension_order)) |file| {
                // ServeBundler cares about the package.json
                if (!cache_files) {
                    // Determine the package folder by looking at the last node_modules/ folder in the path
                    if (strings.lastIndexOf(file.path, "node_modules" ++ std.fs.path.sep_str)) |last_node_modules_folder| {
                        const node_modules_folder_offset = last_node_modules_folder + ("node_modules" ++ std.fs.path.sep_str).len;
                        // Determine the package name by looking at the next separator
                        if (strings.indexOfChar(file.path[node_modules_folder_offset..], std.fs.path.sep)) |package_name_length| {
                            if ((r.dirInfoCached(file.path[0 .. node_modules_folder_offset + package_name_length]) catch null)) |package_dir_info| {
                                if (package_dir_info.package_json) |package_json| {
                                    return MatchResult{
                                        .path_pair = .{ .primary = Path.init(file.path) },
                                        .diff_case = file.diff_case,
                                        .dirname_fd = file.dirname_fd,
                                        .package_json = package_json,
                                    };
                                }
                            }
                        }
                    }
                }

                return MatchResult{
                    .path_pair = .{ .primary = Path.init(file.path) },
                    .diff_case = file.diff_case,
                    .dirname_fd = file.dirname_fd,
                };
            }

            // Is this a directory?
            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Attempting to load \"{s}\" as a directory", .{path}) catch {};
                debug.increaseIndent() catch {};
            }

            defer {
                if (r.debug_logs) |*debug| {
                    debug.decreaseIndent() catch {};
                }
            }

            const dir_info = (r.dirInfoCached(path) catch null) orelse return null;
            var package_json: ?*PackageJSON = null;

            // Try using the main field(s) from "package.json"
            if (dir_info.package_json) |pkg_json| {
                package_json = pkg_json;
                if (pkg_json.main_fields.count() > 0) {
                    const main_field_values = pkg_json.main_fields;
                    const main_field_keys = r.opts.main_fields;
                    // TODO: check this works right. Not sure this will really work.
                    const auto_main = r.opts.main_fields.ptr == options.Platform.DefaultMainFields.get(r.opts.platform).ptr;

                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("Searching for main fields in \"{s}\"", .{pkg_json.source.path.text}) catch {};
                    }

                    for (main_field_keys) |key| {
                        const field_rel_path = (main_field_values.get(key)) orelse {
                            if (r.debug_logs) |*debug| {
                                debug.addNoteFmt("Did not find main field \"{s}\"", .{key}) catch {};
                            }
                            continue;
                        };

                        var _result = r.loadFromMainField(path, dir_info, field_rel_path, key, extension_order) orelse continue;

                        // If the user did not manually configure a "main" field order, then
                        // use a special per-module automatic algorithm to decide whether to
                        // use "module" or "main" based on whether the package is imported
                        // using "import" or "require".
                        if (auto_main and strings.eqlComptime(key, "module")) {
                            var absolute_result: ?MatchResult = null;

                            if (main_field_values.get("main")) |main_rel_path| {
                                if (main_rel_path.len > 0) {
                                    absolute_result = r.loadFromMainField(path, dir_info, main_rel_path, "main", extension_order);
                                }
                            } else {
                                // Some packages have a "module" field without a "main" field but
                                // still have an implicit "index.js" file. In that case, treat that
                                // as the value for "main".
                                absolute_result = r.loadAsIndexWithBrowserRemapping(dir_info, path, extension_order);
                            }

                            if (absolute_result) |auto_main_result| {
                                // If both the "main" and "module" fields exist, use "main" if the
                                // path is for "require" and "module" if the path is for "import".
                                // If we're using "module", return enough information to be able to
                                // fall back to "main" later if something ended up using "require()"
                                // with this same path. The goal of this code is to avoid having
                                // both the "module" file and the "main" file in the bundle at the
                                // same time.
                                if (kind != ast.ImportKind.require) {
                                    if (r.debug_logs) |*debug| {
                                        debug.addNoteFmt("Resolved to \"{s}\" using the \"module\" field in \"{s}\"", .{ auto_main_result.path_pair.primary.text, pkg_json.source.key_path.text }) catch {};

                                        debug.addNoteFmt("The fallback path in case of \"require\" is {s}", .{auto_main_result.path_pair.primary.text}) catch {};
                                    }

                                    return MatchResult{
                                        .path_pair = .{
                                            .primary = auto_main_result.path_pair.primary,
                                            .secondary = _result.path_pair.primary,
                                        },
                                        .diff_case = auto_main_result.diff_case,
                                        .dirname_fd = auto_main_result.dirname_fd,
                                        .package_json = package_json,
                                    };
                                } else {
                                    if (r.debug_logs) |*debug| {
                                        debug.addNoteFmt("Resolved to \"{s}\" using the \"{s}\" field in \"{s}\"", .{
                                            auto_main_result.path_pair.primary.text,
                                            key,
                                            pkg_json.source.key_path.text,
                                        }) catch {};
                                    }
                                    var _auto_main_result = auto_main_result;
                                    _auto_main_result.package_json = package_json;
                                    return _auto_main_result;
                                }
                            }
                        }

                        _result.package_json = _result.package_json orelse package_json;
                        return _result;
                    }
                }
            }

            // Look for an "index" file with known extensions
            if (r.loadAsIndexWithBrowserRemapping(dir_info, path, extension_order)) |*res| {
                res.package_json = res.package_json orelse package_json;
                return res.*;
            }

            return null;
        }

        pub fn loadAsFile(r: *ThisResolver, path: string, extension_order: []const string) ?LoadResult {
            var rfs: *Fs.FileSystem.RealFS = &r.fs.fs;

            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Attempting to load \"{s}\" as a file", .{path}) catch {};
                debug.increaseIndent() catch {};
            }
            defer {
                if (r.debug_logs) |*debug| {
                    debug.decreaseIndent() catch {};
                }
            }

            const dir_path = Dirname.dirname(path);

            const dir_entry: *Fs.FileSystem.RealFS.EntriesOption = rfs.readDirectory(
                dir_path,
                null,
            ) catch {
                return null;
            };

            if (@as(Fs.FileSystem.RealFS.EntriesOption.Tag, dir_entry.*) == .err) {
                if (dir_entry.err.original_err != error.ENOENT) {
                    r.log.addErrorFmt(
                        null,
                        logger.Loc.Empty,
                        r.allocator,
                        "Cannot read directory \"{s}\": {s}",
                        .{
                            r.prettyPath(Path.init(dir_path)),
                            @errorName(dir_entry.err.original_err),
                        },
                    ) catch {};
                }
                return null;
            }

            const entries = dir_entry.entries;

            const base = std.fs.path.basename(path);

            // Try the plain path without any extensions
            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Checking for file \"{s}\" ", .{base}) catch {};
            }

            if (entries.get(base)) |query| {
                if (query.entry.kind(rfs) == .file) {
                    if (r.debug_logs) |*debug| {
                        debug.addNoteFmt("Found file \"{s}\" ", .{base}) catch {};
                    }
                    const abs_path_parts = [_]string{ query.entry.dir, query.entry.base() };
                    const abs_path = r.fs.dirname_store.append(string, r.fs.absBuf(&abs_path_parts, &TemporaryBuffer.ExtensionPathBuf)) catch unreachable;

                    return LoadResult{
                        .path = abs_path,
                        .diff_case = query.diff_case,
                        .dirname_fd = entries.fd,
                    };
                }
            }

            // Try the path with extensions
            std.mem.copy(u8, &TemporaryBuffer.ExtensionPathBuf, path);
            for (r.opts.extension_order) |ext| {
                var buffer = TemporaryBuffer.ExtensionPathBuf[0 .. path.len + ext.len];
                std.mem.copy(u8, buffer[path.len..buffer.len], ext);
                const file_name = buffer[path.len - base.len .. buffer.len];

                if (r.debug_logs) |*debug| {
                    debug.addNoteFmt("Checking for file \"{s}\" ", .{buffer}) catch {};
                }

                if (entries.get(file_name)) |query| {
                    if (query.entry.kind(rfs) == .file) {
                        if (r.debug_logs) |*debug| {
                            debug.addNoteFmt("Found file \"{s}\" ", .{buffer}) catch {};
                        }

                        // now that we've found it, we allocate it.
                        return LoadResult{
                            .path = r.fs.dirname_store.append(@TypeOf(buffer), buffer) catch unreachable,
                            .diff_case = query.diff_case,
                            .dirname_fd = entries.fd,
                        };
                    }
                }
            }

            // TypeScript-specific behavior: if the extension is ".js" or ".jsx", try
            // replacing it with ".ts" or ".tsx". At the time of writing this specific
            // behavior comes from the function "loadModuleFromFile()" in the file
            // "moduleNameThisResolver.ts" in the TypeScript compiler source code. It
            // contains this comment:
            //
            //   If that didn't work, try stripping a ".js" or ".jsx" extension and
            //   replacing it with a TypeScript one; e.g. "./foo.js" can be matched
            //   by "./foo.ts" or "./foo.d.ts"
            //
            // We don't care about ".d.ts" files because we can't do anything with
            // those, so we ignore that part of the behavior.
            //
            // See the discussion here for more historical context:
            // https://github.com/microsoft/TypeScript/issues/4595
            if (strings.lastIndexOfChar(base, '.')) |last_dot| {
                const ext = base[last_dot..base.len];
                if (strings.eql(ext, ".js") or strings.eql(ext, ".jsx")) {
                    const segment = base[0..last_dot];
                    std.mem.copy(u8, &TemporaryBuffer.ExtensionPathBuf, segment);

                    const exts = comptime [_]string{ ".ts", ".tsx" };

                    for (exts) |ext_to_replace| {
                        var buffer = TemporaryBuffer.ExtensionPathBuf[0 .. segment.len + ext_to_replace.len];
                        std.mem.copy(u8, buffer[segment.len..buffer.len], ext_to_replace);

                        if (entries.get(buffer)) |query| {
                            if (query.entry.kind(rfs) == .file) {
                                if (r.debug_logs) |*debug| {
                                    debug.addNoteFmt("Rewrote to \"{s}\" ", .{buffer}) catch {};
                                }

                                return LoadResult{
                                    .path = r.fs.dirname_store.append(@TypeOf(buffer), buffer) catch unreachable,
                                    .diff_case = query.diff_case,
                                    .dirname_fd = entries.fd,
                                };
                            }
                        }
                        if (r.debug_logs) |*debug| {
                            debug.addNoteFmt("Failed to rewrite \"{s}\" ", .{base}) catch {};
                        }
                    }
                }
            }

            if (r.debug_logs) |*debug| {
                debug.addNoteFmt("Failed to find \"{s}\" ", .{path}) catch {};
            }

            if (comptime FeatureFlags.watch_directories) {
                // For existent directories which don't find a match
                // Start watching it automatically,
                // onStartWatchingDirectory fn decides whether to actually watch.
                if (r.onStartWatchingDirectoryCtx) |ctx| {
                    r.onStartWatchingDirectory.?(ctx, entries.dir, entries.fd);
                }
            }
            return null;
        }

        fn dirInfoUncached(
            r: *ThisResolver,
            path: string,
            _entries: *Fs.FileSystem.RealFS.EntriesOption,
            _result: allocators.Result,
            dir_entry_index: allocators.IndexType,
            parent: ?*DirInfo,
            parent_index: allocators.IndexType,
            fd: FileDescriptorType,
        ) anyerror!DirInfo {
            var result = _result;

            var rfs: *Fs.FileSystem.RealFS = &r.fs.fs;
            var entries = _entries.entries;

            var info = DirInfo{
                .abs_path = path,
                // .abs_real_path = path,
                .parent = parent_index,
                .entries = dir_entry_index,
            };

            // A "node_modules" directory isn't allowed to directly contain another "node_modules" directory
            var base = std.fs.path.basename(path);

            // base must
            if (base.len > 1 and base[base.len - 1] == std.fs.path.sep) base = base[0 .. base.len - 1];

            // if (entries != null) {
            if (!strings.eqlComptime(base, "node_modules")) {
                if (entries.getComptimeQuery("node_modules")) |entry| {
                    // the catch might be wrong!
                    info.has_node_modules = (entry.entry.kind(rfs)) == .dir;
                }
            }
            // }

            if (parent != null) {

                // Propagate the browser scope into child directories
                info.enclosing_browser_scope = parent.?.enclosing_browser_scope;

                // Make sure "absRealPath" is the real path of the directory (resolving any symlinks)
                if (!r.opts.preserve_symlinks) {
                    if (parent.?.getEntries()) |parent_entries| {
                        if (parent_entries.get(base)) |lookup| {
                            const entry = lookup.entry;

                            var symlink = entry.symlink(rfs);
                            if (symlink.len > 0) {
                                if (r.debug_logs) |*logs| {
                                    try logs.addNote(std.fmt.allocPrint(r.allocator, "Resolved symlink \"{s}\" to \"{s}\"", .{ path, symlink }) catch unreachable);
                                }
                                info.abs_real_path = symlink;
                            } else if (parent.?.abs_real_path.len > 0) {
                                // this might leak a little i'm not sure
                                const parts = [_]string{ parent.?.abs_real_path, base };
                                symlink = r.fs.dirname_store.append(string, r.fs.joinBuf(&parts, &dir_info_uncached_filename_buf)) catch unreachable;

                                if (r.debug_logs) |*logs| {
                                    try logs.addNote(std.fmt.allocPrint(r.allocator, "Resolved symlink \"{s}\" to \"{s}\"", .{ path, symlink }) catch unreachable);
                                }
                                info.abs_real_path = symlink;
                            }
                        }
                    }
                }
            }

            // Record if this directory has a package.json file
            if (entries.getComptimeQuery("package.json")) |lookup| {
                const entry = lookup.entry;
                if (entry.kind(rfs) == .file) {
                    info.package_json = r.parsePackageJSON(path, if (FeatureFlags.store_file_descriptors) fd else 0) catch null;

                    if (info.package_json) |pkg| {
                        if (pkg.browser_map.count() > 0) {
                            info.enclosing_browser_scope = result.index;
                        }

                        if (r.debug_logs) |*logs| {
                            logs.addNoteFmt("Resolved package.json in \"{s}\"", .{
                                path,
                            }) catch unreachable;
                        }
                    }
                }
            }

            // Record if this directory has a tsconfig.json or jsconfig.json file
            {
                var tsconfig_path: ?string = null;
                if (r.opts.tsconfig_override == null) {
                    if (entries.getComptimeQuery("tsconfig.json")) |lookup| {
                        const entry = lookup.entry;
                        if (entry.kind(rfs) == .file) {
                            const parts = [_]string{ path, "tsconfig.json" };

                            tsconfig_path = r.fs.absBuf(&parts, &dir_info_uncached_filename_buf);
                        }
                    }
                    if (tsconfig_path == null) {
                        if (entries.getComptimeQuery("jsconfig.json")) |lookup| {
                            const entry = lookup.entry;
                            if (entry.kind(rfs) == .file) {
                                const parts = [_]string{ path, "jsconfig.json" };
                                tsconfig_path = r.fs.absBuf(&parts, &dir_info_uncached_filename_buf);
                            }
                        }
                    }
                } else if (parent == null) {
                    tsconfig_path = r.opts.tsconfig_override.?;
                }

                if (tsconfig_path) |tsconfigpath| {
                    info.tsconfig_json = r.parseTSConfig(
                        tsconfigpath,
                        if (FeatureFlags.store_file_descriptors) fd else 0,
                    ) catch |err| brk: {
                        const pretty = r.prettyPath(Path.init(tsconfigpath));

                        if (err == error.ENOENT) {
                            r.log.addErrorFmt(null, logger.Loc.Empty, r.allocator, "Cannot find tsconfig file \"{s}\"", .{pretty}) catch unreachable;
                        } else if (err != error.ParseErrorAlreadyLogged and err != error.IsDir) {
                            r.log.addErrorFmt(null, logger.Loc.Empty, r.allocator, "Cannot read file \"{s}\": {s}", .{ pretty, @errorName(err) }) catch unreachable;
                        }
                        break :brk null;
                    };
                }
            }

            if (info.tsconfig_json == null and parent != null) {
                info.tsconfig_json = parent.?.tsconfig_json;
            }

            return info;
        }
    };
}

pub const Resolver = NewResolver(
    true,
);
pub const ResolverUncached = NewResolver(
    false,
);

const Dirname = struct {
    pub fn dirname(path: string) string {
        if (path.len == 0)
            return "/";

        var end_index: usize = path.len - 1;
        while (path[end_index] == '/') {
            if (end_index == 0)
                return "/";
            end_index -= 1;
        }

        while (path[end_index] != '/') {
            if (end_index == 0)
                return "/";
            end_index -= 1;
        }

        if (end_index == 0 and path[0] == '/')
            return path[0..1];

        if (end_index == 0)
            return "/";

        return path[0 .. end_index + 1];
    }
};