Skip to main content

fallow_core/plugins/registry/
mod.rs

1//! Plugin registry: discovers active plugins, collects patterns, parses configs.
2#![expect(
3    clippy::excessive_nesting,
4    reason = "plugin config parsing requires deep AST matching"
5)]
6
7use rustc_hash::FxHashSet;
8use std::path::{Path, PathBuf};
9
10use fallow_config::{EntryPointRole, ExternalPluginDef, PackageJson};
11
12use super::Plugin;
13
14pub(crate) mod builtin;
15mod helpers;
16
17use helpers::{
18    check_has_config_file, discover_json_config_files, process_config_result,
19    process_external_plugins, process_static_patterns,
20};
21
22/// Registry of all available plugins (built-in + external).
23pub struct PluginRegistry {
24    plugins: Vec<Box<dyn Plugin>>,
25    external_plugins: Vec<ExternalPluginDef>,
26}
27
28/// Aggregated results from all active plugins for a project.
29#[derive(Debug, Default)]
30pub struct AggregatedPluginResult {
31    /// All entry point patterns from active plugins: (pattern, plugin_name).
32    pub entry_patterns: Vec<(String, String)>,
33    /// Coverage role for each plugin contributing entry point patterns.
34    pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
35    /// All config file patterns from active plugins.
36    pub config_patterns: Vec<String>,
37    /// All always-used file patterns from active plugins: (pattern, plugin_name).
38    pub always_used: Vec<(String, String)>,
39    /// All used export rules from active plugins.
40    pub used_exports: Vec<(String, Vec<String>)>,
41    /// Dependencies referenced in config files (should not be flagged unused).
42    pub referenced_dependencies: Vec<String>,
43    /// Additional always-used files discovered from config parsing: (pattern, plugin_name).
44    pub discovered_always_used: Vec<(String, String)>,
45    /// Setup files discovered from config parsing: (path, plugin_name).
46    pub setup_files: Vec<(PathBuf, String)>,
47    /// Tooling dependencies (should not be flagged as unused devDeps).
48    pub tooling_dependencies: Vec<String>,
49    /// Package names discovered as used in package.json scripts (binary invocations).
50    pub script_used_packages: FxHashSet<String>,
51    /// Import prefixes for virtual modules provided by active frameworks.
52    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
53    pub virtual_module_prefixes: Vec<String>,
54    /// Import suffixes for build-time generated relative imports.
55    /// Unresolved imports ending with these suffixes are suppressed.
56    pub generated_import_patterns: Vec<String>,
57    /// Path alias mappings from active plugins (prefix → replacement directory).
58    /// Used by the resolver to substitute import prefixes before re-resolving.
59    pub path_aliases: Vec<(String, String)>,
60    /// Names of active plugins.
61    pub active_plugins: Vec<String>,
62    /// Test fixture glob patterns from active plugins: (pattern, plugin_name).
63    pub fixture_patterns: Vec<(String, String)>,
64}
65
66impl PluginRegistry {
67    /// Create a registry with all built-in plugins and optional external plugins.
68    #[must_use]
69    pub fn new(external: Vec<ExternalPluginDef>) -> Self {
70        Self {
71            plugins: builtin::create_builtin_plugins(),
72            external_plugins: external,
73        }
74    }
75
76    /// Run all plugins against a project, returning aggregated results.
77    ///
78    /// This discovers which plugins are active, collects their static patterns,
79    /// then parses any config files to extract dynamic information.
80    pub fn run(
81        &self,
82        pkg: &PackageJson,
83        root: &Path,
84        discovered_files: &[PathBuf],
85    ) -> AggregatedPluginResult {
86        let _span = tracing::info_span!("run_plugins").entered();
87        let mut result = AggregatedPluginResult::default();
88
89        // Phase 1: Determine which plugins are active
90        // Compute deps once to avoid repeated Vec<String> allocation per plugin
91        let all_deps = pkg.all_dependency_names();
92        let active: Vec<&dyn Plugin> = self
93            .plugins
94            .iter()
95            .filter(|p| p.is_enabled_with_deps(&all_deps, root))
96            .map(AsRef::as_ref)
97            .collect();
98
99        tracing::info!(
100            plugins = active
101                .iter()
102                .map(|p| p.name())
103                .collect::<Vec<_>>()
104                .join(", "),
105            "active plugins"
106        );
107
108        // Warn when meta-frameworks are active but their generated configs are missing.
109        // Without these, tsconfig extends chains break and import resolution fails.
110        check_meta_framework_prerequisites(&active, root);
111
112        // Phase 2: Collect static patterns from active plugins
113        for plugin in &active {
114            process_static_patterns(*plugin, root, &mut result);
115        }
116
117        // Phase 2b: Process external plugins (includes inline framework definitions)
118        process_external_plugins(
119            &self.external_plugins,
120            &all_deps,
121            root,
122            discovered_files,
123            &mut result,
124        );
125
126        // Phase 3: Find and parse config files for dynamic resolution
127        // Pre-compile all config patterns
128        let config_matchers: Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> = active
129            .iter()
130            .filter(|p| !p.config_patterns().is_empty())
131            .map(|p| {
132                let matchers: Vec<globset::GlobMatcher> = p
133                    .config_patterns()
134                    .iter()
135                    .filter_map(|pat| globset::Glob::new(pat).ok().map(|g| g.compile_matcher()))
136                    .collect();
137                (*p, matchers)
138            })
139            .collect();
140
141        // Build relative paths for matching (used by Phase 3 and 4)
142        let relative_files: Vec<(&PathBuf, String)> = discovered_files
143            .iter()
144            .map(|f| {
145                let rel = f
146                    .strip_prefix(root)
147                    .unwrap_or(f)
148                    .to_string_lossy()
149                    .into_owned();
150                (f, rel)
151            })
152            .collect();
153
154        if !config_matchers.is_empty() {
155            // Phase 3a: Match config files from discovered source files
156            let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
157
158            for (plugin, matchers) in &config_matchers {
159                for (abs_path, rel_path) in &relative_files {
160                    if matchers.iter().any(|m| m.is_match(rel_path.as_str())) {
161                        // Mark as resolved regardless of result to prevent Phase 3b
162                        // from re-parsing a JSON config for the same plugin.
163                        resolved_plugins.insert(plugin.name());
164                        if let Ok(source) = std::fs::read_to_string(abs_path) {
165                            let plugin_result = plugin.resolve_config(abs_path, &source, root);
166                            if !plugin_result.is_empty() {
167                                tracing::debug!(
168                                    plugin = plugin.name(),
169                                    config = rel_path.as_str(),
170                                    entries = plugin_result.entry_patterns.len(),
171                                    deps = plugin_result.referenced_dependencies.len(),
172                                    "resolved config"
173                                );
174                                process_config_result(plugin.name(), plugin_result, &mut result);
175                            }
176                        }
177                    }
178                }
179            }
180
181            // Phase 3b: Filesystem fallback for JSON config files.
182            // JSON files (angular.json, project.json) are not in the discovered file set
183            // because fallow only discovers JS/TS/CSS/Vue/etc. files.
184            let json_configs = discover_json_config_files(
185                &config_matchers,
186                &resolved_plugins,
187                &relative_files,
188                root,
189            );
190            for (abs_path, plugin) in &json_configs {
191                if let Ok(source) = std::fs::read_to_string(abs_path) {
192                    let plugin_result = plugin.resolve_config(abs_path, &source, root);
193                    if !plugin_result.is_empty() {
194                        let rel = abs_path
195                            .strip_prefix(root)
196                            .map(|p| p.to_string_lossy())
197                            .unwrap_or_default();
198                        tracing::debug!(
199                            plugin = plugin.name(),
200                            config = %rel,
201                            entries = plugin_result.entry_patterns.len(),
202                            deps = plugin_result.referenced_dependencies.len(),
203                            "resolved config (filesystem fallback)"
204                        );
205                        process_config_result(plugin.name(), plugin_result, &mut result);
206                    }
207                }
208            }
209        }
210
211        // Phase 4: Package.json inline config fallback
212        // For plugins that define `package_json_config_key()`, check if the root
213        // package.json contains that key and no standalone config file was found.
214        for plugin in &active {
215            if let Some(key) = plugin.package_json_config_key()
216                && !check_has_config_file(*plugin, &config_matchers, &relative_files)
217            {
218                // Try to extract the key from package.json
219                let pkg_path = root.join("package.json");
220                if let Ok(content) = std::fs::read_to_string(&pkg_path)
221                    && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
222                    && let Some(config_value) = json.get(key)
223                {
224                    let config_json = serde_json::to_string(config_value).unwrap_or_default();
225                    let fake_path = root.join(format!("{key}.config.json"));
226                    let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
227                    if !plugin_result.is_empty() {
228                        tracing::debug!(
229                            plugin = plugin.name(),
230                            key = key,
231                            "resolved inline package.json config"
232                        );
233                        process_config_result(plugin.name(), plugin_result, &mut result);
234                    }
235                }
236            }
237        }
238
239        result
240    }
241
242    /// Fast variant of `run()` for workspace packages.
243    ///
244    /// Reuses pre-compiled config matchers and pre-computed relative files from the root
245    /// project run, avoiding repeated glob compilation and path computation per workspace.
246    /// Skips external plugins (they only activate at root level) and package.json inline
247    /// config (workspace packages rarely have inline configs).
248    pub fn run_workspace_fast(
249        &self,
250        pkg: &PackageJson,
251        root: &Path,
252        project_root: &Path,
253        precompiled_config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
254        relative_files: &[(&PathBuf, String)],
255    ) -> AggregatedPluginResult {
256        let _span = tracing::info_span!("run_plugins").entered();
257        let mut result = AggregatedPluginResult::default();
258
259        // Phase 1: Determine which plugins are active (with pre-computed deps)
260        let all_deps = pkg.all_dependency_names();
261        let active: Vec<&dyn Plugin> = self
262            .plugins
263            .iter()
264            .filter(|p| p.is_enabled_with_deps(&all_deps, root))
265            .map(AsRef::as_ref)
266            .collect();
267
268        tracing::info!(
269            plugins = active
270                .iter()
271                .map(|p| p.name())
272                .collect::<Vec<_>>()
273                .join(", "),
274            "active plugins"
275        );
276
277        // Early exit if no plugins are active (common for leaf workspace packages)
278        if active.is_empty() {
279            return result;
280        }
281
282        // Phase 2: Collect static patterns from active plugins
283        for plugin in &active {
284            process_static_patterns(*plugin, root, &mut result);
285        }
286
287        // Phase 3: Find and parse config files using pre-compiled matchers
288        // Only check matchers for plugins that are active in this workspace
289        let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
290        let workspace_matchers: Vec<_> = precompiled_config_matchers
291            .iter()
292            .filter(|(p, _)| active_names.contains(p.name()))
293            .collect();
294
295        let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
296        if !workspace_matchers.is_empty() {
297            for (plugin, matchers) in &workspace_matchers {
298                for (abs_path, rel_path) in relative_files {
299                    if matchers.iter().any(|m| m.is_match(rel_path.as_str()))
300                        && let Ok(source) = std::fs::read_to_string(abs_path)
301                    {
302                        // Mark resolved regardless of result to prevent Phase 3b
303                        // from re-parsing a JSON config for the same plugin.
304                        resolved_ws_plugins.insert(plugin.name());
305                        let plugin_result = plugin.resolve_config(abs_path, &source, root);
306                        if !plugin_result.is_empty() {
307                            tracing::debug!(
308                                plugin = plugin.name(),
309                                config = rel_path.as_str(),
310                                entries = plugin_result.entry_patterns.len(),
311                                deps = plugin_result.referenced_dependencies.len(),
312                                "resolved config"
313                            );
314                            process_config_result(plugin.name(), plugin_result, &mut result);
315                        }
316                    }
317                }
318            }
319        }
320
321        // Phase 3b: Filesystem fallback for JSON config files at the project root.
322        // Config files like angular.json live at the monorepo root, but Angular is
323        // only active in workspace packages. Check the project root for unresolved
324        // config patterns.
325        let mut ws_json_configs: Vec<(PathBuf, &dyn Plugin)> = Vec::new();
326        let mut ws_seen_paths: FxHashSet<PathBuf> = FxHashSet::default();
327        for plugin in &active {
328            if resolved_ws_plugins.contains(plugin.name()) || plugin.config_patterns().is_empty() {
329                continue;
330            }
331            for pat in plugin.config_patterns() {
332                let has_glob = pat.contains("**") || pat.contains('*') || pat.contains('?');
333                if has_glob {
334                    // Glob pattern (e.g., "**/project.json") — check directories
335                    // that contain discovered source files
336                    let filename = std::path::Path::new(pat)
337                        .file_name()
338                        .and_then(|n| n.to_str())
339                        .unwrap_or(pat);
340                    let matcher = globset::Glob::new(pat).ok().map(|g| g.compile_matcher());
341                    if let Some(matcher) = matcher {
342                        let mut checked_dirs: FxHashSet<&Path> = FxHashSet::default();
343                        checked_dirs.insert(root);
344                        if root != project_root {
345                            checked_dirs.insert(project_root);
346                        }
347                        for (abs_path, _) in relative_files {
348                            if let Some(parent) = abs_path.parent() {
349                                checked_dirs.insert(parent);
350                            }
351                        }
352                        for dir in checked_dirs {
353                            let candidate = dir.join(filename);
354                            if candidate.is_file() && ws_seen_paths.insert(candidate.clone()) {
355                                let rel = candidate
356                                    .strip_prefix(project_root)
357                                    .map(|p| p.to_string_lossy())
358                                    .unwrap_or_default();
359                                if matcher.is_match(rel.as_ref()) {
360                                    ws_json_configs.push((candidate, *plugin));
361                                }
362                            }
363                        }
364                    }
365                } else {
366                    // Check both workspace root and project root (deduplicate when equal)
367                    let check_roots: Vec<&Path> = if root == project_root {
368                        vec![root]
369                    } else {
370                        vec![root, project_root]
371                    };
372                    for check_root in check_roots {
373                        let abs_path = check_root.join(pat);
374                        if abs_path.is_file() && ws_seen_paths.insert(abs_path.clone()) {
375                            ws_json_configs.push((abs_path, *plugin));
376                            break; // Found it — don't check other roots for this pattern
377                        }
378                    }
379                }
380            }
381        }
382        // Parse discovered JSON config files
383        for (abs_path, plugin) in &ws_json_configs {
384            if let Ok(source) = std::fs::read_to_string(abs_path) {
385                let plugin_result = plugin.resolve_config(abs_path, &source, root);
386                if !plugin_result.is_empty() {
387                    let rel = abs_path
388                        .strip_prefix(project_root)
389                        .map(|p| p.to_string_lossy())
390                        .unwrap_or_default();
391                    tracing::debug!(
392                        plugin = plugin.name(),
393                        config = %rel,
394                        entries = plugin_result.entry_patterns.len(),
395                        deps = plugin_result.referenced_dependencies.len(),
396                        "resolved config (workspace filesystem fallback)"
397                    );
398                    process_config_result(plugin.name(), plugin_result, &mut result);
399                }
400            }
401        }
402
403        result
404    }
405
406    /// Pre-compile config pattern glob matchers for all plugins that have config patterns.
407    /// Returns a vec of (plugin, matchers) pairs that can be reused across multiple `run_workspace_fast` calls.
408    #[must_use]
409    pub fn precompile_config_matchers(&self) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
410        self.plugins
411            .iter()
412            .filter(|p| !p.config_patterns().is_empty())
413            .map(|p| {
414                let matchers: Vec<globset::GlobMatcher> = p
415                    .config_patterns()
416                    .iter()
417                    .filter_map(|pat| globset::Glob::new(pat).ok().map(|g| g.compile_matcher()))
418                    .collect();
419                (p.as_ref(), matchers)
420            })
421            .collect()
422    }
423}
424
425impl Default for PluginRegistry {
426    fn default() -> Self {
427        Self::new(vec![])
428    }
429}
430
431/// Warn when meta-frameworks are active but their generated configs are missing.
432///
433/// Meta-frameworks like Nuxt and Astro generate tsconfig/types files during a
434/// "prepare" step. Without these, the tsconfig extends chain breaks and
435/// extensionless imports fail wholesale (e.g. 2000+ unresolved imports).
436fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
437    for plugin in active_plugins {
438        match plugin.name() {
439            "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => {
440                tracing::warn!(
441                    "Nuxt project missing .nuxt/tsconfig.json \u{2014} run `nuxt prepare` \
442                     before fallow for accurate analysis"
443                );
444            }
445            "astro" if !root.join(".astro").exists() => {
446                tracing::warn!(
447                    "Astro project missing .astro/ types \u{2014} run `astro sync` \
448                     before fallow for accurate analysis"
449                );
450            }
451            _ => {}
452        }
453    }
454}
455
456#[cfg(test)]
457mod tests;