Skip to main content

fallow_core/plugins/registry/
virtual_module.rs

1//! The rules that credit the package behind the virtual and generated
2//! modules of a plugin, such as `@sveltejs/kit` for `$app/state` and
3//! `./$types`.
4
5use std::path::Path;
6
7use crate::extract::ModuleInfo;
8
9/// The extensions that an import of a generated module can carry
10/// (`./$types.js`).
11const GENERATED_IMPORT_EXTENSIONS: &[&str] = &[".js", ".ts"];
12
13/// How a [`VirtualModuleProviderRule`] matches an import specifier.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum VirtualModuleMatch {
16    /// A `Plugin::virtual_module_prefixes` entry. A prefix with a trailing
17    /// `/`, such as `$app/`, matches each specifier below it. A prefix
18    /// without one, such as `$service-worker`, matches that module and its
19    /// subpaths, not `$service-workerx`.
20    Prefix(String),
21    /// A `Plugin::generated_import_patterns` entry such as `/$types`. It
22    /// matches a relative specifier whose directory part has only `.` and
23    /// `..` segments, after one `.js` or `.ts` extension is stripped:
24    /// `./$types` and `../$types.js`, not `./lib/$types`, which names a
25    /// project file.
26    Generated(String),
27}
28
29/// One import-specifier rule crediting the package that provides a plugin's
30/// virtual or generated modules. See [`Plugin::virtual_module_package`].
31///
32/// [`Plugin::virtual_module_package`]: crate::plugins::Plugin::virtual_module_package
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct VirtualModuleProviderRule {
35    /// The plugin that declares the package.
36    pub plugin: String,
37    /// The project-relative root of the package the plugin is active in.
38    /// Empty for the project root.
39    pub scope: String,
40    /// The specifier matcher a virtual-module or generated-import entry of
41    /// the plugin contributed.
42    pub matcher: VirtualModuleMatch,
43    /// The package a matched import credits.
44    pub package: String,
45}
46
47impl VirtualModuleProviderRule {
48    /// Whether this rule covers `specifier` written in the file at `path`.
49    ///
50    /// A rule applies only to the files under the package root where its
51    /// plugin is active, so a virtual-module import in another workspace
52    /// credits no package. A match hides an unused package, so the match is
53    /// narrower than the unresolved-import filter.
54    #[must_use]
55    pub fn matches(&self, root: &Path, path: &Path, specifier: &str) -> bool {
56        if !self.scope.is_empty() && !path.starts_with(root.join(&self.scope)) {
57            return false;
58        }
59        match &self.matcher {
60            VirtualModuleMatch::Prefix(prefix) => names_virtual_module(prefix, specifier),
61            VirtualModuleMatch::Generated(pattern) => names_generated_module(pattern, specifier),
62        }
63    }
64}
65
66fn names_generated_module(pattern: &str, specifier: &str) -> bool {
67    let bare = GENERATED_IMPORT_EXTENSIONS
68        .iter()
69        .find_map(|extension| specifier.strip_suffix(extension))
70        .unwrap_or(specifier);
71    let Some((dir, name)) = bare.rsplit_once('/') else {
72        return false;
73    };
74    name == pattern.trim_start_matches('/')
75        && dir
76            .split('/')
77            .all(|segment| segment == "." || segment == "..")
78}
79
80fn names_virtual_module(prefix: &str, specifier: &str) -> bool {
81    if prefix.ends_with('/') {
82        return specifier.starts_with(prefix);
83    }
84    specifier
85        .strip_prefix(prefix)
86        .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
87}
88
89/// Every literal specifier of the module: static imports, re-exports,
90/// literal dynamic imports and `require()` calls. Resolved or not, each is
91/// evidence that the file uses the framework module it names.
92pub fn module_specifiers(module: &ModuleInfo) -> impl Iterator<Item = &str> {
93    module
94        .imports
95        .iter()
96        .map(|import| import.source.as_str())
97        .chain(
98            module
99                .re_exports
100                .iter()
101                .map(|re_export| re_export.source.as_str()),
102        )
103        .chain(
104            module
105                .dynamic_imports
106                .iter()
107                .map(|import| import.source.as_str()),
108        )
109        .chain(module.require_calls.iter().map(|call| call.source.as_str()))
110}
111
112#[cfg(test)]
113mod tests {
114    use std::path::Path;
115
116    use super::{VirtualModuleMatch, VirtualModuleProviderRule};
117
118    fn rule(matcher: VirtualModuleMatch) -> VirtualModuleProviderRule {
119        VirtualModuleProviderRule {
120            plugin: "sveltekit".to_string(),
121            scope: String::new(),
122            matcher,
123            package: "@sveltejs/kit".to_string(),
124        }
125    }
126
127    fn matches(matcher: VirtualModuleMatch, specifier: &str) -> bool {
128        let root = Path::new("/project");
129        rule(matcher).matches(root, &root.join("src/routes/+page.ts"), specifier)
130    }
131
132    #[test]
133    fn a_prefix_without_a_slash_names_one_module_and_its_subpaths() {
134        let prefix = || VirtualModuleMatch::Prefix("$service-worker".to_string());
135        assert!(matches(prefix(), "$service-worker"));
136        assert!(matches(prefix(), "$service-worker/build"));
137        assert!(!matches(prefix(), "$service-workerx"));
138    }
139
140    #[test]
141    fn a_prefix_with_a_slash_names_each_module_below_it() {
142        let prefix = || VirtualModuleMatch::Prefix("$app/".to_string());
143        assert!(matches(prefix(), "$app/state"));
144        assert!(!matches(prefix(), "$app"));
145        assert!(!matches(prefix(), "$application/state"));
146    }
147
148    #[test]
149    fn a_generated_import_must_be_relative() {
150        let generated = || VirtualModuleMatch::Generated("/$types".to_string());
151        assert!(matches(generated(), "./$types"));
152        assert!(matches(generated(), "../$types.js"));
153        assert!(matches(generated(), "../../$types.ts"));
154        assert!(!matches(generated(), "some-pkg/$types"));
155        assert!(!matches(generated(), "./$typesx"));
156        assert!(!matches(generated(), "./lib/$types"));
157        assert!(!matches(generated(), "../shared/$types.js"));
158    }
159
160    #[test]
161    fn a_scoped_rule_covers_only_its_package() {
162        let root = Path::new("/project");
163        let scoped = VirtualModuleProviderRule {
164            scope: "packages/app".to_string(),
165            ..rule(VirtualModuleMatch::Prefix("$app/".to_string()))
166        };
167        assert!(scoped.matches(root, &root.join("packages/app/src/a.ts"), "$app/state"));
168        assert!(!scoped.matches(root, &root.join("packages/other/src/a.ts"), "$app/state"));
169    }
170}