-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathresolver.rs
More file actions
6791 lines (6302 loc) · 315 KB
/
Copy pathresolver.rs
File metadata and controls
6791 lines (6302 loc) · 315 KB
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
//! The [`Resolver`] state machine: import-path resolution against the on-disk
//! filesystem, `node_modules` tree, `tsconfig.json` paths, package `exports`,
//! `browser` maps, and the standalone (compiled) module graph. Holds the
//! `Resolver` struct and its impl,
//! plus the local helper shims (`bun_paths` value-dispatch joins,
//! `bun_sys` dir-open wrappers, `FdExt`) and threadlocal scratch buffers.
use crate::{is_package_path, is_package_path_not_absolute};
use core::ptr::NonNull;
use std::io::Write as _;
// ── Cross-crate type surface ──────────────────────────────────────────────
// Higher-tier symbols are reached through lower-tier crates:
// • install value types + AutoInstaller trait — bun_install_types (MOVE_DOWN)
// • HardcodedModule alias table — bun_resolve_builtins
// • StandaloneModuleGraph — trait below; impl in bun_standalone_graph
// • perf / crash_handler — real bun_perf / bun_crash_handler
use ::bun_install_types::resolver_hooks as Install;
use ::bun_install_types::resolver_hooks::{AutoInstaller, Resolution};
use ::bun_semver as Semver;
// Re-exported so downstream (bun_bundler) can name the trait in
// `Transpiler::get_package_manager`'s return type without a direct
// `bun_install_types` dep (LAYERING: pass-through, no new edge).
pub use ::bun_install_types::resolver_hooks::AutoInstaller as PackageManagerTrait;
// LAYERING: `PackageManager.initWithRuntime` lives in
// `bun_install`, which depends on this crate. The lazy-init body is defined
// `#[no_mangle]` in `bun_install::auto_installer` and resolved at link time
// (same pattern as `__bun_regex_*` / `__BUN_RUNTIME_HOOKS`). `install` is the
// `?*Api.BunInstall` (`self.opts.install`); `env` is the `*DotEnv.Loader`
// (lifetime-erased to `'static` — the install crate stores it as a raw
// `NonNull<Loader<'static>>`).
unsafe extern "Rust" {
/// SAFETY (genuine FFI precondition — NOT a `safe fn` candidate): impl
/// reborrows `&mut *log` / `&mut *env` and reads `*install` if non-null.
/// All three must point at process-lifetime Transpiler-owned storage; the
/// returned `NonNull` names the `'static` `PackageManager` singleton.
/// Errs when the one-time init fails (e.g. the top-level directory is
/// unreadable); the failure is sticky across calls.
fn __bun_resolver_init_package_manager(
log: NonNull<bun_ast::Log>,
install: Option<NonNull<bun_options_types::schema::api::BunInstall>>,
env: NonNull<bun_dotenv::Loader<'static>>,
) -> core::result::Result<NonNull<dyn AutoInstaller>, bun_core::Error>;
}
use crate::cache::Set as CacheSet;
use ::bun_resolve_builtins::{Alias as HardcodedAlias, Cfg as HardcodedAliasCfg};
/// `Dependency` namespace as the body spells it (`Dependency::Version` /
/// `Dependency::Behavior`). Re-exports the canonical `bun_install_types` items.
pub mod Dependency {
pub use ::bun_install_types::resolver_hooks::{
Behavior, Dependency, DependencyVersion as Version, DependencyVersionTag,
};
pub mod version {
pub use ::bun_install_types::resolver_hooks::DependencyVersionTag as Tag;
}
}
/// Transitional re-export module: `package_json.rs` and a few external crates
/// still spell these paths via `__forward_decls`; the items are now real
/// re-exports of `bun_install_types` (no local stubs).
pub(crate) mod __forward_decls {}
// bun_paths shim — value-dispatched join helpers over `resolve_path::Platform`.
// `dirname` (`Option`-returning) and
// `PosixToWinNormalizer` are the real `::bun_paths` items — brought in by the
// glob / explicit re-export below, no local re-implementation.
mod bun_paths {
pub(super) use ::bun_paths::resolve_path::PosixToWinNormalizer;
pub(super) use ::bun_paths::resolve_path::is_sep_any;
pub(super) use ::bun_paths::*;
/// Value-dispatch over `Platform` to the const-generic `PlatformT`
/// monomorphizations in `resolve_path`. The resolver body threads
/// `Platform::AUTO` / `Platform::Loose` at runtime.
macro_rules! dispatch_platform {
($p:expr, |$P:ident| $body:expr) => {{
use ::bun_paths::resolve_path::{self as rp, platform};
match $p {
rp::Platform::Loose => {
type $P = platform::Loose;
$body
}
rp::Platform::Windows => {
type $P = platform::Windows;
$body
}
rp::Platform::Posix => {
type $P = platform::Posix;
$body
}
rp::Platform::Nt => {
type $P = platform::Nt;
$body
}
}
}};
}
pub(super) fn dirname_platform(p: &[u8], platform: Platform) -> &[u8] {
dispatch_platform!(platform, |P| ::bun_paths::resolve_path::dirname::<P>(p))
}
/// Port of `bun.path.joinAbsStringBuf` (value-dispatched).
pub(super) fn join_abs_string_buf<'b>(
cwd: &'b [u8],
buf: &'b mut [u8],
parts: &[&[u8]],
platform: Platform,
) -> &'b [u8] {
dispatch_platform!(
platform,
|P| ::bun_paths::resolve_path::join_abs_string_buf::<P>(cwd, buf, parts)
)
}
pub(super) fn join_abs(cwd: &[u8], platform: Platform, part: &[u8]) -> &'static [u8] {
// NOTE: `resolve_path::join_abs` ties the result lifetime to `cwd`, but the
// returned slice always points into the threadlocal `PARSER_JOIN_INPUT_BUFFER`
// (or is `cwd` itself when `parts.is_empty()`, which never happens here — we
// pass exactly one part). Re-erase to `'static` so the resolver can hold it
// across `&mut self` calls.
let s = dispatch_platform!(platform, |P| ::bun_paths::resolve_path::join_abs::<P>(
cwd, part
));
// SAFETY: see NOTE — slice borrows threadlocal storage, valid 'static per-thread.
unsafe { bun_ptr::detach_lifetime(s) }
}
pub(super) fn join(parts: &[&[u8]], platform: Platform) -> &'static [u8] {
dispatch_platform!(platform, |P| ::bun_paths::resolve_path::join::<P>(parts))
}
pub(super) fn join_string_buf<'b>(
buf: &'b mut [u8],
parts: &[&[u8]],
platform: Platform,
) -> &'b [u8] {
dispatch_platform!(
platform,
|P| ::bun_paths::resolve_path::join_string_buf::<P>(buf, parts)
)
}
/// Compile-time platform-separator literal (`/` → `\` on Windows). A
/// const fn can't transform a borrowed `&'static [u8]`, so this is a
/// macro that emits a fresh const array with the swap applied. Result is
/// `&'static [u8; N]` (coerces to `&[u8]`).
#[macro_export]
#[doc(hidden)]
macro_rules! __resolver_path_literal {
($p:expr) => {{
const __IN: &[u8] = $p;
const __N: usize = __IN.len();
const fn __swap(input: &[u8]) -> [u8; __N] {
let mut out = [0u8; __N];
let mut i = 0;
while i < __N {
out[i] = if cfg!(windows) && input[i] == b'/' {
b'\\'
} else {
input[i]
};
i += 1;
}
out
}
const __OUT: [u8; __N] = __swap(__IN);
&__OUT
}};
}
pub(super) use __resolver_path_literal as path_literal;
#[cfg(windows)]
pub(super) fn windows_filesystem_root(p: &[u8]) -> &[u8] {
::bun_paths::resolve_path::windows_filesystem_root(p)
}
}
// bun_core::strings shim — re-export the canonical `immutable/paths` helpers
// (`without_trailing_slash_windows_path` / `path_contains_node_modules_folder` /
// `without_leading_path_separator` / `char_is_any_slash`) instead of locally
// re-implementing them. The previous local copies diverged from the spec
// (single-strip vs. while-loop, `is_sep_any` vs. platform `SEP`).
mod strings {
pub(super) use bun_paths::strings::paths::{
char_is_any_slash, path_contains_node_modules_folder, without_leading_path_separator,
without_trailing_slash_windows_path,
};
pub(super) use bun_paths::strings::*;
#[inline]
pub(super) fn index_of_any(slice: &[u8], chars: &'static [u8]) -> Option<usize> {
bun_core::strings::index_of_any(slice, chars)
}
}
// bun_sys shim — adds the `std.fs`-shaped dir-open surface the resolver names
// (`openDirAbsoluteZ` / `Dir.openDirZ`) on top of the real `::bun_sys` crate.
// `open` / `open_dir_for_iteration` / `get_fd_path` / `OpenDirOptions` /
// `iterate_dir` are now provided by the `pub use ::bun_sys::*` glob.
mod bun_sys {
pub(super) use ::bun_sys::*;
/// `open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC[|O_NOFOLLOW])`.
/// `opts.iterate` is a no-op on POSIX (just an open mode hint).
#[cfg(not(windows))]
pub(super) fn open_dir_absolute_z(
path: &::bun_core::ZStr,
opts: OpenDirOptions,
) -> core::result::Result<Fd, ::bun_core::Error> {
#[cfg(unix)]
let nofollow = if opts.no_follow { libc::O_NOFOLLOW } else { 0 };
#[cfg(not(unix))]
let nofollow = {
let _ = opts;
0
};
::bun_sys::open(path, O::DIRECTORY | O::CLOEXEC | O::RDONLY | nofollow, 0)
.map_err(Into::into)
}
/// Opens a directory relative to `dir`: `openat(dir, path, O_DIRECTORY|O_RDONLY|O_CLOEXEC)`.
pub(super) fn open_dir_z(
dir: Fd,
path: &[u8],
_opts: OpenDirOptions,
) -> core::result::Result<Fd, ::bun_core::Error> {
// NOTE: callers pass either a `&'static [u8]` literal or a NUL-terminated
// slice; `open_dir_at` builds its own ZStr internally so we strip the sentinel.
let path = if path.last() == Some(&0) {
&path[..path.len() - 1]
} else {
path
};
::bun_sys::open_dir_at(dir, path).map_err(Into::into)
}
// `iterate_dir` / `dir_iterator::WrappedIterator` are real ports in
// `::bun_sys::dir_iterator` (POSIX getdents / Windows NtQueryDirectoryFile)
// and reach this module via the `pub use ::bun_sys::*` glob above.
}
/// `bun_sys::Fd` extension surface — thin method-syntax wrappers over the
/// free functions `::bun_sys::{close, get_fd_path}` and `Fd::native`, so the
/// resolver body can spell `fd.close()` / `fd.get_fd_path(buf)`.
trait FdExt: Sized {
fn close(self);
fn get_fd_path<'b>(
self,
buf: &'b mut ::bun_paths::PathBuffer,
) -> core::result::Result<&'b [u8], ::bun_core::Error>;
}
impl FdExt for ::bun_sys::Fd {
#[inline]
fn close(self) {
let _ = ::bun_sys::close(self);
}
#[inline]
fn get_fd_path<'b>(
self,
buf: &'b mut ::bun_paths::PathBuffer,
) -> core::result::Result<&'b [u8], ::bun_core::Error> {
::bun_sys::get_fd_path(self, buf)
.map(|s| &*s)
.map_err(Into::into)
}
}
trait FdZero {
const ZERO: ::bun_sys::Fd;
}
impl FdZero for ::bun_sys::Fd {
const ZERO: ::bun_sys::Fd = ::bun_sys::Fd::INVALID;
}
use self::bun_paths as ResolvePath;
use ::bun_ast::import_record as ast;
use ::bun_core::{FeatureFlags, Generation};
use bun_ast::Msg;
use bun_collections::BoundedArray;
use bun_dotenv::env_loader as DotEnv;
use bun_paths::{MAX_PATH_BYTES, PathBuffer, SEP, SEP_STR};
use bun_perf::system_timer::Timer;
use bun_ptr::Interned;
use bun_sys::Fd as FD;
use bun_threading::Mutex;
use crate::fs as Fs;
use crate::fs::FilenameStoreAppender;
use crate::node_fallbacks as NodeFallbackModules;
use crate::package_json::{BrowserMap, ESModule, PackageJSON};
use crate::tsconfig_json::TSConfigJSON;
pub use crate::data_url::DataURL;
pub use crate::dir_info as DirInfo;
pub use crate::dir_info::DirInfoRef;
pub use ::bun_options_types::global_cache::GlobalCache;
// Sibling resolver modules. They retain the same item names so cross-references
// inside `impl Resolver` resolve unchanged.
use crate::options;
use crate::result::{
DebugLogs, DirEntryResolveQueueItem, FlushMode, LoadResult, MatchResult, MatchStatus, PathPair,
PendingResolution, PendingResolutionTag, Result, ResultFlags, ResultUnion,
};
use crate::standalone_module_graph::StandaloneModuleGraph;
use bun_alloc as allocators;
// `bun.resolver.SideEffects` — same type as `Result.primary_side_effects_data`
// (re-exported from `bun_ast`; see `result.rs`).
use bun_ast::SideEffects;
// ── Process-lifetime arenas for DirInfo-cached parses ─────────────────────
// The DirInfo cache (`DirInfo::hash_map_instance()`) is a true process-lifetime
// singleton; entries hold `&'static PackageJSON` / `&'static TSConfigJSON` and
// borrow `&'static [u8]` source bytes. PORTING.md §Forbidden bars `Box::leak`/
// `mem::forget` for this — process-lifetime storage must go through
// `LazyLock`. These append-only arenas are that storage; the `Box<T>` heap
// address is stable across `Vec` growth, so handing out `&'static T` is sound.
/// Intern a parsed `PackageJSON` into the process-lifetime DirInfo arena.
/// Returns `NonNull` (not `&'static`) so the mut-provenance survives into
/// `DirInfo::reset()`'s `drop_in_place` -- handing out `&T` here and casting
/// back to `*mut T` at the drop site would be UB under Stacked Borrows.
fn intern_package_json(pkg: PackageJSON) -> core::ptr::NonNull<PackageJSON> {
// `Box` is load-bearing: returns `NonNull<PackageJSON>` derived from the
// box interior, treated as `'static`; unboxing would dangle on `Vec` realloc.
#[expect(clippy::vec_box)]
static ARENA: std::sync::LazyLock<bun_threading::Guarded<Vec<Box<PackageJSON>>>> =
std::sync::LazyLock::new(Default::default);
let mut guard = ARENA.lock();
guard.push(Box::new(pkg));
// SAFETY: ARENA is `'static` (LazyLock); entries are never removed; the
// `Box<PackageJSON>` heap address is stable across `Vec` reallocation.
// Derive from `&mut **last` so the returned pointer carries mut-provenance.
core::ptr::NonNull::from(&mut **guard.last_mut().unwrap())
}
// `bun_core::declare_scope!` emits the per-scope `static ScopedLogger`; the
// `debuglog!` macro forwards to the real `bun_core::scoped_log!` so debug builds
// emit and release builds dead-strip (PORTING.md §Logging).
//
bun_core::define_scoped_log!(debuglog, Resolver, hidden);
// Used by `bustDirCache`. Same `Resolver` tag as `debuglog` above (so
// `BUN_DEBUG_Resolver` controls both) but visible by default. `declare_scope!`
// derives the tag from the static's ident, so this one is hand-declared to
// keep the printed tag identical.
#[allow(non_upper_case_globals)]
static ResolverDev: bun_core::output::ScopedLogger =
bun_core::output::ScopedLogger::new("Resolver", bun_core::output::Visibility::Visible);
// NOTE: `Path` in the body is the `'static`-interned variant (paths borrow
// DirnameStore/FilenameStore). Alias here so the ~80 bare-`Path` use sites
// resolve without a per-site lifetime annotation.
type Path = crate::fs::Path<'static>;
use crate::dir_info::HashMapExt as _;
/// A temporary threadlocal buffer with a lifetime more than the current
/// function call.
///
/// These used to be individual `threadlocal var x: bun.PathBuffer = undefined`
/// declarations. On Windows each `PathBuffer` is 96 KB (vs 4 KB on POSIX) and
/// PE/COFF has no TLS-BSS, so 25 of them here cost ~2.5 MB of raw zeros in
/// bun.exe and in every thread's TLS block. Grouping them behind a lazily
/// allocated pointer brings that down to 8 bytes. See `bun.ThreadlocalBuffers`.
///
/// Experimenting with making this one struct instead of a bunch of different
/// threadlocal vars yielded no performance improvement on macOS when bundling
/// 10 copies of Three.js. Potentially revisit after https://github.com/oven-sh/bun/issues/2716
pub struct Bufs {
pub extension_path: PathBuffer,
pub tsconfig_match_full_buf: PathBuffer,
pub tsconfig_match_full_buf2: PathBuffer,
pub tsconfig_match_full_buf3: PathBuffer,
pub esm_subpath: [u8; 512],
pub esm_absolute_package_path: PathBuffer,
pub esm_absolute_package_path_joined: PathBuffer,
// NOTE: `DirEntryResolveQueueItem` holds
// `&'static [u8]` fields, so a zeroed bit-pattern is UB. Use
// `MaybeUninit` and `assume_init_{ref,mut}` at the (linear write-then-read)
// use sites in `dir_info_cached_maybe_log`.
pub dir_entry_paths_to_resolve: [core::mem::MaybeUninit<DirEntryResolveQueueItem>; 256],
pub open_dirs: [FD; 256],
pub resolve_without_remapping: PathBuffer,
pub index: PathBuffer,
pub dir_info_uncached_filename: PathBuffer,
pub node_bin_path: PathBuffer,
pub dir_info_uncached_path: PathBuffer,
pub tsconfig_base_url: PathBuffer,
pub relative_abs_path: PathBuffer,
pub load_as_file_or_directory_via_tsconfig_base_path: PathBuffer,
pub node_modules_check: PathBuffer,
pub field_abs_path: PathBuffer,
pub tsconfig_path_abs: PathBuffer,
pub check_browser_map: PathBuffer,
pub remap_path: PathBuffer,
pub load_as_file: PathBuffer,
pub remap_path_trailing_slash: PathBuffer,
pub path_in_global_disk_cache: PathBuffer,
pub abs_to_rel: PathBuffer,
pub node_modules_paths_buf: PathBuffer,
pub import_path_for_standalone_module_graph: PathBuffer,
#[cfg(windows)]
pub win32_normalized_dir_info_cache: [u8; MAX_PATH_BYTES * 2],
#[cfg(not(windows))]
pub win32_normalized_dir_info_cache: (),
}
// `Bufs` is modeled as a `thread_local! { static BUFS_PTR: BufsSlot }` caching a
// leaked `Box<Bufs>` pointer. `BufsSlot`'s `Drop` reclaims that box when a
// worker/transpiler-pool thread exits; the main thread's lives process-lifetime.
// The `bufs!()` macro hands out `&mut` to a
// single field. This relies on the caller never holding two `bufs!()` borrows
// simultaneously across the same field.
struct BufsSlot(core::cell::Cell<*mut Bufs>);
impl Drop for BufsSlot {
fn drop(&mut self) {
// Reclaim the per-thread `Box<Bufs>` when a worker/transpiler-pool
// thread exits. Main-thread Bufs lives as long as the process, but
// every worker that touches the resolver allocates a fresh ~116 KiB
// box that was previously stranded.
let p = self.0.get();
if !p.is_null() {
// SAFETY: produced by `Box::leak` in `bufs_storage_init`; this
// thread is exiting so no resolver call frame holds a `bufs!()`
// borrow into it.
drop(unsafe { Box::from_raw(p) });
}
}
}
thread_local! {
static BUFS_PTR: BufsSlot = const { BufsSlot(core::cell::Cell::new(core::ptr::null_mut())) };
}
#[inline(always)]
fn bufs_storage_get() -> *mut Bufs {
// Fast path: TLS access + null check. `BUFS_PTR` is a `BufsSlot` (it has a
// `Drop`), so `with()` goes through `thread_local!`'s destructor-state check
// before the `Cell::get` load — still only a few instructions, no
// RefCell/Option/closure machinery on the hot path (benches: misc/require-fs).
let p = BUFS_PTR.with(|s| s.0.get());
if !p.is_null() {
return p;
}
bufs_storage_init()
}
#[cold]
fn bufs_storage_init() -> *mut Bufs {
// SAFETY: every field of `Bufs` is a byte/integer array
// (`PathBuffer` = `[u8; N]`, `[FD; 256]` where `Fd` is a
// `#[repr(C)]` integer newtype, `[MaybeUninit<_>; 256]` which has
// no validity requirement, `()`), so EVERY bit-pattern — not just
// all-zero — is a valid `Bufs`. Each
// field is scratch (write-then-read within a single resolve call,
// including `open_dirs` which is bounded by `open_dir_count`), so
// there is no need to pay for zero-filling ~100 KiB on first use.
let p: *mut Bufs = Box::leak(unsafe { Box::<Bufs>::new_uninit().assume_init() });
BUFS_PTR.with(|s| s.0.set(p));
p
}
/// `bufs(.field)` → `bufs!(field)` returns `&mut <field type>`.
/// // SAFETY: callers must not alias the same field; threadlocal so no cross-thread races.
macro_rules! bufs {
($field:ident) => {
// SAFETY: threadlocal storage; callers must not alias the same field within one call frame.
unsafe { &mut (*bufs_storage_get()).$field }
};
}
// This is a global so even if multiple resolvers are created, the mutex will still work
// `pub(crate)` so the `fs::EntriesMap::inner` debug-assert can verify it is held
// (the resolver mutex is one of the two documented guards for the entries singleton).
pub(crate) static RESOLVER_MUTEX: Mutex = Mutex::new();
type BinFolderArray = BoundedArray<&'static [u8], 128>;
// `BoundedArray` has no const constructor; init lazily under
// `BIN_FOLDERS_LOADED`.
static BIN_FOLDERS: bun_core::RacyCell<core::mem::MaybeUninit<BinFolderArray>> =
bun_core::RacyCell::new(core::mem::MaybeUninit::uninit());
static BIN_FOLDERS_LOCK: Mutex = Mutex::new();
static BIN_FOLDERS_LOADED: core::sync::atomic::AtomicBool =
core::sync::atomic::AtomicBool::new(false);
// LAYERING: `AnyResolveWatcher` is the erased vtable the resolver calls to
// register directory watches. The concrete callback lives in `bun_watcher`
// (lower tier); defining the vtable shape there and re-exporting here keeps a
// single type so `Watcher::get_resolve_watcher()` flows directly into
// `Resolver.watcher` without a seam converter.
pub use bun_watcher::AnyResolveWatcher;
// NOTE: const fn-pointer generics (`adt_const_params` for fn ptrs) and
// const params depending on type params are both forbidden. Carry a
// runtime fn-pointer alongside the context — `init` produces the
// `AnyResolveWatcher` erased shim.
pub struct ResolveWatcher<C> {
on_watch: fn(*mut C, &[u8], FD),
_marker: core::marker::PhantomData<*mut C>,
}
impl<C> ResolveWatcher<C> {
pub const fn new(on_watch: fn(*mut C, &[u8], FD)) -> Self {
Self {
on_watch,
_marker: core::marker::PhantomData,
}
}
pub fn init(self, ctx: *mut C) -> AnyResolveWatcher {
AnyResolveWatcher {
context: ctx.cast(),
// SAFETY: `fn(*mut C, ..)` and `fn(*mut (), ..)` are ABI-identical
// (Rust-ABI, thin-ptr first arg). The callback body discharges its
// own type-recovery.
callback: unsafe {
bun_ptr::cast_fn_ptr::<fn(*mut C, &[u8], FD), fn(*mut (), &[u8], FD)>(self.on_watch)
},
}
}
}
pub struct Resolver<'a> {
pub opts: options::BundleOptions,
// NOTE: `fs` / `log` are raw aliasing
// pointers — the bundler builds a `Resolver` per worker thread sharing the
// process-wide `FileSystem` singleton, so `&'a mut` here would manufacture
// aliased unique refs across threads (instant UB). Model as `*mut` /
// `NonNull` (never-null but raw-aliasing) and deref through the `fs()` /
// `log()` accessors below.
pub fs: *mut Fs::FileSystem,
pub log: NonNull<bun_ast::Log>,
// allocator dropped — global mimalloc
/// NOTE: saved/restored across nested resolves.
/// Stored as a `Copy` enum tag (no self-reference) and resolved on demand
/// via [`Self::extension_order`] / [`options::BundleOptions::ext_order_slice`].
pub extension_order: options::ExtOrder,
pub timer: Timer,
pub care_about_bin_folder: bool,
pub care_about_scripts: bool,
/// Read the "browser" field in package.json files?
/// For Bun's runtime, we don't.
pub care_about_browser_field: bool,
pub debug_logs: Option<DebugLogs>,
pub elapsed: u64, // tracing
pub watcher: Option<AnyResolveWatcher>,
pub caches: CacheSet,
pub generation: Generation,
/// Auto-install backend. `bun_install::PackageManager` implements
/// [`AutoInstaller`]; the resolver only sees the trait object so it stays
/// below `bun_install` in the dep graph. `None` until the auto-install
/// path is first reached: [`get_package_manager`] then initializes the
/// singleton through the link-time `__bun_resolver_init_package_manager`
/// factory and caches the pointer here. A failed init (e.g. unreadable
/// top-level directory) is returned as an error and leaves this `None`.
pub package_manager: Option<NonNull<dyn AutoInstaller>>,
pub on_wake_package_manager: Install::WakeHandler,
// Stored as `NonNull` (not `&'a Loader`) because the same allocation is
// mutably reborrowed via `Transpiler.env: *mut Loader` after this field is
// set (e.g. bake/production.rs assigns this then calls `configure_defines()`
// → `run_env_loader()` which takes `&mut *self.env`). Holding a live
// `&Loader` across that `&mut Loader` would be aliased-&mut UB; a raw
// pointer carries no aliasing guarantee.
pub env_loader: Option<NonNull<DotEnv::Loader<'a>>>,
pub store_fd: bool,
pub standalone_module_graph: Option<&'a dyn StandaloneModuleGraph>,
// These are sets that represent various conditions for the "exports" field
// in package.json.
// esm_conditions_default: bun.StringHashMap(bool),
// esm_conditions_import: bun.StringHashMap(bool),
// esm_conditions_require: bun.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.
pub mutex: &'static Mutex,
/// This cache maps a directory path to information about that directory and
/// all parent directories. When interacting with this structure, make sure
/// to validate your keys with `Resolver.assertValidCacheKey`
// NOTE: a raw aliasing pointer to the
// `DirInfo::hash_map_instance()` singleton. Modeled as `*mut` (not `&'static mut`)
// for the same reason as `fs`/`log` above — every per-worker `Resolver` shares the
// singleton, so a `&'static mut` here would manufacture aliased unique refs (UB).
// Deref through the `dir_cache()` accessor below.
pub dir_cache: *mut DirInfo::HashMap,
/// This is set to false for the runtime. The runtime should choose "main"
/// over "module" in package.json
pub prefer_module_field: bool,
/// This is an array of paths to resolve against. Used for passing an
/// object '{ paths: string[] }' to `require` and `resolve`; This field
/// is overwritten while the resolution happens.
///
/// When this is null, it is as if it is set to `&.{ path.dirname(referrer) }`.
pub custom_dir_paths: Option<&'a [bun_core::String]>,
}
/// RAII guard returned by [`Resolver::scoped_log`]. Restores the previous
/// `Resolver::log` pointer on drop.
pub struct ResolverLogScope {
slot: *mut NonNull<bun_ast::Log>,
prev: NonNull<bun_ast::Log>,
}
impl Drop for ResolverLogScope {
#[inline]
fn drop(&mut self) {
// SAFETY: `slot` was derived via `addr_of_mut!` from the raw resolver
// pointer in `scoped_log` (SharedReadWrite provenance); caller contract
// guarantees the resolver outlives this guard.
unsafe { *self.slot = self.prev };
}
}
impl<'a> Resolver<'a> {
/// Per-worker constructor — replaces the bundler's prior bitwise
/// copy-from-`from` for the resolver
/// portion. Every `Copy` / raw-pointer field is copied from `from`; the
/// per-worker `caches` (the only `Drop`-carrying field, via the
/// `Json` cache's `MimallocArena`) and `debug_logs`/`timer` are freshly
/// constructed so nothing the parent owns is aliased into the worker.
///
/// `opts` and `log` are supplied by the caller (the worker projects a
/// fresh `BundleOptions` subset and arena-allocates its own `Log`).
///
/// # Safety
/// `from`'s `standalone_module_graph` / `env_loader` borrow data that
/// outlives the returned resolver (process-lifetime singletons in every
/// caller). The lifetime is widened from `'from` to `'a` here; callers
/// must uphold that the borrowed data outlives `'a`.
pub unsafe fn for_worker(
from: &Resolver<'_>,
log: NonNull<bun_ast::Log>,
opts: options::BundleOptions,
) -> Resolver<'a> {
Resolver {
opts,
fs: from.fs,
log,
extension_order: from.extension_order,
timer: Timer::start().unwrap_or_else(|_| panic!("Timer fail")),
care_about_bin_folder: from.care_about_bin_folder,
care_about_scripts: from.care_about_scripts,
care_about_browser_field: from.care_about_browser_field,
// `DebugLogs` owns Vecs — per-worker fresh.
debug_logs: None,
elapsed: 0,
watcher: from.watcher,
caches: CacheSet::init(),
generation: from.generation,
package_manager: from.package_manager,
on_wake_package_manager: from.on_wake_package_manager,
// SAFETY: see fn doc — pointee outlives `'a`.
env_loader: from.env_loader.map(|p| p.cast::<DotEnv::Loader<'a>>()),
store_fd: from.store_fd,
// SAFETY: see fn doc — lifetime-widen the trait-object borrow. The
// vtable layout is identical (only the borrow-checker tag differs);
// a raw-pointer `as`-cast cannot change the `+ 'b` bound, so widen
// via a layout-preserving transmute on the `Option<&dyn>`.
standalone_module_graph: unsafe {
core::mem::transmute::<
Option<&'_ dyn StandaloneModuleGraph>,
Option<&'a dyn StandaloneModuleGraph>,
>(from.standalone_module_graph)
},
mutex: from.mutex,
dir_cache: from.dir_cache,
prefer_module_field: from.prefer_module_field,
// Transient per-resolve scratch (only set for `require(..., {paths})`);
// never carried across worker init.
custom_dir_paths: None,
}
}
/// NOTE (Stacked Borrows): returns the RAW `*mut` (NOT `&'a mut`). A
/// `&'a mut` accessor would let two `fs()` calls manufacture coexisting
/// aliased unique refs to the same singleton (PORTING.md §Forbidden:
/// aliased-&mut), and any later `&mut *self.fs` retag would pop a previously
/// returned `&'a mut`'s SB tag while it's still nominally live for `'a`.
/// Callers must `unsafe { &mut *r.fs() }` at the narrowest use site and let
/// the projection die at end-of-expression.
#[inline(always)]
pub fn fs(&self) -> *mut Fs::FileSystem {
self.fs
}
/// Shared-borrow of the FileSystem singleton for read-only methods
/// (`abs_buf*`, `normalize_buf`, `dirname_store`, `filename_store`,
/// `top_level_dir`). Preferred over `unsafe { &mut *self.fs() }` whenever
/// the callee takes `&self` — avoids materializing a `&mut FileSystem`
/// that could (under Stacked Borrows) pop a coexisting `rfs_ptr()` /
/// `&mut *query.entry` tag derived from the same allocation.
#[inline(always)]
pub fn fs_ref(&self) -> &Fs::FileSystem {
// SAFETY: BACKREF — `self.fs` is the process-global FileSystem singleton
// (LIFETIMES.tsv: STATIC); resolver mutex serializes all mutation. A
// shared `&` cannot alias-UB with the raw `*mut RealFS` projections
// used elsewhere because no Unique tag is pushed.
unsafe { &*self.fs }
}
/// Unique-borrow of the `FileSystem` singleton. Centralizes the
/// `unsafe { &mut *self.fs() }` retag for call sites that hold no other
/// borrow of `self` across the call. Sites that need `&mut FileSystem`
/// while also borrowing a disjoint `self.<field>` (e.g.
/// `self.caches.fs.read_file_with_allocator`) cannot route through
/// `&mut self` and continue to narrow-retag via the raw [`fs()`](Self::fs)
/// accessor — same caveat as [`log_mut`](Self::log_mut).
#[inline(always)]
pub fn fs_mut(&mut self) -> &mut Fs::FileSystem {
// SAFETY: BACKREF — `self.fs` is the never-null process-global
// `FileSystem` singleton (set in `init1`); resolver mutex serializes
// all mutation across worker clones; `&mut self` rules out
// intra-instance aliasing.
unsafe { &mut *self.fs }
}
/// Resolve the current [`options::ExtOrder`] tag to the slice it names
/// inside `self.opts`.
#[inline(always)]
pub fn extension_order(&self) -> &[Box<[u8]>] {
self.opts.ext_order_slice(self.extension_order)
}
/// Raw-pointer projection to the inner `RealFS` (`self.fs.fs`).
///
/// NOTE (Stacked Borrows): derived directly from the raw `*mut
/// FileSystem` field via `addr_of_mut!` so the resulting `*mut RealFS`
/// carries SharedReadWrite provenance — later `fs_ref()` (Shared) or
/// short-lived `&mut *self.fs()` retags do NOT invalidate it. Callers
/// re-borrow `&mut *self.rfs_ptr()` per use; do not bind a `&mut RealFS`
/// across another `fs()` deref.
#[inline(always)]
pub fn rfs_ptr(&self) -> *mut Fs::file_system::RealFS {
// SAFETY: `self.fs` is the process-global FileSystem singleton; valid
// for the resolver's lifetime. `addr_of_mut!` creates a raw place
// projection without an intermediate `&mut FileSystem`.
unsafe { core::ptr::addr_of_mut!((*self.fs).fs) }
}
/// NOTE (Stacked Borrows): returns RAW `*mut` (see `fs()` note). BACKREF
/// — owner (Transpiler/BundleV2) outlives the Resolver; worker clones share
/// the same Log under the resolver mutex. Caller `unsafe { &mut *r.log() }`
/// at each use site; do not bind the projected `&mut Log` across another
/// `log()` deref.
#[inline(always)]
pub fn log(&self) -> *mut bun_ast::Log {
self.log.as_ptr()
}
/// Temporarily redirect `self.log` to `log`, returning a guard that
/// restores the previous pointer on drop.
///
/// Takes a raw `*mut Self` (not `&mut self`) so the stored slot pointer
/// carries SharedReadWrite provenance and stays valid under Stacked
/// Borrows when the caller subsequently reborrows the resolver
/// (`read_dir_info` etc.) before the guard drops.
///
/// # Safety
/// `self_` must point at a `Resolver` that outlives the returned guard,
/// and `log` must remain valid for that same duration (declare the guard
/// *after* the temporary `Log` so it drops first).
#[inline]
pub unsafe fn scoped_log(self_: *mut Self, log: NonNull<bun_ast::Log>) -> ResolverLogScope {
// SAFETY: caller contract — `self_` is live; `addr_of_mut!` projects
// the field place without an intermediate `&mut Resolver`.
let slot = unsafe { core::ptr::addr_of_mut!((*self_).log) };
// SAFETY: `slot` just derived from a live resolver.
let prev = unsafe { *slot };
// SAFETY: same as above — `slot` points at a live resolver field.
unsafe { *slot = log };
ResolverLogScope { slot, prev }
}
/// Shared-borrow of the resolver's `Log` for read-only inspection
/// (e.g. `log.level`). Preferred over `unsafe { &*self.log() }`.
#[inline(always)]
pub fn log_ref(&self) -> &bun_ast::Log {
// SAFETY: BACKREF — `self.log` is set in `init1` / `scoped_log`,
// owner-allocated, outlives the Resolver. Resolver mutex serializes
// mutation; a Shared `&` here pushes no Unique tag and so cannot
// alias-UB with the narrow `log_mut()` retags elsewhere (none are live
// across a `log_ref()` call).
unsafe { self.log.as_ref() }
}
/// Unique-borrow of the resolver's `Log` for `add_*_fmt` / `add_msg`.
///
/// Centralizes the per-site `unsafe { &mut *self.log() }` retag. `&mut
/// self` rules out two coexisting `&mut Log` from the SAME `Resolver`;
/// cross-clone aliasing (worker copies share the owner's `Log`) is
/// guarded by the resolver `mutex` — same invariant the open-coded sites
/// already relied on.
///
/// Sites that need `&mut Log` while holding a disjoint `&mut self.<field>`
/// (`flush_debug_logs` ↔ `self.debug_logs`, `parse_tsconfig` ↔
/// `self.caches.json`) cannot route through `&mut self` and continue to
/// narrow-retag via the raw [`log()`](Self::log) accessor.
#[inline(always)]
pub fn log_mut(&mut self) -> &mut bun_ast::Log {
// SAFETY: BACKREF — `self.log` is set in `init1` / `scoped_log`; the
// pointee (owner-allocated `Log`, or a stack `Log` pinned by a live
// `ResolverLogScope`) outlives every borrow returned here. Resolver
// mutex serializes mutation across worker clones.
unsafe { self.log.as_mut() }
}
/// NOTE (Stacked Borrows): returns RAW `*mut` (see `fs()` note). ARENA —
/// `DirInfo::hash_map_instance()` singleton; never freed. Caller
/// `unsafe { &mut *r.dir_cache() }` at each use site.
#[inline(always)]
pub fn dir_cache(&self) -> *mut DirInfo::HashMap {
self.dir_cache
}
/// Unique-borrow of the `DirInfo` BSSMap singleton.
///
/// Centralizes the `unsafe { &mut *self.dir_cache() }` retag that every
/// call site previously open-coded. `&mut self` ensures no two coexisting
/// `&mut HashMap` are produced from the SAME `Resolver`; cross-clone
/// aliasing (per-worker `Resolver`s share the singleton) is
/// guarded by the resolver `mutex` — identical invariant to the prior
/// per-site `unsafe`.
///
/// Stacked Borrows: each call pushes a fresh Unique tag on the BSSMap
/// allocation, so any `*mut DirInfo` previously projected from an earlier
/// `dir_cache_mut()` borrow is popped. Slot pointers that must survive a
/// subsequent map access are re-derived from the raw singleton via
/// `DirInfo::put_slot` / `DirInfo::slot_ptr_at`; refs from `at_index` /
/// `ref_at_index` are only durable until the next map access.
#[inline(always)]
pub fn dir_cache_mut(&mut self) -> &mut DirInfo::HashMap {
// SAFETY: ARENA — `self.dir_cache` is the never-null
// `DirInfo::hash_map_instance()` static (set in `init1`, never
// reassigned, never freed). Resolver mutex serializes all mutation
// across worker clones; `&mut self` rules out intra-instance aliasing.
unsafe { &mut *self.dir_cache }
}
/// Lazily initializing
/// `PackageManager.initWithRuntime` here directly would
/// be a `bun_resolver → bun_install` cycle, so the lazy init is
/// dispatched through the link-time `extern "Rust"` factory
/// [`__bun_resolver_init_package_manager`] (defined `#[no_mangle]` in
/// `bun_install::auto_installer`). The factory performs
/// `HTTPThread.init` + `PackageManager.initWithRuntime` and returns the
/// process-static singleton as a `dyn AutoInstaller`. We then wire
/// `on_wake` and cache the pointer. Reached from
/// the auto-install path (`load_node_modules` global-cache block) when
/// [`use_package_manager`] is `true`. Errs (without caching, but sticky
/// inside the factory) when the one-time init fails, e.g. the top-level
/// directory was deleted or is unreadable — callers surface that as a
/// resolve failure rather than panicking.
pub fn get_package_manager(
&mut self,
) -> core::result::Result<*mut dyn AutoInstaller, bun_core::Error> {
if let Some(pm) = self.package_manager {
return Ok(pm.as_ptr());
}
// SAFETY: `DotEnv::Loader<'a>` is layout-identical across `'a`;
// `init_with_runtime` only borrows it for the synchronous init (the
// static `PackageManager` retains a raw `NonNull<Loader<'static>>`).
let env: NonNull<DotEnv::Loader<'static>> = self
.env_loader
.expect("Resolver.env_loader must be set before auto-install")
.cast::<DotEnv::Loader<'static>>();
// SAFETY: `__bun_resolver_init_package_manager` is defined
// `#[no_mangle]` in `bun_install::auto_installer` and linked into the
// final binary; `self.log` / `self.opts.install` / `env` point at
// process-lifetime storage (Transpiler-owned). The returned pointer
// names the `PackageManager` singleton (`'static`).
let pm: NonNull<dyn AutoInstaller> =
unsafe { __bun_resolver_init_package_manager(self.log, self.opts.install, env) }?;
// SAFETY: `pm` is the just-initialized singleton; sole `&mut` here.
unsafe { (*pm.as_ptr()).set_on_wake(self.on_wake_package_manager) };
self.package_manager = Some(pm);
Ok(pm.as_ptr())
}
/// Safe accessor for the optional [`AutoInstaller`] back-reference.
///
/// Single `unsafe` deref site for the `package_manager:
/// Option<NonNull<dyn AutoInstaller>>` field. The pointee is the
/// process-static `PackageManager` singleton (set via
/// [`get_package_manager`](Self::get_package_manager) /
/// `__bun_resolver_init_package_manager`), so it strictly outlives the
/// resolver. `&mut self` ensures the returned `&mut dyn AutoInstaller` is
/// the only live reference for its lifetime.
#[inline]
pub fn auto_installer(&mut self) -> Option<&mut dyn AutoInstaller> {
// SAFETY: BACKREF — `package_manager` names the bun_install-owned
// singleton, live for the resolver's lifetime once installed; `&mut
// self` ⇒ exclusive access to the only Rust handle.
self.package_manager.map(|mut pm| unsafe { pm.as_mut() })
}
/// Safe read-only accessor for the optional `DotEnv::Loader` back-reference.
///
/// Single `unsafe` deref site for the `env_loader: Option<NonNull<_>>`
/// field. The pointee is the Transpiler-owned loader (set from
/// `transpiler.env`) and strictly outlives the resolver. Only called once
/// resolution has begun (after `run_env_loader()`), so no `&mut Loader` is
/// live concurrently — see the field comment for why this is *not* stored
/// as `Option<&'a Loader>`.
#[inline]
pub fn env_loader(&self) -> Option<&'a DotEnv::Loader<'a>> {
// SAFETY: BACKREF — `env_loader` names the Transpiler-owned
// `DotEnv::Loader`, live for the resolver's lifetime `'a`; resolution
// never mutates the env, so no `&mut Loader` overlaps this shared
// borrow. Returned as `&'a` (not tied to `&self`) so callers may keep
// the env borrow across `&mut self` resolver calls.
self.env_loader.map(|p| unsafe { p.as_ref() })
}
#[inline]
pub fn use_package_manager(&self) -> bool {
// TODO: make this configurable. the rationale for disabling
// auto-install in standalone mode is that such executable must either:
//
// - bundle the dependency itself. dynamic `require`/`import` could be
// changed to bundle potential dependencies specified in package.json
//
// - want to load the user's node_modules, which is what currently happens.
//
// auto install, as of writing, is also quite buggy and untested, it always
// installs the latest version regardless of a user's package.json or specifier.
// in addition to being not fully stable, it is completely unexpected to invoke
// a package manager after bundling an executable. if enough people run into
// this, we could implement point 1
if self.standalone_module_graph.is_some() {
return false;
}
self.opts.global_cache.is_enabled()
}
pub fn init1(
log: NonNull<bun_ast::Log>,
_fs: *mut Fs::FileSystem,
opts: options::BundleOptions,
) -> Self {
// resolver_Mutex_loaded check elided; static is const-inited in Rust.
let care_about_browser_field = opts.target == options::Target::Browser;
Resolver {
// allocator dropped
// Route through the per-monomorphization singleton so this field and
// `DirInfo::get_parent()` / `get_enclosing_browser_scope()` share storage.
dir_cache: DirInfo::hash_map_instance(),
mutex: &RESOLVER_MUTEX,
caches: CacheSet::init(),
opts,
timer: Timer::start().unwrap_or_else(|_| panic!("Timer fail")),
fs: _fs,
log,
extension_order: options::ExtOrder::DefaultDefault,
care_about_browser_field,
care_about_bin_folder: false,
care_about_scripts: false,
debug_logs: None,
elapsed: 0,
watcher: None,
generation: 0,
package_manager: None,
on_wake_package_manager: Default::default(),
env_loader: None,
store_fd: false,
standalone_module_graph: None,
prefer_module_field: true,
custom_dir_paths: None,