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