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::{discover::project_read, scripts};
14
15use super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, ProvidedDependencyRule};
16
17pub(crate) mod builtin;
18mod helpers;
19mod plugin_diagnostics;
20mod tooling_evidence;
21mod virtual_module;
22
23#[cfg(test)]
24use plugin_diagnostics::PluginDiagnostic;
25use plugin_diagnostics::{
26 detect_enabler_typos, detect_pattern_collisions, emit_plugin_diagnostics,
27};
28pub(crate) use tooling_evidence::find_config_file;
29pub(crate) use virtual_module::module_specifiers;
30pub use virtual_module::{VirtualModuleMatch, VirtualModuleProviderRule};
31
32#[must_use]
37pub fn builtin_plugin_names() -> Vec<&'static str> {
38 builtin::create_builtin_plugins()
39 .iter()
40 .map(|plugin| plugin.name())
41 .collect()
42}
43
44#[must_use]
49pub fn builtin_config_patterns() -> Vec<&'static str> {
50 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
51 .iter()
52 .flat_map(|plugin| plugin.config_patterns().iter().copied())
53 .collect();
54 patterns.sort_unstable();
55 patterns.dedup();
56 patterns
57}
58
59#[must_use]
63pub fn builtin_config_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
64 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
65 .iter()
66 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
67 .flat_map(|plugin| plugin.config_patterns().iter().copied())
68 .collect();
69 patterns.sort_unstable();
70 patterns.dedup();
71 patterns
72}
73
74#[must_use]
79pub fn builtin_config_lookup(
80 plugin_name: &str,
81) -> Option<(&'static [&'static str], &'static [&'static str])> {
82 builtin::create_builtin_plugins()
83 .iter()
84 .find(|plugin| plugin.name() == plugin_name)
85 .map(|plugin| (plugin.config_patterns(), plugin.script_config_binaries()))
86}
87
88#[must_use]
92pub fn builtin_always_used_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
93 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
94 .iter()
95 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
96 .flat_map(|plugin| plugin.always_used().iter().copied())
97 .collect();
98 patterns.sort_unstable();
99 patterns.dedup();
100 patterns
101}
102
103pub use helpers::ConfigCandidateIndex;
104pub use helpers::is_external_plugin_active;
105use helpers::{
106 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
107 process_external_plugins, process_package_json_metadata, process_static_patterns,
108};
109
110fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
111 matches!(
112 plugin_name,
113 "eslint" | "docusaurus" | "jest" | "storybook" | "tanstack-router" | "vitest"
114 )
115}
116
117fn compile_config_matchers<'a>(
118 active: &[&'a dyn Plugin],
119) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
120 active
121 .iter()
122 .filter(|plugin| !plugin.config_patterns().is_empty())
123 .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
124 .collect()
125}
126
127fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
128 plugin
129 .config_patterns()
130 .iter()
131 .filter_map(|pattern| {
132 let prepared = prepare_config_pattern(pattern);
133 globset::Glob::new(&prepared)
134 .ok()
135 .map(|glob| glob.compile_matcher())
136 })
137 .collect()
138}
139
140struct CachedPluginConfigMatchers {
141 patterns: &'static [&'static str],
142 matchers: Vec<globset::GlobMatcher>,
143}
144
145#[derive(Default)]
146struct PluginConfigMatcherCache {
147 by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
148}
149
150impl PluginConfigMatcherCache {
151 fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
152 let patterns = plugin.config_patterns();
153 let cached = self
154 .by_name
155 .read()
156 .unwrap_or_else(std::sync::PoisonError::into_inner)
157 .get(plugin.name())
158 .and_then(|variants| {
159 variants
160 .iter()
161 .find(|entry| entry.patterns == patterns)
162 .map(|entry| entry.matchers.clone())
163 });
164 if let Some(matchers) = cached {
165 return matchers;
166 }
167
168 let matchers = compile_plugin_config_matchers(plugin);
169 {
170 let mut by_name = self
171 .by_name
172 .write()
173 .unwrap_or_else(std::sync::PoisonError::into_inner);
174 let variants = by_name.entry(plugin.name()).or_default();
175 if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
176 return entry.matchers.clone();
177 }
178 variants.push(CachedPluginConfigMatchers {
179 patterns,
180 matchers: matchers.clone(),
181 });
182 drop(by_name);
183 }
184 matchers
185 }
186}
187
188fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
189 static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
190 MATCHERS
191 .get_or_init(PluginConfigMatcherCache::default)
192 .get_or_compile(plugin)
193}
194
195fn log_active_plugins(active: &[&dyn Plugin]) {
197 tracing::info!(
198 plugins = active
199 .iter()
200 .map(|p| p.name())
201 .collect::<Vec<_>>()
202 .join(", "),
203 "active plugins"
204 );
205}
206
207fn compute_relative_files(
211 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
212 active: &[&dyn Plugin],
213 discovered_files: &[PathBuf],
214 root: &Path,
215) -> Vec<(PathBuf, String)> {
216 use rayon::prelude::*;
217 let needs_relative_files =
218 !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
219 if !needs_relative_files {
220 return Vec::new();
221 }
222 discovered_files
223 .par_iter()
224 .map(|f| {
225 let rel = f
226 .strip_prefix(root)
227 .unwrap_or(f)
228 .to_string_lossy()
229 .into_owned();
230 (f.clone(), rel)
231 })
232 .collect()
233}
234
235pub struct PluginRegistry {
237 plugins: Vec<Box<dyn Plugin>>,
238 external_plugins: Vec<ExternalPluginDef>,
239}
240
241pub(crate) struct RootPluginContext<'a> {
243 pub(crate) active_plugins: FxHashSet<&'a str>,
245 pub(crate) dependencies: Vec<String>,
247}
248
249impl<'a> RootPluginContext<'a> {
250 pub(crate) fn new(root_pkg: Option<&PackageJson>, active_plugins: &'a [String]) -> Self {
251 Self {
252 active_plugins: active_plugins.iter().map(String::as_str).collect(),
253 dependencies: root_pkg.map_or_else(Vec::new, PackageJson::all_dependency_names),
254 }
255 }
256}
257
258pub(crate) struct WorkspacePluginRunInput<'a> {
260 pub(crate) pkg: &'a PackageJson,
261 pub(crate) root: &'a Path,
262 pub(crate) project_root: &'a Path,
263 pub(crate) root_dependencies: &'a [String],
267 pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
268 pub(crate) relative_files: &'a [(PathBuf, String)],
269 pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
270 pub(crate) production_mode: bool,
271 pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
272}
273
274struct PluginRunContext<'a> {
275 all_deps: Vec<String>,
276 active: Vec<&'a dyn Plugin>,
277}
278
279struct PluginActivationInput<'a> {
281 pkg: &'a PackageJson,
282 root: &'a Path,
283 discovered_files: &'a [PathBuf],
284 all_deps: &'a [String],
285 script_packages: &'a FxHashSet<String>,
286 candidate_index: Option<&'a ConfigCandidateIndex>,
287}
288
289#[derive(Debug, Clone, PartialEq, Eq)]
291pub struct PluginRegexValidationError {
292 plugin_name: String,
293 config_path: Option<PathBuf>,
294 rule_kind: &'static str,
295 field: &'static str,
296 rule_pattern: String,
297 regex_pattern: String,
298 source: String,
299}
300
301impl PluginRegexValidationError {
302 fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
303 Self {
304 plugin_name: input.plugin_name.to_owned(),
305 config_path: input.config_path.map(Path::to_path_buf),
306 rule_kind: input.rule_kind,
307 field: input.field,
308 rule_pattern: input.rule_pattern.to_owned(),
309 regex_pattern: input.regex_pattern.to_owned(),
310 source: input.source.to_string(),
311 }
312 }
313}
314
315#[derive(Clone, Copy)]
316struct PluginRegexValidationErrorInput<'a> {
317 plugin_name: &'a str,
318 config_path: Option<&'a Path>,
319 rule_kind: &'static str,
320 field: &'static str,
321 rule_pattern: &'a str,
322 regex_pattern: &'a str,
323 source: &'a regex::Error,
324}
325
326impl fmt::Display for PluginRegexValidationError {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 let location = self
329 .config_path
330 .as_ref()
331 .map(|path| format!(" in {}", path.display()))
332 .unwrap_or_default();
333 write!(
334 f,
335 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
336 self.plugin_name,
337 location,
338 self.regex_pattern,
339 self.rule_kind,
340 self.field,
341 self.rule_pattern,
342 self.source
343 )
344 }
345}
346
347#[must_use]
348pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
349 let joined = errors
350 .iter()
351 .map(ToString::to_string)
352 .collect::<Vec<_>>()
353 .join("\n - ");
354 format!(
355 "invalid plugin regex configuration:\n - {joined}\n\nRewrite the plugin config with Rust-compatible regex syntax, or remove unsupported constructs such as JavaScript lookahead and lookbehind."
356 )
357}
358
359#[derive(Debug, Clone, Default, PartialEq, Eq)]
367pub struct PluginToolingDependencies {
368 pub plugin: String,
370 pub dependencies: Vec<String>,
372 pub references: Vec<String>,
376 pub own_config: Option<PathBuf>,
379}
380
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub enum PluginToolingEvidence<'a> {
384 OwnConfig(&'a Path),
386 Reference(&'a str),
388}
389
390impl PluginToolingDependencies {
391 #[must_use]
395 pub fn evidence<'a>(
396 &'a self,
397 script_used_packages: &FxHashSet<String>,
398 ) -> Option<PluginToolingEvidence<'a>> {
399 if let Some(config) = &self.own_config {
400 return Some(PluginToolingEvidence::OwnConfig(config));
401 }
402 self.references
403 .iter()
404 .find(|name| script_used_packages.contains(name.as_str()))
405 .map(|name| PluginToolingEvidence::Reference(name))
406 }
407}
408
409#[derive(Debug, Clone, PartialEq, Eq)]
411pub struct CheckedAliasPrefix {
412 pub scope: String,
416 pub prefix: String,
418}
419
420impl CheckedAliasPrefix {
421 #[must_use]
423 pub fn covers(&self, root: &Path, from_file: &Path, specifier: &str) -> bool {
424 specifier.starts_with(&self.prefix)
425 && (self.scope.is_empty() || from_file.starts_with(root.join(&self.scope)))
426 }
427}
428
429#[derive(Debug, Clone, Default)]
431pub struct AggregatedPluginResult {
432 pub entry_patterns: Vec<(PathRule, String)>,
434 pub replaced_entry_plugins: FxHashSet<String>,
439 pub config_entry_patterns: FxHashSet<(String, String)>,
443 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
445 pub config_patterns: Vec<String>,
447 pub always_used: Vec<(String, String)>,
449 pub used_exports: Vec<PluginUsedExportRule>,
451 pub config_export_credits: Vec<PluginUsedExportRule>,
459 pub used_class_members: Vec<UsedClassMemberRule>,
463 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
465 pub referenced_dependencies: Vec<String>,
467 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
469 pub required_dependencies: Vec<super::RequiredDependency>,
471 pub discovered_always_used: Vec<(String, String)>,
473 pub setup_files: Vec<(PathBuf, String)>,
475 pub tooling_dependencies: Vec<String>,
479 pub plugin_tooling: Vec<PluginToolingDependencies>,
483 pub script_used_packages: FxHashSet<String>,
485 pub dependency_binaries: crate::scripts::DependencyBinaries,
489 pub dev_dependency_names: FxHashSet<String>,
494 pub virtual_module_prefixes: Vec<String>,
497 pub virtual_package_suffixes: Vec<String>,
500 pub generated_import_patterns: Vec<String>,
503 pub generated_type_import_prefixes: Vec<String>,
506 pub virtual_module_providers: Vec<VirtualModuleProviderRule>,
511 pub path_aliases: Vec<(String, String)>,
514 pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
519 pub checked_alias_prefixes: Vec<CheckedAliasPrefix>,
523 pub auto_imports: Vec<AutoImportRule>,
527 pub active_plugins: Vec<String>,
529 pub active_plugin_scopes: Vec<(String, String)>,
533 pub fixture_patterns: Vec<(String, String)>,
535 pub scss_include_paths: Vec<PathBuf>,
540 pub static_dir_mappings: Vec<(PathBuf, String)>,
542 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
545 pub provided_dependencies: Vec<ProvidedDependencyRule>,
547 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
551 pub federation_sources: Vec<super::FederationSource>,
554 pub jsx_import_sources: Vec<JsxImportSourceRule>,
558 pub jsx_package_credits: Vec<JsxImportSourceRule>,
563 pub tsconfig_jsx_dirs: Vec<TsconfigJsxDir>,
566 pub web_server_app_dirs: Vec<PathBuf>,
571}
572
573#[derive(Debug, Clone, PartialEq, Eq)]
576pub struct TsconfigJsxDir {
577 pub dir: PathBuf,
579 pub automatic_react: bool,
584}
585
586fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
591 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
592 for item in incoming {
593 if seen.insert(item.clone()) {
594 target.push(item);
595 }
596 }
597}
598
599fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
602 for item in incoming {
603 if !target.contains(&item) {
604 target.push(item);
605 }
606 }
607}
608
609fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
613 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
614 pat.to_string()
615 } else {
616 format!("{ws_prefix}/{pat}")
617 }
618}
619
620impl AggregatedPluginResult {
621 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
627 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
628 self.entry_patterns
629 .iter()
630 .filter(move |entry| seen.insert(entry))
631 }
632
633 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
649 for (rule, _) in &mut self.entry_patterns {
650 *rule = rule.prefixed(ws_prefix);
651 }
652 for (pat, _) in &mut self.always_used {
653 *pat = prefix_if_needed(pat, ws_prefix);
654 }
655 for (pat, _) in &mut self.discovered_always_used {
656 *pat = prefix_if_needed(pat, ws_prefix);
657 }
658 for (pat, _) in &mut self.fixture_patterns {
659 *pat = prefix_if_needed(pat, ws_prefix);
660 }
661 for rule in &mut self.used_exports {
662 *rule = rule.prefixed(ws_prefix);
663 }
664 for (_, scope) in &mut self.active_plugin_scopes {
665 *scope = ws_prefix.to_string();
666 }
667 for rule in &mut self.virtual_module_providers {
668 rule.scope = ws_prefix.to_string();
669 }
670 for rule in &mut self.config_export_credits {
671 *rule = rule.prefixed(ws_prefix);
672 }
673 for rule in &mut self.provided_dependencies {
674 *rule = rule.prefixed(ws_prefix);
675 }
676 for source in &mut self.federation_sources {
677 *source = source.prefixed(ws_prefix);
678 }
679 if !ws_prefix.is_empty() {
680 for checked in &mut self.checked_alias_prefixes {
681 checked.scope = ws_prefix.to_string();
682 }
683 self.scoped_path_aliases
684 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
685 fallow_graph::resolve::ScopedPathAlias {
686 scope: ws_prefix.to_string(),
687 prefix,
688 replacement: if replacement.is_empty() {
689 ws_prefix.to_string()
690 } else {
691 format!("{ws_prefix}/{replacement}")
692 },
693 }
694 }));
695 }
696 }
697
698 pub(crate) fn merge_into(&mut self, other: Self) {
712 let Self {
713 entry_patterns,
714 replaced_entry_plugins: _,
716 config_entry_patterns: _,
717 entry_point_roles,
718 config_patterns,
719 always_used,
720 used_exports,
721 config_export_credits,
722 used_class_members,
723 framework_class_member_contracts,
724 referenced_dependencies,
725 package_referenced_dependencies,
726 required_dependencies,
727 discovered_always_used,
728 setup_files,
729 tooling_dependencies,
730 plugin_tooling,
731 script_used_packages,
732 dependency_binaries: _,
733 dev_dependency_names,
734 virtual_module_prefixes,
735 virtual_package_suffixes,
736 generated_import_patterns,
737 generated_type_import_prefixes,
738 virtual_module_providers,
739 path_aliases,
740 scoped_path_aliases,
741 checked_alias_prefixes,
742 auto_imports,
743 active_plugins,
744 active_plugin_scopes,
745 fixture_patterns,
746 scss_include_paths,
747 static_dir_mappings,
748 framework_static_dir_mappings,
749 provided_dependencies,
750 config_diagnostics,
751 federation_sources,
752 jsx_import_sources,
753 jsx_package_credits,
754 tsconfig_jsx_dirs,
755 web_server_app_dirs,
756 } = other;
757
758 self.entry_patterns.extend(entry_patterns);
759 for (plugin_name, role) in entry_point_roles {
760 self.entry_point_roles.entry(plugin_name).or_insert(role);
761 }
762 self.config_patterns.extend(config_patterns);
763 self.always_used.extend(always_used);
764 self.used_exports.extend(used_exports);
765 self.config_export_credits.extend(config_export_credits);
766 self.used_class_members.extend(used_class_members);
767 for contract in framework_class_member_contracts {
768 if !self.framework_class_member_contracts.contains(&contract) {
769 self.framework_class_member_contracts.push(contract);
770 }
771 }
772 self.referenced_dependencies.extend(referenced_dependencies);
773 self.package_referenced_dependencies
774 .extend(package_referenced_dependencies);
775 push_missing(&mut self.required_dependencies, required_dependencies);
776 self.discovered_always_used.extend(discovered_always_used);
777 self.setup_files.extend(setup_files);
778 self.tooling_dependencies.extend(tooling_dependencies);
779 self.plugin_tooling.extend(plugin_tooling);
780 self.dev_dependency_names.extend(dev_dependency_names);
781 self.script_used_packages.extend(script_used_packages);
782 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
783 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
784 extend_unique(
785 &mut self.generated_import_patterns,
786 generated_import_patterns,
787 );
788 extend_unique(
789 &mut self.generated_type_import_prefixes,
790 generated_type_import_prefixes,
791 );
792 push_missing(&mut self.virtual_module_providers, virtual_module_providers);
793 self.path_aliases.extend(path_aliases);
794 self.scoped_path_aliases.extend(scoped_path_aliases);
795 push_missing(&mut self.checked_alias_prefixes, checked_alias_prefixes);
796 self.auto_imports.extend(auto_imports);
797 extend_unique(&mut self.active_plugins, active_plugins);
798 push_missing(&mut self.active_plugin_scopes, active_plugin_scopes);
799 self.fixture_patterns.extend(fixture_patterns);
800 self.scss_include_paths.extend(scss_include_paths);
801 self.static_dir_mappings.extend(static_dir_mappings);
802 self.framework_static_dir_mappings
803 .extend(framework_static_dir_mappings);
804 self.provided_dependencies.extend(provided_dependencies);
805 self.federation_sources.extend(federation_sources);
806 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
807 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
808 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
809 push_missing(&mut self.web_server_app_dirs, web_server_app_dirs);
810 push_missing(&mut self.config_diagnostics, config_diagnostics);
811 }
812}
813
814impl PluginRegistry {
815 #[must_use]
817 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
818 Self {
819 plugins: builtin::create_builtin_plugins(),
820 external_plugins: external,
821 }
822 }
823
824 #[must_use]
828 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
829 super::bun::preload_files(root)
830 }
831
832 #[must_use]
837 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
838 let all_deps = pkg.all_dependency_names();
839 let mut seen = FxHashSet::default();
840 let mut dirs = Vec::new();
841
842 for plugin in &self.plugins {
843 if !plugin.is_enabled_with_deps(&all_deps, root) {
844 continue;
845 }
846 for dir in plugin.discovery_hidden_dirs() {
847 if seen.insert(*dir) {
848 dirs.push((*dir).to_string());
849 }
850 }
851 }
852
853 dirs
854 }
855
856 #[cfg(test)]
861 fn run(
862 &self,
863 pkg: &PackageJson,
864 root: &Path,
865 discovered_files: &[PathBuf],
866 ) -> AggregatedPluginResult {
867 self.try_run(pkg, root, discovered_files)
868 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
869 }
870
871 pub fn try_run(
873 &self,
874 pkg: &PackageJson,
875 root: &Path,
876 discovered_files: &[PathBuf],
877 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
878 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
879 }
880
881 #[expect(
884 clippy::too_many_arguments,
885 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
886 )]
887 pub(crate) fn try_run_with_search_roots(
888 &self,
889 pkg: &PackageJson,
890 root: &Path,
891 discovered_files: &[PathBuf],
892 config_search_roots: &[&Path],
893 production_mode: bool,
894 candidate_index: Option<&ConfigCandidateIndex>,
895 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
896 let _span = tracing::info_span!("run_plugins").entered();
897 let mut result = AggregatedPluginResult::default();
898 let mut regex_errors = Vec::new();
899
900 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
901 pkg,
902 root,
903 discovered_files,
904 production_mode,
905 candidate_index,
906 );
907
908 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
909
910 for plugin in &active {
911 process_static_patterns(*plugin, root, &mut result);
912 }
913 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
914
915 process_external_plugins(
916 &self.external_plugins,
917 &all_deps,
918 root,
919 discovered_files,
920 &mut result,
921 );
922 tooling_evidence::record_plugin_tooling(
923 &tooling_evidence::ToolingEvidenceInput {
924 active: &active,
925 external_plugins: &self.external_plugins,
926 all_deps: &all_deps,
927 roots: &[root],
928 extra_roots: if production_mode {
932 &[]
933 } else {
934 config_search_roots
935 },
936 candidate_index,
937 discovered_files,
938 },
939 &mut result,
940 );
941
942 let config_matchers = compile_config_matchers(&active);
943 let relative_files =
944 compute_relative_files(&config_matchers, &active, discovered_files, root);
945
946 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
947 config_matchers: &config_matchers,
948 relative_files: &relative_files,
949 config_search_roots,
950 production_mode,
951 candidate_index,
952 root,
953 result: &mut result,
954 regex_errors: &mut regex_errors,
955 });
956
957 process_package_json_inline_configs(
958 &InlineConfigInput {
959 active: &active,
960 config_matchers: &config_matchers,
961 relative_files: &relative_files,
962 pkg,
963 root,
964 project_root: root,
965 },
966 &mut result,
967 &mut regex_errors,
968 );
969
970 if regex_errors.is_empty() {
971 Ok(result)
972 } else {
973 Err(regex_errors)
974 }
975 }
976
977 #[cfg(test)]
982 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
983 self.try_run_workspace_fast(input)
984 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
985 }
986
987 pub(crate) fn try_run_workspace_fast(
994 &self,
995 input: &WorkspacePluginRunInput<'_>,
996 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
997 let _span = tracing::info_span!("run_plugins").entered();
998 let mut result = AggregatedPluginResult::default();
999 let mut regex_errors = Vec::new();
1000
1001 let (all_deps, script_packages) = workspace_activation_deps(
1002 input.pkg,
1003 (input.root, input.project_root),
1004 input.root_dependencies,
1005 input.production_mode,
1006 );
1007 let workspace_files: Vec<PathBuf> = input
1008 .relative_files
1009 .iter()
1010 .map(|(abs_path, _)| abs_path.clone())
1011 .collect();
1012
1013 let active = self.collect_active_plugins(&PluginActivationInput {
1014 pkg: input.pkg,
1015 root: input.root,
1016 discovered_files: &workspace_files,
1017 all_deps: &all_deps,
1018 script_packages: &script_packages,
1019 candidate_index: input.candidate_index,
1020 });
1021
1022 log_active_plugins(&active);
1023
1024 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
1025
1026 process_external_plugins(
1027 &self.external_plugins,
1028 &all_deps,
1029 input.root,
1030 &workspace_files,
1031 &mut result,
1032 );
1033
1034 if active.is_empty() && result.active_plugins.is_empty() {
1035 return Ok(result);
1036 }
1037
1038 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
1039 let evidence_roots: &[&Path] = if input.root == input.project_root {
1041 &[input.root]
1042 } else {
1043 &[input.root, input.project_root]
1044 };
1045 tooling_evidence::record_plugin_tooling(
1046 &tooling_evidence::ToolingEvidenceInput {
1047 active: &active,
1048 external_plugins: &self.external_plugins,
1049 all_deps: &all_deps,
1050 roots: evidence_roots,
1051 extra_roots: &[],
1052 candidate_index: input.candidate_index,
1053 discovered_files: &workspace_files,
1054 },
1055 &mut result,
1056 );
1057 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
1058 if input.root != input.project_root {
1060 process_package_json_inline_configs(
1061 &InlineConfigInput {
1062 active: &active,
1063 config_matchers: input.precompiled_config_matchers,
1064 relative_files: input.relative_files,
1065 pkg: input.pkg,
1066 root: input.root,
1067 project_root: input.project_root,
1068 },
1069 &mut result,
1070 &mut regex_errors,
1071 );
1072 }
1073
1074 if regex_errors.is_empty() {
1075 Ok(result)
1076 } else {
1077 Err(regex_errors)
1078 }
1079 }
1080
1081 #[must_use]
1084 pub(crate) fn precompile_config_matchers(
1085 &self,
1086 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
1087 self.plugins
1088 .iter()
1089 .filter(|p| !p.config_patterns().is_empty())
1090 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
1091 .collect()
1092 }
1093
1094 pub(crate) fn resolve_script_config_files(
1105 &self,
1106 config_files: &[scripts::BinaryConfigFile],
1107 package_root: &Path,
1108 project_root: &Path,
1109 ws_prefix: &str,
1110 ) -> AggregatedPluginResult {
1111 let mut aggregated = AggregatedPluginResult::default();
1112 for config_file in config_files {
1113 let Some(rel_path) =
1114 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
1115 else {
1116 continue;
1117 };
1118 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1119 let in_package_root = abs_path.parent() == Some(package_root);
1124 let binary = config_file
1127 .binary
1128 .rsplit('/')
1129 .next()
1130 .unwrap_or(&config_file.binary);
1131 for plugin in &self.plugins {
1132 let plugin = plugin.as_ref();
1133 if !plugin.script_config_binaries().contains(&binary)
1134 || (in_package_root
1135 && cached_plugin_config_matchers(plugin)
1136 .iter()
1137 .any(|m| m.is_match(rel_path.as_str())))
1138 {
1139 continue;
1140 }
1141 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1142 continue;
1143 }
1144 let Some(source) = project_read::read_project_file(project_root, &abs_path) else {
1145 continue;
1146 };
1147 let mut file_result = AggregatedPluginResult::default();
1148 file_result
1149 .entry_point_roles
1150 .insert(plugin.name().to_string(), plugin.entry_point_role());
1151 let plugin_result =
1152 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1153 if let Err(errors) = process_config_result(
1154 plugin.name(),
1155 plugin_result,
1156 &mut file_result,
1157 Some(&abs_path),
1158 ) {
1159 for error in errors {
1160 tracing::warn!("{error}");
1161 }
1162 continue;
1163 }
1164 if !ws_prefix.is_empty() {
1165 file_result.apply_workspace_prefix(ws_prefix);
1166 }
1167 file_result.used_exports.push(PluginUsedExportRule::new(
1169 plugin.name().to_string(),
1170 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1171 ));
1172 aggregated.merge_into(file_result);
1173 }
1174 }
1175 aggregated
1176 }
1177}
1178
1179fn process_workspace_active_plugins(
1180 active: &[&dyn Plugin],
1181 input: &WorkspacePluginRunInput<'_>,
1182 result: &mut AggregatedPluginResult,
1183 regex_errors: &mut Vec<PluginRegexValidationError>,
1184) {
1185 for plugin in active {
1186 process_static_patterns(*plugin, input.root, result);
1187 }
1188 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1189}
1190
1191fn resolve_workspace_plugin_configs(
1192 active: &[&dyn Plugin],
1193 input: &WorkspacePluginRunInput<'_>,
1194 result: &mut AggregatedPluginResult,
1195 regex_errors: &mut Vec<PluginRegexValidationError>,
1196) {
1197 let workspace_matchers = select_workspace_matchers(
1198 input.precompiled_config_matchers,
1199 active,
1200 input.skip_config_plugins,
1201 );
1202
1203 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1204 for (plugin, matchers) in &workspace_matchers {
1205 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1206 plugin: *plugin,
1207 matchers,
1208 relative_files: input.relative_files,
1209 root: input.root,
1210 project_root: input.project_root,
1211 result,
1212 regex_errors,
1213 resolved_plugins: &mut resolved_ws_plugins,
1214 });
1215 }
1216
1217 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1218 workspace_matchers: &workspace_matchers,
1219 resolved_ws_plugins: &resolved_ws_plugins,
1220 root: input.root,
1221 project_root: input.project_root,
1222 production_mode: input.production_mode,
1223 candidate_index: input.candidate_index,
1224 result,
1225 regex_errors,
1226 });
1227}
1228
1229impl Default for PluginRegistry {
1230 fn default() -> Self {
1231 Self::new(vec![])
1232 }
1233}
1234
1235impl PluginRegistry {
1236 fn prepare_plugin_run_context<'a>(
1237 &'a self,
1238 pkg: &PackageJson,
1239 root: &Path,
1240 discovered_files: &[PathBuf],
1241 production_mode: bool,
1242 candidate_index: Option<&ConfigCandidateIndex>,
1243 ) -> PluginRunContext<'a> {
1244 let all_deps = pkg.all_dependency_names();
1245 let script_packages =
1246 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1247 let active = self.collect_active_plugins(&PluginActivationInput {
1248 pkg,
1249 root,
1250 discovered_files,
1251 all_deps: &all_deps,
1252 script_packages: &script_packages,
1253 candidate_index,
1254 });
1255
1256 PluginRunContext { all_deps, active }
1257 }
1258
1259 fn run_plugin_preflight(
1260 &self,
1261 active: &[&dyn Plugin],
1262 all_deps: &[String],
1263 root: &Path,
1264 discovered_files: &[PathBuf],
1265 ) {
1266 log_active_plugins(active);
1267 check_meta_framework_prerequisites(active, root);
1268 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1269 }
1270
1271 fn collect_active_plugins<'a>(
1274 &'a self,
1275 activation: &PluginActivationInput<'_>,
1276 ) -> Vec<&'a dyn Plugin> {
1277 self.plugins
1278 .iter()
1279 .filter(|p| {
1280 p.is_enabled_with_files(
1281 activation.all_deps,
1282 activation.root,
1283 activation.discovered_files,
1284 activation.candidate_index,
1285 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1286 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1287 })
1288 .map(AsRef::as_ref)
1289 .collect()
1290 }
1291
1292 fn emit_silent_fail_diagnostics(
1301 &self,
1302 active: &[&dyn Plugin],
1303 all_deps: &[String],
1304 root: &Path,
1305 discovered_files: &[PathBuf],
1306 ) {
1307 let active_external: Vec<&ExternalPluginDef> = self
1308 .external_plugins
1309 .iter()
1310 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1311 .collect();
1312 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1313 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1314 emit_plugin_diagnostics(&diagnostics);
1315 }
1316}
1317
1318fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1323 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1324 std::sync::OnceLock::new();
1325 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1326}
1327
1328struct PluginConfigResolutionInput<'a> {
1329 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1330 relative_files: &'a [(PathBuf, String)],
1331 config_search_roots: &'a [&'a Path],
1332 production_mode: bool,
1333 candidate_index: Option<&'a ConfigCandidateIndex>,
1334 root: &'a Path,
1335 result: &'a mut AggregatedPluginResult,
1336 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1337}
1338
1339fn select_workspace_matchers<'a>(
1342 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1343 active: &[&dyn Plugin],
1344 skip_config_plugins: &FxHashSet<&str>,
1345) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1346 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1347 precompiled_config_matchers
1348 .iter()
1349 .filter(|(p, _)| {
1350 active_names.contains(p.name())
1351 && (!skip_config_plugins.contains(p.name())
1352 || must_parse_workspace_config_when_root_active(p.name()))
1353 })
1354 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1355 .collect()
1356}
1357
1358struct WorkspaceFsConfigInput<'a> {
1359 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1360 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1361 root: &'a Path,
1362 project_root: &'a Path,
1363 production_mode: bool,
1364 candidate_index: Option<&'a ConfigCandidateIndex>,
1365 result: &'a mut AggregatedPluginResult,
1366 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1367}
1368
1369fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1372 let search_roots: &[&Path] = if input.root == input.project_root {
1373 &[input.root]
1374 } else {
1375 &[input.root, input.project_root]
1376 };
1377 let ws_json_configs = discover_config_files(
1378 input.workspace_matchers,
1379 input.resolved_ws_plugins,
1380 search_roots,
1381 input.production_mode,
1382 input.candidate_index,
1383 );
1384 for (abs_path, plugin) in &ws_json_configs {
1385 let Some(source) =
1386 crate::discover::project_read::read_project_file(input.project_root, abs_path)
1387 else {
1388 continue;
1389 };
1390 let plugin_result =
1391 crate::discover::project_read::with_project_root(input.project_root, || {
1392 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root)
1393 });
1394 if plugin_result.is_empty() {
1395 continue;
1396 }
1397 let rel = abs_path
1398 .strip_prefix(input.project_root)
1399 .map(|p| p.to_string_lossy())
1400 .unwrap_or_default();
1401 tracing::debug!(
1402 plugin = plugin.name(),
1403 config = %rel,
1404 entries = plugin_result.entry_patterns.len(),
1405 deps = plugin_result.referenced_dependencies.len(),
1406 "resolved config (workspace filesystem fallback)"
1407 );
1408 if let Err(mut errors) =
1409 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1410 {
1411 input.regex_errors.append(&mut errors);
1412 }
1413 }
1414}
1415
1416fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1417 if input.config_matchers.is_empty() {
1418 return;
1419 }
1420
1421 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1422 for (plugin, matchers) in input.config_matchers {
1423 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1424 plugin: *plugin,
1425 matchers,
1426 relative_files: input.relative_files,
1427 root: input.root,
1428 project_root: input.root,
1429 result: input.result,
1430 regex_errors: input.regex_errors,
1431 resolved_plugins: &mut resolved_plugins,
1432 });
1433 }
1434
1435 let json_configs = discover_config_files(
1436 input.config_matchers,
1437 &resolved_plugins,
1438 input.config_search_roots,
1439 input.production_mode,
1440 input.candidate_index,
1441 );
1442 for (abs_path, plugin) in &json_configs {
1443 resolve_plugin_filesystem_config(
1444 *plugin,
1445 abs_path,
1446 input.root,
1447 input.result,
1448 input.regex_errors,
1449 );
1450 }
1451}
1452
1453struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1454 plugin: &'plugins dyn Plugin,
1455 matchers: &'data [globset::GlobMatcher],
1456 relative_files: &'data [(PathBuf, String)],
1457 root: &'data Path,
1458 project_root: &'data Path,
1459 result: &'state mut AggregatedPluginResult,
1460 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1461 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1462}
1463
1464fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1465 use rayon::prelude::*;
1466
1467 let plugin_hits: Vec<&PathBuf> = input
1468 .relative_files
1469 .par_iter()
1470 .filter_map(|(abs_path, rel_path)| {
1471 input
1472 .matchers
1473 .iter()
1474 .any(|m| m.is_match(rel_path.as_str()))
1475 .then_some(abs_path)
1476 })
1477 .collect();
1478 for abs_path in plugin_hits {
1479 let Some(source) =
1480 crate::discover::project_read::read_project_file(input.project_root, abs_path)
1481 else {
1482 continue;
1483 };
1484 let plugin_result =
1485 crate::discover::project_read::with_project_root(input.project_root, || {
1486 input.plugin.resolve_config_in_project(
1487 abs_path,
1488 &source,
1489 input.root,
1490 input.project_root,
1491 )
1492 });
1493 if plugin_result.is_empty() {
1494 continue;
1495 }
1496 input.resolved_plugins.insert(input.plugin.name());
1497 process_resolved_plugin_config(ResolvedPluginConfigInput {
1498 plugin: input.plugin,
1499 abs_path,
1500 plugin_result,
1501 result: input.result,
1502 regex_errors: input.regex_errors,
1503 message: "resolved config",
1504 config_display: abs_path.display(),
1505 });
1506 }
1507}
1508
1509fn resolve_plugin_filesystem_config(
1510 plugin: &dyn Plugin,
1511 abs_path: &Path,
1512 root: &Path,
1513 result: &mut AggregatedPluginResult,
1514 regex_errors: &mut Vec<PluginRegexValidationError>,
1515) {
1516 let Some(source) = crate::discover::project_read::read_project_file(root, abs_path) else {
1517 return;
1518 };
1519 let plugin_result = crate::discover::project_read::with_project_root(root, || {
1520 plugin.resolve_config(abs_path, &source, root)
1521 });
1522 if plugin_result.is_empty() {
1523 return;
1524 }
1525 let rel = abs_path
1526 .strip_prefix(root)
1527 .map(|p| p.to_string_lossy())
1528 .unwrap_or_default();
1529 process_resolved_plugin_config(ResolvedPluginConfigInput {
1530 plugin,
1531 abs_path,
1532 plugin_result,
1533 result,
1534 regex_errors,
1535 message: "resolved config (filesystem fallback)",
1536 config_display: rel,
1537 });
1538}
1539
1540struct ResolvedPluginConfigInput<'a, D> {
1541 plugin: &'a dyn Plugin,
1542 abs_path: &'a Path,
1543 plugin_result: PluginResult,
1544 result: &'a mut AggregatedPluginResult,
1545 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1546 message: &'static str,
1547 config_display: D,
1548}
1549
1550fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1551 tracing::debug!(
1552 plugin = input.plugin.name(),
1553 config = %input.config_display,
1554 entries = input.plugin_result.entry_patterns.len(),
1555 deps = input.plugin_result.referenced_dependencies.len(),
1556 input.message
1557 );
1558 if let Err(mut errors) = process_config_result(
1559 input.plugin.name(),
1560 input.plugin_result,
1561 input.result,
1562 Some(input.abs_path),
1563 ) {
1564 input.regex_errors.append(&mut errors);
1565 }
1566}
1567
1568fn should_warn(key: String) -> bool {
1572 plugin_warn_dedupe()
1573 .lock()
1574 .map_or(true, |mut set| set.insert(key))
1575}
1576fn process_package_json_inline_configs(
1588 input: &InlineConfigInput<'_>,
1589 result: &mut AggregatedPluginResult,
1590 regex_errors: &mut Vec<PluginRegexValidationError>,
1591) {
1592 let pkg_path = input.root.join("package.json");
1593 let credited_manifests: Vec<PathBuf> = if input.root == input.project_root {
1594 Vec::new()
1595 } else {
1596 input
1597 .root
1598 .ancestors()
1599 .take_while(|dir| dir.starts_with(input.project_root))
1600 .map(|dir| dir.join("package.json"))
1601 .collect()
1602 };
1603 for plugin in input.active {
1604 let Some(key) = plugin.package_json_config_key() else {
1605 continue;
1606 };
1607 let Some(config_value) = input.pkg.inline_tool_config(key) else {
1608 continue;
1609 };
1610 if check_has_config_file(*plugin, input.config_matchers, input.relative_files) {
1611 continue;
1612 }
1613 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1614 let fake_path = input.root.join(format!("{key}.config.json"));
1615 let mut plugin_result =
1616 crate::discover::project_read::with_project_root(input.project_root, || {
1617 plugin.resolve_config_in_project(
1618 &fake_path,
1619 &config_json,
1620 input.root,
1621 input.project_root,
1622 )
1623 });
1624 if plugin_result.is_empty() {
1625 continue;
1626 }
1627 tracing::debug!(
1628 plugin = plugin.name(),
1629 key = key,
1630 "resolved inline package.json config"
1631 );
1632 if !credited_manifests.is_empty() {
1633 for dep in std::mem::take(&mut plugin_result.referenced_dependencies) {
1634 plugin_result.package_referenced_dependencies.extend(
1635 credited_manifests
1636 .iter()
1637 .map(|manifest| (manifest.clone(), dep.clone())),
1638 );
1639 }
1640 }
1641 if let Err(mut errors) =
1642 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1643 {
1644 regex_errors.append(&mut errors);
1645 }
1646 }
1647}
1648
1649struct InlineConfigInput<'a> {
1651 active: &'a [&'a dyn Plugin],
1652 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1653 relative_files: &'a [(PathBuf, String)],
1654 pkg: &'a PackageJson,
1655 root: &'a Path,
1656 project_root: &'a Path,
1657}
1658
1659#[derive(Debug)]
1662struct MetaFrameworkWarning {
1663 dedupe_key: &'static str,
1664 message: &'static str,
1665}
1666
1667fn missing_meta_framework_prerequisites(
1677 active_plugins: &[&dyn Plugin],
1678 root: &Path,
1679) -> Vec<MetaFrameworkWarning> {
1680 active_plugins
1681 .iter()
1682 .filter_map(|plugin| match plugin.name() {
1683 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1684 dedupe_key: "meta-prereq::nuxt",
1685 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1686 before fallow for accurate analysis",
1687 }),
1688 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1689 dedupe_key: "meta-prereq::astro",
1690 message: "Astro project missing .astro/ types: run `astro sync` \
1691 before fallow for accurate analysis",
1692 }),
1693 _ => None,
1694 })
1695 .collect()
1696}
1697
1698fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1708 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1709 if should_warn(warning.dedupe_key.to_owned()) {
1710 tracing::warn!("{}", warning.message);
1711 }
1712 }
1713}
1714
1715fn workspace_activation_deps(
1724 pkg: &PackageJson,
1725 (root, project_root): (&Path, &Path),
1726 root_dependencies: &[String],
1727 production_mode: bool,
1728) -> (Vec<String>, FxHashSet<String>) {
1729 let mut deps = pkg.all_dependency_names();
1730 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1731 let hoisted: Vec<String> = root_dependencies
1732 .iter()
1733 .filter(|dep| !own.contains(dep.as_str()))
1734 .cloned()
1735 .collect();
1736 let mut script_deps = deps.clone();
1737 script_deps.extend(hoisted.iter().cloned());
1738 let script_packages = script_activation_packages(
1739 pkg,
1740 root,
1741 &[root, project_root],
1742 &script_deps,
1743 production_mode,
1744 );
1745 deps.extend(
1746 hoisted
1747 .into_iter()
1748 .filter(|dep| script_packages.contains(dep)),
1749 );
1750 (deps, script_packages)
1751}
1752
1753#[must_use]
1757pub fn workspace_activation_dependencies(
1758 pkg: &PackageJson,
1759 root: &Path,
1760 project_root: &Path,
1761 root_dependencies: &[String],
1762 production_mode: bool,
1763) -> Vec<String> {
1764 workspace_activation_deps(
1765 pkg,
1766 (root, project_root),
1767 root_dependencies,
1768 production_mode,
1769 )
1770 .0
1771}
1772
1773fn script_activation_packages(
1776 pkg: &PackageJson,
1777 root: &Path,
1778 node_modules_roots: &[&Path],
1779 all_deps: &[String],
1780 production_mode: bool,
1781) -> FxHashSet<String> {
1782 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1783 return FxHashSet::default();
1784 };
1785
1786 let scripts_to_analyze = if production_mode {
1787 scripts::filter_production_scripts(pkg_scripts)
1788 } else {
1789 pkg_scripts.clone()
1790 };
1791
1792 let mut nm_roots: Vec<&Path> = Vec::new();
1793 for nm_root in node_modules_roots {
1794 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1795 nm_roots.push(nm_root);
1796 }
1797 }
1798 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1799 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1800 let catalog =
1801 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1802
1803 scripts::analyze_scripts_with_dependency_context(
1804 &scripts_to_analyze,
1805 root,
1806 &bin_map,
1807 &dep_set,
1808 &catalog,
1809 scripts::IgnoredCommandEntries::NONE,
1810 )
1811 .used_packages
1812}
1813
1814#[cfg(test)]
1815mod entry_pattern_tests;
1816#[cfg(test)]
1817mod tests;