Skip to main content

fallow_core/plugins/registry/
mod.rs

1//! Plugin registry: discovers active plugins, collects patterns, parses configs.
2
3use rustc_hash::{FxHashMap, FxHashSet};
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::{OnceLock, RwLock};
7
8use fallow_config::{
9    AutoImportRule, EntryPointRole, ExternalPluginDef, JsxImportSourceRule, PackageJson,
10    UsedClassMemberRule,
11};
12
13use crate::scripts;
14
15use super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, ProvidedDependencyRule};
16
17pub(crate) mod builtin;
18mod helpers;
19mod tooling_evidence;
20
21pub(crate) use tooling_evidence::find_config_file;
22
23/// Names of every built-in framework plugin, in registry order.
24///
25/// Derived live from the plugin registry so capability introspection
26/// (`fallow schema`) can list plugins without a hand-maintained mirror.
27#[must_use]
28pub fn builtin_plugin_names() -> Vec<&'static str> {
29    builtin::create_builtin_plugins()
30        .iter()
31        .map(|plugin| plugin.name())
32        .collect()
33}
34
35/// Config file globs that any built-in framework plugin can read, sorted and
36/// without duplicates. A pattern is relative to the directory the plugin
37/// searches, so a caller that matches root-relative paths also tries it
38/// under `**/`.
39#[must_use]
40pub fn builtin_config_patterns() -> Vec<&'static str> {
41    let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
42        .iter()
43        .flat_map(|plugin| plugin.config_patterns().iter().copied())
44        .collect();
45    patterns.sort_unstable();
46    patterns.dedup();
47    patterns
48}
49
50/// The config file globs of the named built-in plugins, sorted and without
51/// duplicates. A name that is not a built-in plugin adds no glob. A pattern
52/// is relative to the directory the plugin searches.
53#[must_use]
54pub fn builtin_config_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
55    let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
56        .iter()
57        .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
58        .flat_map(|plugin| plugin.config_patterns().iter().copied())
59        .collect();
60    patterns.sort_unstable();
61    patterns.dedup();
62    patterns
63}
64
65/// The always-used globs of the active built-in plugins, sorted and without
66/// duplicates. Some plugins list their config file here instead of in
67/// `config_patterns`, for example `.vitepress/config.ts`.
68#[must_use]
69pub fn builtin_always_used_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
70    let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
71        .iter()
72        .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
73        .flat_map(|plugin| plugin.always_used().iter().copied())
74        .collect();
75    patterns.sort_unstable();
76    patterns.dedup();
77    patterns
78}
79
80pub use helpers::ConfigCandidateIndex;
81pub use helpers::is_external_plugin_active;
82use helpers::{
83    check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
84    process_external_plugins, process_package_json_metadata, process_static_patterns,
85};
86
87fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
88    matches!(
89        plugin_name,
90        "eslint" | "docusaurus" | "jest" | "storybook" | "tanstack-router" | "vitest"
91    )
92}
93
94fn compile_config_matchers<'a>(
95    active: &[&'a dyn Plugin],
96) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
97    active
98        .iter()
99        .filter(|plugin| !plugin.config_patterns().is_empty())
100        .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
101        .collect()
102}
103
104fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
105    plugin
106        .config_patterns()
107        .iter()
108        .filter_map(|pattern| {
109            let prepared = prepare_config_pattern(pattern);
110            globset::Glob::new(&prepared)
111                .ok()
112                .map(|glob| glob.compile_matcher())
113        })
114        .collect()
115}
116
117struct CachedPluginConfigMatchers {
118    patterns: &'static [&'static str],
119    matchers: Vec<globset::GlobMatcher>,
120}
121
122#[derive(Default)]
123struct PluginConfigMatcherCache {
124    by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
125}
126
127impl PluginConfigMatcherCache {
128    fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
129        let patterns = plugin.config_patterns();
130        let cached = self
131            .by_name
132            .read()
133            .unwrap_or_else(std::sync::PoisonError::into_inner)
134            .get(plugin.name())
135            .and_then(|variants| {
136                variants
137                    .iter()
138                    .find(|entry| entry.patterns == patterns)
139                    .map(|entry| entry.matchers.clone())
140            });
141        if let Some(matchers) = cached {
142            return matchers;
143        }
144
145        let matchers = compile_plugin_config_matchers(plugin);
146        {
147            let mut by_name = self
148                .by_name
149                .write()
150                .unwrap_or_else(std::sync::PoisonError::into_inner);
151            let variants = by_name.entry(plugin.name()).or_default();
152            if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
153                return entry.matchers.clone();
154            }
155            variants.push(CachedPluginConfigMatchers {
156                patterns,
157                matchers: matchers.clone(),
158            });
159            drop(by_name);
160        }
161        matchers
162    }
163}
164
165fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
166    static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
167    MATCHERS
168        .get_or_init(PluginConfigMatcherCache::default)
169        .get_or_compile(plugin)
170}
171
172/// Emit one info-level line naming every active plugin.
173fn log_active_plugins(active: &[&dyn Plugin]) {
174    tracing::info!(
175        plugins = active
176            .iter()
177            .map(|p| p.name())
178            .collect::<Vec<_>>()
179            .join(", "),
180        "active plugins"
181    );
182}
183
184/// Compute `(absolute, root-relative)` file pairs, but only when at least one
185/// active plugin needs config matching or a package.json config key. Returns an
186/// empty vec otherwise to skip the per-file path work.
187fn compute_relative_files(
188    config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
189    active: &[&dyn Plugin],
190    discovered_files: &[PathBuf],
191    root: &Path,
192) -> Vec<(PathBuf, String)> {
193    use rayon::prelude::*;
194    let needs_relative_files =
195        !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
196    if !needs_relative_files {
197        return Vec::new();
198    }
199    discovered_files
200        .par_iter()
201        .map(|f| {
202            let rel = f
203                .strip_prefix(root)
204                .unwrap_or(f)
205                .to_string_lossy()
206                .into_owned();
207            (f.clone(), rel)
208        })
209        .collect()
210}
211
212/// Registry of all available plugins (built-in + external).
213pub struct PluginRegistry {
214    plugins: Vec<Box<dyn Plugin>>,
215    external_plugins: Vec<ExternalPluginDef>,
216}
217
218/// Inputs for the workspace-fast plugin path.
219pub(crate) struct WorkspacePluginRunInput<'a> {
220    pub(crate) pkg: &'a PackageJson,
221    pub(crate) root: &'a Path,
222    pub(crate) project_root: &'a Path,
223    pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
224    pub(crate) relative_files: &'a [(PathBuf, String)],
225    pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
226    pub(crate) production_mode: bool,
227    pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
228}
229
230struct PluginRunContext<'a> {
231    all_deps: Vec<String>,
232    active: Vec<&'a dyn Plugin>,
233}
234
235/// Inputs governing which built-in plugins activate for a project.
236struct PluginActivationInput<'a> {
237    pkg: &'a PackageJson,
238    root: &'a Path,
239    discovered_files: &'a [PathBuf],
240    all_deps: &'a [String],
241    script_packages: &'a FxHashSet<String>,
242    candidate_index: Option<&'a ConfigCandidateIndex>,
243}
244
245/// Invalid user-authored regex extracted from a plugin config file.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct PluginRegexValidationError {
248    plugin_name: String,
249    config_path: Option<PathBuf>,
250    rule_kind: &'static str,
251    field: &'static str,
252    rule_pattern: String,
253    regex_pattern: String,
254    source: String,
255}
256
257impl PluginRegexValidationError {
258    fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
259        Self {
260            plugin_name: input.plugin_name.to_owned(),
261            config_path: input.config_path.map(Path::to_path_buf),
262            rule_kind: input.rule_kind,
263            field: input.field,
264            rule_pattern: input.rule_pattern.to_owned(),
265            regex_pattern: input.regex_pattern.to_owned(),
266            source: input.source.to_string(),
267        }
268    }
269}
270
271#[derive(Clone, Copy)]
272struct PluginRegexValidationErrorInput<'a> {
273    plugin_name: &'a str,
274    config_path: Option<&'a Path>,
275    rule_kind: &'static str,
276    field: &'static str,
277    rule_pattern: &'a str,
278    regex_pattern: &'a str,
279    source: &'a regex::Error,
280}
281
282impl fmt::Display for PluginRegexValidationError {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        let location = self
285            .config_path
286            .as_ref()
287            .map(|path| format!(" in {}", path.display()))
288            .unwrap_or_default();
289        write!(
290            f,
291            "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
292            self.plugin_name,
293            location,
294            self.regex_pattern,
295            self.rule_kind,
296            self.field,
297            self.rule_pattern,
298            self.source
299        )
300    }
301}
302
303#[must_use]
304pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
305    let joined = errors
306        .iter()
307        .map(ToString::to_string)
308        .collect::<Vec<_>>()
309        .join("\n  - ");
310    format!(
311        "invalid plugin regex configuration:\n  - {joined}\n\nRewrite the plugin config with Rust-compatible regex syntax, or remove unsupported constructs such as JavaScript lookahead and lookbehind."
312    )
313}
314
315/// The tooling dependencies of one active plugin, plus the evidence that the
316/// project uses the plugin.
317///
318/// The unused devDependency check credits `dependencies` only when the plugin
319/// found a config of its own (`own_config`), or when a package.json script, a
320/// CI workflow or a git hook invokes one of `references`. An active plugin
321/// alone is no evidence: a declared package activates it.
322#[derive(Debug, Clone, Default, PartialEq, Eq)]
323pub struct PluginToolingDependencies {
324    /// The plugin name.
325    pub plugin: String,
326    /// The tooling dependencies the plugin declares.
327    pub dependencies: Vec<String>,
328    /// The package names whose script, CI or hook invocation shows that the
329    /// project runs the plugin's tool: its tooling dependencies and its exact
330    /// enablers.
331    pub references: Vec<String>,
332    /// The config file the plugin found, or the package.json that holds its
333    /// config. Absolute path.
334    pub own_config: Option<PathBuf>,
335}
336
337/// Why a plugin's tooling dependencies are credited.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum PluginToolingEvidence<'a> {
340    /// The plugin found this config file, or the package.json with its config.
341    OwnConfig(&'a Path),
342    /// A script, CI workflow or git hook invokes this package.
343    Reference(&'a str),
344}
345
346impl PluginToolingDependencies {
347    /// The evidence that the project uses the plugin, given the packages that
348    /// scripts, CI workflows and git hooks invoke. `None` means the plugin's
349    /// tooling dependencies are not credited.
350    #[must_use]
351    pub fn evidence<'a>(
352        &'a self,
353        script_used_packages: &FxHashSet<String>,
354    ) -> Option<PluginToolingEvidence<'a>> {
355        if let Some(config) = &self.own_config {
356            return Some(PluginToolingEvidence::OwnConfig(config));
357        }
358        self.references
359            .iter()
360            .find(|name| script_used_packages.contains(name.as_str()))
361            .map(|name| PluginToolingEvidence::Reference(name))
362    }
363}
364
365/// Aggregated results from all active plugins for a project.
366#[derive(Debug, Clone, Default)]
367pub struct AggregatedPluginResult {
368    /// All entry point patterns from active plugins: (rule, plugin_name).
369    pub entry_patterns: Vec<(PathRule, String)>,
370    /// Plugins whose config already replaced their static entry patterns.
371    /// A later config of a plugin that sets
372    /// `accumulate_config_entry_patterns` adds to the config patterns and does
373    /// not remove them.
374    pub replaced_entry_plugins: FxHashSet<String>,
375    /// The `(plugin, pattern)` pairs that config files added. The first
376    /// replacing config of a plugin that sets
377    /// `accumulate_config_entry_patterns` keeps these patterns.
378    pub config_entry_patterns: FxHashSet<(String, String)>,
379    /// Coverage role for each plugin contributing entry point patterns.
380    pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
381    /// All config file patterns from active plugins.
382    pub config_patterns: Vec<String>,
383    /// All always-used file patterns from active plugins: (pattern, plugin_name).
384    pub always_used: Vec<(String, String)>,
385    /// All used export rules from active plugins.
386    pub used_exports: Vec<PluginUsedExportRule>,
387    /// The config-file export credit of each active plugin: one `default`
388    /// rule for each config pattern minus the plugin's
389    /// `config_default_export_opt_out`, plus the anchored
390    /// `config_file_exports` rules with their own export names, plus the
391    /// entry export credits that config results give. The
392    /// unused-export analysis reads these rules only under
393    /// `includeEntryExports`, so they never change the default output.
394    pub config_export_credits: Vec<PluginUsedExportRule>,
395    /// Class member rules contributed by active plugins that should never be
396    /// flagged as unused. Extends the built-in Angular/React lifecycle allowlist
397    /// with framework-invoked method names, optionally scoped by class heritage.
398    pub used_class_members: Vec<UsedClassMemberRule>,
399    /// Exact framework contracts with plugin and package provenance.
400    pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
401    /// Dependencies referenced in config files (should not be flagged unused).
402    pub referenced_dependencies: Vec<String>,
403    /// Dependencies referenced by package.json metadata, scoped to that package.json path.
404    pub package_referenced_dependencies: Vec<(PathBuf, String)>,
405    /// Packages that a config needs installed, with the config location.
406    pub required_dependencies: Vec<super::RequiredDependency>,
407    /// Additional always-used files discovered from config parsing: (pattern, plugin_name).
408    pub discovered_always_used: Vec<(String, String)>,
409    /// Setup files discovered from config parsing: (path, plugin_name).
410    pub setup_files: Vec<(PathBuf, String)>,
411    /// Tooling dependencies of every active plugin, whether or not the plugin
412    /// found evidence that the project uses it. The unlisted-dependency and
413    /// dev-dependency-in-production checks read this list.
414    pub tooling_dependencies: Vec<String>,
415    /// Tooling dependencies grouped by the active plugin that declares them,
416    /// with the evidence that decides whether an unused devDependency check
417    /// credits them. See [`PluginToolingDependencies`].
418    pub plugin_tooling: Vec<PluginToolingDependencies>,
419    /// Package names discovered as used in package.json scripts (binary invocations).
420    pub script_used_packages: FxHashSet<String>,
421    /// The binary names that the declared dependencies provide. Script
422    /// analysis fills it for the root result; workspace results keep the
423    /// default.
424    pub dependency_binaries: crate::scripts::DependencyBinaries,
425    /// The names that the root and workspace manifests declare in
426    /// `devDependencies`. Script analysis fills it for the root result, so
427    /// the trace credits a dependency only where the unused devDependency
428    /// check would.
429    pub dev_dependency_names: FxHashSet<String>,
430    /// Import prefixes for virtual modules provided by active frameworks.
431    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
432    pub virtual_module_prefixes: Vec<String>,
433    /// Package name suffixes that identify virtual or convention-based specifiers.
434    /// Extracted package names ending with any of these suffixes are not flagged as unlisted.
435    pub virtual_package_suffixes: Vec<String>,
436    /// Import suffixes for build-time generated relative imports.
437    /// Unresolved imports ending with these suffixes are suppressed.
438    pub generated_import_patterns: Vec<String>,
439    /// Import prefixes for build-time generated type-only relative imports.
440    /// Unresolved type-only imports starting with these prefixes are suppressed.
441    pub generated_type_import_prefixes: Vec<String>,
442    /// Path alias mappings from active plugins (prefix → replacement directory).
443    /// Used by the resolver to substitute import prefixes before re-resolving.
444    pub path_aliases: Vec<(String, String)>,
445    /// Convention-based auto-import rules from active plugins (Nuxt components).
446    /// The resolver matches each file's captured `auto_import_candidates` against
447    /// these and synthesizes a graph edge to the rule's source. See issue #704.
448    pub auto_imports: Vec<AutoImportRule>,
449    /// Names of active plugins.
450    pub active_plugins: Vec<String>,
451    /// Test fixture glob patterns from active plugins: (pattern, plugin_name).
452    pub fixture_patterns: Vec<(String, String)>,
453    /// Absolute directories contributed by plugins that should be searched
454    /// when resolving SCSS/Sass `@import`/`@use` specifiers. Populated from
455    /// Angular's `stylePreprocessorOptions.includePaths` and equivalent
456    /// framework settings. See issue #103.
457    pub scss_include_paths: Vec<PathBuf>,
458    /// Static directory mappings contributed by plugins.
459    pub static_dir_mappings: Vec<(PathBuf, String)>,
460    /// Mounts a framework serves for the whole project, so any HTML document
461    /// reaches them, unlike the tool-scoped mounts above.
462    pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
463    /// File-scoped dependency provider rules from active plugins.
464    pub provided_dependencies: Vec<ProvidedDependencyRule>,
465    /// Advisories about the config files active plugins read. Converted to
466    /// workspace diagnostics once, at the end of the plugin run, where the
467    /// project root is known.
468    pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
469    /// Where Module Federation configs expose files and declare remote
470    /// aliases, for the trace output.
471    pub federation_sources: Vec<super::FederationSource>,
472    /// JSX import sources that bundler and test configs set, with the files
473    /// each config transforms. The resolver adds the runtime edge to each
474    /// matching module with `jsx_runtime_from_config` set.
475    pub jsx_import_sources: Vec<JsxImportSourceRule>,
476    /// Runtime packages that a JSX transform imports when its config sets no
477    /// import source. The analysis credits a package only when a matching
478    /// module has `jsx_runtime_from_config` set. These rules add no graph
479    /// edge.
480    pub jsx_package_credits: Vec<JsxImportSourceRule>,
481    /// The directories of the tsconfig files that set the JSX runtime of
482    /// TypeScript files, so Vite does not use the default `react` runtime for
483    /// the TypeScript files below them.
484    pub tsconfig_jsx_dirs: Vec<PathBuf>,
485}
486
487/// Append `incoming` string items to `target`, skipping values already present
488/// in `target` or earlier in `incoming`. Matches the deduplication the
489/// workspace merge applied via per-field `seen` sets before #444 centralized
490/// it on [`AggregatedPluginResult::merge_into`].
491fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
492    let mut seen: FxHashSet<String> = target.iter().cloned().collect();
493    for item in incoming {
494        if seen.insert(item.clone()) {
495            target.push(item);
496        }
497    }
498}
499
500/// Append each incoming item that `target` does not hold yet. For the small
501/// lists whose items have no hash.
502fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
503    for item in incoming {
504        if !target.contains(&item) {
505            target.push(item);
506        }
507    }
508}
509
510/// Prefix a workspace-relative pattern so it matches from the monorepo root,
511/// unless it is already workspace-prefixed or project-root-relative (leading
512/// `/`, e.g. an angular.json path). Mirrors the pre-#444 inline closure.
513fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
514    if pat.starts_with(ws_prefix) || pat.starts_with('/') {
515        pat.to_string()
516    } else {
517        format!("{ws_prefix}/{pat}")
518    }
519}
520
521impl AggregatedPluginResult {
522    /// The entry patterns without exact repeats, in first-seen order.
523    ///
524    /// The project pass, each workspace pass, and each config file of a plugin
525    /// can seed the same rule for the same plugin. A repeat adds no match, so
526    /// the compiled glob set keeps one copy.
527    pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
528        let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
529        self.entry_patterns
530            .iter()
531            .filter(move |entry| seen.insert(entry))
532    }
533
534    /// Apply a workspace prefix to every path-bearing field in place.
535    ///
536    /// Workspace-package results are collected with patterns relative to the
537    /// package root; to be matchable from the monorepo root they need the
538    /// package's prefix applied. This transform is call-site-specific (it
539    /// depends on `ws_prefix`), so it stays separate from [`Self::merge_into`],
540    /// which is a prefix-agnostic union. The root project's own result is
541    /// never prefixed.
542    ///
543    /// Fields that carry package names, absolute paths, or import-specifier
544    /// boundaries (referenced/tooling deps, setup files, static dir mappings,
545    /// auto-imports, virtual prefixes/suffixes, generated patterns) are left
546    /// untouched, matching the pre-#444 merge loop. `config_diagnostics` is one
547    /// of those: it holds the ABSOLUTE path of the config file a plugin read,
548    /// which needs no prefix to name the right file from the monorepo root.
549    pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
550        for (rule, _) in &mut self.entry_patterns {
551            *rule = rule.prefixed(ws_prefix);
552        }
553        for (pat, _) in &mut self.always_used {
554            *pat = prefix_if_needed(pat, ws_prefix);
555        }
556        for (pat, _) in &mut self.discovered_always_used {
557            *pat = prefix_if_needed(pat, ws_prefix);
558        }
559        for (pat, _) in &mut self.fixture_patterns {
560            *pat = prefix_if_needed(pat, ws_prefix);
561        }
562        for rule in &mut self.used_exports {
563            *rule = rule.prefixed(ws_prefix);
564        }
565        for rule in &mut self.config_export_credits {
566            *rule = rule.prefixed(ws_prefix);
567        }
568        for rule in &mut self.provided_dependencies {
569            *rule = rule.prefixed(ws_prefix);
570        }
571        for source in &mut self.federation_sources {
572            *source = source.prefixed(ws_prefix);
573        }
574        for (_, replacement) in &mut self.path_aliases {
575            *replacement = format!("{ws_prefix}/{replacement}");
576        }
577    }
578
579    /// Merge `other` into `self`, taking the union of every field.
580    ///
581    /// Exhaustively destructures `Self` so adding a field to
582    /// `AggregatedPluginResult` becomes a `missing field in pattern` compile
583    /// error here instead of a silently-dropped field. See issue #444.
584    ///
585    /// Callers that need the workspace prefix applied must call
586    /// [`Self::apply_workspace_prefix`] on `other` first; this method does not
587    /// transform any path. Dedup-bearing fields (`active_plugins`, the virtual
588    /// prefix/suffix, generated-pattern, and semantic framework-contract lists)
589    /// deduplicate the incoming values against the contents already in `self`,
590    /// matching the pre-#444 `seen`-set behavior. `entry_point_roles` is
591    /// first-writer-wins.
592    pub(crate) fn merge_into(&mut self, other: Self) {
593        let Self {
594            entry_patterns,
595            // Only the config pass of one plugin run reads this field.
596            replaced_entry_plugins: _,
597            config_entry_patterns: _,
598            entry_point_roles,
599            config_patterns,
600            always_used,
601            used_exports,
602            config_export_credits,
603            used_class_members,
604            framework_class_member_contracts,
605            referenced_dependencies,
606            package_referenced_dependencies,
607            required_dependencies,
608            discovered_always_used,
609            setup_files,
610            tooling_dependencies,
611            plugin_tooling,
612            script_used_packages,
613            dependency_binaries: _,
614            dev_dependency_names,
615            virtual_module_prefixes,
616            virtual_package_suffixes,
617            generated_import_patterns,
618            generated_type_import_prefixes,
619            path_aliases,
620            auto_imports,
621            active_plugins,
622            fixture_patterns,
623            scss_include_paths,
624            static_dir_mappings,
625            framework_static_dir_mappings,
626            provided_dependencies,
627            config_diagnostics,
628            federation_sources,
629            jsx_import_sources,
630            jsx_package_credits,
631            tsconfig_jsx_dirs,
632        } = other;
633
634        self.entry_patterns.extend(entry_patterns);
635        for (plugin_name, role) in entry_point_roles {
636            self.entry_point_roles.entry(plugin_name).or_insert(role);
637        }
638        self.config_patterns.extend(config_patterns);
639        self.always_used.extend(always_used);
640        self.used_exports.extend(used_exports);
641        self.config_export_credits.extend(config_export_credits);
642        self.used_class_members.extend(used_class_members);
643        for contract in framework_class_member_contracts {
644            if !self.framework_class_member_contracts.contains(&contract) {
645                self.framework_class_member_contracts.push(contract);
646            }
647        }
648        self.referenced_dependencies.extend(referenced_dependencies);
649        self.package_referenced_dependencies
650            .extend(package_referenced_dependencies);
651        push_missing(&mut self.required_dependencies, required_dependencies);
652        self.discovered_always_used.extend(discovered_always_used);
653        self.setup_files.extend(setup_files);
654        self.tooling_dependencies.extend(tooling_dependencies);
655        self.plugin_tooling.extend(plugin_tooling);
656        self.dev_dependency_names.extend(dev_dependency_names);
657        self.script_used_packages.extend(script_used_packages);
658        extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
659        extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
660        extend_unique(
661            &mut self.generated_import_patterns,
662            generated_import_patterns,
663        );
664        extend_unique(
665            &mut self.generated_type_import_prefixes,
666            generated_type_import_prefixes,
667        );
668        self.path_aliases.extend(path_aliases);
669        self.auto_imports.extend(auto_imports);
670        extend_unique(&mut self.active_plugins, active_plugins);
671        self.fixture_patterns.extend(fixture_patterns);
672        self.scss_include_paths.extend(scss_include_paths);
673        self.static_dir_mappings.extend(static_dir_mappings);
674        self.framework_static_dir_mappings
675            .extend(framework_static_dir_mappings);
676        self.provided_dependencies.extend(provided_dependencies);
677        self.federation_sources.extend(federation_sources);
678        push_missing(&mut self.jsx_import_sources, jsx_import_sources);
679        push_missing(&mut self.jsx_package_credits, jsx_package_credits);
680        push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
681        push_missing(&mut self.config_diagnostics, config_diagnostics);
682    }
683}
684
685impl PluginRegistry {
686    /// Create a registry with all built-in plugins and optional external plugins.
687    #[must_use]
688    pub fn new(external: Vec<ExternalPluginDef>) -> Self {
689        Self {
690            plugins: builtin::create_builtin_plugins(),
691            external_plugins: external,
692        }
693    }
694
695    /// Hidden directory names that should be traversed before full plugin execution.
696    ///
697    /// Source discovery runs before plugin config parsing, so this helper only uses
698    /// package-activation checks and static plugin metadata.
699    #[must_use]
700    pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
701        let all_deps = pkg.all_dependency_names();
702        let mut seen = FxHashSet::default();
703        let mut dirs = Vec::new();
704
705        for plugin in &self.plugins {
706            if !plugin.is_enabled_with_deps(&all_deps, root) {
707                continue;
708            }
709            for dir in plugin.discovery_hidden_dirs() {
710                if seen.insert(*dir) {
711                    dirs.push((*dir).to_string());
712                }
713            }
714        }
715
716        dirs
717    }
718
719    /// Test convenience wrapper for running all plugins against a project.
720    ///
721    /// This discovers which plugins are active, collects their static patterns,
722    /// then parses any config files to extract dynamic information.
723    #[cfg(test)]
724    fn run(
725        &self,
726        pkg: &PackageJson,
727        root: &Path,
728        discovered_files: &[PathBuf],
729    ) -> AggregatedPluginResult {
730        self.try_run(pkg, root, discovered_files)
731            .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
732    }
733
734    /// Run all plugins, returning invalid plugin regexes as hard errors.
735    pub fn try_run(
736        &self,
737        pkg: &PackageJson,
738        root: &Path,
739        discovered_files: &[PathBuf],
740    ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
741        self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
742    }
743
744    /// Run all plugins against a project with explicit config-file search roots,
745    /// returning invalid plugin regexes as hard errors.
746    #[expect(
747        clippy::too_many_arguments,
748        reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
749    )]
750    pub(crate) fn try_run_with_search_roots(
751        &self,
752        pkg: &PackageJson,
753        root: &Path,
754        discovered_files: &[PathBuf],
755        config_search_roots: &[&Path],
756        production_mode: bool,
757        candidate_index: Option<&ConfigCandidateIndex>,
758    ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
759        let _span = tracing::info_span!("run_plugins").entered();
760        let mut result = AggregatedPluginResult::default();
761        let mut regex_errors = Vec::new();
762
763        let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
764            pkg,
765            root,
766            discovered_files,
767            production_mode,
768            candidate_index,
769        );
770
771        self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
772
773        for plugin in &active {
774            process_static_patterns(*plugin, root, &mut result);
775        }
776        process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
777
778        process_external_plugins(
779            &self.external_plugins,
780            &all_deps,
781            root,
782            discovered_files,
783            &mut result,
784        );
785        tooling_evidence::record_plugin_tooling(
786            &tooling_evidence::ToolingEvidenceInput {
787                active: &active,
788                external_plugins: &self.external_plugins,
789                all_deps: &all_deps,
790                roots: &[root],
791                // Production mode turns the unused devDependency check off, so a
792                // workspace config file credits nothing there and the probe of
793                // every search root is pure cost.
794                extra_roots: if production_mode {
795                    &[]
796                } else {
797                    config_search_roots
798                },
799                candidate_index,
800                discovered_files,
801            },
802            &mut result,
803        );
804
805        let config_matchers = compile_config_matchers(&active);
806        let relative_files =
807            compute_relative_files(&config_matchers, &active, discovered_files, root);
808
809        resolve_plugin_config_files(&mut PluginConfigResolutionInput {
810            config_matchers: &config_matchers,
811            relative_files: &relative_files,
812            config_search_roots,
813            production_mode,
814            candidate_index,
815            root,
816            result: &mut result,
817            regex_errors: &mut regex_errors,
818        });
819
820        process_package_json_inline_configs(
821            &active,
822            &config_matchers,
823            &relative_files,
824            root,
825            &mut result,
826            &mut regex_errors,
827        );
828
829        if regex_errors.is_empty() {
830            Ok(result)
831        } else {
832            Err(regex_errors)
833        }
834    }
835
836    /// Test convenience wrapper for the fast workspace plugin path.
837    ///
838    /// Reuses pre-compiled config matchers and pre-computed relative files from the root
839    /// project run, avoiding repeated glob compilation and path computation per workspace.
840    /// Skips package.json inline config (workspace packages rarely have inline configs).
841    #[cfg(test)]
842    fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
843        self.try_run_workspace_fast(input)
844            .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
845    }
846
847    /// Fast variant of `try_run()` for workspace packages.
848    ///
849    /// Reuses pre-compiled config matchers and pre-computed relative files from the root
850    /// project run, avoiding repeated glob compilation and path computation per workspace.
851    /// Skips package.json inline config (workspace packages rarely have inline configs).
852    pub(crate) fn try_run_workspace_fast(
853        &self,
854        input: &WorkspacePluginRunInput<'_>,
855    ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
856        let _span = tracing::info_span!("run_plugins").entered();
857        let mut result = AggregatedPluginResult::default();
858        let mut regex_errors = Vec::new();
859
860        let all_deps = input.pkg.all_dependency_names();
861        let script_packages =
862            script_activation_packages(input.pkg, input.root, &all_deps, input.production_mode);
863        let workspace_files: Vec<PathBuf> = input
864            .relative_files
865            .iter()
866            .map(|(abs_path, _)| abs_path.clone())
867            .collect();
868
869        let active = self.collect_active_plugins(&PluginActivationInput {
870            pkg: input.pkg,
871            root: input.root,
872            discovered_files: &workspace_files,
873            all_deps: &all_deps,
874            script_packages: &script_packages,
875            candidate_index: input.candidate_index,
876        });
877
878        log_active_plugins(&active);
879
880        self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
881
882        process_external_plugins(
883            &self.external_plugins,
884            &all_deps,
885            input.root,
886            &workspace_files,
887            &mut result,
888        );
889
890        if active.is_empty() && result.active_plugins.is_empty() {
891            return Ok(result);
892        }
893
894        process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
895        // A config file at the project root applies to a workspace package too.
896        let evidence_roots: &[&Path] = if input.root == input.project_root {
897            &[input.root]
898        } else {
899            &[input.root, input.project_root]
900        };
901        tooling_evidence::record_plugin_tooling(
902            &tooling_evidence::ToolingEvidenceInput {
903                active: &active,
904                external_plugins: &self.external_plugins,
905                all_deps: &all_deps,
906                roots: evidence_roots,
907                extra_roots: &[],
908                candidate_index: input.candidate_index,
909                discovered_files: &workspace_files,
910            },
911            &mut result,
912        );
913        resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
914
915        if regex_errors.is_empty() {
916            Ok(result)
917        } else {
918            Err(regex_errors)
919        }
920    }
921
922    /// Pre-compile config pattern glob matchers for all plugins that have config patterns.
923    /// Returns a vec of (plugin, matchers) pairs that can be reused across multiple `run_workspace_fast` calls.
924    #[must_use]
925    pub(crate) fn precompile_config_matchers(
926        &self,
927    ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
928        self.plugins
929            .iter()
930            .filter(|p| !p.config_patterns().is_empty())
931            .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
932            .collect()
933    }
934
935    /// Resolve the config files that package scripts pass to a plugin binary
936    /// with `--config` / `-c`.
937    ///
938    /// `package_root` is the directory of the `package.json` that holds the
939    /// scripts, and `ws_prefix` is its path relative to `project_root`
940    /// (empty for the root package). Each file is resolved into its own
941    /// result, so a `test.include` in a script config adds entry patterns
942    /// and does not replace the patterns of the plugin's default config.
943    /// A file in the package root that a `config_patterns()` entry matches is
944    /// skipped, because the normal plugin run resolves it already.
945    pub(crate) fn resolve_script_config_files(
946        &self,
947        config_files: &[scripts::BinaryConfigFile],
948        package_root: &Path,
949        project_root: &Path,
950        ws_prefix: &str,
951    ) -> AggregatedPluginResult {
952        let mut aggregated = AggregatedPluginResult::default();
953        for config_file in config_files {
954            let Some(rel_path) =
955                scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
956            else {
957                continue;
958            };
959            let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
960            // The normal plugin run reads a matched config with its own
961            // directory as the directory that the tool runs in. A script runs
962            // the tool in the package root, so a matched config below the
963            // package root is also read here, against the package root.
964            let in_package_root = abs_path.parent() == Some(package_root);
965            for plugin in &self.plugins {
966                let plugin = plugin.as_ref();
967                if !plugin
968                    .script_config_binaries()
969                    .contains(&config_file.binary.as_str())
970                    || (in_package_root
971                        && cached_plugin_config_matchers(plugin)
972                            .iter()
973                            .any(|m| m.is_match(rel_path.as_str())))
974                {
975                    continue;
976                }
977                if !super::config_parser::is_inside_root(&abs_path, project_root) {
978                    continue;
979                }
980                let Ok(source) = std::fs::read_to_string(&abs_path) else {
981                    continue;
982                };
983                let mut file_result = AggregatedPluginResult::default();
984                file_result
985                    .entry_point_roles
986                    .insert(plugin.name().to_string(), plugin.entry_point_role());
987                let plugin_result =
988                    plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
989                if let Err(errors) = process_config_result(
990                    plugin.name(),
991                    plugin_result,
992                    &mut file_result,
993                    Some(&abs_path),
994                ) {
995                    for error in errors {
996                        tracing::warn!("{error}");
997                    }
998                    continue;
999                }
1000                if !ws_prefix.is_empty() {
1001                    file_result.apply_workspace_prefix(ws_prefix);
1002                }
1003                // The tool loads the config module and reads its default export.
1004                file_result.used_exports.push(PluginUsedExportRule::new(
1005                    plugin.name().to_string(),
1006                    super::UsedExportRule::new(rel_path.clone(), ["default"]),
1007                ));
1008                aggregated.merge_into(file_result);
1009            }
1010        }
1011        aggregated
1012    }
1013}
1014
1015fn process_workspace_active_plugins(
1016    active: &[&dyn Plugin],
1017    input: &WorkspacePluginRunInput<'_>,
1018    result: &mut AggregatedPluginResult,
1019    regex_errors: &mut Vec<PluginRegexValidationError>,
1020) {
1021    for plugin in active {
1022        process_static_patterns(*plugin, input.root, result);
1023    }
1024    process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1025}
1026
1027fn resolve_workspace_plugin_configs(
1028    active: &[&dyn Plugin],
1029    input: &WorkspacePluginRunInput<'_>,
1030    result: &mut AggregatedPluginResult,
1031    regex_errors: &mut Vec<PluginRegexValidationError>,
1032) {
1033    let workspace_matchers = select_workspace_matchers(
1034        input.precompiled_config_matchers,
1035        active,
1036        input.skip_config_plugins,
1037    );
1038
1039    let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1040    for (plugin, matchers) in &workspace_matchers {
1041        resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1042            plugin: *plugin,
1043            matchers,
1044            relative_files: input.relative_files,
1045            root: input.root,
1046            project_root: input.project_root,
1047            result,
1048            regex_errors,
1049            resolved_plugins: &mut resolved_ws_plugins,
1050        });
1051    }
1052
1053    load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1054        workspace_matchers: &workspace_matchers,
1055        resolved_ws_plugins: &resolved_ws_plugins,
1056        root: input.root,
1057        project_root: input.project_root,
1058        production_mode: input.production_mode,
1059        candidate_index: input.candidate_index,
1060        result,
1061        regex_errors,
1062    });
1063}
1064
1065impl Default for PluginRegistry {
1066    fn default() -> Self {
1067        Self::new(vec![])
1068    }
1069}
1070
1071impl PluginRegistry {
1072    fn prepare_plugin_run_context<'a>(
1073        &'a self,
1074        pkg: &PackageJson,
1075        root: &Path,
1076        discovered_files: &[PathBuf],
1077        production_mode: bool,
1078        candidate_index: Option<&ConfigCandidateIndex>,
1079    ) -> PluginRunContext<'a> {
1080        let all_deps = pkg.all_dependency_names();
1081        let script_packages = script_activation_packages(pkg, root, &all_deps, production_mode);
1082        let active = self.collect_active_plugins(&PluginActivationInput {
1083            pkg,
1084            root,
1085            discovered_files,
1086            all_deps: &all_deps,
1087            script_packages: &script_packages,
1088            candidate_index,
1089        });
1090
1091        PluginRunContext { all_deps, active }
1092    }
1093
1094    fn run_plugin_preflight(
1095        &self,
1096        active: &[&dyn Plugin],
1097        all_deps: &[String],
1098        root: &Path,
1099        discovered_files: &[PathBuf],
1100    ) {
1101        log_active_plugins(active);
1102        check_meta_framework_prerequisites(active, root);
1103        self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1104    }
1105
1106    /// Collect every built-in plugin enabled for this project via files,
1107    /// scripts, or package.json. Shared by the root and workspace-fast paths.
1108    fn collect_active_plugins<'a>(
1109        &'a self,
1110        activation: &PluginActivationInput<'_>,
1111    ) -> Vec<&'a dyn Plugin> {
1112        self.plugins
1113            .iter()
1114            .filter(|p| {
1115                p.is_enabled_with_files(
1116                    activation.all_deps,
1117                    activation.root,
1118                    activation.discovered_files,
1119                    activation.candidate_index,
1120                ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1121                    || p.is_enabled_with_package_json(activation.pkg, activation.root)
1122            })
1123            .map(AsRef::as_ref)
1124            .collect()
1125    }
1126
1127    /// Collect the active subset of external plugins, run the silent-fail
1128    /// diagnostics (#479), and emit one `tracing::warn!` per finding (dedup'd
1129    /// across analysis passes via [`plugin_warn_dedupe`]).
1130    ///
1131    /// Called from both `run_with_search_roots` (top-level) and
1132    /// `run_workspace_fast` (per-workspace) so a typo'd enabler or pattern
1133    /// collision surfaces regardless of which entry point dispatched the
1134    /// analysis.
1135    fn emit_silent_fail_diagnostics(
1136        &self,
1137        active: &[&dyn Plugin],
1138        all_deps: &[String],
1139        root: &Path,
1140        discovered_files: &[PathBuf],
1141    ) {
1142        let active_external: Vec<&ExternalPluginDef> = self
1143            .external_plugins
1144            .iter()
1145            .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1146            .collect();
1147        let mut diagnostics = detect_pattern_collisions(active, &active_external);
1148        diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1149        emit_plugin_diagnostics(&diagnostics);
1150    }
1151}
1152
1153/// Process-wide dedupe key cache for plugin-system diagnostic warnings.
1154///
1155/// Combined-mode runs `PluginRegistry::run_with_search_roots` three times
1156/// (check + dupes + health) per analysis, so a naive warn would triple-emit
1157/// every diagnostic. Each warn helper builds a unique key, inserts it here,
1158/// and only emits when the key was previously absent.
1159fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1160    static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1161        std::sync::OnceLock::new();
1162    WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1163}
1164
1165struct PluginConfigResolutionInput<'a> {
1166    config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1167    relative_files: &'a [(PathBuf, String)],
1168    config_search_roots: &'a [&'a Path],
1169    production_mode: bool,
1170    candidate_index: Option<&'a ConfigCandidateIndex>,
1171    root: &'a Path,
1172    result: &'a mut AggregatedPluginResult,
1173    regex_errors: &'a mut Vec<PluginRegexValidationError>,
1174}
1175
1176/// Filter pre-compiled matchers down to active plugins, keeping a config-skipped
1177/// plugin only when it must still parse its workspace config while root-active.
1178fn select_workspace_matchers<'a>(
1179    precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1180    active: &[&dyn Plugin],
1181    skip_config_plugins: &FxHashSet<&str>,
1182) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1183    let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1184    precompiled_config_matchers
1185        .iter()
1186        .filter(|(p, _)| {
1187            active_names.contains(p.name())
1188                && (!skip_config_plugins.contains(p.name())
1189                    || must_parse_workspace_config_when_root_active(p.name()))
1190        })
1191        .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1192        .collect()
1193}
1194
1195struct WorkspaceFsConfigInput<'a> {
1196    workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1197    resolved_ws_plugins: &'a FxHashSet<&'a str>,
1198    root: &'a Path,
1199    project_root: &'a Path,
1200    production_mode: bool,
1201    candidate_index: Option<&'a ConfigCandidateIndex>,
1202    result: &'a mut AggregatedPluginResult,
1203    regex_errors: &'a mut Vec<PluginRegexValidationError>,
1204}
1205
1206/// Discover and parse workspace config files on disk for plugins not already
1207/// matched against discovered source files (workspace filesystem fallback).
1208fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1209    let search_roots: &[&Path] = if input.root == input.project_root {
1210        &[input.root]
1211    } else {
1212        &[input.root, input.project_root]
1213    };
1214    let ws_json_configs = discover_config_files(
1215        input.workspace_matchers,
1216        input.resolved_ws_plugins,
1217        search_roots,
1218        input.production_mode,
1219        input.candidate_index,
1220    );
1221    for (abs_path, plugin) in &ws_json_configs {
1222        let Ok(source) = std::fs::read_to_string(abs_path) else {
1223            continue;
1224        };
1225        let plugin_result =
1226            plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1227        if plugin_result.is_empty() {
1228            continue;
1229        }
1230        let rel = abs_path
1231            .strip_prefix(input.project_root)
1232            .map(|p| p.to_string_lossy())
1233            .unwrap_or_default();
1234        tracing::debug!(
1235            plugin = plugin.name(),
1236            config = %rel,
1237            entries = plugin_result.entry_patterns.len(),
1238            deps = plugin_result.referenced_dependencies.len(),
1239            "resolved config (workspace filesystem fallback)"
1240        );
1241        if let Err(mut errors) =
1242            process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1243        {
1244            input.regex_errors.append(&mut errors);
1245        }
1246    }
1247}
1248
1249fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1250    if input.config_matchers.is_empty() {
1251        return;
1252    }
1253
1254    let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1255    for (plugin, matchers) in input.config_matchers {
1256        resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1257            plugin: *plugin,
1258            matchers,
1259            relative_files: input.relative_files,
1260            root: input.root,
1261            project_root: input.root,
1262            result: input.result,
1263            regex_errors: input.regex_errors,
1264            resolved_plugins: &mut resolved_plugins,
1265        });
1266    }
1267
1268    let json_configs = discover_config_files(
1269        input.config_matchers,
1270        &resolved_plugins,
1271        input.config_search_roots,
1272        input.production_mode,
1273        input.candidate_index,
1274    );
1275    for (abs_path, plugin) in &json_configs {
1276        resolve_plugin_filesystem_config(
1277            *plugin,
1278            abs_path,
1279            input.root,
1280            input.result,
1281            input.regex_errors,
1282        );
1283    }
1284}
1285
1286struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1287    plugin: &'plugins dyn Plugin,
1288    matchers: &'data [globset::GlobMatcher],
1289    relative_files: &'data [(PathBuf, String)],
1290    root: &'data Path,
1291    project_root: &'data Path,
1292    result: &'state mut AggregatedPluginResult,
1293    regex_errors: &'state mut Vec<PluginRegexValidationError>,
1294    resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1295}
1296
1297fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1298    use rayon::prelude::*;
1299
1300    let plugin_hits: Vec<&PathBuf> = input
1301        .relative_files
1302        .par_iter()
1303        .filter_map(|(abs_path, rel_path)| {
1304            input
1305                .matchers
1306                .iter()
1307                .any(|m| m.is_match(rel_path.as_str()))
1308                .then_some(abs_path)
1309        })
1310        .collect();
1311    for abs_path in plugin_hits {
1312        let Ok(source) = std::fs::read_to_string(abs_path) else {
1313            continue;
1314        };
1315        let plugin_result = input.plugin.resolve_config_in_project(
1316            abs_path,
1317            &source,
1318            input.root,
1319            input.project_root,
1320        );
1321        if plugin_result.is_empty() {
1322            continue;
1323        }
1324        input.resolved_plugins.insert(input.plugin.name());
1325        process_resolved_plugin_config(ResolvedPluginConfigInput {
1326            plugin: input.plugin,
1327            abs_path,
1328            plugin_result,
1329            result: input.result,
1330            regex_errors: input.regex_errors,
1331            message: "resolved config",
1332            config_display: abs_path.display(),
1333        });
1334    }
1335}
1336
1337fn resolve_plugin_filesystem_config(
1338    plugin: &dyn Plugin,
1339    abs_path: &Path,
1340    root: &Path,
1341    result: &mut AggregatedPluginResult,
1342    regex_errors: &mut Vec<PluginRegexValidationError>,
1343) {
1344    let Ok(source) = std::fs::read_to_string(abs_path) else {
1345        return;
1346    };
1347    let plugin_result = plugin.resolve_config(abs_path, &source, root);
1348    if plugin_result.is_empty() {
1349        return;
1350    }
1351    let rel = abs_path
1352        .strip_prefix(root)
1353        .map(|p| p.to_string_lossy())
1354        .unwrap_or_default();
1355    process_resolved_plugin_config(ResolvedPluginConfigInput {
1356        plugin,
1357        abs_path,
1358        plugin_result,
1359        result,
1360        regex_errors,
1361        message: "resolved config (filesystem fallback)",
1362        config_display: rel,
1363    });
1364}
1365
1366struct ResolvedPluginConfigInput<'a, D> {
1367    plugin: &'a dyn Plugin,
1368    abs_path: &'a Path,
1369    plugin_result: PluginResult,
1370    result: &'a mut AggregatedPluginResult,
1371    regex_errors: &'a mut Vec<PluginRegexValidationError>,
1372    message: &'static str,
1373    config_display: D,
1374}
1375
1376fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1377    tracing::debug!(
1378        plugin = input.plugin.name(),
1379        config = %input.config_display,
1380        entries = input.plugin_result.entry_patterns.len(),
1381        deps = input.plugin_result.referenced_dependencies.len(),
1382        input.message
1383    );
1384    if let Err(mut errors) = process_config_result(
1385        input.plugin.name(),
1386        input.plugin_result,
1387        input.result,
1388        Some(input.abs_path),
1389    ) {
1390        input.regex_errors.append(&mut errors);
1391    }
1392}
1393
1394/// Insert `key` into the dedupe set and return `true` when it was newly
1395/// inserted (caller should emit). Returns `true` on a poisoned mutex so
1396/// over-warning beats swallowing.
1397fn should_warn(key: String) -> bool {
1398    plugin_warn_dedupe()
1399        .lock()
1400        .map_or(true, |mut set| set.insert(key))
1401}
1402
1403/// Structured diagnostic surfaced by the silent-fail plugin checks (#479).
1404///
1405/// Returned by [`detect_pattern_collisions`] and [`detect_enabler_typos`] so
1406/// unit tests can assert on the findings without standing up a tracing
1407/// subscriber. The runtime path calls [`emit_plugin_diagnostics`] to convert
1408/// each variant into one `tracing::warn!` line.
1409#[derive(Debug, Clone, PartialEq, Eq)]
1410enum PluginDiagnostic {
1411    /// Two or more plugins declared an identical `config_patterns` entry.
1412    PatternCollision {
1413        pattern: String,
1414        owners: Vec<String>,
1415    },
1416    /// An external plugin enabler does not match any project dependency, but
1417    /// at least one Levenshtein-close dep name exists.
1418    EnablerTypo {
1419        plugin: String,
1420        enabler: String,
1421        suggestion: String,
1422    },
1423}
1424
1425/// Detect plugins whose `config_patterns` collide byte-for-byte.
1426///
1427/// Detection is byte-equal on the pattern string. Overlapping but non-identical
1428/// globs (e.g. `vite.config.{ts,js}` vs `vite.config.ts`) require pattern
1429/// intersection logic and are intentionally out of scope. The warning's purpose
1430/// is to surface USER-AUTHORED collisions between external plugins or between an
1431/// external plugin and a built-in, so the user can disambiguate by editing one
1432/// side.
1433///
1434/// Built-in-vs-built-in collisions are intentionally NOT reported: they are
1435/// curated and benign (Phase 3a config matching runs every matching plugin's
1436/// `resolve_config` independently, so there is no data loss), and the warning's
1437/// remediation advice ("rename one of the patterns or remove the duplicate
1438/// plugin") is impossible to follow for a built-in. Such a collision exists by
1439/// design, e.g. both `vite` and `tanstack-router` claim
1440/// `vite.config.{ts,js,mts,mjs}` because tanstack-router parses the
1441/// `tanstackRouter({...})` call inside the vite config to find a custom
1442/// `generatedRouteTree` path (#808). A finding is therefore emitted only when
1443/// at least one owner is an external (user-authored) plugin.
1444///
1445/// Precedence rule when two plugins claim the same pattern: the one registered
1446/// first wins. For built-in plugins, registration order is defined in
1447/// [`builtin::create_builtin_plugins`]. External plugins (file-loaded plus
1448/// inline `framework[]`) run AFTER built-ins, so they cannot displace a
1449/// built-in's `resolve_config` result for the same file.
1450fn detect_pattern_collisions(
1451    builtin_active: &[&dyn Plugin],
1452    external_active: &[&ExternalPluginDef],
1453) -> Vec<PluginDiagnostic> {
1454    use rustc_hash::FxHashMap;
1455
1456    let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1457        FxHashMap::default();
1458
1459    let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1460                  pattern: String,
1461                  name: String| {
1462        let (list, seen) = pattern_owners.entry(pattern).or_default();
1463        if seen.insert(name.clone()) {
1464            list.push(name);
1465        }
1466    };
1467
1468    for plugin in builtin_active {
1469        for pat in plugin.config_patterns() {
1470            record(
1471                &mut pattern_owners,
1472                (*pat).to_string(),
1473                plugin.name().to_string(),
1474            );
1475        }
1476    }
1477    for ext in external_active {
1478        for pat in &ext.config_patterns {
1479            record(&mut pattern_owners, pat.clone(), ext.name.clone());
1480        }
1481    }
1482
1483    // Names of built-in plugins. Built-in-only collisions are curated + benign
1484    // (every matching plugin runs `resolve_config` independently), so they must
1485    // not surface an un-actionable warning (#808). Keying on the built-in set
1486    // and emitting only when an owner is NOT built-in is robust even if a
1487    // user-authored external plugin happens to share a built-in's name: the
1488    // built-in owner alone never re-enables the warning.
1489    let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1490
1491    let mut findings: Vec<PluginDiagnostic> = pattern_owners
1492        .into_iter()
1493        .filter_map(|(pattern, (owners, _seen))| {
1494            if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1495                None
1496            } else {
1497                Some(PluginDiagnostic::PatternCollision { pattern, owners })
1498            }
1499        })
1500        .collect();
1501    findings.sort_unstable_by(|a, b| match (a, b) {
1502        (
1503            PluginDiagnostic::PatternCollision { pattern: ap, .. },
1504            PluginDiagnostic::PatternCollision { pattern: bp, .. },
1505        ) => ap.cmp(bp),
1506        _ => std::cmp::Ordering::Equal,
1507    });
1508    findings
1509}
1510
1511/// Detect external plugins whose enablers do not match any project dependency
1512/// AND at least one enabler is a plausible typo of a real dep.
1513///
1514/// Scope:
1515/// - Only external plugins (file-loaded plus inline `framework[]`). Built-in
1516///   plugins' enablers are hard-coded so cannot be misspelled.
1517/// - Skip plugins with a `detection` block: detection is the rich-logic path
1518///   and false negatives there are not enabler typos.
1519/// - Skip plugins with empty `enablers` (no signal to validate against).
1520/// - Stay silent when no Levenshtein-close dep exists: the plugin may
1521///   legitimately not apply to this project.
1522///
1523/// Matches the established #467 / #510 pattern: tracing-warn with a `did you
1524/// mean` suggestion at the call site. No exit non-zero, no new CLI flag.
1525fn detect_enabler_typos(
1526    external_plugins: &[ExternalPluginDef],
1527    all_deps: &[String],
1528) -> Vec<PluginDiagnostic> {
1529    let mut findings = Vec::new();
1530
1531    for ext in external_plugins {
1532        if ext.detection.is_some() || ext.enablers.is_empty() {
1533            continue;
1534        }
1535
1536        let any_match = ext.enablers.iter().any(|enabler| {
1537            if enabler.ends_with('/') {
1538                all_deps.iter().any(|d| d.starts_with(enabler))
1539            } else {
1540                all_deps.iter().any(|d| d == enabler)
1541            }
1542        });
1543        if any_match {
1544            continue;
1545        }
1546
1547        for enabler in &ext.enablers {
1548            let candidates = all_deps.iter().map(String::as_str);
1549            let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1550            else {
1551                continue;
1552            };
1553
1554            findings.push(PluginDiagnostic::EnablerTypo {
1555                plugin: ext.name.clone(),
1556                enabler: enabler.clone(),
1557                suggestion: suggestion.to_string(),
1558            });
1559        }
1560    }
1561
1562    findings
1563}
1564
1565/// Emit one `tracing::warn!` per finding, dedup'd against the process-wide
1566/// `plugin_warn_dedupe` set so combined-mode does not triple-warn.
1567fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1568    for finding in findings {
1569        match finding {
1570            PluginDiagnostic::PatternCollision { pattern, owners } => {
1571                let key = format!("collision::{pattern}::{owners:?}");
1572                if !should_warn(key) {
1573                    continue;
1574                }
1575                let winner = &owners[0];
1576                let others = owners[1..].join(", ");
1577                tracing::warn!(
1578                    "plugin config_patterns collision: identical pattern \
1579                     '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1580                     runs first (registration order), others ({others}) \
1581                     follow. Rename one of the patterns or remove the \
1582                     duplicate plugin to make resolution explicit. A future \
1583                     release may reject identical-pattern collisions.",
1584                    joined = owners.join(", "),
1585                );
1586            }
1587            PluginDiagnostic::EnablerTypo {
1588                plugin,
1589                enabler,
1590                suggestion,
1591            } => {
1592                let key = format!("enabler::{plugin}::{enabler}");
1593                if !should_warn(key) {
1594                    continue;
1595                }
1596                tracing::warn!(
1597                    "plugin '{plugin}' enabler '{enabler}' does not match any \
1598                     dependency in package.json; did you mean '{suggestion}'? \
1599                     The plugin will not activate. A future release may reject \
1600                     unmatched enablers.",
1601                );
1602            }
1603        }
1604    }
1605}
1606
1607/// Phase 4 of `PluginRegistry::run_with_search_roots`: for any active plugin
1608/// that supports inline package.json configuration via
1609/// [`Plugin::package_json_config_key`], read the root `package.json`, extract
1610/// the relevant key, and feed the result through `resolve_config`.
1611fn process_package_json_inline_configs(
1612    active: &[&dyn Plugin],
1613    config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1614    relative_files: &[(PathBuf, String)],
1615    root: &Path,
1616    result: &mut AggregatedPluginResult,
1617    regex_errors: &mut Vec<PluginRegexValidationError>,
1618) {
1619    for plugin in active {
1620        let Some(key) = plugin.package_json_config_key() else {
1621            continue;
1622        };
1623        if check_has_config_file(*plugin, config_matchers, relative_files) {
1624            continue;
1625        }
1626        let pkg_path = root.join("package.json");
1627        let Ok(content) = std::fs::read_to_string(&pkg_path) else {
1628            continue;
1629        };
1630        let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
1631            continue;
1632        };
1633        let Some(config_value) = json.get(key) else {
1634            continue;
1635        };
1636        let config_json = serde_json::to_string(config_value).unwrap_or_default();
1637        let fake_path = root.join(format!("{key}.config.json"));
1638        let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
1639        if plugin_result.is_empty() {
1640            continue;
1641        }
1642        tracing::debug!(
1643            plugin = plugin.name(),
1644            key = key,
1645            "resolved inline package.json config"
1646        );
1647        if let Err(mut errors) =
1648            process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1649        {
1650            regex_errors.append(&mut errors);
1651        }
1652    }
1653}
1654
1655/// A missing meta-framework prerequisite: the per-process dedupe key and the
1656/// warning message to emit.
1657#[derive(Debug)]
1658struct MetaFrameworkWarning {
1659    dedupe_key: &'static str,
1660    message: &'static str,
1661}
1662
1663/// Pure detection: which active meta-frameworks are missing their generated
1664/// config/types directory under `root`. Separated from emission so the
1665/// detection logic is unit-testable without a tracing subscriber or the
1666/// process-wide dedupe set.
1667///
1668/// When adding a framework here, also extend `MATERIALIZED_CONTEXT_DIRS` in
1669/// `fallow-cli`'s `audit.rs` with its generated dir, otherwise `fallow audit`'s
1670/// base worktree will not symlink that dir and the broken-tsconfig-chain bug
1671/// resurfaces on the base pass for the new framework.
1672fn missing_meta_framework_prerequisites(
1673    active_plugins: &[&dyn Plugin],
1674    root: &Path,
1675) -> Vec<MetaFrameworkWarning> {
1676    active_plugins
1677        .iter()
1678        .filter_map(|plugin| match plugin.name() {
1679            "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1680                dedupe_key: "meta-prereq::nuxt",
1681                message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1682                          before fallow for accurate analysis",
1683            }),
1684            "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1685                dedupe_key: "meta-prereq::astro",
1686                message: "Astro project missing .astro/ types: run `astro sync` \
1687                          before fallow for accurate analysis",
1688            }),
1689            _ => None,
1690        })
1691        .collect()
1692}
1693
1694/// Warn when meta-frameworks are active but their generated configs are missing.
1695///
1696/// Meta-frameworks like Nuxt and Astro generate tsconfig/types files during a
1697/// "prepare" step. Without these, the tsconfig extends chain breaks and
1698/// extensionless imports fail wholesale (e.g. 2000+ unresolved imports).
1699///
1700/// Deduped per framework so combined-mode (check + dupes + health through one
1701/// loader) does not re-warn. The advice is generic and does not name the root,
1702/// so one line per process per framework is the right bound (issue #637).
1703fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1704    for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1705        if should_warn(warning.dedupe_key.to_owned()) {
1706            tracing::warn!("{}", warning.message);
1707        }
1708    }
1709}
1710
1711fn script_activation_packages(
1712    pkg: &PackageJson,
1713    root: &Path,
1714    all_deps: &[String],
1715    production_mode: bool,
1716) -> FxHashSet<String> {
1717    let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1718        return FxHashSet::default();
1719    };
1720
1721    let scripts_to_analyze = if production_mode {
1722        scripts::filter_production_scripts(pkg_scripts)
1723    } else {
1724        pkg_scripts.clone()
1725    };
1726
1727    let mut nm_roots = Vec::new();
1728    if root.join("node_modules").is_dir() {
1729        nm_roots.push(root);
1730    }
1731    let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1732    let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1733    let catalog =
1734        scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1735
1736    scripts::analyze_scripts_with_dependency_context(
1737        &scripts_to_analyze,
1738        root,
1739        &bin_map,
1740        &dep_set,
1741        &catalog,
1742        scripts::IgnoredCommandEntries::NONE,
1743    )
1744    .used_packages
1745}
1746
1747#[cfg(test)]
1748mod entry_pattern_tests;
1749#[cfg(test)]
1750mod tests;