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