1use rustc_hash::{FxHashMap, FxHashSet};
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::{OnceLock, RwLock};
7
8use fallow_config::{
9 AutoImportRule, EntryPointRole, ExternalPluginDef, JsxImportSourceRule, PackageJson,
10 UsedClassMemberRule,
11};
12
13use crate::scripts;
14
15use super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, ProvidedDependencyRule};
16
17pub(crate) mod builtin;
18mod helpers;
19mod tooling_evidence;
20
21pub(crate) use tooling_evidence::find_config_file;
22
23#[must_use]
28pub fn builtin_plugin_names() -> Vec<&'static str> {
29 builtin::create_builtin_plugins()
30 .iter()
31 .map(|plugin| plugin.name())
32 .collect()
33}
34
35#[must_use]
40pub fn builtin_config_patterns() -> Vec<&'static str> {
41 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
42 .iter()
43 .flat_map(|plugin| plugin.config_patterns().iter().copied())
44 .collect();
45 patterns.sort_unstable();
46 patterns.dedup();
47 patterns
48}
49
50#[must_use]
54pub fn builtin_config_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
55 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
56 .iter()
57 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
58 .flat_map(|plugin| plugin.config_patterns().iter().copied())
59 .collect();
60 patterns.sort_unstable();
61 patterns.dedup();
62 patterns
63}
64
65#[must_use]
70pub fn builtin_config_lookup(
71 plugin_name: &str,
72) -> Option<(&'static [&'static str], &'static [&'static str])> {
73 builtin::create_builtin_plugins()
74 .iter()
75 .find(|plugin| plugin.name() == plugin_name)
76 .map(|plugin| (plugin.config_patterns(), plugin.script_config_binaries()))
77}
78
79#[must_use]
83pub fn builtin_always_used_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
84 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
85 .iter()
86 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
87 .flat_map(|plugin| plugin.always_used().iter().copied())
88 .collect();
89 patterns.sort_unstable();
90 patterns.dedup();
91 patterns
92}
93
94pub use helpers::ConfigCandidateIndex;
95pub use helpers::is_external_plugin_active;
96use helpers::{
97 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
98 process_external_plugins, process_package_json_metadata, process_static_patterns,
99};
100
101fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
102 matches!(
103 plugin_name,
104 "eslint" | "docusaurus" | "jest" | "storybook" | "tanstack-router" | "vitest"
105 )
106}
107
108fn compile_config_matchers<'a>(
109 active: &[&'a dyn Plugin],
110) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
111 active
112 .iter()
113 .filter(|plugin| !plugin.config_patterns().is_empty())
114 .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
115 .collect()
116}
117
118fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
119 plugin
120 .config_patterns()
121 .iter()
122 .filter_map(|pattern| {
123 let prepared = prepare_config_pattern(pattern);
124 globset::Glob::new(&prepared)
125 .ok()
126 .map(|glob| glob.compile_matcher())
127 })
128 .collect()
129}
130
131struct CachedPluginConfigMatchers {
132 patterns: &'static [&'static str],
133 matchers: Vec<globset::GlobMatcher>,
134}
135
136#[derive(Default)]
137struct PluginConfigMatcherCache {
138 by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
139}
140
141impl PluginConfigMatcherCache {
142 fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
143 let patterns = plugin.config_patterns();
144 let cached = self
145 .by_name
146 .read()
147 .unwrap_or_else(std::sync::PoisonError::into_inner)
148 .get(plugin.name())
149 .and_then(|variants| {
150 variants
151 .iter()
152 .find(|entry| entry.patterns == patterns)
153 .map(|entry| entry.matchers.clone())
154 });
155 if let Some(matchers) = cached {
156 return matchers;
157 }
158
159 let matchers = compile_plugin_config_matchers(plugin);
160 {
161 let mut by_name = self
162 .by_name
163 .write()
164 .unwrap_or_else(std::sync::PoisonError::into_inner);
165 let variants = by_name.entry(plugin.name()).or_default();
166 if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
167 return entry.matchers.clone();
168 }
169 variants.push(CachedPluginConfigMatchers {
170 patterns,
171 matchers: matchers.clone(),
172 });
173 drop(by_name);
174 }
175 matchers
176 }
177}
178
179fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
180 static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
181 MATCHERS
182 .get_or_init(PluginConfigMatcherCache::default)
183 .get_or_compile(plugin)
184}
185
186fn log_active_plugins(active: &[&dyn Plugin]) {
188 tracing::info!(
189 plugins = active
190 .iter()
191 .map(|p| p.name())
192 .collect::<Vec<_>>()
193 .join(", "),
194 "active plugins"
195 );
196}
197
198fn compute_relative_files(
202 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
203 active: &[&dyn Plugin],
204 discovered_files: &[PathBuf],
205 root: &Path,
206) -> Vec<(PathBuf, String)> {
207 use rayon::prelude::*;
208 let needs_relative_files =
209 !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
210 if !needs_relative_files {
211 return Vec::new();
212 }
213 discovered_files
214 .par_iter()
215 .map(|f| {
216 let rel = f
217 .strip_prefix(root)
218 .unwrap_or(f)
219 .to_string_lossy()
220 .into_owned();
221 (f.clone(), rel)
222 })
223 .collect()
224}
225
226pub struct PluginRegistry {
228 plugins: Vec<Box<dyn Plugin>>,
229 external_plugins: Vec<ExternalPluginDef>,
230}
231
232pub(crate) struct RootPluginContext<'a> {
234 pub(crate) active_plugins: FxHashSet<&'a str>,
236 pub(crate) dependencies: Vec<String>,
238}
239
240impl<'a> RootPluginContext<'a> {
241 pub(crate) fn new(root_pkg: Option<&PackageJson>, active_plugins: &'a [String]) -> Self {
242 Self {
243 active_plugins: active_plugins.iter().map(String::as_str).collect(),
244 dependencies: root_pkg.map_or_else(Vec::new, PackageJson::all_dependency_names),
245 }
246 }
247}
248
249pub(crate) struct WorkspacePluginRunInput<'a> {
251 pub(crate) pkg: &'a PackageJson,
252 pub(crate) root: &'a Path,
253 pub(crate) project_root: &'a Path,
254 pub(crate) root_dependencies: &'a [String],
258 pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
259 pub(crate) relative_files: &'a [(PathBuf, String)],
260 pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
261 pub(crate) production_mode: bool,
262 pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
263}
264
265struct PluginRunContext<'a> {
266 all_deps: Vec<String>,
267 active: Vec<&'a dyn Plugin>,
268}
269
270struct PluginActivationInput<'a> {
272 pkg: &'a PackageJson,
273 root: &'a Path,
274 discovered_files: &'a [PathBuf],
275 all_deps: &'a [String],
276 script_packages: &'a FxHashSet<String>,
277 candidate_index: Option<&'a ConfigCandidateIndex>,
278}
279
280#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct PluginRegexValidationError {
283 plugin_name: String,
284 config_path: Option<PathBuf>,
285 rule_kind: &'static str,
286 field: &'static str,
287 rule_pattern: String,
288 regex_pattern: String,
289 source: String,
290}
291
292impl PluginRegexValidationError {
293 fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
294 Self {
295 plugin_name: input.plugin_name.to_owned(),
296 config_path: input.config_path.map(Path::to_path_buf),
297 rule_kind: input.rule_kind,
298 field: input.field,
299 rule_pattern: input.rule_pattern.to_owned(),
300 regex_pattern: input.regex_pattern.to_owned(),
301 source: input.source.to_string(),
302 }
303 }
304}
305
306#[derive(Clone, Copy)]
307struct PluginRegexValidationErrorInput<'a> {
308 plugin_name: &'a str,
309 config_path: Option<&'a Path>,
310 rule_kind: &'static str,
311 field: &'static str,
312 rule_pattern: &'a str,
313 regex_pattern: &'a str,
314 source: &'a regex::Error,
315}
316
317impl fmt::Display for PluginRegexValidationError {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 let location = self
320 .config_path
321 .as_ref()
322 .map(|path| format!(" in {}", path.display()))
323 .unwrap_or_default();
324 write!(
325 f,
326 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
327 self.plugin_name,
328 location,
329 self.regex_pattern,
330 self.rule_kind,
331 self.field,
332 self.rule_pattern,
333 self.source
334 )
335 }
336}
337
338#[must_use]
339pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
340 let joined = errors
341 .iter()
342 .map(ToString::to_string)
343 .collect::<Vec<_>>()
344 .join("\n - ");
345 format!(
346 "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."
347 )
348}
349
350#[derive(Debug, Clone, Default, PartialEq, Eq)]
358pub struct PluginToolingDependencies {
359 pub plugin: String,
361 pub dependencies: Vec<String>,
363 pub references: Vec<String>,
367 pub own_config: Option<PathBuf>,
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum PluginToolingEvidence<'a> {
375 OwnConfig(&'a Path),
377 Reference(&'a str),
379}
380
381impl PluginToolingDependencies {
382 #[must_use]
386 pub fn evidence<'a>(
387 &'a self,
388 script_used_packages: &FxHashSet<String>,
389 ) -> Option<PluginToolingEvidence<'a>> {
390 if let Some(config) = &self.own_config {
391 return Some(PluginToolingEvidence::OwnConfig(config));
392 }
393 self.references
394 .iter()
395 .find(|name| script_used_packages.contains(name.as_str()))
396 .map(|name| PluginToolingEvidence::Reference(name))
397 }
398}
399
400#[derive(Debug, Clone, PartialEq, Eq)]
402pub struct CheckedAliasPrefix {
403 pub scope: String,
407 pub prefix: String,
409}
410
411impl CheckedAliasPrefix {
412 #[must_use]
414 pub fn covers(&self, root: &Path, from_file: &Path, specifier: &str) -> bool {
415 specifier.starts_with(&self.prefix)
416 && (self.scope.is_empty() || from_file.starts_with(root.join(&self.scope)))
417 }
418}
419
420#[derive(Debug, Clone, Default)]
422pub struct AggregatedPluginResult {
423 pub entry_patterns: Vec<(PathRule, String)>,
425 pub replaced_entry_plugins: FxHashSet<String>,
430 pub config_entry_patterns: FxHashSet<(String, String)>,
434 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
436 pub config_patterns: Vec<String>,
438 pub always_used: Vec<(String, String)>,
440 pub used_exports: Vec<PluginUsedExportRule>,
442 pub config_export_credits: Vec<PluginUsedExportRule>,
450 pub used_class_members: Vec<UsedClassMemberRule>,
454 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
456 pub referenced_dependencies: Vec<String>,
458 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
460 pub required_dependencies: Vec<super::RequiredDependency>,
462 pub discovered_always_used: Vec<(String, String)>,
464 pub setup_files: Vec<(PathBuf, String)>,
466 pub tooling_dependencies: Vec<String>,
470 pub plugin_tooling: Vec<PluginToolingDependencies>,
474 pub script_used_packages: FxHashSet<String>,
476 pub dependency_binaries: crate::scripts::DependencyBinaries,
480 pub dev_dependency_names: FxHashSet<String>,
485 pub virtual_module_prefixes: Vec<String>,
488 pub virtual_package_suffixes: Vec<String>,
491 pub generated_import_patterns: Vec<String>,
494 pub generated_type_import_prefixes: Vec<String>,
497 pub path_aliases: Vec<(String, String)>,
500 pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
505 pub checked_alias_prefixes: Vec<CheckedAliasPrefix>,
509 pub auto_imports: Vec<AutoImportRule>,
513 pub active_plugins: Vec<String>,
515 pub active_plugin_scopes: Vec<(String, String)>,
519 pub fixture_patterns: Vec<(String, String)>,
521 pub scss_include_paths: Vec<PathBuf>,
526 pub static_dir_mappings: Vec<(PathBuf, String)>,
528 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
531 pub provided_dependencies: Vec<ProvidedDependencyRule>,
533 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
537 pub federation_sources: Vec<super::FederationSource>,
540 pub jsx_import_sources: Vec<JsxImportSourceRule>,
544 pub jsx_package_credits: Vec<JsxImportSourceRule>,
549 pub tsconfig_jsx_dirs: Vec<TsconfigJsxDir>,
552}
553
554#[derive(Debug, Clone, PartialEq, Eq)]
557pub struct TsconfigJsxDir {
558 pub dir: PathBuf,
560 pub automatic_react: bool,
565}
566
567fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
572 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
573 for item in incoming {
574 if seen.insert(item.clone()) {
575 target.push(item);
576 }
577 }
578}
579
580fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
583 for item in incoming {
584 if !target.contains(&item) {
585 target.push(item);
586 }
587 }
588}
589
590fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
594 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
595 pat.to_string()
596 } else {
597 format!("{ws_prefix}/{pat}")
598 }
599}
600
601impl AggregatedPluginResult {
602 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
608 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
609 self.entry_patterns
610 .iter()
611 .filter(move |entry| seen.insert(entry))
612 }
613
614 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
630 for (rule, _) in &mut self.entry_patterns {
631 *rule = rule.prefixed(ws_prefix);
632 }
633 for (pat, _) in &mut self.always_used {
634 *pat = prefix_if_needed(pat, ws_prefix);
635 }
636 for (pat, _) in &mut self.discovered_always_used {
637 *pat = prefix_if_needed(pat, ws_prefix);
638 }
639 for (pat, _) in &mut self.fixture_patterns {
640 *pat = prefix_if_needed(pat, ws_prefix);
641 }
642 for rule in &mut self.used_exports {
643 *rule = rule.prefixed(ws_prefix);
644 }
645 for (_, scope) in &mut self.active_plugin_scopes {
646 *scope = ws_prefix.to_string();
647 }
648 for rule in &mut self.config_export_credits {
649 *rule = rule.prefixed(ws_prefix);
650 }
651 for rule in &mut self.provided_dependencies {
652 *rule = rule.prefixed(ws_prefix);
653 }
654 for source in &mut self.federation_sources {
655 *source = source.prefixed(ws_prefix);
656 }
657 if !ws_prefix.is_empty() {
658 for checked in &mut self.checked_alias_prefixes {
659 checked.scope = ws_prefix.to_string();
660 }
661 self.scoped_path_aliases
662 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
663 fallow_graph::resolve::ScopedPathAlias {
664 scope: ws_prefix.to_string(),
665 prefix,
666 replacement: format!("{ws_prefix}/{replacement}"),
667 }
668 }));
669 }
670 }
671
672 pub(crate) fn merge_into(&mut self, other: Self) {
686 let Self {
687 entry_patterns,
688 replaced_entry_plugins: _,
690 config_entry_patterns: _,
691 entry_point_roles,
692 config_patterns,
693 always_used,
694 used_exports,
695 config_export_credits,
696 used_class_members,
697 framework_class_member_contracts,
698 referenced_dependencies,
699 package_referenced_dependencies,
700 required_dependencies,
701 discovered_always_used,
702 setup_files,
703 tooling_dependencies,
704 plugin_tooling,
705 script_used_packages,
706 dependency_binaries: _,
707 dev_dependency_names,
708 virtual_module_prefixes,
709 virtual_package_suffixes,
710 generated_import_patterns,
711 generated_type_import_prefixes,
712 path_aliases,
713 scoped_path_aliases,
714 checked_alias_prefixes,
715 auto_imports,
716 active_plugins,
717 active_plugin_scopes,
718 fixture_patterns,
719 scss_include_paths,
720 static_dir_mappings,
721 framework_static_dir_mappings,
722 provided_dependencies,
723 config_diagnostics,
724 federation_sources,
725 jsx_import_sources,
726 jsx_package_credits,
727 tsconfig_jsx_dirs,
728 } = other;
729
730 self.entry_patterns.extend(entry_patterns);
731 for (plugin_name, role) in entry_point_roles {
732 self.entry_point_roles.entry(plugin_name).or_insert(role);
733 }
734 self.config_patterns.extend(config_patterns);
735 self.always_used.extend(always_used);
736 self.used_exports.extend(used_exports);
737 self.config_export_credits.extend(config_export_credits);
738 self.used_class_members.extend(used_class_members);
739 for contract in framework_class_member_contracts {
740 if !self.framework_class_member_contracts.contains(&contract) {
741 self.framework_class_member_contracts.push(contract);
742 }
743 }
744 self.referenced_dependencies.extend(referenced_dependencies);
745 self.package_referenced_dependencies
746 .extend(package_referenced_dependencies);
747 push_missing(&mut self.required_dependencies, required_dependencies);
748 self.discovered_always_used.extend(discovered_always_used);
749 self.setup_files.extend(setup_files);
750 self.tooling_dependencies.extend(tooling_dependencies);
751 self.plugin_tooling.extend(plugin_tooling);
752 self.dev_dependency_names.extend(dev_dependency_names);
753 self.script_used_packages.extend(script_used_packages);
754 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
755 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
756 extend_unique(
757 &mut self.generated_import_patterns,
758 generated_import_patterns,
759 );
760 extend_unique(
761 &mut self.generated_type_import_prefixes,
762 generated_type_import_prefixes,
763 );
764 self.path_aliases.extend(path_aliases);
765 self.scoped_path_aliases.extend(scoped_path_aliases);
766 push_missing(&mut self.checked_alias_prefixes, checked_alias_prefixes);
767 self.auto_imports.extend(auto_imports);
768 extend_unique(&mut self.active_plugins, active_plugins);
769 push_missing(&mut self.active_plugin_scopes, active_plugin_scopes);
770 self.fixture_patterns.extend(fixture_patterns);
771 self.scss_include_paths.extend(scss_include_paths);
772 self.static_dir_mappings.extend(static_dir_mappings);
773 self.framework_static_dir_mappings
774 .extend(framework_static_dir_mappings);
775 self.provided_dependencies.extend(provided_dependencies);
776 self.federation_sources.extend(federation_sources);
777 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
778 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
779 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
780 push_missing(&mut self.config_diagnostics, config_diagnostics);
781 }
782}
783
784impl PluginRegistry {
785 #[must_use]
787 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
788 Self {
789 plugins: builtin::create_builtin_plugins(),
790 external_plugins: external,
791 }
792 }
793
794 #[must_use]
798 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
799 super::bun::preload_files(root)
800 }
801
802 #[must_use]
807 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
808 let all_deps = pkg.all_dependency_names();
809 let mut seen = FxHashSet::default();
810 let mut dirs = Vec::new();
811
812 for plugin in &self.plugins {
813 if !plugin.is_enabled_with_deps(&all_deps, root) {
814 continue;
815 }
816 for dir in plugin.discovery_hidden_dirs() {
817 if seen.insert(*dir) {
818 dirs.push((*dir).to_string());
819 }
820 }
821 }
822
823 dirs
824 }
825
826 #[cfg(test)]
831 fn run(
832 &self,
833 pkg: &PackageJson,
834 root: &Path,
835 discovered_files: &[PathBuf],
836 ) -> AggregatedPluginResult {
837 self.try_run(pkg, root, discovered_files)
838 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
839 }
840
841 pub fn try_run(
843 &self,
844 pkg: &PackageJson,
845 root: &Path,
846 discovered_files: &[PathBuf],
847 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
848 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
849 }
850
851 #[expect(
854 clippy::too_many_arguments,
855 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
856 )]
857 pub(crate) fn try_run_with_search_roots(
858 &self,
859 pkg: &PackageJson,
860 root: &Path,
861 discovered_files: &[PathBuf],
862 config_search_roots: &[&Path],
863 production_mode: bool,
864 candidate_index: Option<&ConfigCandidateIndex>,
865 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
866 let _span = tracing::info_span!("run_plugins").entered();
867 let mut result = AggregatedPluginResult::default();
868 let mut regex_errors = Vec::new();
869
870 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
871 pkg,
872 root,
873 discovered_files,
874 production_mode,
875 candidate_index,
876 );
877
878 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
879
880 for plugin in &active {
881 process_static_patterns(*plugin, root, &mut result);
882 }
883 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
884
885 process_external_plugins(
886 &self.external_plugins,
887 &all_deps,
888 root,
889 discovered_files,
890 &mut result,
891 );
892 tooling_evidence::record_plugin_tooling(
893 &tooling_evidence::ToolingEvidenceInput {
894 active: &active,
895 external_plugins: &self.external_plugins,
896 all_deps: &all_deps,
897 roots: &[root],
898 extra_roots: if production_mode {
902 &[]
903 } else {
904 config_search_roots
905 },
906 candidate_index,
907 discovered_files,
908 },
909 &mut result,
910 );
911
912 let config_matchers = compile_config_matchers(&active);
913 let relative_files =
914 compute_relative_files(&config_matchers, &active, discovered_files, root);
915
916 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
917 config_matchers: &config_matchers,
918 relative_files: &relative_files,
919 config_search_roots,
920 production_mode,
921 candidate_index,
922 root,
923 result: &mut result,
924 regex_errors: &mut regex_errors,
925 });
926
927 process_package_json_inline_configs(
928 &InlineConfigInput {
929 active: &active,
930 config_matchers: &config_matchers,
931 relative_files: &relative_files,
932 pkg,
933 root,
934 project_root: root,
935 },
936 &mut result,
937 &mut regex_errors,
938 );
939
940 if regex_errors.is_empty() {
941 Ok(result)
942 } else {
943 Err(regex_errors)
944 }
945 }
946
947 #[cfg(test)]
952 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
953 self.try_run_workspace_fast(input)
954 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
955 }
956
957 pub(crate) fn try_run_workspace_fast(
964 &self,
965 input: &WorkspacePluginRunInput<'_>,
966 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
967 let _span = tracing::info_span!("run_plugins").entered();
968 let mut result = AggregatedPluginResult::default();
969 let mut regex_errors = Vec::new();
970
971 let (all_deps, script_packages) = workspace_activation_deps(
972 input.pkg,
973 (input.root, input.project_root),
974 input.root_dependencies,
975 input.production_mode,
976 );
977 let workspace_files: Vec<PathBuf> = input
978 .relative_files
979 .iter()
980 .map(|(abs_path, _)| abs_path.clone())
981 .collect();
982
983 let active = self.collect_active_plugins(&PluginActivationInput {
984 pkg: input.pkg,
985 root: input.root,
986 discovered_files: &workspace_files,
987 all_deps: &all_deps,
988 script_packages: &script_packages,
989 candidate_index: input.candidate_index,
990 });
991
992 log_active_plugins(&active);
993
994 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
995
996 process_external_plugins(
997 &self.external_plugins,
998 &all_deps,
999 input.root,
1000 &workspace_files,
1001 &mut result,
1002 );
1003
1004 if active.is_empty() && result.active_plugins.is_empty() {
1005 return Ok(result);
1006 }
1007
1008 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
1009 let evidence_roots: &[&Path] = if input.root == input.project_root {
1011 &[input.root]
1012 } else {
1013 &[input.root, input.project_root]
1014 };
1015 tooling_evidence::record_plugin_tooling(
1016 &tooling_evidence::ToolingEvidenceInput {
1017 active: &active,
1018 external_plugins: &self.external_plugins,
1019 all_deps: &all_deps,
1020 roots: evidence_roots,
1021 extra_roots: &[],
1022 candidate_index: input.candidate_index,
1023 discovered_files: &workspace_files,
1024 },
1025 &mut result,
1026 );
1027 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
1028 if input.root != input.project_root {
1030 process_package_json_inline_configs(
1031 &InlineConfigInput {
1032 active: &active,
1033 config_matchers: input.precompiled_config_matchers,
1034 relative_files: input.relative_files,
1035 pkg: input.pkg,
1036 root: input.root,
1037 project_root: input.project_root,
1038 },
1039 &mut result,
1040 &mut regex_errors,
1041 );
1042 }
1043
1044 if regex_errors.is_empty() {
1045 Ok(result)
1046 } else {
1047 Err(regex_errors)
1048 }
1049 }
1050
1051 #[must_use]
1054 pub(crate) fn precompile_config_matchers(
1055 &self,
1056 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
1057 self.plugins
1058 .iter()
1059 .filter(|p| !p.config_patterns().is_empty())
1060 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
1061 .collect()
1062 }
1063
1064 pub(crate) fn resolve_script_config_files(
1075 &self,
1076 config_files: &[scripts::BinaryConfigFile],
1077 package_root: &Path,
1078 project_root: &Path,
1079 ws_prefix: &str,
1080 ) -> AggregatedPluginResult {
1081 let mut aggregated = AggregatedPluginResult::default();
1082 for config_file in config_files {
1083 let Some(rel_path) =
1084 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
1085 else {
1086 continue;
1087 };
1088 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1089 let in_package_root = abs_path.parent() == Some(package_root);
1094 let binary = config_file
1097 .binary
1098 .rsplit('/')
1099 .next()
1100 .unwrap_or(&config_file.binary);
1101 for plugin in &self.plugins {
1102 let plugin = plugin.as_ref();
1103 if !plugin.script_config_binaries().contains(&binary)
1104 || (in_package_root
1105 && cached_plugin_config_matchers(plugin)
1106 .iter()
1107 .any(|m| m.is_match(rel_path.as_str())))
1108 {
1109 continue;
1110 }
1111 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1112 continue;
1113 }
1114 let Ok(source) = std::fs::read_to_string(&abs_path) else {
1115 continue;
1116 };
1117 let mut file_result = AggregatedPluginResult::default();
1118 file_result
1119 .entry_point_roles
1120 .insert(plugin.name().to_string(), plugin.entry_point_role());
1121 let plugin_result =
1122 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1123 if let Err(errors) = process_config_result(
1124 plugin.name(),
1125 plugin_result,
1126 &mut file_result,
1127 Some(&abs_path),
1128 ) {
1129 for error in errors {
1130 tracing::warn!("{error}");
1131 }
1132 continue;
1133 }
1134 if !ws_prefix.is_empty() {
1135 file_result.apply_workspace_prefix(ws_prefix);
1136 }
1137 file_result.used_exports.push(PluginUsedExportRule::new(
1139 plugin.name().to_string(),
1140 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1141 ));
1142 aggregated.merge_into(file_result);
1143 }
1144 }
1145 aggregated
1146 }
1147}
1148
1149fn process_workspace_active_plugins(
1150 active: &[&dyn Plugin],
1151 input: &WorkspacePluginRunInput<'_>,
1152 result: &mut AggregatedPluginResult,
1153 regex_errors: &mut Vec<PluginRegexValidationError>,
1154) {
1155 for plugin in active {
1156 process_static_patterns(*plugin, input.root, result);
1157 }
1158 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1159}
1160
1161fn resolve_workspace_plugin_configs(
1162 active: &[&dyn Plugin],
1163 input: &WorkspacePluginRunInput<'_>,
1164 result: &mut AggregatedPluginResult,
1165 regex_errors: &mut Vec<PluginRegexValidationError>,
1166) {
1167 let workspace_matchers = select_workspace_matchers(
1168 input.precompiled_config_matchers,
1169 active,
1170 input.skip_config_plugins,
1171 );
1172
1173 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1174 for (plugin, matchers) in &workspace_matchers {
1175 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1176 plugin: *plugin,
1177 matchers,
1178 relative_files: input.relative_files,
1179 root: input.root,
1180 project_root: input.project_root,
1181 result,
1182 regex_errors,
1183 resolved_plugins: &mut resolved_ws_plugins,
1184 });
1185 }
1186
1187 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1188 workspace_matchers: &workspace_matchers,
1189 resolved_ws_plugins: &resolved_ws_plugins,
1190 root: input.root,
1191 project_root: input.project_root,
1192 production_mode: input.production_mode,
1193 candidate_index: input.candidate_index,
1194 result,
1195 regex_errors,
1196 });
1197}
1198
1199impl Default for PluginRegistry {
1200 fn default() -> Self {
1201 Self::new(vec![])
1202 }
1203}
1204
1205impl PluginRegistry {
1206 fn prepare_plugin_run_context<'a>(
1207 &'a self,
1208 pkg: &PackageJson,
1209 root: &Path,
1210 discovered_files: &[PathBuf],
1211 production_mode: bool,
1212 candidate_index: Option<&ConfigCandidateIndex>,
1213 ) -> PluginRunContext<'a> {
1214 let all_deps = pkg.all_dependency_names();
1215 let script_packages =
1216 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1217 let active = self.collect_active_plugins(&PluginActivationInput {
1218 pkg,
1219 root,
1220 discovered_files,
1221 all_deps: &all_deps,
1222 script_packages: &script_packages,
1223 candidate_index,
1224 });
1225
1226 PluginRunContext { all_deps, active }
1227 }
1228
1229 fn run_plugin_preflight(
1230 &self,
1231 active: &[&dyn Plugin],
1232 all_deps: &[String],
1233 root: &Path,
1234 discovered_files: &[PathBuf],
1235 ) {
1236 log_active_plugins(active);
1237 check_meta_framework_prerequisites(active, root);
1238 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1239 }
1240
1241 fn collect_active_plugins<'a>(
1244 &'a self,
1245 activation: &PluginActivationInput<'_>,
1246 ) -> Vec<&'a dyn Plugin> {
1247 self.plugins
1248 .iter()
1249 .filter(|p| {
1250 p.is_enabled_with_files(
1251 activation.all_deps,
1252 activation.root,
1253 activation.discovered_files,
1254 activation.candidate_index,
1255 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1256 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1257 })
1258 .map(AsRef::as_ref)
1259 .collect()
1260 }
1261
1262 fn emit_silent_fail_diagnostics(
1271 &self,
1272 active: &[&dyn Plugin],
1273 all_deps: &[String],
1274 root: &Path,
1275 discovered_files: &[PathBuf],
1276 ) {
1277 let active_external: Vec<&ExternalPluginDef> = self
1278 .external_plugins
1279 .iter()
1280 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1281 .collect();
1282 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1283 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1284 emit_plugin_diagnostics(&diagnostics);
1285 }
1286}
1287
1288fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1293 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1294 std::sync::OnceLock::new();
1295 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1296}
1297
1298struct PluginConfigResolutionInput<'a> {
1299 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1300 relative_files: &'a [(PathBuf, String)],
1301 config_search_roots: &'a [&'a Path],
1302 production_mode: bool,
1303 candidate_index: Option<&'a ConfigCandidateIndex>,
1304 root: &'a Path,
1305 result: &'a mut AggregatedPluginResult,
1306 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1307}
1308
1309fn select_workspace_matchers<'a>(
1312 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1313 active: &[&dyn Plugin],
1314 skip_config_plugins: &FxHashSet<&str>,
1315) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1316 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1317 precompiled_config_matchers
1318 .iter()
1319 .filter(|(p, _)| {
1320 active_names.contains(p.name())
1321 && (!skip_config_plugins.contains(p.name())
1322 || must_parse_workspace_config_when_root_active(p.name()))
1323 })
1324 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1325 .collect()
1326}
1327
1328struct WorkspaceFsConfigInput<'a> {
1329 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1330 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1331 root: &'a Path,
1332 project_root: &'a Path,
1333 production_mode: bool,
1334 candidate_index: Option<&'a ConfigCandidateIndex>,
1335 result: &'a mut AggregatedPluginResult,
1336 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1337}
1338
1339fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1342 let search_roots: &[&Path] = if input.root == input.project_root {
1343 &[input.root]
1344 } else {
1345 &[input.root, input.project_root]
1346 };
1347 let ws_json_configs = discover_config_files(
1348 input.workspace_matchers,
1349 input.resolved_ws_plugins,
1350 search_roots,
1351 input.production_mode,
1352 input.candidate_index,
1353 );
1354 for (abs_path, plugin) in &ws_json_configs {
1355 let Ok(source) = std::fs::read_to_string(abs_path) else {
1356 continue;
1357 };
1358 let plugin_result =
1359 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1360 if plugin_result.is_empty() {
1361 continue;
1362 }
1363 let rel = abs_path
1364 .strip_prefix(input.project_root)
1365 .map(|p| p.to_string_lossy())
1366 .unwrap_or_default();
1367 tracing::debug!(
1368 plugin = plugin.name(),
1369 config = %rel,
1370 entries = plugin_result.entry_patterns.len(),
1371 deps = plugin_result.referenced_dependencies.len(),
1372 "resolved config (workspace filesystem fallback)"
1373 );
1374 if let Err(mut errors) =
1375 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1376 {
1377 input.regex_errors.append(&mut errors);
1378 }
1379 }
1380}
1381
1382fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1383 if input.config_matchers.is_empty() {
1384 return;
1385 }
1386
1387 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1388 for (plugin, matchers) in input.config_matchers {
1389 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1390 plugin: *plugin,
1391 matchers,
1392 relative_files: input.relative_files,
1393 root: input.root,
1394 project_root: input.root,
1395 result: input.result,
1396 regex_errors: input.regex_errors,
1397 resolved_plugins: &mut resolved_plugins,
1398 });
1399 }
1400
1401 let json_configs = discover_config_files(
1402 input.config_matchers,
1403 &resolved_plugins,
1404 input.config_search_roots,
1405 input.production_mode,
1406 input.candidate_index,
1407 );
1408 for (abs_path, plugin) in &json_configs {
1409 resolve_plugin_filesystem_config(
1410 *plugin,
1411 abs_path,
1412 input.root,
1413 input.result,
1414 input.regex_errors,
1415 );
1416 }
1417}
1418
1419struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1420 plugin: &'plugins dyn Plugin,
1421 matchers: &'data [globset::GlobMatcher],
1422 relative_files: &'data [(PathBuf, String)],
1423 root: &'data Path,
1424 project_root: &'data Path,
1425 result: &'state mut AggregatedPluginResult,
1426 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1427 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1428}
1429
1430fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1431 use rayon::prelude::*;
1432
1433 let plugin_hits: Vec<&PathBuf> = input
1434 .relative_files
1435 .par_iter()
1436 .filter_map(|(abs_path, rel_path)| {
1437 input
1438 .matchers
1439 .iter()
1440 .any(|m| m.is_match(rel_path.as_str()))
1441 .then_some(abs_path)
1442 })
1443 .collect();
1444 for abs_path in plugin_hits {
1445 let Ok(source) = std::fs::read_to_string(abs_path) else {
1446 continue;
1447 };
1448 let plugin_result = input.plugin.resolve_config_in_project(
1449 abs_path,
1450 &source,
1451 input.root,
1452 input.project_root,
1453 );
1454 if plugin_result.is_empty() {
1455 continue;
1456 }
1457 input.resolved_plugins.insert(input.plugin.name());
1458 process_resolved_plugin_config(ResolvedPluginConfigInput {
1459 plugin: input.plugin,
1460 abs_path,
1461 plugin_result,
1462 result: input.result,
1463 regex_errors: input.regex_errors,
1464 message: "resolved config",
1465 config_display: abs_path.display(),
1466 });
1467 }
1468}
1469
1470fn resolve_plugin_filesystem_config(
1471 plugin: &dyn Plugin,
1472 abs_path: &Path,
1473 root: &Path,
1474 result: &mut AggregatedPluginResult,
1475 regex_errors: &mut Vec<PluginRegexValidationError>,
1476) {
1477 let Ok(source) = std::fs::read_to_string(abs_path) else {
1478 return;
1479 };
1480 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1481 if plugin_result.is_empty() {
1482 return;
1483 }
1484 let rel = abs_path
1485 .strip_prefix(root)
1486 .map(|p| p.to_string_lossy())
1487 .unwrap_or_default();
1488 process_resolved_plugin_config(ResolvedPluginConfigInput {
1489 plugin,
1490 abs_path,
1491 plugin_result,
1492 result,
1493 regex_errors,
1494 message: "resolved config (filesystem fallback)",
1495 config_display: rel,
1496 });
1497}
1498
1499struct ResolvedPluginConfigInput<'a, D> {
1500 plugin: &'a dyn Plugin,
1501 abs_path: &'a Path,
1502 plugin_result: PluginResult,
1503 result: &'a mut AggregatedPluginResult,
1504 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1505 message: &'static str,
1506 config_display: D,
1507}
1508
1509fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1510 tracing::debug!(
1511 plugin = input.plugin.name(),
1512 config = %input.config_display,
1513 entries = input.plugin_result.entry_patterns.len(),
1514 deps = input.plugin_result.referenced_dependencies.len(),
1515 input.message
1516 );
1517 if let Err(mut errors) = process_config_result(
1518 input.plugin.name(),
1519 input.plugin_result,
1520 input.result,
1521 Some(input.abs_path),
1522 ) {
1523 input.regex_errors.append(&mut errors);
1524 }
1525}
1526
1527fn should_warn(key: String) -> bool {
1531 plugin_warn_dedupe()
1532 .lock()
1533 .map_or(true, |mut set| set.insert(key))
1534}
1535
1536#[derive(Debug, Clone, PartialEq, Eq)]
1543enum PluginDiagnostic {
1544 PatternCollision {
1546 pattern: String,
1547 owners: Vec<String>,
1548 },
1549 EnablerTypo {
1552 plugin: String,
1553 enabler: String,
1554 suggestion: String,
1555 },
1556}
1557
1558fn detect_pattern_collisions(
1584 builtin_active: &[&dyn Plugin],
1585 external_active: &[&ExternalPluginDef],
1586) -> Vec<PluginDiagnostic> {
1587 use rustc_hash::FxHashMap;
1588
1589 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1590 FxHashMap::default();
1591
1592 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1593 pattern: String,
1594 name: String| {
1595 let (list, seen) = pattern_owners.entry(pattern).or_default();
1596 if seen.insert(name.clone()) {
1597 list.push(name);
1598 }
1599 };
1600
1601 for plugin in builtin_active {
1602 for pat in plugin.config_patterns() {
1603 record(
1604 &mut pattern_owners,
1605 (*pat).to_string(),
1606 plugin.name().to_string(),
1607 );
1608 }
1609 }
1610 for ext in external_active {
1611 for pat in &ext.config_patterns {
1612 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1613 }
1614 }
1615
1616 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1623
1624 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1625 .into_iter()
1626 .filter_map(|(pattern, (owners, _seen))| {
1627 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1628 None
1629 } else {
1630 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1631 }
1632 })
1633 .collect();
1634 findings.sort_unstable_by(|a, b| match (a, b) {
1635 (
1636 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1637 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1638 ) => ap.cmp(bp),
1639 _ => std::cmp::Ordering::Equal,
1640 });
1641 findings
1642}
1643
1644fn detect_enabler_typos(
1659 external_plugins: &[ExternalPluginDef],
1660 all_deps: &[String],
1661) -> Vec<PluginDiagnostic> {
1662 let mut findings = Vec::new();
1663
1664 for ext in external_plugins {
1665 if ext.detection.is_some() || ext.enablers.is_empty() {
1666 continue;
1667 }
1668
1669 let any_match = ext.enablers.iter().any(|enabler| {
1670 if enabler.ends_with('/') {
1671 all_deps.iter().any(|d| d.starts_with(enabler))
1672 } else {
1673 all_deps.iter().any(|d| d == enabler)
1674 }
1675 });
1676 if any_match {
1677 continue;
1678 }
1679
1680 for enabler in &ext.enablers {
1681 let candidates = all_deps.iter().map(String::as_str);
1682 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1683 else {
1684 continue;
1685 };
1686
1687 findings.push(PluginDiagnostic::EnablerTypo {
1688 plugin: ext.name.clone(),
1689 enabler: enabler.clone(),
1690 suggestion: suggestion.to_string(),
1691 });
1692 }
1693 }
1694
1695 findings
1696}
1697
1698fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1701 for finding in findings {
1702 match finding {
1703 PluginDiagnostic::PatternCollision { pattern, owners } => {
1704 let key = format!("collision::{pattern}::{owners:?}");
1705 if !should_warn(key) {
1706 continue;
1707 }
1708 let winner = &owners[0];
1709 let others = owners[1..].join(", ");
1710 tracing::warn!(
1711 "plugin config_patterns collision: identical pattern \
1712 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1713 runs first (registration order), others ({others}) \
1714 follow. Rename one of the patterns or remove the \
1715 duplicate plugin to make resolution explicit. A future \
1716 release may reject identical-pattern collisions.",
1717 joined = owners.join(", "),
1718 );
1719 }
1720 PluginDiagnostic::EnablerTypo {
1721 plugin,
1722 enabler,
1723 suggestion,
1724 } => {
1725 let key = format!("enabler::{plugin}::{enabler}");
1726 if !should_warn(key) {
1727 continue;
1728 }
1729 tracing::warn!(
1730 "plugin '{plugin}' enabler '{enabler}' does not match any \
1731 dependency in package.json; did you mean '{suggestion}'? \
1732 The plugin will not activate. A future release may reject \
1733 unmatched enablers.",
1734 );
1735 }
1736 }
1737 }
1738}
1739
1740fn process_package_json_inline_configs(
1752 input: &InlineConfigInput<'_>,
1753 result: &mut AggregatedPluginResult,
1754 regex_errors: &mut Vec<PluginRegexValidationError>,
1755) {
1756 let pkg_path = input.root.join("package.json");
1757 let credited_manifests: Vec<PathBuf> = if input.root == input.project_root {
1758 Vec::new()
1759 } else {
1760 input
1761 .root
1762 .ancestors()
1763 .take_while(|dir| dir.starts_with(input.project_root))
1764 .map(|dir| dir.join("package.json"))
1765 .collect()
1766 };
1767 for plugin in input.active {
1768 let Some(key) = plugin.package_json_config_key() else {
1769 continue;
1770 };
1771 let Some(config_value) = input.pkg.inline_tool_config(key) else {
1772 continue;
1773 };
1774 if check_has_config_file(*plugin, input.config_matchers, input.relative_files) {
1775 continue;
1776 }
1777 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1778 let fake_path = input.root.join(format!("{key}.config.json"));
1779 let mut plugin_result = plugin.resolve_config_in_project(
1780 &fake_path,
1781 &config_json,
1782 input.root,
1783 input.project_root,
1784 );
1785 if plugin_result.is_empty() {
1786 continue;
1787 }
1788 tracing::debug!(
1789 plugin = plugin.name(),
1790 key = key,
1791 "resolved inline package.json config"
1792 );
1793 if !credited_manifests.is_empty() {
1794 for dep in std::mem::take(&mut plugin_result.referenced_dependencies) {
1795 plugin_result.package_referenced_dependencies.extend(
1796 credited_manifests
1797 .iter()
1798 .map(|manifest| (manifest.clone(), dep.clone())),
1799 );
1800 }
1801 }
1802 if let Err(mut errors) =
1803 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1804 {
1805 regex_errors.append(&mut errors);
1806 }
1807 }
1808}
1809
1810struct InlineConfigInput<'a> {
1812 active: &'a [&'a dyn Plugin],
1813 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1814 relative_files: &'a [(PathBuf, String)],
1815 pkg: &'a PackageJson,
1816 root: &'a Path,
1817 project_root: &'a Path,
1818}
1819
1820#[derive(Debug)]
1823struct MetaFrameworkWarning {
1824 dedupe_key: &'static str,
1825 message: &'static str,
1826}
1827
1828fn missing_meta_framework_prerequisites(
1838 active_plugins: &[&dyn Plugin],
1839 root: &Path,
1840) -> Vec<MetaFrameworkWarning> {
1841 active_plugins
1842 .iter()
1843 .filter_map(|plugin| match plugin.name() {
1844 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1845 dedupe_key: "meta-prereq::nuxt",
1846 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1847 before fallow for accurate analysis",
1848 }),
1849 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1850 dedupe_key: "meta-prereq::astro",
1851 message: "Astro project missing .astro/ types: run `astro sync` \
1852 before fallow for accurate analysis",
1853 }),
1854 _ => None,
1855 })
1856 .collect()
1857}
1858
1859fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1869 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1870 if should_warn(warning.dedupe_key.to_owned()) {
1871 tracing::warn!("{}", warning.message);
1872 }
1873 }
1874}
1875
1876fn workspace_activation_deps(
1885 pkg: &PackageJson,
1886 (root, project_root): (&Path, &Path),
1887 root_dependencies: &[String],
1888 production_mode: bool,
1889) -> (Vec<String>, FxHashSet<String>) {
1890 let mut deps = pkg.all_dependency_names();
1891 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1892 let hoisted: Vec<String> = root_dependencies
1893 .iter()
1894 .filter(|dep| !own.contains(dep.as_str()))
1895 .cloned()
1896 .collect();
1897 let mut script_deps = deps.clone();
1898 script_deps.extend(hoisted.iter().cloned());
1899 let script_packages = script_activation_packages(
1900 pkg,
1901 root,
1902 &[root, project_root],
1903 &script_deps,
1904 production_mode,
1905 );
1906 deps.extend(
1907 hoisted
1908 .into_iter()
1909 .filter(|dep| script_packages.contains(dep)),
1910 );
1911 (deps, script_packages)
1912}
1913
1914#[must_use]
1918pub fn workspace_activation_dependencies(
1919 pkg: &PackageJson,
1920 root: &Path,
1921 project_root: &Path,
1922 root_dependencies: &[String],
1923 production_mode: bool,
1924) -> Vec<String> {
1925 workspace_activation_deps(
1926 pkg,
1927 (root, project_root),
1928 root_dependencies,
1929 production_mode,
1930 )
1931 .0
1932}
1933
1934fn script_activation_packages(
1937 pkg: &PackageJson,
1938 root: &Path,
1939 node_modules_roots: &[&Path],
1940 all_deps: &[String],
1941 production_mode: bool,
1942) -> FxHashSet<String> {
1943 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1944 return FxHashSet::default();
1945 };
1946
1947 let scripts_to_analyze = if production_mode {
1948 scripts::filter_production_scripts(pkg_scripts)
1949 } else {
1950 pkg_scripts.clone()
1951 };
1952
1953 let mut nm_roots: Vec<&Path> = Vec::new();
1954 for nm_root in node_modules_roots {
1955 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1956 nm_roots.push(nm_root);
1957 }
1958 }
1959 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1960 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1961 let catalog =
1962 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1963
1964 scripts::analyze_scripts_with_dependency_context(
1965 &scripts_to_analyze,
1966 root,
1967 &bin_map,
1968 &dep_set,
1969 &catalog,
1970 scripts::IgnoredCommandEntries::NONE,
1971 )
1972 .used_packages
1973}
1974
1975#[cfg(test)]
1976mod entry_pattern_tests;
1977#[cfg(test)]
1978mod tests;