fallow_core/plugins/registry/mod.rs
1//! Plugin registry: discovers active plugins, collects patterns, parses configs.
2
3use rustc_hash::FxHashSet;
4use std::path::{Path, PathBuf};
5
6use fallow_config::{EntryPointRole, ExternalPluginDef, PackageJson, UsedClassMemberRule};
7
8use super::{PathRule, Plugin, PluginUsedExportRule};
9
10pub(crate) mod builtin;
11mod helpers;
12
13use helpers::{
14 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
15 process_external_plugins, process_static_patterns,
16};
17
18// ESLint is included because each workspace owns its own eslint.config.{mjs,js,...}
19// that may import a shared workspace eslint-config package. Those transitive deps
20// (e.g. eslint-config-next, eslint-plugin-react) are declared in the workspace's
21// devDependencies and will be flagged as unused if we skip config parsing here.
22fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
23 matches!(
24 plugin_name,
25 "eslint" | "docusaurus" | "jest" | "tanstack-router" | "vitest"
26 )
27}
28
29/// Registry of all available plugins (built-in + external).
30pub struct PluginRegistry {
31 plugins: Vec<Box<dyn Plugin>>,
32 external_plugins: Vec<ExternalPluginDef>,
33}
34
35/// Aggregated results from all active plugins for a project.
36#[derive(Debug, Default)]
37pub struct AggregatedPluginResult {
38 /// All entry point patterns from active plugins: (rule, plugin_name).
39 pub entry_patterns: Vec<(PathRule, String)>,
40 /// Coverage role for each plugin contributing entry point patterns.
41 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
42 /// All config file patterns from active plugins.
43 pub config_patterns: Vec<String>,
44 /// All always-used file patterns from active plugins: (pattern, plugin_name).
45 pub always_used: Vec<(String, String)>,
46 /// All used export rules from active plugins.
47 pub used_exports: Vec<PluginUsedExportRule>,
48 /// Class member rules contributed by active plugins that should never be
49 /// flagged as unused. Extends the built-in Angular/React lifecycle allowlist
50 /// with framework-invoked method names, optionally scoped by class heritage.
51 pub used_class_members: Vec<UsedClassMemberRule>,
52 /// Dependencies referenced in config files (should not be flagged unused).
53 pub referenced_dependencies: Vec<String>,
54 /// Additional always-used files discovered from config parsing: (pattern, plugin_name).
55 pub discovered_always_used: Vec<(String, String)>,
56 /// Setup files discovered from config parsing: (path, plugin_name).
57 pub setup_files: Vec<(PathBuf, String)>,
58 /// Tooling dependencies (should not be flagged as unused devDeps).
59 pub tooling_dependencies: Vec<String>,
60 /// Package names discovered as used in package.json scripts (binary invocations).
61 pub script_used_packages: FxHashSet<String>,
62 /// Import prefixes for virtual modules provided by active frameworks.
63 /// Imports matching these prefixes should not be flagged as unlisted dependencies.
64 pub virtual_module_prefixes: Vec<String>,
65 /// Package name suffixes that identify virtual or convention-based specifiers.
66 /// Extracted package names ending with any of these suffixes are not flagged as unlisted.
67 pub virtual_package_suffixes: Vec<String>,
68 /// Import suffixes for build-time generated relative imports.
69 /// Unresolved imports ending with these suffixes are suppressed.
70 pub generated_import_patterns: Vec<String>,
71 /// Path alias mappings from active plugins (prefix → replacement directory).
72 /// Used by the resolver to substitute import prefixes before re-resolving.
73 pub path_aliases: Vec<(String, String)>,
74 /// Names of active plugins.
75 pub active_plugins: Vec<String>,
76 /// Test fixture glob patterns from active plugins: (pattern, plugin_name).
77 pub fixture_patterns: Vec<(String, String)>,
78 /// Absolute directories contributed by plugins that should be searched
79 /// when resolving SCSS/Sass `@import`/`@use` specifiers. Populated from
80 /// Angular's `stylePreprocessorOptions.includePaths` and equivalent
81 /// framework settings. See issue #103.
82 pub scss_include_paths: Vec<PathBuf>,
83}
84
85impl PluginRegistry {
86 /// Create a registry with all built-in plugins and optional external plugins.
87 #[must_use]
88 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
89 Self {
90 plugins: builtin::create_builtin_plugins(),
91 external_plugins: external,
92 }
93 }
94
95 /// Hidden directory names that should be traversed before full plugin execution.
96 ///
97 /// Source discovery runs before plugin config parsing, so this helper only uses
98 /// package-activation checks and static plugin metadata.
99 #[must_use]
100 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
101 let all_deps = pkg.all_dependency_names();
102 let mut seen = FxHashSet::default();
103 let mut dirs = Vec::new();
104
105 for plugin in &self.plugins {
106 if !plugin.is_enabled_with_deps(&all_deps, root) {
107 continue;
108 }
109 for dir in plugin.discovery_hidden_dirs() {
110 if seen.insert(*dir) {
111 dirs.push((*dir).to_string());
112 }
113 }
114 }
115
116 dirs
117 }
118
119 /// Run all plugins against a project, returning aggregated results.
120 ///
121 /// This discovers which plugins are active, collects their static patterns,
122 /// then parses any config files to extract dynamic information.
123 pub fn run(
124 &self,
125 pkg: &PackageJson,
126 root: &Path,
127 discovered_files: &[PathBuf],
128 ) -> AggregatedPluginResult {
129 self.run_with_search_roots(pkg, root, discovered_files, &[root], false)
130 }
131
132 /// Run all plugins against a project with explicit config-file search roots.
133 ///
134 /// `config_search_roots` should stay narrowly focused to directories that are
135 /// already known to matter for this project. Broad recursive scans are
136 /// intentionally avoided because they become prohibitively expensive on
137 /// large monorepos with populated `node_modules` trees.
138 ///
139 /// `production_mode` controls the FS fallback for source-extension config
140 /// patterns. In production mode the source walker excludes `*.config.*` so
141 /// the FS walk is required; otherwise Phase 3a's in-memory matcher covers
142 /// them and the walk is skipped.
143 pub fn run_with_search_roots(
144 &self,
145 pkg: &PackageJson,
146 root: &Path,
147 discovered_files: &[PathBuf],
148 config_search_roots: &[&Path],
149 production_mode: bool,
150 ) -> AggregatedPluginResult {
151 let _span = tracing::info_span!("run_plugins").entered();
152 let mut result = AggregatedPluginResult::default();
153
154 // Phase 1: Determine which plugins are active
155 // Compute deps once to avoid repeated Vec<String> allocation per plugin
156 let all_deps = pkg.all_dependency_names();
157 let active: Vec<&dyn Plugin> = self
158 .plugins
159 .iter()
160 .filter(|p| p.is_enabled_with_deps(&all_deps, root))
161 .map(AsRef::as_ref)
162 .collect();
163
164 tracing::info!(
165 plugins = active
166 .iter()
167 .map(|p| p.name())
168 .collect::<Vec<_>>()
169 .join(", "),
170 "active plugins"
171 );
172
173 // Warn when meta-frameworks are active but their generated configs are missing.
174 // Without these, tsconfig extends chains break and import resolution fails.
175 check_meta_framework_prerequisites(&active, root);
176
177 // Phase 2: Collect static patterns from active plugins
178 for plugin in &active {
179 process_static_patterns(*plugin, root, &mut result);
180 }
181
182 // Phase 2b: Process external plugins (includes inline framework definitions)
183 process_external_plugins(
184 &self.external_plugins,
185 &all_deps,
186 root,
187 discovered_files,
188 &mut result,
189 );
190
191 // Phase 3: Find and parse config files for dynamic resolution
192 // Pre-compile all config patterns. Source-extension root-anchored
193 // patterns are wrapped with `**/` so they match nested files via the
194 // discovered file set (Phase 3a), letting Phase 3b skip those plugins
195 // and avoid a per-directory stat storm on large monorepos.
196 let config_matchers: Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> = active
197 .iter()
198 .filter(|p| !p.config_patterns().is_empty())
199 .map(|p| {
200 let matchers: Vec<globset::GlobMatcher> = p
201 .config_patterns()
202 .iter()
203 .filter_map(|pat| {
204 let prepared = prepare_config_pattern(pat);
205 globset::Glob::new(&prepared)
206 .ok()
207 .map(|g| g.compile_matcher())
208 })
209 .collect();
210 (*p, matchers)
211 })
212 .collect();
213
214 // Build relative paths lazily: only needed when config matchers exist
215 // or plugins have package_json_config_key. Skip entirely for projects
216 // with no config-parsing plugins (e.g., only React), avoiding O(files)
217 // String allocations.
218 let needs_relative_files = !config_matchers.is_empty()
219 || active.iter().any(|p| p.package_json_config_key().is_some());
220 let relative_files: Vec<(PathBuf, String)> = if needs_relative_files {
221 discovered_files
222 .iter()
223 .map(|f| {
224 let rel = f
225 .strip_prefix(root)
226 .unwrap_or(f)
227 .to_string_lossy()
228 .into_owned();
229 (f.clone(), rel)
230 })
231 .collect()
232 } else {
233 Vec::new()
234 };
235
236 if !config_matchers.is_empty() {
237 // Phase 3a: Match config files from discovered source files
238 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
239
240 for (plugin, matchers) in &config_matchers {
241 for (abs_path, rel_path) in &relative_files {
242 if matchers.iter().any(|m| m.is_match(rel_path.as_str()))
243 && let Ok(source) = std::fs::read_to_string(abs_path)
244 {
245 let plugin_result = plugin.resolve_config(abs_path, &source, root);
246 if !plugin_result.is_empty() {
247 resolved_plugins.insert(plugin.name());
248 tracing::debug!(
249 plugin = plugin.name(),
250 config = rel_path.as_str(),
251 entries = plugin_result.entry_patterns.len(),
252 deps = plugin_result.referenced_dependencies.len(),
253 "resolved config"
254 );
255 process_config_result(plugin.name(), plugin_result, &mut result);
256 }
257 }
258 }
259 }
260
261 // Phase 3b: Filesystem fallback for JSON config files.
262 // JSON files (angular.json, project.json) are not in the discovered file set
263 // because fallow only discovers JS/TS/CSS/Vue/etc. files. In production
264 // mode, source-extension configs (`*.config.*`, dotfiles) are also
265 // excluded from the walker, so the FS walk runs for those patterns too.
266 let json_configs = discover_config_files(
267 &config_matchers,
268 &resolved_plugins,
269 config_search_roots,
270 production_mode,
271 );
272 for (abs_path, plugin) in &json_configs {
273 if let Ok(source) = std::fs::read_to_string(abs_path) {
274 let plugin_result = plugin.resolve_config(abs_path, &source, root);
275 if !plugin_result.is_empty() {
276 let rel = abs_path
277 .strip_prefix(root)
278 .map(|p| p.to_string_lossy())
279 .unwrap_or_default();
280 tracing::debug!(
281 plugin = plugin.name(),
282 config = %rel,
283 entries = plugin_result.entry_patterns.len(),
284 deps = plugin_result.referenced_dependencies.len(),
285 "resolved config (filesystem fallback)"
286 );
287 process_config_result(plugin.name(), plugin_result, &mut result);
288 }
289 }
290 }
291 }
292
293 // Phase 4: Package.json inline config fallback
294 // For plugins that define `package_json_config_key()`, check if the root
295 // package.json contains that key and no standalone config file was found.
296 for plugin in &active {
297 if let Some(key) = plugin.package_json_config_key()
298 && !check_has_config_file(*plugin, &config_matchers, &relative_files)
299 {
300 // Try to extract the key from package.json
301 let pkg_path = root.join("package.json");
302 if let Ok(content) = std::fs::read_to_string(&pkg_path)
303 && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
304 && let Some(config_value) = json.get(key)
305 {
306 let config_json = serde_json::to_string(config_value).unwrap_or_default();
307 let fake_path = root.join(format!("{key}.config.json"));
308 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
309 if !plugin_result.is_empty() {
310 tracing::debug!(
311 plugin = plugin.name(),
312 key = key,
313 "resolved inline package.json config"
314 );
315 process_config_result(plugin.name(), plugin_result, &mut result);
316 }
317 }
318 }
319 }
320
321 result
322 }
323
324 /// Fast variant of `run()` for workspace packages.
325 ///
326 /// Reuses pre-compiled config matchers and pre-computed relative files from the root
327 /// project run, avoiding repeated glob compilation and path computation per workspace.
328 /// Skips package.json inline config (workspace packages rarely have inline configs).
329 #[expect(
330 clippy::too_many_arguments,
331 reason = "Each parameter is a distinct, small value with no natural grouping; \
332 bundling them into a struct hurts call-site readability."
333 )]
334 pub fn run_workspace_fast(
335 &self,
336 pkg: &PackageJson,
337 root: &Path,
338 project_root: &Path,
339 precompiled_config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
340 relative_files: &[(PathBuf, String)],
341 skip_config_plugins: &FxHashSet<&str>,
342 production_mode: bool,
343 ) -> AggregatedPluginResult {
344 let _span = tracing::info_span!("run_plugins").entered();
345 let mut result = AggregatedPluginResult::default();
346
347 // Phase 1: Determine which plugins are active (with pre-computed deps)
348 let all_deps = pkg.all_dependency_names();
349 let active: Vec<&dyn Plugin> = self
350 .plugins
351 .iter()
352 .filter(|p| p.is_enabled_with_deps(&all_deps, root))
353 .map(AsRef::as_ref)
354 .collect();
355
356 let workspace_files: Vec<PathBuf> = relative_files
357 .iter()
358 .map(|(abs_path, _)| abs_path.clone())
359 .collect();
360
361 tracing::info!(
362 plugins = active
363 .iter()
364 .map(|p| p.name())
365 .collect::<Vec<_>>()
366 .join(", "),
367 "active plugins"
368 );
369
370 process_external_plugins(
371 &self.external_plugins,
372 &all_deps,
373 root,
374 &workspace_files,
375 &mut result,
376 );
377
378 // Early exit if no plugins are active (common for leaf workspace packages)
379 if active.is_empty() && result.active_plugins.is_empty() {
380 return result;
381 }
382
383 // Phase 2: Collect static patterns from active plugins
384 for plugin in &active {
385 process_static_patterns(*plugin, root, &mut result);
386 }
387
388 // Phase 3: Find and parse config files using pre-compiled matchers
389 // Only check matchers for plugins that are active in this workspace
390 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
391 let workspace_matchers: Vec<_> = precompiled_config_matchers
392 .iter()
393 .filter(|(p, _)| {
394 active_names.contains(p.name())
395 && (!skip_config_plugins.contains(p.name())
396 || must_parse_workspace_config_when_root_active(p.name()))
397 })
398 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
399 .collect();
400
401 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
402 if !workspace_matchers.is_empty() {
403 for (plugin, matchers) in &workspace_matchers {
404 for (abs_path, rel_path) in relative_files {
405 if matchers.iter().any(|m| m.is_match(rel_path.as_str()))
406 && let Ok(source) = std::fs::read_to_string(abs_path)
407 {
408 let plugin_result = plugin.resolve_config(abs_path, &source, root);
409 if !plugin_result.is_empty() {
410 resolved_ws_plugins.insert(plugin.name());
411 tracing::debug!(
412 plugin = plugin.name(),
413 config = rel_path.as_str(),
414 entries = plugin_result.entry_patterns.len(),
415 deps = plugin_result.referenced_dependencies.len(),
416 "resolved config"
417 );
418 process_config_result(plugin.name(), plugin_result, &mut result);
419 }
420 }
421 }
422 }
423 }
424
425 // Phase 3b: Filesystem fallback for JSON config files at the project root.
426 // Config files like angular.json live at the monorepo root, but Angular is
427 // only active in workspace packages. Check the project root for unresolved
428 // config patterns.
429 let ws_json_configs = if root == project_root {
430 discover_config_files(
431 &workspace_matchers,
432 &resolved_ws_plugins,
433 &[root],
434 production_mode,
435 )
436 } else {
437 discover_config_files(
438 &workspace_matchers,
439 &resolved_ws_plugins,
440 &[root, project_root],
441 production_mode,
442 )
443 };
444 // Parse discovered JSON config files
445 for (abs_path, plugin) in &ws_json_configs {
446 if let Ok(source) = std::fs::read_to_string(abs_path) {
447 let plugin_result = plugin.resolve_config(abs_path, &source, root);
448 if !plugin_result.is_empty() {
449 let rel = abs_path
450 .strip_prefix(project_root)
451 .map(|p| p.to_string_lossy())
452 .unwrap_or_default();
453 tracing::debug!(
454 plugin = plugin.name(),
455 config = %rel,
456 entries = plugin_result.entry_patterns.len(),
457 deps = plugin_result.referenced_dependencies.len(),
458 "resolved config (workspace filesystem fallback)"
459 );
460 process_config_result(plugin.name(), plugin_result, &mut result);
461 }
462 }
463 }
464
465 result
466 }
467
468 /// Pre-compile config pattern glob matchers for all plugins that have config patterns.
469 /// Returns a vec of (plugin, matchers) pairs that can be reused across multiple `run_workspace_fast` calls.
470 #[must_use]
471 pub fn precompile_config_matchers(&self) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
472 self.plugins
473 .iter()
474 .filter(|p| !p.config_patterns().is_empty())
475 .map(|p| {
476 let matchers: Vec<globset::GlobMatcher> = p
477 .config_patterns()
478 .iter()
479 .filter_map(|pat| {
480 let prepared = prepare_config_pattern(pat);
481 globset::Glob::new(&prepared)
482 .ok()
483 .map(|g| g.compile_matcher())
484 })
485 .collect();
486 (p.as_ref(), matchers)
487 })
488 .collect()
489 }
490}
491
492impl Default for PluginRegistry {
493 fn default() -> Self {
494 Self::new(vec![])
495 }
496}
497
498/// Warn when meta-frameworks are active but their generated configs are missing.
499///
500/// Meta-frameworks like Nuxt and Astro generate tsconfig/types files during a
501/// "prepare" step. Without these, the tsconfig extends chain breaks and
502/// extensionless imports fail wholesale (e.g. 2000+ unresolved imports).
503fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
504 for plugin in active_plugins {
505 match plugin.name() {
506 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => {
507 tracing::warn!(
508 "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
509 before fallow for accurate analysis"
510 );
511 }
512 "astro" if !root.join(".astro").exists() => {
513 tracing::warn!(
514 "Astro project missing .astro/ types: run `astro sync` \
515 before fallow for accurate analysis"
516 );
517 }
518 _ => {}
519 }
520 }
521}
522
523#[cfg(test)]
524mod tests;