1use std::collections::BTreeMap;
11use std::sync::Arc;
12
13use crate::vfs::{within_root, OsFs, SharedFs, SourceFs};
14use crate::{
15 build_potentials, ext_kind, resolve_path_spec, source_dir, MultiSourceOptions, Resolution,
16 Resolver, ResolverInput, NONE,
17};
18
19const NODE_MODULES_LEVELS: usize = 7;
23
24fn base_for(
27 input: &ResolverInput<'_>,
28 is_file: &dyn Fn(&str) -> bool,
29 dir: &dyn Fn(&str) -> String,
30) -> String {
31 let raw = match input.source_path() {
32 Some(path) => path,
33 None => input.options.path.clone(),
34 };
35 if raw.is_empty() {
36 return String::new();
37 }
38 if is_file(&raw) {
39 dir(&raw)
40 } else {
41 raw
42 }
43}
44
45#[derive(Clone, Debug, Default)]
55pub struct MapResolver {
56 files: Arc<BTreeMap<String, String>>,
57}
58
59impl MapResolver {
60 pub fn new() -> Self {
62 Self::default()
63 }
64
65 pub fn from_map(files: BTreeMap<String, String>) -> Self {
67 MapResolver {
68 files: Arc::new(files),
69 }
70 }
71
72 pub fn paths(&self) -> Vec<&str> {
74 self.files.keys().map(String::as_str).collect()
75 }
76}
77
78impl<K, V> FromIterator<(K, V)> for MapResolver
79where
80 K: Into<String>,
81 V: Into<String>,
82{
83 fn from_iter<T: IntoIterator<Item = (K, V)>>(entries: T) -> Self {
84 MapResolver::from_map(
85 entries
86 .into_iter()
87 .map(|(path, content)| (path.into(), content.into()))
88 .collect(),
89 )
90 }
91}
92
93impl<K, V, const N: usize> From<[(K, V); N]> for MapResolver
94where
95 K: Into<String>,
96 V: Into<String>,
97{
98 fn from(entries: [(K, V); N]) -> Self {
99 entries.into_iter().collect()
100 }
101}
102
103impl Resolver for MapResolver {
104 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution {
105 let files = Arc::clone(&self.files);
111 let is_file = move |path: &str| files.contains_key(path);
112 let base = base_for(input, &is_file, &|path| source_dir(path));
113
114 let spec = resolve_path_spec(reference, &base);
115 let Some(full) = spec.full.clone() else {
116 return Resolution::not_found(spec);
117 };
118
119 let potentials = if spec.kind == NONE {
120 build_potentials(&full, &input.options.implicit_ext)
121 } else {
122 vec![full]
123 };
124
125 for candidate in &potentials {
126 if let Some(src) = self.files.get(candidate) {
127 return Resolution::found(spec, candidate, src.clone())
128 .with_search(potentials.clone());
129 }
130 }
131
132 Resolution::not_found(spec).with_search(potentials)
133 }
134}
135
136pub type PathFinder = Arc<dyn Fn(&str) -> String + Send + Sync>;
142
143#[derive(Clone, Default)]
150pub struct FileResolver {
151 pathfinder: Option<PathFinder>,
152 preload: Arc<BTreeMap<String, String>>,
153 fs: Option<SharedFs>,
154 root: Option<String>,
155}
156
157impl std::fmt::Debug for FileResolver {
158 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 formatter
160 .debug_struct("FileResolver")
161 .field(
162 "pathfinder",
163 &self.pathfinder.as_ref().map(|_| "<function>"),
164 )
165 .field("preload", &self.preload.len())
166 .field("fs", &self.fs.as_ref().map(|_| "<SourceFs>"))
167 .field("root", &self.root)
168 .finish()
169 }
170}
171
172impl FileResolver {
173 pub fn new() -> Self {
175 Self::default()
176 }
177
178 pub fn with_pathfinder(
180 mut self,
181 pathfinder: impl Fn(&str) -> String + Send + Sync + 'static,
182 ) -> Self {
183 self.pathfinder = Some(Arc::new(pathfinder));
184 self
185 }
186
187 pub fn with_preload(mut self, preload: BTreeMap<String, String>) -> Self {
190 self.preload = Arc::new(preload);
191 self
192 }
193
194 pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
196 self.fs = Some(Arc::new(filesystem));
197 self
198 }
199
200 pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
202 self.fs = Some(filesystem);
203 self
204 }
205
206 pub fn with_root(mut self, root: impl Into<String>) -> Self {
228 self.root = Some(root.into());
229 self
230 }
231
232 fn filesystem(&self, options: &MultiSourceOptions) -> SharedFs {
233 self.fs
234 .clone()
235 .or_else(|| options.fs.clone())
236 .unwrap_or_else(|| Arc::new(OsFs))
237 }
238
239 fn load(&self, filesystem: &dyn SourceFs, path: &str, root: &Confinement) -> Option<String> {
240 if !root.allows(filesystem, path) {
241 return None;
242 }
243 if let Some(src) = self.preload.get(path) {
244 return Some(src.clone());
245 }
246 filesystem.read_file(path)
247 }
248}
249
250struct Confinement {
258 root: Option<String>,
259 os_paths: bool,
260}
261
262impl Confinement {
263 fn new(filesystem: &dyn SourceFs, root: Option<&String>) -> Self {
264 Confinement {
265 root: root.map(|root| {
271 filesystem
272 .real_path(root)
273 .unwrap_or_else(|| filesystem.canon(root))
274 }),
275 os_paths: filesystem.native_paths(),
276 }
277 }
278
279 fn allows(&self, filesystem: &dyn SourceFs, candidate: &str) -> bool {
280 let Some(root) = &self.root else {
281 return true;
282 };
283 match filesystem.real_path(candidate) {
284 Some(real) => within_root(&real, root, self.os_paths),
285 None => false,
288 }
289 }
290}
291
292impl Resolver for FileResolver {
293 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution {
294 let filesystem = self.filesystem(input.options);
295 let root = Confinement::new(filesystem.as_ref(), self.root.as_ref());
296
297 let found = reference.map(|reference| match &self.pathfinder {
298 Some(pathfinder) => pathfinder(reference),
299 None => reference.to_string(),
300 });
301
302 let is_file =
308 |path: &str| self.preload.contains_key(path) || filesystem.read_file(path).is_some();
309 let dir = |path: &str| filesystem.dir(path);
310 let base = base_for(input, &is_file, &dir);
311
312 let mut spec = resolve_path_spec(found.as_deref(), &base);
313 let Some(full) = spec.full.clone() else {
314 return Resolution::not_found(spec);
315 };
316
317 let full = filesystem.canon(&full);
318 spec.full = Some(full.clone());
319 spec.kind = ext_kind(Some(&full));
320
321 let mut search = vec![full.clone()];
322
323 if let Some(src) = self.load(filesystem.as_ref(), &full, &root) {
324 return Resolution::found(spec, full, src).with_search(search);
325 }
326
327 let mut potentials: Vec<String> = Vec::new();
328
329 if let Some(path) = &spec.path {
333 let mut level = base.clone();
334 let mut last: Option<String> = None;
335 for _ in 0..NODE_MODULES_LEVELS {
336 potentials.push(filesystem.canon(&filesystem.join(&[
337 &level,
338 "node_modules",
339 path,
340 ])));
341 let parent = filesystem.dir(&level);
342 if last.as_deref() == Some(parent.as_str()) {
343 break;
344 }
345 last = Some(parent.clone());
346 level = parent;
347 }
348 }
349
350 if spec.kind == NONE {
351 potentials.extend(
354 build_potentials(&full, &input.options.implicit_ext)
355 .into_iter()
356 .skip(1),
357 );
358 }
359
360 search.extend(potentials.iter().cloned());
361
362 for candidate in &potentials {
363 if let Some(src) = self.load(filesystem.as_ref(), candidate, &root) {
364 return Resolution::found(spec, candidate, src).with_search(search);
365 }
366 }
367
368 Resolution::not_found(spec).with_search(search)
369 }
370}
371
372#[derive(Clone, Default)]
384pub struct PkgResolver {
385 paths: Vec<String>,
386 fs: Option<SharedFs>,
387 root: Option<String>,
388}
389
390impl std::fmt::Debug for PkgResolver {
391 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
392 formatter
393 .debug_struct("PkgResolver")
394 .field("paths", &self.paths)
395 .field("fs", &self.fs.as_ref().map(|_| "<SourceFs>"))
396 .field("root", &self.root)
397 .finish()
398 }
399}
400
401impl PkgResolver {
402 pub fn new() -> Self {
404 Self::default()
405 }
406
407 pub fn with_paths<I, S>(mut self, paths: I) -> Self
409 where
410 I: IntoIterator<Item = S>,
411 S: Into<String>,
412 {
413 self.paths = paths.into_iter().map(Into::into).collect();
414 self
415 }
416
417 pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
419 self.fs = Some(Arc::new(filesystem));
420 self
421 }
422
423 pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
425 self.fs = Some(filesystem);
426 self
427 }
428
429 pub fn with_root(mut self, root: impl Into<String>) -> Self {
432 self.root = Some(root.into());
433 self
434 }
435
436 fn filesystem(&self, options: &MultiSourceOptions) -> SharedFs {
437 self.fs
438 .clone()
439 .or_else(|| options.fs.clone())
440 .unwrap_or_else(|| Arc::new(OsFs))
441 }
442}
443
444fn is_relative_ref(reference: &str) -> bool {
449 reference == "."
450 || reference == ".."
451 || reference.starts_with("./")
452 || reference.starts_with("../")
453 || reference.starts_with(".\\")
454 || reference.starts_with("..\\")
455}
456
457fn ancestors(filesystem: &dyn SourceFs, dir: &str) -> Vec<String> {
459 if dir.is_empty() {
460 return Vec::new();
461 }
462 let mut dirs = Vec::new();
463 let mut current = dir.to_string();
464 loop {
465 dirs.push(current.clone());
466 let parent = filesystem.dir(¤t);
467 if parent == current {
468 break;
469 }
470 current = parent;
471 if dirs.len() > 64 {
475 break;
476 }
477 }
478 dirs
479}
480
481impl Resolver for PkgResolver {
482 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution {
483 let filesystem = self.filesystem(input.options);
484 let root = Confinement::new(filesystem.as_ref(), self.root.as_ref());
485 let os_paths = filesystem.native_paths();
486
487 let is_file = |path: &str| filesystem.read_file(path).is_some();
488 let dir = |path: &str| filesystem.dir(path);
489 let base = base_for(input, &is_file, &dir);
490
491 let spec = resolve_path_spec(reference, &base);
492 let Some(path) = spec.path.clone() else {
493 return Resolution::not_found(spec);
494 };
495 if path.is_empty() {
496 return Resolution::not_found(spec);
497 }
498
499 let load = |candidate: &str| -> Option<String> {
500 if !root.allows(filesystem.as_ref(), candidate) {
501 return None;
502 }
503 filesystem.read_file(candidate)
504 };
505
506 if is_relative_ref(&path) {
511 let Some(full) = spec.full.clone() else {
512 return Resolution::not_found(spec);
513 };
514 let full = filesystem.canon(&full);
515 let potentials = if ext_kind(Some(&full)) == NONE {
516 build_potentials(&full, &input.options.implicit_ext)
517 } else {
518 vec![full]
519 };
520 for candidate in &potentials {
521 if let Some(src) = load(candidate) {
522 return Resolution::found(spec, candidate, src).with_search(potentials.clone());
523 }
524 }
525 return Resolution::not_found(spec).with_search(potentials);
526 }
527
528 let roots: Vec<String> = if !self.paths.is_empty() {
529 self.paths.clone()
530 } else if os_paths {
531 std::env::current_dir()
532 .map(|cwd| vec![cwd.to_string_lossy().into_owned()])
533 .unwrap_or_default()
534 } else {
535 vec![".".to_string()]
536 };
537
538 let mut seen: Vec<String> = Vec::new();
539 let mut search: Vec<String> = Vec::new();
540
541 for root in &roots {
542 for folder in ancestors(filesystem.as_ref(), &filesystem.canon(root)) {
543 let node_modules = filesystem.join(&[&folder, "node_modules"]);
544 if seen.contains(&node_modules) {
545 continue;
546 }
547 seen.push(node_modules.clone());
548
549 if let Some((full, src)) = resolve_in_pkg_dir(
550 filesystem.as_ref(),
551 &load,
552 &node_modules,
553 &path,
554 &input.options.implicit_ext,
555 &mut search,
556 ) {
557 return Resolution::found(spec, full, src).with_search(search);
558 }
559 }
560 }
561
562 Resolution::not_found(spec).with_search(search)
563 }
564}
565
566fn resolve_in_pkg_dir(
570 filesystem: &dyn SourceFs,
571 load: &dyn Fn(&str) -> Option<String>,
572 node_modules: &str,
573 reference: &str,
574 implicit_ext: &[String],
575 search: &mut Vec<String>,
576) -> Option<(String, String)> {
577 let target = filesystem.join(&[node_modules, reference]);
578
579 let (files, indexes): (Vec<String>, Vec<String>) = build_potentials(&target, implicit_ext)
587 .into_iter()
588 .partition(|candidate| !is_index_of(candidate, &target));
589
590 for candidate in &files {
591 search.push(candidate.clone());
592 if let Some(src) = load(candidate) {
593 return Some((candidate.clone(), src));
594 }
595 }
596
597 if let Some(main) = manifest_main(load, filesystem, &target, search) {
598 let main_path = filesystem.join(&[&target, &main]);
599 for candidate in build_potentials(&main_path, implicit_ext) {
600 search.push(candidate.clone());
601 if let Some(src) = load(&candidate) {
602 return Some((candidate, src));
603 }
604 }
605 }
606
607 for candidate in &indexes {
608 search.push(candidate.clone());
609 if let Some(src) = load(candidate) {
610 return Some((candidate.clone(), src));
611 }
612 }
613
614 None
615}
616
617fn is_index_of(candidate: &str, target: &str) -> bool {
620 candidate
621 .strip_prefix(target)
622 .and_then(|rest| rest.strip_prefix(['/', '\\']))
623 .is_some_and(|name| name.starts_with("index."))
624}
625
626fn manifest_main(
629 load: &dyn Fn(&str) -> Option<String>,
630 filesystem: &dyn SourceFs,
631 target: &str,
632 search: &mut Vec<String>,
633) -> Option<String> {
634 let manifest = filesystem.join(&[target, "package.json"]);
635 search.push(manifest.clone());
636 let text = load(&manifest)?;
637 let main = serde_json::from_str::<serde_json::Value>(&text)
638 .ok()
639 .and_then(|value| {
640 value
641 .get("main")
642 .and_then(serde_json::Value::as_str)
643 .map(str::to_string)
644 })?;
645 if main.is_empty() {
646 return None;
647 }
648 Some(main)
649}