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