1use rustc_hash::FxHashSet;
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use fallow_config::{
8 AutoImportRule, EntryPointRole, ExternalPluginDef, PackageJson, UsedClassMemberRule,
9};
10
11use crate::scripts;
12
13use super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, ProvidedDependencyRule};
14
15pub(crate) mod builtin;
16mod helpers;
17
18#[must_use]
23pub fn builtin_plugin_names() -> Vec<&'static str> {
24 builtin::create_builtin_plugins()
25 .iter()
26 .map(|plugin| plugin.name())
27 .collect()
28}
29
30#[must_use]
35pub fn builtin_plugin_config_candidate_basenames() -> Vec<String> {
36 let mut set: FxHashSet<String> = FxHashSet::default();
37 for plugin in builtin::create_builtin_plugins() {
38 for pattern in plugin.config_patterns() {
39 let basename = pattern.rsplit('/').next().unwrap_or(pattern);
40 set.insert(basename.to_string());
41 }
42 }
43 let mut basenames = set.into_iter().collect::<Vec<_>>();
44 basenames.sort_unstable();
45 basenames
46}
47
48pub use helpers::ConfigCandidateIndex;
49pub use helpers::is_external_plugin_active;
50use helpers::{
51 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
52 process_external_plugins, process_package_json_metadata, process_static_patterns,
53};
54
55fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
56 matches!(
57 plugin_name,
58 "eslint" | "docusaurus" | "jest" | "tanstack-router" | "vitest"
59 )
60}
61
62fn compile_config_matchers<'a>(
63 active: &[&'a dyn Plugin],
64) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
65 active
66 .iter()
67 .filter(|plugin| !plugin.config_patterns().is_empty())
68 .map(|plugin| {
69 let matchers = plugin
70 .config_patterns()
71 .iter()
72 .filter_map(|pattern| {
73 let prepared = prepare_config_pattern(pattern);
74 globset::Glob::new(&prepared)
75 .ok()
76 .map(|glob| glob.compile_matcher())
77 })
78 .collect();
79 (*plugin, matchers)
80 })
81 .collect()
82}
83
84fn log_active_plugins(active: &[&dyn Plugin]) {
86 tracing::info!(
87 plugins = active
88 .iter()
89 .map(|p| p.name())
90 .collect::<Vec<_>>()
91 .join(", "),
92 "active plugins"
93 );
94}
95
96fn compute_relative_files(
100 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
101 active: &[&dyn Plugin],
102 discovered_files: &[PathBuf],
103 root: &Path,
104) -> Vec<(PathBuf, String)> {
105 use rayon::prelude::*;
106 let needs_relative_files =
107 !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
108 if !needs_relative_files {
109 return Vec::new();
110 }
111 discovered_files
112 .par_iter()
113 .map(|f| {
114 let rel = f
115 .strip_prefix(root)
116 .unwrap_or(f)
117 .to_string_lossy()
118 .into_owned();
119 (f.clone(), rel)
120 })
121 .collect()
122}
123
124pub struct PluginRegistry {
126 plugins: Vec<Box<dyn Plugin>>,
127 external_plugins: Vec<ExternalPluginDef>,
128}
129
130pub struct WorkspacePluginRunInput<'a> {
132 pub pkg: &'a PackageJson,
133 pub root: &'a Path,
134 pub project_root: &'a Path,
135 pub precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
136 pub relative_files: &'a [(PathBuf, String)],
137 pub skip_config_plugins: &'a FxHashSet<&'a str>,
138 pub production_mode: bool,
139 pub candidate_index: Option<&'a ConfigCandidateIndex>,
140}
141
142struct PluginRunContext<'a> {
143 all_deps: Vec<String>,
144 active: Vec<&'a dyn Plugin>,
145}
146
147struct PluginActivationInput<'a> {
149 pkg: &'a PackageJson,
150 root: &'a Path,
151 discovered_files: &'a [PathBuf],
152 all_deps: &'a [String],
153 script_packages: &'a FxHashSet<String>,
154 candidate_index: Option<&'a ConfigCandidateIndex>,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct PluginRegexValidationError {
160 plugin_name: String,
161 config_path: Option<PathBuf>,
162 rule_kind: &'static str,
163 field: &'static str,
164 rule_pattern: String,
165 regex_pattern: String,
166 source: String,
167}
168
169impl PluginRegexValidationError {
170 pub(crate) fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
171 Self {
172 plugin_name: input.plugin_name.to_owned(),
173 config_path: input.config_path.map(Path::to_path_buf),
174 rule_kind: input.rule_kind,
175 field: input.field,
176 rule_pattern: input.rule_pattern.to_owned(),
177 regex_pattern: input.regex_pattern.to_owned(),
178 source: input.source.to_string(),
179 }
180 }
181}
182
183#[derive(Clone, Copy)]
184pub(crate) struct PluginRegexValidationErrorInput<'a> {
185 pub(crate) plugin_name: &'a str,
186 pub(crate) config_path: Option<&'a Path>,
187 pub(crate) rule_kind: &'static str,
188 pub(crate) field: &'static str,
189 pub(crate) rule_pattern: &'a str,
190 pub(crate) regex_pattern: &'a str,
191 pub(crate) source: &'a regex::Error,
192}
193
194impl fmt::Display for PluginRegexValidationError {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 let location = self
197 .config_path
198 .as_ref()
199 .map(|path| format!(" in {}", path.display()))
200 .unwrap_or_default();
201 write!(
202 f,
203 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
204 self.plugin_name,
205 location,
206 self.regex_pattern,
207 self.rule_kind,
208 self.field,
209 self.rule_pattern,
210 self.source
211 )
212 }
213}
214
215#[must_use]
216pub fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
217 let joined = errors
218 .iter()
219 .map(ToString::to_string)
220 .collect::<Vec<_>>()
221 .join("\n - ");
222 format!(
223 "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."
224 )
225}
226
227#[derive(Debug, Clone, Default)]
229pub struct AggregatedPluginResult {
230 pub entry_patterns: Vec<(PathRule, String)>,
232 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
234 pub config_patterns: Vec<String>,
236 pub always_used: Vec<(String, String)>,
238 pub used_exports: Vec<PluginUsedExportRule>,
240 pub used_class_members: Vec<UsedClassMemberRule>,
244 pub referenced_dependencies: Vec<String>,
246 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
248 pub discovered_always_used: Vec<(String, String)>,
250 pub setup_files: Vec<(PathBuf, String)>,
252 pub tooling_dependencies: Vec<String>,
254 pub script_used_packages: FxHashSet<String>,
256 pub virtual_module_prefixes: Vec<String>,
259 pub virtual_package_suffixes: Vec<String>,
262 pub generated_import_patterns: Vec<String>,
265 pub generated_type_import_prefixes: Vec<String>,
268 pub path_aliases: Vec<(String, String)>,
271 pub auto_imports: Vec<AutoImportRule>,
275 pub active_plugins: Vec<String>,
277 pub fixture_patterns: Vec<(String, String)>,
279 pub scss_include_paths: Vec<PathBuf>,
284 pub static_dir_mappings: Vec<(PathBuf, String)>,
286 pub provided_dependencies: Vec<ProvidedDependencyRule>,
288}
289
290fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
295 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
296 for item in incoming {
297 if seen.insert(item.clone()) {
298 target.push(item);
299 }
300 }
301}
302
303fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
307 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
308 pat.to_string()
309 } else {
310 format!("{ws_prefix}/{pat}")
311 }
312}
313
314impl AggregatedPluginResult {
315 pub fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
329 for (rule, _) in &mut self.entry_patterns {
330 *rule = rule.prefixed(ws_prefix);
331 }
332 for (pat, _) in &mut self.always_used {
333 *pat = prefix_if_needed(pat, ws_prefix);
334 }
335 for (pat, _) in &mut self.discovered_always_used {
336 *pat = prefix_if_needed(pat, ws_prefix);
337 }
338 for (pat, _) in &mut self.fixture_patterns {
339 *pat = prefix_if_needed(pat, ws_prefix);
340 }
341 for rule in &mut self.used_exports {
342 *rule = rule.prefixed(ws_prefix);
343 }
344 for rule in &mut self.provided_dependencies {
345 *rule = rule.prefixed(ws_prefix);
346 }
347 for (_, replacement) in &mut self.path_aliases {
348 *replacement = format!("{ws_prefix}/{replacement}");
349 }
350 }
351
352 pub fn merge_into(&mut self, other: Self) {
365 let Self {
366 entry_patterns,
367 entry_point_roles,
368 config_patterns,
369 always_used,
370 used_exports,
371 used_class_members,
372 referenced_dependencies,
373 package_referenced_dependencies,
374 discovered_always_used,
375 setup_files,
376 tooling_dependencies,
377 script_used_packages,
378 virtual_module_prefixes,
379 virtual_package_suffixes,
380 generated_import_patterns,
381 generated_type_import_prefixes,
382 path_aliases,
383 auto_imports,
384 active_plugins,
385 fixture_patterns,
386 scss_include_paths,
387 static_dir_mappings,
388 provided_dependencies,
389 } = other;
390
391 self.entry_patterns.extend(entry_patterns);
392 for (plugin_name, role) in entry_point_roles {
393 self.entry_point_roles.entry(plugin_name).or_insert(role);
394 }
395 self.config_patterns.extend(config_patterns);
396 self.always_used.extend(always_used);
397 self.used_exports.extend(used_exports);
398 self.used_class_members.extend(used_class_members);
399 self.referenced_dependencies.extend(referenced_dependencies);
400 self.package_referenced_dependencies
401 .extend(package_referenced_dependencies);
402 self.discovered_always_used.extend(discovered_always_used);
403 self.setup_files.extend(setup_files);
404 self.tooling_dependencies.extend(tooling_dependencies);
405 self.script_used_packages.extend(script_used_packages);
406 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
407 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
408 extend_unique(
409 &mut self.generated_import_patterns,
410 generated_import_patterns,
411 );
412 extend_unique(
413 &mut self.generated_type_import_prefixes,
414 generated_type_import_prefixes,
415 );
416 self.path_aliases.extend(path_aliases);
417 self.auto_imports.extend(auto_imports);
418 extend_unique(&mut self.active_plugins, active_plugins);
419 self.fixture_patterns.extend(fixture_patterns);
420 self.scss_include_paths.extend(scss_include_paths);
421 self.static_dir_mappings.extend(static_dir_mappings);
422 self.provided_dependencies.extend(provided_dependencies);
423 }
424}
425
426impl PluginRegistry {
427 #[must_use]
429 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
430 Self {
431 plugins: builtin::create_builtin_plugins(),
432 external_plugins: external,
433 }
434 }
435
436 #[must_use]
441 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
442 let all_deps = pkg.all_dependency_names();
443 let mut seen = FxHashSet::default();
444 let mut dirs = Vec::new();
445
446 for plugin in &self.plugins {
447 if !plugin.is_enabled_with_deps(&all_deps, root) {
448 continue;
449 }
450 for dir in plugin.discovery_hidden_dirs() {
451 if seen.insert(*dir) {
452 dirs.push((*dir).to_string());
453 }
454 }
455 }
456
457 dirs
458 }
459
460 #[cfg(test)]
465 pub fn run(
466 &self,
467 pkg: &PackageJson,
468 root: &Path,
469 discovered_files: &[PathBuf],
470 ) -> AggregatedPluginResult {
471 self.try_run(pkg, root, discovered_files)
472 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
473 }
474
475 pub fn try_run(
477 &self,
478 pkg: &PackageJson,
479 root: &Path,
480 discovered_files: &[PathBuf],
481 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
482 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
483 }
484
485 #[expect(
488 clippy::too_many_arguments,
489 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
490 )]
491 pub fn try_run_with_search_roots(
492 &self,
493 pkg: &PackageJson,
494 root: &Path,
495 discovered_files: &[PathBuf],
496 config_search_roots: &[&Path],
497 production_mode: bool,
498 candidate_index: Option<&ConfigCandidateIndex>,
499 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
500 let _span = tracing::info_span!("run_plugins").entered();
501 let mut result = AggregatedPluginResult::default();
502 let mut regex_errors = Vec::new();
503
504 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
505 pkg,
506 root,
507 discovered_files,
508 production_mode,
509 candidate_index,
510 );
511
512 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
513
514 for plugin in &active {
515 process_static_patterns(*plugin, root, &mut result);
516 }
517 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
518
519 process_external_plugins(
520 &self.external_plugins,
521 &all_deps,
522 root,
523 discovered_files,
524 &mut result,
525 );
526
527 let config_matchers = compile_config_matchers(&active);
528 let relative_files =
529 compute_relative_files(&config_matchers, &active, discovered_files, root);
530
531 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
532 config_matchers: &config_matchers,
533 relative_files: &relative_files,
534 config_search_roots,
535 production_mode,
536 candidate_index,
537 root,
538 result: &mut result,
539 regex_errors: &mut regex_errors,
540 });
541
542 process_package_json_inline_configs(
543 &active,
544 &config_matchers,
545 &relative_files,
546 root,
547 &mut result,
548 &mut regex_errors,
549 );
550
551 if regex_errors.is_empty() {
552 Ok(result)
553 } else {
554 Err(regex_errors)
555 }
556 }
557
558 #[cfg(test)]
564 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
565 self.try_run_workspace_fast(input)
566 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
567 }
568
569 pub fn try_run_workspace_fast(
575 &self,
576 input: &WorkspacePluginRunInput<'_>,
577 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
578 let _span = tracing::info_span!("run_plugins").entered();
579 let mut result = AggregatedPluginResult::default();
580 let mut regex_errors = Vec::new();
581
582 let all_deps = input.pkg.all_dependency_names();
583 let script_packages =
584 script_activation_packages(input.pkg, input.root, &all_deps, input.production_mode);
585 let workspace_files: Vec<PathBuf> = input
586 .relative_files
587 .iter()
588 .map(|(abs_path, _)| abs_path.clone())
589 .collect();
590
591 let active = self.collect_active_plugins(&PluginActivationInput {
592 pkg: input.pkg,
593 root: input.root,
594 discovered_files: &workspace_files,
595 all_deps: &all_deps,
596 script_packages: &script_packages,
597 candidate_index: input.candidate_index,
598 });
599
600 log_active_plugins(&active);
601
602 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
603
604 process_external_plugins(
605 &self.external_plugins,
606 &all_deps,
607 input.root,
608 &workspace_files,
609 &mut result,
610 );
611
612 if active.is_empty() && result.active_plugins.is_empty() {
613 return Ok(result);
614 }
615
616 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
617 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
618
619 if regex_errors.is_empty() {
620 Ok(result)
621 } else {
622 Err(regex_errors)
623 }
624 }
625
626 #[must_use]
629 pub fn precompile_config_matchers(&self) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
630 self.plugins
631 .iter()
632 .filter(|p| !p.config_patterns().is_empty())
633 .map(|p| {
634 let matchers: Vec<globset::GlobMatcher> = p
635 .config_patterns()
636 .iter()
637 .filter_map(|pat| {
638 let prepared = prepare_config_pattern(pat);
639 globset::Glob::new(&prepared)
640 .ok()
641 .map(|g| g.compile_matcher())
642 })
643 .collect();
644 (p.as_ref(), matchers)
645 })
646 .collect()
647 }
648}
649
650fn process_workspace_active_plugins(
651 active: &[&dyn Plugin],
652 input: &WorkspacePluginRunInput<'_>,
653 result: &mut AggregatedPluginResult,
654 regex_errors: &mut Vec<PluginRegexValidationError>,
655) {
656 for plugin in active {
657 process_static_patterns(*plugin, input.root, result);
658 }
659 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
660}
661
662fn resolve_workspace_plugin_configs(
663 active: &[&dyn Plugin],
664 input: &WorkspacePluginRunInput<'_>,
665 result: &mut AggregatedPluginResult,
666 regex_errors: &mut Vec<PluginRegexValidationError>,
667) {
668 let workspace_matchers = select_workspace_matchers(
669 input.precompiled_config_matchers,
670 active,
671 input.skip_config_plugins,
672 );
673
674 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
675 for (plugin, matchers) in &workspace_matchers {
676 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
677 plugin: *plugin,
678 matchers,
679 relative_files: input.relative_files,
680 root: input.root,
681 result,
682 regex_errors,
683 resolved_plugins: &mut resolved_ws_plugins,
684 });
685 }
686
687 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
688 workspace_matchers: &workspace_matchers,
689 resolved_ws_plugins: &resolved_ws_plugins,
690 root: input.root,
691 project_root: input.project_root,
692 production_mode: input.production_mode,
693 candidate_index: input.candidate_index,
694 result,
695 regex_errors,
696 });
697}
698
699impl Default for PluginRegistry {
700 fn default() -> Self {
701 Self::new(vec![])
702 }
703}
704
705impl PluginRegistry {
706 fn prepare_plugin_run_context<'a>(
707 &'a self,
708 pkg: &PackageJson,
709 root: &Path,
710 discovered_files: &[PathBuf],
711 production_mode: bool,
712 candidate_index: Option<&ConfigCandidateIndex>,
713 ) -> PluginRunContext<'a> {
714 let all_deps = pkg.all_dependency_names();
715 let script_packages = script_activation_packages(pkg, root, &all_deps, production_mode);
716 let active = self.collect_active_plugins(&PluginActivationInput {
717 pkg,
718 root,
719 discovered_files,
720 all_deps: &all_deps,
721 script_packages: &script_packages,
722 candidate_index,
723 });
724
725 PluginRunContext { all_deps, active }
726 }
727
728 fn run_plugin_preflight(
729 &self,
730 active: &[&dyn Plugin],
731 all_deps: &[String],
732 root: &Path,
733 discovered_files: &[PathBuf],
734 ) {
735 log_active_plugins(active);
736 check_meta_framework_prerequisites(active, root);
737 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
738 }
739
740 fn collect_active_plugins<'a>(
743 &'a self,
744 activation: &PluginActivationInput<'_>,
745 ) -> Vec<&'a dyn Plugin> {
746 self.plugins
747 .iter()
748 .filter(|p| {
749 p.is_enabled_with_files(
750 activation.all_deps,
751 activation.root,
752 activation.discovered_files,
753 activation.candidate_index,
754 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
755 || p.is_enabled_with_package_json(activation.pkg, activation.root)
756 })
757 .map(AsRef::as_ref)
758 .collect()
759 }
760
761 fn emit_silent_fail_diagnostics(
770 &self,
771 active: &[&dyn Plugin],
772 all_deps: &[String],
773 root: &Path,
774 discovered_files: &[PathBuf],
775 ) {
776 let active_external: Vec<&ExternalPluginDef> = self
777 .external_plugins
778 .iter()
779 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
780 .collect();
781 let mut diagnostics = detect_pattern_collisions(active, &active_external);
782 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
783 emit_plugin_diagnostics(&diagnostics);
784 }
785}
786
787fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
794 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
795 std::sync::OnceLock::new();
796 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
797}
798
799struct PluginConfigResolutionInput<'a> {
800 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
801 relative_files: &'a [(PathBuf, String)],
802 config_search_roots: &'a [&'a Path],
803 production_mode: bool,
804 candidate_index: Option<&'a ConfigCandidateIndex>,
805 root: &'a Path,
806 result: &'a mut AggregatedPluginResult,
807 regex_errors: &'a mut Vec<PluginRegexValidationError>,
808}
809
810fn select_workspace_matchers<'a>(
813 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
814 active: &[&dyn Plugin],
815 skip_config_plugins: &FxHashSet<&str>,
816) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
817 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
818 precompiled_config_matchers
819 .iter()
820 .filter(|(p, _)| {
821 active_names.contains(p.name())
822 && (!skip_config_plugins.contains(p.name())
823 || must_parse_workspace_config_when_root_active(p.name()))
824 })
825 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
826 .collect()
827}
828
829struct WorkspaceFsConfigInput<'a> {
830 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
831 resolved_ws_plugins: &'a FxHashSet<&'a str>,
832 root: &'a Path,
833 project_root: &'a Path,
834 production_mode: bool,
835 candidate_index: Option<&'a ConfigCandidateIndex>,
836 result: &'a mut AggregatedPluginResult,
837 regex_errors: &'a mut Vec<PluginRegexValidationError>,
838}
839
840fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
843 let search_roots: &[&Path] = if input.root == input.project_root {
844 &[input.root]
845 } else {
846 &[input.root, input.project_root]
847 };
848 let ws_json_configs = discover_config_files(
849 input.workspace_matchers,
850 input.resolved_ws_plugins,
851 search_roots,
852 input.production_mode,
853 input.candidate_index,
854 );
855 for (abs_path, plugin) in &ws_json_configs {
856 let Ok(source) = std::fs::read_to_string(abs_path) else {
857 continue;
858 };
859 let plugin_result = plugin.resolve_config(abs_path, &source, input.root);
860 if plugin_result.is_empty() {
861 continue;
862 }
863 let rel = abs_path
864 .strip_prefix(input.project_root)
865 .map(|p| p.to_string_lossy())
866 .unwrap_or_default();
867 tracing::debug!(
868 plugin = plugin.name(),
869 config = %rel,
870 entries = plugin_result.entry_patterns.len(),
871 deps = plugin_result.referenced_dependencies.len(),
872 "resolved config (workspace filesystem fallback)"
873 );
874 if let Err(mut errors) =
875 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
876 {
877 input.regex_errors.append(&mut errors);
878 }
879 }
880}
881
882fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
883 if input.config_matchers.is_empty() {
884 return;
885 }
886
887 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
888 for (plugin, matchers) in input.config_matchers {
889 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
890 plugin: *plugin,
891 matchers,
892 relative_files: input.relative_files,
893 root: input.root,
894 result: input.result,
895 regex_errors: input.regex_errors,
896 resolved_plugins: &mut resolved_plugins,
897 });
898 }
899
900 let json_configs = discover_config_files(
901 input.config_matchers,
902 &resolved_plugins,
903 input.config_search_roots,
904 input.production_mode,
905 input.candidate_index,
906 );
907 for (abs_path, plugin) in &json_configs {
908 resolve_plugin_filesystem_config(
909 *plugin,
910 abs_path,
911 input.root,
912 input.result,
913 input.regex_errors,
914 );
915 }
916}
917
918struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
919 plugin: &'plugins dyn Plugin,
920 matchers: &'data [globset::GlobMatcher],
921 relative_files: &'data [(PathBuf, String)],
922 root: &'data Path,
923 result: &'state mut AggregatedPluginResult,
924 regex_errors: &'state mut Vec<PluginRegexValidationError>,
925 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
926}
927
928fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
929 use rayon::prelude::*;
930
931 let plugin_hits: Vec<&PathBuf> = input
932 .relative_files
933 .par_iter()
934 .filter_map(|(abs_path, rel_path)| {
935 input
936 .matchers
937 .iter()
938 .any(|m| m.is_match(rel_path.as_str()))
939 .then_some(abs_path)
940 })
941 .collect();
942 for abs_path in plugin_hits {
943 let Ok(source) = std::fs::read_to_string(abs_path) else {
944 continue;
945 };
946 let plugin_result = input.plugin.resolve_config(abs_path, &source, input.root);
947 if plugin_result.is_empty() {
948 continue;
949 }
950 input.resolved_plugins.insert(input.plugin.name());
951 process_resolved_plugin_config(ResolvedPluginConfigInput {
952 plugin: input.plugin,
953 abs_path,
954 plugin_result,
955 result: input.result,
956 regex_errors: input.regex_errors,
957 message: "resolved config",
958 config_display: abs_path.display(),
959 });
960 }
961}
962
963fn resolve_plugin_filesystem_config(
964 plugin: &dyn Plugin,
965 abs_path: &Path,
966 root: &Path,
967 result: &mut AggregatedPluginResult,
968 regex_errors: &mut Vec<PluginRegexValidationError>,
969) {
970 let Ok(source) = std::fs::read_to_string(abs_path) else {
971 return;
972 };
973 let plugin_result = plugin.resolve_config(abs_path, &source, root);
974 if plugin_result.is_empty() {
975 return;
976 }
977 let rel = abs_path
978 .strip_prefix(root)
979 .map(|p| p.to_string_lossy())
980 .unwrap_or_default();
981 process_resolved_plugin_config(ResolvedPluginConfigInput {
982 plugin,
983 abs_path,
984 plugin_result,
985 result,
986 regex_errors,
987 message: "resolved config (filesystem fallback)",
988 config_display: rel,
989 });
990}
991
992struct ResolvedPluginConfigInput<'a, D> {
993 plugin: &'a dyn Plugin,
994 abs_path: &'a Path,
995 plugin_result: PluginResult,
996 result: &'a mut AggregatedPluginResult,
997 regex_errors: &'a mut Vec<PluginRegexValidationError>,
998 message: &'static str,
999 config_display: D,
1000}
1001
1002fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1003 tracing::debug!(
1004 plugin = input.plugin.name(),
1005 config = %input.config_display,
1006 entries = input.plugin_result.entry_patterns.len(),
1007 deps = input.plugin_result.referenced_dependencies.len(),
1008 input.message
1009 );
1010 if let Err(mut errors) = process_config_result(
1011 input.plugin.name(),
1012 input.plugin_result,
1013 input.result,
1014 Some(input.abs_path),
1015 ) {
1016 input.regex_errors.append(&mut errors);
1017 }
1018}
1019
1020fn should_warn(key: String) -> bool {
1024 plugin_warn_dedupe()
1025 .lock()
1026 .map_or(true, |mut set| set.insert(key))
1027}
1028
1029#[derive(Debug, Clone, PartialEq, Eq)]
1036pub(crate) enum PluginDiagnostic {
1037 PatternCollision {
1039 pattern: String,
1040 owners: Vec<String>,
1041 },
1042 EnablerTypo {
1045 plugin: String,
1046 enabler: String,
1047 suggestion: String,
1048 },
1049}
1050
1051pub(crate) fn detect_pattern_collisions(
1077 builtin_active: &[&dyn Plugin],
1078 external_active: &[&ExternalPluginDef],
1079) -> Vec<PluginDiagnostic> {
1080 use rustc_hash::FxHashMap;
1081
1082 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1083 FxHashMap::default();
1084
1085 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1086 pattern: String,
1087 name: String| {
1088 let (list, seen) = pattern_owners.entry(pattern).or_default();
1089 if seen.insert(name.clone()) {
1090 list.push(name);
1091 }
1092 };
1093
1094 for plugin in builtin_active {
1095 for pat in plugin.config_patterns() {
1096 record(
1097 &mut pattern_owners,
1098 (*pat).to_string(),
1099 plugin.name().to_string(),
1100 );
1101 }
1102 }
1103 for ext in external_active {
1104 for pat in &ext.config_patterns {
1105 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1106 }
1107 }
1108
1109 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1116
1117 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1118 .into_iter()
1119 .filter_map(|(pattern, (owners, _seen))| {
1120 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1121 None
1122 } else {
1123 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1124 }
1125 })
1126 .collect();
1127 findings.sort_unstable_by(|a, b| match (a, b) {
1128 (
1129 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1130 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1131 ) => ap.cmp(bp),
1132 _ => std::cmp::Ordering::Equal,
1133 });
1134 findings
1135}
1136
1137pub(crate) fn detect_enabler_typos(
1152 external_plugins: &[ExternalPluginDef],
1153 all_deps: &[String],
1154) -> Vec<PluginDiagnostic> {
1155 let mut findings = Vec::new();
1156
1157 for ext in external_plugins {
1158 if ext.detection.is_some() || ext.enablers.is_empty() {
1159 continue;
1160 }
1161
1162 let any_match = ext.enablers.iter().any(|enabler| {
1163 if enabler.ends_with('/') {
1164 all_deps.iter().any(|d| d.starts_with(enabler))
1165 } else {
1166 all_deps.iter().any(|d| d == enabler)
1167 }
1168 });
1169 if any_match {
1170 continue;
1171 }
1172
1173 for enabler in &ext.enablers {
1174 let candidates = all_deps.iter().map(String::as_str);
1175 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1176 else {
1177 continue;
1178 };
1179
1180 findings.push(PluginDiagnostic::EnablerTypo {
1181 plugin: ext.name.clone(),
1182 enabler: enabler.clone(),
1183 suggestion: suggestion.to_string(),
1184 });
1185 }
1186 }
1187
1188 findings
1189}
1190
1191fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1194 for finding in findings {
1195 match finding {
1196 PluginDiagnostic::PatternCollision { pattern, owners } => {
1197 let key = format!("collision::{pattern}::{owners:?}");
1198 if !should_warn(key) {
1199 continue;
1200 }
1201 let winner = &owners[0];
1202 let others = owners[1..].join(", ");
1203 tracing::warn!(
1204 "plugin config_patterns collision: identical pattern \
1205 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1206 runs first (registration order), others ({others}) \
1207 follow. Rename one of the patterns or remove the \
1208 duplicate plugin to make resolution explicit. A future \
1209 release may reject identical-pattern collisions.",
1210 joined = owners.join(", "),
1211 );
1212 }
1213 PluginDiagnostic::EnablerTypo {
1214 plugin,
1215 enabler,
1216 suggestion,
1217 } => {
1218 let key = format!("enabler::{plugin}::{enabler}");
1219 if !should_warn(key) {
1220 continue;
1221 }
1222 tracing::warn!(
1223 "plugin '{plugin}' enabler '{enabler}' does not match any \
1224 dependency in package.json; did you mean '{suggestion}'? \
1225 The plugin will not activate. A future release may reject \
1226 unmatched enablers.",
1227 );
1228 }
1229 }
1230 }
1231}
1232
1233fn process_package_json_inline_configs(
1238 active: &[&dyn Plugin],
1239 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1240 relative_files: &[(PathBuf, String)],
1241 root: &Path,
1242 result: &mut AggregatedPluginResult,
1243 regex_errors: &mut Vec<PluginRegexValidationError>,
1244) {
1245 for plugin in active {
1246 let Some(key) = plugin.package_json_config_key() else {
1247 continue;
1248 };
1249 if check_has_config_file(*plugin, config_matchers, relative_files) {
1250 continue;
1251 }
1252 let pkg_path = root.join("package.json");
1253 let Ok(content) = std::fs::read_to_string(&pkg_path) else {
1254 continue;
1255 };
1256 let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
1257 continue;
1258 };
1259 let Some(config_value) = json.get(key) else {
1260 continue;
1261 };
1262 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1263 let fake_path = root.join(format!("{key}.config.json"));
1264 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
1265 if plugin_result.is_empty() {
1266 continue;
1267 }
1268 tracing::debug!(
1269 plugin = plugin.name(),
1270 key = key,
1271 "resolved inline package.json config"
1272 );
1273 if let Err(mut errors) =
1274 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1275 {
1276 regex_errors.append(&mut errors);
1277 }
1278 }
1279}
1280
1281#[derive(Debug)]
1284struct MetaFrameworkWarning {
1285 dedupe_key: &'static str,
1286 message: &'static str,
1287}
1288
1289fn missing_meta_framework_prerequisites(
1299 active_plugins: &[&dyn Plugin],
1300 root: &Path,
1301) -> Vec<MetaFrameworkWarning> {
1302 active_plugins
1303 .iter()
1304 .filter_map(|plugin| match plugin.name() {
1305 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1306 dedupe_key: "meta-prereq::nuxt",
1307 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1308 before fallow for accurate analysis",
1309 }),
1310 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1311 dedupe_key: "meta-prereq::astro",
1312 message: "Astro project missing .astro/ types: run `astro sync` \
1313 before fallow for accurate analysis",
1314 }),
1315 _ => None,
1316 })
1317 .collect()
1318}
1319
1320fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1330 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1331 if should_warn(warning.dedupe_key.to_owned()) {
1332 tracing::warn!("{}", warning.message);
1333 }
1334 }
1335}
1336
1337fn script_activation_packages(
1338 pkg: &PackageJson,
1339 root: &Path,
1340 all_deps: &[String],
1341 production_mode: bool,
1342) -> FxHashSet<String> {
1343 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1344 return FxHashSet::default();
1345 };
1346
1347 let scripts_to_analyze = if production_mode {
1348 scripts::filter_production_scripts(pkg_scripts)
1349 } else {
1350 pkg_scripts.clone()
1351 };
1352
1353 let mut nm_roots = Vec::new();
1354 if root.join("node_modules").is_dir() {
1355 nm_roots.push(root);
1356 }
1357 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1358 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1359 let script_names: FxHashSet<String> = pkg_scripts.keys().cloned().collect();
1360
1361 scripts::analyze_scripts_with_dependency_context(
1362 &scripts_to_analyze,
1363 root,
1364 &bin_map,
1365 &dep_set,
1366 &script_names,
1367 )
1368 .used_packages
1369}
1370
1371#[cfg(test)]
1372mod tests;