Skip to main content

tabnas_multisource/
resolver.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! The three resolvers: an in-memory map, the filesystem, and package
4//! folders.
5//!
6//! Each one is the sandbox for the references it serves. A resolver only
7//! ever reports what it can see, so a caller chooses what a document can
8//! reach by choosing the resolver and the filesystem behind it.
9
10use 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
19/// How many parent folders a reference is chased up through when looking
20/// for a linked package, matching the canonical TypeScript file
21/// resolver's heuristic.
22const NODE_MODULES_LEVELS: usize = 7;
23
24/// The base a reference resolves against: the directory of the source
25/// that contains it, else the configured base path.
26fn 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// ---------------------------------------------------------------------
46// The in-memory resolver
47// ---------------------------------------------------------------------
48
49/// Resolve references against a map of path to content.
50///
51/// Keys are used exactly as given, so a map is a closed world: nothing
52/// outside it can be reached, whatever a document asks for. This is the
53/// resolver the shared fixtures run against.
54#[derive(Clone, Debug, Default)]
55pub struct MapResolver {
56    files: Arc<BTreeMap<String, String>>,
57}
58
59impl MapResolver {
60    /// A resolver over no sources.
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// A resolver over `files`.
66    pub fn from_map(files: BTreeMap<String, String>) -> Self {
67        MapResolver {
68            files: Arc::new(files),
69        }
70    }
71
72    /// Every path this resolver can serve, in sorted order.
73    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        // Only a path that is itself a key names a source, and only that
106        // one is reduced to its containing folder, so a relative
107        // reference resolves against the source that contains it. A bare
108        // key such as `a.jsonic` has no folder, which is why an empty
109        // base has to stay empty rather than become `.`.
110        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
136// ---------------------------------------------------------------------
137// The file resolver
138// ---------------------------------------------------------------------
139
140/// Transform a raw reference before it is resolved.
141pub type PathFinder = Arc<dyn Fn(&str) -> String + Send + Sync>;
142
143/// Resolve references against a filesystem.
144///
145/// By default that is the real filesystem, with references resolved to
146/// absolute paths. Give it a [`crate::MapFs`] and it touches no disk at all;
147/// give it a root and no reference can name anything outside that
148/// directory, however many `..` segments it carries.
149#[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    /// A resolver over the real filesystem.
174    pub fn new() -> Self {
175        Self::default()
176    }
177
178    /// Transform each raw reference before resolving it.
179    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    /// Serve these paths from memory before touching the filesystem.
188    /// The map [`crate::preload_files`] returns goes here.
189    pub fn with_preload(mut self, preload: BTreeMap<String, String>) -> Self {
190        self.preload = Arc::new(preload);
191        self
192    }
193
194    /// Read from `filesystem` instead of the one the plugin options name.
195    pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
196        self.fs = Some(Arc::new(filesystem));
197        self
198    }
199
200    /// Read from an already shared filesystem handle.
201    pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
202        self.fs = Some(filesystem);
203        self
204    }
205
206    /// Confine every candidate path to `root`.
207    ///
208    /// The root and every candidate are resolved through the filesystem
209    /// first ([`SourceFs::real_path`]), then compared by whole segment.
210    /// So neither `../../etc/passwd` nor a sibling directory whose name
211    /// merely starts with the root's can be reached, a relative root
212    /// names the same directory a relative candidate does, and a
213    /// symbolic link inside the root is judged by where it POINTS
214    /// rather than by where it sits. A link that resolves to nothing at
215    /// all is refused outright, since its target could be created
216    /// before a read reaches it.
217    ///
218    /// What this cannot do is stop a link created in the instant
219    /// between the check and the read: the check answers for the
220    /// filesystem as it was. A root whose contents another process can
221    /// write needs a filesystem that enforces the boundary, not a
222    /// resolver.
223    ///
224    /// Neither the canonical TypeScript nor the Go port has this: they
225    /// resolve wherever the reference points. It is additive, so a
226    /// resolver without a root behaves exactly as they do.
227    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
250/// A configured sandbox root, resolved once per resolution.
251///
252/// The root is put through the same filesystem as the candidates, so a
253/// relative root names the same directory a relative candidate does
254/// (before, an absolute candidate was compared against a root still
255/// spelled `srv/app`, and every reference inside the root was reported
256/// missing), and a link is judged by its target rather than its name.
257struct 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            // A root the filesystem cannot resolve (it is not there,
266            // or is itself a link to nothing) still has to be compared
267            // against something, so fall back to the lexical form. A
268            // candidate that cannot be resolved is refused on its own
269            // account below, so nothing is let through by this.
270            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            // The candidate resolves to nothing that can be compared:
286            // a dangling or looping link. Refuse it.
287            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        // A preloaded source is a file this resolver can serve, whether
303        // or not the filesystem still holds it: the preload workflow
304        // exists so a parse can run with the files gone. Asking only the
305        // filesystem made such a source look like a DIRECTORY, so a
306        // relative reference inside it resolved under the source itself.
307        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        // Support npm-linked references, as the canonical TypeScript
330        // file resolver does: chase `node_modules/<path>` up through the
331        // base's parents.
332        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            // `build_potentials` leads with the path itself, which was
352            // tried above.
353            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// ---------------------------------------------------------------------
373// The package resolver
374// ---------------------------------------------------------------------
375
376/// Resolve references inside `node_modules` folders.
377///
378/// Node's `require.resolve` has no Rust counterpart, so this is the
379/// portable subset the Go port also implements: it walks `node_modules`
380/// directories, honours a package's `package.json` `main` for a bare
381/// reference, and tries implicit extensions and index files. Node's
382/// conditional `exports` are not implemented.
383#[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    /// A resolver that walks up from the working directory.
403    pub fn new() -> Self {
404        Self::default()
405    }
406
407    /// Search these directories, and each of their parents, instead.
408    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    /// Read from `filesystem` instead of the one the plugin options name.
418    pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
419        self.fs = Some(Arc::new(filesystem));
420        self
421    }
422
423    /// Read from an already shared filesystem handle.
424    pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
425        self.fs = Some(filesystem);
426        self
427    }
428
429    /// Confine every candidate path to `root`. See
430    /// [`FileResolver::with_root`].
431    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
444/// Is `reference` an explicit relative reference?
445///
446/// Such a reference is resolved against the containing source's
447/// directory rather than treated as a package name.
448fn 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
457/// `dir` followed by each of its parents.
458fn 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(&current);
467        if parent == current {
468            break;
469        }
470        current = parent;
471        // A malformed filesystem view that never reaches a fixed point
472        // would loop forever; the real ones reach one in a handful of
473        // steps, and a reference has no business climbing further.
474        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        // A relative reference found inside a source loaded from a
507        // package is not a package name: resolve it against the
508        // containing source's directory, exactly as the file resolver
509        // does.
510        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
566/// Resolve a package reference inside one `node_modules` directory:
567/// the reference itself, with implicit extensions and index files, then
568/// the target package's `package.json` `main`.
569fn 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    // The canonical resolver is Node's `require.resolve`, whose order
580    // for a bare reference is: the reference as a FILE (itself, then
581    // each implicit extension), then the target package's `package.json`
582    // `main`, and only then a directory index. Trying every potential
583    // first returned `index.jsonic` for a package that declares a main,
584    // which is a normal package layout, so the port loaded a different
585    // file from the canonical one.
586    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
617/// Is `candidate` an index file INSIDE the target folder, rather than
618/// the target itself under some extension?
619fn 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
626/// The `main` a package's `package.json` declares, if it declares a
627/// usable one.
628fn 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}