1use rustc_hash::FxHashSet;
13use std::path::{Path, PathBuf};
14
15use fallow_config::{ExternalPluginDef, PackageJson, PluginDetection};
16
17#[derive(Debug, Default)]
19pub struct PluginResult {
20 pub entry_patterns: Vec<String>,
22 pub referenced_dependencies: Vec<String>,
24 pub always_used_files: Vec<String>,
26 pub setup_files: Vec<PathBuf>,
28}
29
30impl PluginResult {
31 pub const fn is_empty(&self) -> bool {
32 self.entry_patterns.is_empty()
33 && self.referenced_dependencies.is_empty()
34 && self.always_used_files.is_empty()
35 && self.setup_files.is_empty()
36 }
37}
38
39pub trait Plugin: Send + Sync {
41 fn name(&self) -> &'static str;
43
44 fn enablers(&self) -> &'static [&'static str] {
47 &[]
48 }
49
50 fn is_enabled(&self, pkg: &PackageJson, root: &Path) -> bool {
53 let deps = pkg.all_dependency_names();
54 self.is_enabled_with_deps(&deps, root)
55 }
56
57 fn is_enabled_with_deps(&self, deps: &[String], _root: &Path) -> bool {
60 let enablers = self.enablers();
61 if enablers.is_empty() {
62 return false;
63 }
64 enablers.iter().any(|enabler| {
65 if enabler.ends_with('/') {
66 deps.iter().any(|d| d.starts_with(enabler))
68 } else {
69 deps.iter().any(|d| d == enabler)
70 }
71 })
72 }
73
74 fn entry_patterns(&self) -> &'static [&'static str] {
76 &[]
77 }
78
79 fn config_patterns(&self) -> &'static [&'static str] {
81 &[]
82 }
83
84 fn always_used(&self) -> &'static [&'static str] {
86 &[]
87 }
88
89 fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
91 vec![]
92 }
93
94 fn tooling_dependencies(&self) -> &'static [&'static str] {
97 &[]
98 }
99
100 fn virtual_module_prefixes(&self) -> &'static [&'static str] {
105 &[]
106 }
107
108 fn path_aliases(&self, _root: &Path) -> Vec<(&'static str, String)> {
118 vec![]
119 }
120
121 fn resolve_config(&self, _config_path: &Path, _source: &str, _root: &Path) -> PluginResult {
126 PluginResult::default()
127 }
128
129 fn package_json_config_key(&self) -> Option<&'static str> {
134 None
135 }
136}
137
138macro_rules! define_plugin {
173 (
174 struct $name:ident => $display:expr,
175 enablers: $enablers:expr
176 $(, entry_patterns: $entry:expr)?
177 $(, config_patterns: $config:expr)?
178 $(, always_used: $always:expr)?
179 $(, tooling_dependencies: $tooling:expr)?
180 $(, virtual_module_prefixes: $virtual:expr)?
181 $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
182 $(,)?
183 ) => {
184 pub struct $name;
185
186 impl Plugin for $name {
187 fn name(&self) -> &'static str {
188 $display
189 }
190
191 fn enablers(&self) -> &'static [&'static str] {
192 $enablers
193 }
194
195 $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
196 $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
197 $( fn always_used(&self) -> &'static [&'static str] { $always } )?
198 $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
199 $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
200
201 $(
202 fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
203 vec![$( ($pat, $exports) ),*]
204 }
205 )?
206 }
207 };
208}
209
210pub mod config_parser;
211mod tooling;
212
213pub use tooling::is_known_tooling_dependency;
214
215mod angular;
216mod astro;
217mod ava;
218mod babel;
219mod biome;
220mod bun;
221mod c8;
222mod capacitor;
223mod changesets;
224mod commitizen;
225mod commitlint;
226mod cspell;
227mod cucumber;
228mod cypress;
229mod dependency_cruiser;
230mod docusaurus;
231mod drizzle;
232mod electron;
233mod eslint;
234mod expo;
235mod gatsby;
236mod graphql_codegen;
237mod husky;
238mod i18next;
239mod jest;
240mod karma;
241mod knex;
242mod kysely;
243mod lefthook;
244mod lint_staged;
245mod markdownlint;
246mod mocha;
247mod msw;
248mod nestjs;
249mod next_intl;
250mod nextjs;
251mod nitro;
252mod nodemon;
253mod nuxt;
254mod nx;
255mod nyc;
256mod openapi_ts;
257mod oxlint;
258mod parcel;
259mod playwright;
260mod plop;
261mod pm2;
262mod postcss;
263mod prettier;
264mod prisma;
265mod react_native;
266mod react_router;
267mod relay;
268mod remark;
269mod remix;
270mod rolldown;
271mod rollup;
272mod rsbuild;
273mod rspack;
274mod sanity;
275mod semantic_release;
276mod sentry;
277mod simple_git_hooks;
278mod storybook;
279mod stylelint;
280mod sveltekit;
281mod svgo;
282mod svgr;
283mod swc;
284mod syncpack;
285mod tailwind;
286mod tanstack_router;
287mod tsdown;
288mod tsup;
289mod turborepo;
290mod typedoc;
291mod typeorm;
292mod typescript;
293mod vite;
294mod vitepress;
295mod vitest;
296mod webdriverio;
297mod webpack;
298mod wrangler;
299
300pub struct PluginRegistry {
302 plugins: Vec<Box<dyn Plugin>>,
303 external_plugins: Vec<ExternalPluginDef>,
304}
305
306#[derive(Debug, Default)]
308pub struct AggregatedPluginResult {
309 pub entry_patterns: Vec<String>,
311 pub config_patterns: Vec<String>,
313 pub always_used: Vec<String>,
315 pub used_exports: Vec<(String, Vec<String>)>,
317 pub referenced_dependencies: Vec<String>,
319 pub discovered_always_used: Vec<String>,
321 pub setup_files: Vec<PathBuf>,
323 pub tooling_dependencies: Vec<String>,
325 pub script_used_packages: FxHashSet<String>,
327 pub virtual_module_prefixes: Vec<String>,
330 pub path_aliases: Vec<(String, String)>,
333 pub active_plugins: Vec<String>,
335}
336
337impl PluginRegistry {
338 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
340 let plugins: Vec<Box<dyn Plugin>> = vec![
341 Box::new(nextjs::NextJsPlugin),
343 Box::new(nuxt::NuxtPlugin),
344 Box::new(remix::RemixPlugin),
345 Box::new(astro::AstroPlugin),
346 Box::new(angular::AngularPlugin),
347 Box::new(react_router::ReactRouterPlugin),
348 Box::new(tanstack_router::TanstackRouterPlugin),
349 Box::new(react_native::ReactNativePlugin),
350 Box::new(expo::ExpoPlugin),
351 Box::new(nestjs::NestJsPlugin),
352 Box::new(docusaurus::DocusaurusPlugin),
353 Box::new(gatsby::GatsbyPlugin),
354 Box::new(sveltekit::SvelteKitPlugin),
355 Box::new(nitro::NitroPlugin),
356 Box::new(capacitor::CapacitorPlugin),
357 Box::new(sanity::SanityPlugin),
358 Box::new(vitepress::VitePressPlugin),
359 Box::new(next_intl::NextIntlPlugin),
360 Box::new(relay::RelayPlugin),
361 Box::new(electron::ElectronPlugin),
362 Box::new(i18next::I18nextPlugin),
363 Box::new(vite::VitePlugin),
365 Box::new(webpack::WebpackPlugin),
366 Box::new(rollup::RollupPlugin),
367 Box::new(rolldown::RolldownPlugin),
368 Box::new(rspack::RspackPlugin),
369 Box::new(rsbuild::RsbuildPlugin),
370 Box::new(tsup::TsupPlugin),
371 Box::new(tsdown::TsdownPlugin),
372 Box::new(parcel::ParcelPlugin),
373 Box::new(vitest::VitestPlugin),
375 Box::new(jest::JestPlugin),
376 Box::new(playwright::PlaywrightPlugin),
377 Box::new(cypress::CypressPlugin),
378 Box::new(mocha::MochaPlugin),
379 Box::new(ava::AvaPlugin),
380 Box::new(storybook::StorybookPlugin),
381 Box::new(karma::KarmaPlugin),
382 Box::new(cucumber::CucumberPlugin),
383 Box::new(webdriverio::WebdriverioPlugin),
384 Box::new(eslint::EslintPlugin),
386 Box::new(biome::BiomePlugin),
387 Box::new(stylelint::StylelintPlugin),
388 Box::new(prettier::PrettierPlugin),
389 Box::new(oxlint::OxlintPlugin),
390 Box::new(markdownlint::MarkdownlintPlugin),
391 Box::new(cspell::CspellPlugin),
392 Box::new(remark::RemarkPlugin),
393 Box::new(typescript::TypeScriptPlugin),
395 Box::new(babel::BabelPlugin),
396 Box::new(swc::SwcPlugin),
397 Box::new(tailwind::TailwindPlugin),
399 Box::new(postcss::PostCssPlugin),
400 Box::new(prisma::PrismaPlugin),
402 Box::new(drizzle::DrizzlePlugin),
403 Box::new(knex::KnexPlugin),
404 Box::new(typeorm::TypeormPlugin),
405 Box::new(kysely::KyselyPlugin),
406 Box::new(turborepo::TurborepoPlugin),
408 Box::new(nx::NxPlugin),
409 Box::new(changesets::ChangesetsPlugin),
410 Box::new(syncpack::SyncpackPlugin),
411 Box::new(commitlint::CommitlintPlugin),
413 Box::new(commitizen::CommitizenPlugin),
414 Box::new(semantic_release::SemanticReleasePlugin),
415 Box::new(wrangler::WranglerPlugin),
417 Box::new(sentry::SentryPlugin),
418 Box::new(husky::HuskyPlugin),
420 Box::new(lint_staged::LintStagedPlugin),
421 Box::new(lefthook::LefthookPlugin),
422 Box::new(simple_git_hooks::SimpleGitHooksPlugin),
423 Box::new(svgo::SvgoPlugin),
425 Box::new(svgr::SvgrPlugin),
426 Box::new(graphql_codegen::GraphqlCodegenPlugin),
428 Box::new(typedoc::TypedocPlugin),
429 Box::new(openapi_ts::OpenapiTsPlugin),
430 Box::new(plop::PlopPlugin),
431 Box::new(c8::C8Plugin),
433 Box::new(nyc::NycPlugin),
434 Box::new(msw::MswPlugin),
436 Box::new(nodemon::NodemonPlugin),
437 Box::new(pm2::Pm2Plugin),
438 Box::new(dependency_cruiser::DependencyCruiserPlugin),
439 Box::new(bun::BunPlugin),
441 ];
442 Self {
443 plugins,
444 external_plugins: external,
445 }
446 }
447
448 #[expect(clippy::cognitive_complexity)] pub fn run(
454 &self,
455 pkg: &PackageJson,
456 root: &Path,
457 discovered_files: &[PathBuf],
458 ) -> AggregatedPluginResult {
459 let _span = tracing::info_span!("run_plugins").entered();
460 let mut result = AggregatedPluginResult::default();
461
462 let all_deps = pkg.all_dependency_names();
465 let active: Vec<&dyn Plugin> = self
466 .plugins
467 .iter()
468 .filter(|p| p.is_enabled_with_deps(&all_deps, root))
469 .map(|p| p.as_ref())
470 .collect();
471
472 tracing::info!(
473 plugins = active
474 .iter()
475 .map(|p| p.name())
476 .collect::<Vec<_>>()
477 .join(", "),
478 "active plugins"
479 );
480
481 for plugin in &active {
483 result.active_plugins.push(plugin.name().to_string());
484
485 for pat in plugin.entry_patterns() {
486 result.entry_patterns.push((*pat).to_string());
487 }
488 for pat in plugin.config_patterns() {
489 result.config_patterns.push((*pat).to_string());
490 }
491 for pat in plugin.always_used() {
492 result.always_used.push((*pat).to_string());
493 }
494 for (file_pat, exports) in plugin.used_exports() {
495 result.used_exports.push((
496 file_pat.to_string(),
497 exports.iter().map(|s| s.to_string()).collect(),
498 ));
499 }
500 for dep in plugin.tooling_dependencies() {
501 result.tooling_dependencies.push((*dep).to_string());
502 }
503 for prefix in plugin.virtual_module_prefixes() {
504 result.virtual_module_prefixes.push((*prefix).to_string());
505 }
506 for (prefix, replacement) in plugin.path_aliases(root) {
507 result.path_aliases.push((prefix.to_string(), replacement));
508 }
509 }
510
511 let all_dep_refs: Vec<&str> = all_deps.iter().map(|s| s.as_str()).collect();
514 for ext in &self.external_plugins {
515 let is_active = if let Some(detection) = &ext.detection {
516 check_plugin_detection(detection, &all_dep_refs, root, discovered_files)
517 } else if !ext.enablers.is_empty() {
518 ext.enablers.iter().any(|enabler| {
519 if enabler.ends_with('/') {
520 all_deps.iter().any(|d| d.starts_with(enabler))
521 } else {
522 all_deps.iter().any(|d| d == enabler)
523 }
524 })
525 } else {
526 false
527 };
528 if is_active {
529 result.active_plugins.push(ext.name.clone());
530 result.entry_patterns.extend(ext.entry_points.clone());
531 result.config_patterns.extend(ext.config_patterns.clone());
534 result.always_used.extend(ext.config_patterns.clone());
535 result.always_used.extend(ext.always_used.clone());
536 result
537 .tooling_dependencies
538 .extend(ext.tooling_dependencies.clone());
539 for ue in &ext.used_exports {
540 result
541 .used_exports
542 .push((ue.pattern.clone(), ue.exports.clone()));
543 }
544 }
545 }
546
547 let config_matchers: Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> = active
550 .iter()
551 .filter(|p| !p.config_patterns().is_empty())
552 .map(|p| {
553 let matchers: Vec<globset::GlobMatcher> = p
554 .config_patterns()
555 .iter()
556 .filter_map(|pat| globset::Glob::new(pat).ok().map(|g| g.compile_matcher()))
557 .collect();
558 (*p, matchers)
559 })
560 .collect();
561
562 let relative_files: Vec<(&PathBuf, String)> = discovered_files
564 .iter()
565 .map(|f| {
566 let rel = f
567 .strip_prefix(root)
568 .unwrap_or(f)
569 .to_string_lossy()
570 .into_owned();
571 (f, rel)
572 })
573 .collect();
574
575 if !config_matchers.is_empty() {
576 for (plugin, matchers) in &config_matchers {
577 for (abs_path, rel_path) in &relative_files {
578 if matchers.iter().any(|m| m.is_match(rel_path.as_str())) {
579 if let Ok(source) = std::fs::read_to_string(abs_path) {
581 let plugin_result = plugin.resolve_config(abs_path, &source, root);
582 if !plugin_result.is_empty() {
583 tracing::debug!(
584 plugin = plugin.name(),
585 config = rel_path.as_str(),
586 entries = plugin_result.entry_patterns.len(),
587 deps = plugin_result.referenced_dependencies.len(),
588 "resolved config"
589 );
590 result.entry_patterns.extend(plugin_result.entry_patterns);
591 result
592 .referenced_dependencies
593 .extend(plugin_result.referenced_dependencies);
594 result
595 .discovered_always_used
596 .extend(plugin_result.always_used_files);
597 result.setup_files.extend(plugin_result.setup_files);
598 }
599 }
600 }
601 }
602 }
603 }
604
605 for plugin in &active {
609 if let Some(key) = plugin.package_json_config_key() {
610 let has_config_file = !plugin.config_patterns().is_empty()
612 && config_matchers.iter().any(|(p, matchers)| {
613 p.name() == plugin.name()
614 && relative_files
615 .iter()
616 .any(|(_, rel)| matchers.iter().any(|m| m.is_match(rel.as_str())))
617 });
618 if !has_config_file {
619 let pkg_path = root.join("package.json");
621 if let Ok(content) = std::fs::read_to_string(&pkg_path)
622 && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
623 && let Some(config_value) = json.get(key)
624 {
625 let config_json = serde_json::to_string(config_value).unwrap_or_default();
626 let fake_path = root.join(format!("{key}.config.json"));
627 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
628 if !plugin_result.is_empty() {
629 tracing::debug!(
630 plugin = plugin.name(),
631 key = key,
632 "resolved inline package.json config"
633 );
634 result.entry_patterns.extend(plugin_result.entry_patterns);
635 result
636 .referenced_dependencies
637 .extend(plugin_result.referenced_dependencies);
638 result
639 .discovered_always_used
640 .extend(plugin_result.always_used_files);
641 result.setup_files.extend(plugin_result.setup_files);
642 }
643 }
644 }
645 }
646 }
647
648 result
649 }
650
651 pub fn run_workspace_fast(
658 &self,
659 pkg: &PackageJson,
660 root: &Path,
661 precompiled_config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
662 relative_files: &[(&PathBuf, String)],
663 ) -> AggregatedPluginResult {
664 let _span = tracing::info_span!("run_plugins").entered();
665 let mut result = AggregatedPluginResult::default();
666
667 let all_deps = pkg.all_dependency_names();
669 let active: Vec<&dyn Plugin> = self
670 .plugins
671 .iter()
672 .filter(|p| p.is_enabled_with_deps(&all_deps, root))
673 .map(|p| p.as_ref())
674 .collect();
675
676 tracing::info!(
677 plugins = active
678 .iter()
679 .map(|p| p.name())
680 .collect::<Vec<_>>()
681 .join(", "),
682 "active plugins"
683 );
684
685 if active.is_empty() {
687 return result;
688 }
689
690 for plugin in &active {
692 result.active_plugins.push(plugin.name().to_string());
693
694 for pat in plugin.entry_patterns() {
695 result.entry_patterns.push((*pat).to_string());
696 }
697 for pat in plugin.config_patterns() {
698 result.config_patterns.push((*pat).to_string());
699 }
700 for pat in plugin.always_used() {
701 result.always_used.push((*pat).to_string());
702 }
703 for (file_pat, exports) in plugin.used_exports() {
704 result.used_exports.push((
705 file_pat.to_string(),
706 exports.iter().map(|s| s.to_string()).collect(),
707 ));
708 }
709 for dep in plugin.tooling_dependencies() {
710 result.tooling_dependencies.push((*dep).to_string());
711 }
712 for prefix in plugin.virtual_module_prefixes() {
713 result.virtual_module_prefixes.push((*prefix).to_string());
714 }
715 for (prefix, replacement) in plugin.path_aliases(root) {
716 result.path_aliases.push((prefix.to_string(), replacement));
717 }
718 }
719
720 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
723 let workspace_matchers: Vec<_> = precompiled_config_matchers
724 .iter()
725 .filter(|(p, _)| active_names.contains(p.name()))
726 .collect();
727
728 if !workspace_matchers.is_empty() {
729 for (plugin, matchers) in workspace_matchers {
730 for (abs_path, rel_path) in relative_files {
731 if matchers.iter().any(|m| m.is_match(rel_path.as_str()))
732 && let Ok(source) = std::fs::read_to_string(abs_path)
733 {
734 let plugin_result = plugin.resolve_config(abs_path, &source, root);
735 if !plugin_result.is_empty() {
736 tracing::debug!(
737 plugin = plugin.name(),
738 config = rel_path.as_str(),
739 entries = plugin_result.entry_patterns.len(),
740 deps = plugin_result.referenced_dependencies.len(),
741 "resolved config"
742 );
743 result.entry_patterns.extend(plugin_result.entry_patterns);
744 result
745 .referenced_dependencies
746 .extend(plugin_result.referenced_dependencies);
747 result
748 .discovered_always_used
749 .extend(plugin_result.always_used_files);
750 result.setup_files.extend(plugin_result.setup_files);
751 }
752 }
753 }
754 }
755 }
756
757 result
758 }
759
760 pub fn precompile_config_matchers(&self) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
763 self.plugins
764 .iter()
765 .filter(|p| !p.config_patterns().is_empty())
766 .map(|p| {
767 let matchers: Vec<globset::GlobMatcher> = p
768 .config_patterns()
769 .iter()
770 .filter_map(|pat| globset::Glob::new(pat).ok().map(|g| g.compile_matcher()))
771 .collect();
772 (p.as_ref(), matchers)
773 })
774 .collect()
775 }
776}
777
778fn check_plugin_detection(
780 detection: &PluginDetection,
781 all_deps: &[&str],
782 root: &Path,
783 discovered_files: &[PathBuf],
784) -> bool {
785 match detection {
786 PluginDetection::Dependency { package } => all_deps.iter().any(|d| *d == package),
787 PluginDetection::FileExists { pattern } => {
788 if let Ok(matcher) = globset::Glob::new(pattern).map(|g| g.compile_matcher()) {
790 for file in discovered_files {
791 let relative = file.strip_prefix(root).unwrap_or(file);
792 if matcher.is_match(relative) {
793 return true;
794 }
795 }
796 }
797 let full_pattern = root.join(pattern).to_string_lossy().to_string();
799 glob::glob(&full_pattern)
800 .ok()
801 .is_some_and(|mut g| g.next().is_some())
802 }
803 PluginDetection::All { conditions } => conditions
804 .iter()
805 .all(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
806 PluginDetection::Any { conditions } => conditions
807 .iter()
808 .any(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
809 }
810}
811
812impl Default for PluginRegistry {
813 fn default() -> Self {
814 Self::new(vec![])
815 }
816}
817
818#[cfg(test)]
819#[expect(clippy::disallowed_types)]
820mod tests {
821 use super::*;
822 use fallow_config::{ExternalPluginDef, ExternalUsedExport, PluginDetection};
823 use std::collections::HashMap;
824
825 fn make_pkg(deps: &[&str]) -> PackageJson {
827 let map: HashMap<String, String> =
828 deps.iter().map(|d| (d.to_string(), "*".into())).collect();
829 PackageJson {
830 dependencies: Some(map),
831 ..Default::default()
832 }
833 }
834
835 fn make_pkg_dev(deps: &[&str]) -> PackageJson {
837 let map: HashMap<String, String> =
838 deps.iter().map(|d| (d.to_string(), "*".into())).collect();
839 PackageJson {
840 dev_dependencies: Some(map),
841 ..Default::default()
842 }
843 }
844
845 #[test]
848 fn nextjs_detected_when_next_in_deps() {
849 let registry = PluginRegistry::default();
850 let pkg = make_pkg(&["next", "react"]);
851 let result = registry.run(&pkg, Path::new("/project"), &[]);
852 assert!(
853 result.active_plugins.contains(&"nextjs".to_string()),
854 "nextjs plugin should be active when 'next' is in deps"
855 );
856 }
857
858 #[test]
859 fn nextjs_not_detected_without_next() {
860 let registry = PluginRegistry::default();
861 let pkg = make_pkg(&["react", "react-dom"]);
862 let result = registry.run(&pkg, Path::new("/project"), &[]);
863 assert!(
864 !result.active_plugins.contains(&"nextjs".to_string()),
865 "nextjs plugin should not be active without 'next' in deps"
866 );
867 }
868
869 #[test]
870 fn prefix_enabler_matches_scoped_packages() {
871 let registry = PluginRegistry::default();
873 let pkg = make_pkg(&["@storybook/react"]);
874 let result = registry.run(&pkg, Path::new("/project"), &[]);
875 assert!(
876 result.active_plugins.contains(&"storybook".to_string()),
877 "storybook should activate via prefix match on @storybook/react"
878 );
879 }
880
881 #[test]
882 fn prefix_enabler_does_not_match_without_slash() {
883 let registry = PluginRegistry::default();
885 let mut map = HashMap::new();
887 map.insert("@storybookish".to_string(), "*".to_string());
888 let pkg = PackageJson {
889 dependencies: Some(map),
890 ..Default::default()
891 };
892 let result = registry.run(&pkg, Path::new("/project"), &[]);
893 assert!(
894 !result.active_plugins.contains(&"storybook".to_string()),
895 "storybook should not activate for '@storybookish' (no slash prefix match)"
896 );
897 }
898
899 #[test]
900 fn multiple_plugins_detected_simultaneously() {
901 let registry = PluginRegistry::default();
902 let pkg = make_pkg(&["next", "vitest", "typescript"]);
903 let result = registry.run(&pkg, Path::new("/project"), &[]);
904 assert!(result.active_plugins.contains(&"nextjs".to_string()));
905 assert!(result.active_plugins.contains(&"vitest".to_string()));
906 assert!(result.active_plugins.contains(&"typescript".to_string()));
907 }
908
909 #[test]
910 fn no_plugins_for_empty_deps() {
911 let registry = PluginRegistry::default();
912 let pkg = PackageJson::default();
913 let result = registry.run(&pkg, Path::new("/project"), &[]);
914 assert!(
915 result.active_plugins.is_empty(),
916 "no plugins should activate with empty package.json"
917 );
918 }
919
920 #[test]
923 fn active_plugin_contributes_entry_patterns() {
924 let registry = PluginRegistry::default();
925 let pkg = make_pkg(&["next"]);
926 let result = registry.run(&pkg, Path::new("/project"), &[]);
927 assert!(
929 result
930 .entry_patterns
931 .iter()
932 .any(|p| p.contains("app/**/page")),
933 "nextjs plugin should add app/**/page entry pattern"
934 );
935 }
936
937 #[test]
938 fn inactive_plugin_does_not_contribute_entry_patterns() {
939 let registry = PluginRegistry::default();
940 let pkg = make_pkg(&["react"]);
941 let result = registry.run(&pkg, Path::new("/project"), &[]);
942 assert!(
944 !result
945 .entry_patterns
946 .iter()
947 .any(|p| p.contains("app/**/page")),
948 "nextjs patterns should not appear when plugin is inactive"
949 );
950 }
951
952 #[test]
953 fn active_plugin_contributes_tooling_deps() {
954 let registry = PluginRegistry::default();
955 let pkg = make_pkg(&["next"]);
956 let result = registry.run(&pkg, Path::new("/project"), &[]);
957 assert!(
958 result.tooling_dependencies.contains(&"next".to_string()),
959 "nextjs plugin should list 'next' as a tooling dependency"
960 );
961 }
962
963 #[test]
964 fn dev_deps_also_trigger_plugins() {
965 let registry = PluginRegistry::default();
966 let pkg = make_pkg_dev(&["vitest"]);
967 let result = registry.run(&pkg, Path::new("/project"), &[]);
968 assert!(
969 result.active_plugins.contains(&"vitest".to_string()),
970 "vitest should activate from devDependencies"
971 );
972 }
973
974 #[test]
977 fn external_plugin_detected_by_enablers() {
978 let ext = ExternalPluginDef {
979 schema: None,
980 name: "my-framework".to_string(),
981 detection: None,
982 enablers: vec!["my-framework".to_string()],
983 entry_points: vec!["src/routes/**/*.ts".to_string()],
984 config_patterns: vec![],
985 always_used: vec!["my.config.ts".to_string()],
986 tooling_dependencies: vec!["my-framework-cli".to_string()],
987 used_exports: vec![],
988 };
989 let registry = PluginRegistry::new(vec![ext]);
990 let pkg = make_pkg(&["my-framework"]);
991 let result = registry.run(&pkg, Path::new("/project"), &[]);
992 assert!(result.active_plugins.contains(&"my-framework".to_string()));
993 assert!(
994 result
995 .entry_patterns
996 .contains(&"src/routes/**/*.ts".to_string())
997 );
998 assert!(
999 result
1000 .tooling_dependencies
1001 .contains(&"my-framework-cli".to_string())
1002 );
1003 }
1004
1005 #[test]
1006 fn external_plugin_not_detected_when_dep_missing() {
1007 let ext = ExternalPluginDef {
1008 schema: None,
1009 name: "my-framework".to_string(),
1010 detection: None,
1011 enablers: vec!["my-framework".to_string()],
1012 entry_points: vec!["src/routes/**/*.ts".to_string()],
1013 config_patterns: vec![],
1014 always_used: vec![],
1015 tooling_dependencies: vec![],
1016 used_exports: vec![],
1017 };
1018 let registry = PluginRegistry::new(vec![ext]);
1019 let pkg = make_pkg(&["react"]);
1020 let result = registry.run(&pkg, Path::new("/project"), &[]);
1021 assert!(!result.active_plugins.contains(&"my-framework".to_string()));
1022 assert!(
1023 !result
1024 .entry_patterns
1025 .contains(&"src/routes/**/*.ts".to_string())
1026 );
1027 }
1028
1029 #[test]
1030 fn external_plugin_prefix_enabler() {
1031 let ext = ExternalPluginDef {
1032 schema: None,
1033 name: "custom-plugin".to_string(),
1034 detection: None,
1035 enablers: vec!["@custom/".to_string()],
1036 entry_points: vec!["custom/**/*.ts".to_string()],
1037 config_patterns: vec![],
1038 always_used: vec![],
1039 tooling_dependencies: vec![],
1040 used_exports: vec![],
1041 };
1042 let registry = PluginRegistry::new(vec![ext]);
1043 let pkg = make_pkg(&["@custom/core"]);
1044 let result = registry.run(&pkg, Path::new("/project"), &[]);
1045 assert!(result.active_plugins.contains(&"custom-plugin".to_string()));
1046 }
1047
1048 #[test]
1049 fn external_plugin_detection_dependency() {
1050 let ext = ExternalPluginDef {
1051 schema: None,
1052 name: "detected-plugin".to_string(),
1053 detection: Some(PluginDetection::Dependency {
1054 package: "special-dep".to_string(),
1055 }),
1056 enablers: vec![],
1057 entry_points: vec!["special/**/*.ts".to_string()],
1058 config_patterns: vec![],
1059 always_used: vec![],
1060 tooling_dependencies: vec![],
1061 used_exports: vec![],
1062 };
1063 let registry = PluginRegistry::new(vec![ext]);
1064 let pkg = make_pkg(&["special-dep"]);
1065 let result = registry.run(&pkg, Path::new("/project"), &[]);
1066 assert!(
1067 result
1068 .active_plugins
1069 .contains(&"detected-plugin".to_string())
1070 );
1071 }
1072
1073 #[test]
1074 fn external_plugin_detection_any_combinator() {
1075 let ext = ExternalPluginDef {
1076 schema: None,
1077 name: "any-plugin".to_string(),
1078 detection: Some(PluginDetection::Any {
1079 conditions: vec![
1080 PluginDetection::Dependency {
1081 package: "pkg-a".to_string(),
1082 },
1083 PluginDetection::Dependency {
1084 package: "pkg-b".to_string(),
1085 },
1086 ],
1087 }),
1088 enablers: vec![],
1089 entry_points: vec!["any/**/*.ts".to_string()],
1090 config_patterns: vec![],
1091 always_used: vec![],
1092 tooling_dependencies: vec![],
1093 used_exports: vec![],
1094 };
1095 let registry = PluginRegistry::new(vec![ext]);
1096 let pkg = make_pkg(&["pkg-b"]);
1098 let result = registry.run(&pkg, Path::new("/project"), &[]);
1099 assert!(result.active_plugins.contains(&"any-plugin".to_string()));
1100 }
1101
1102 #[test]
1103 fn external_plugin_detection_all_combinator_fails_partial() {
1104 let ext = ExternalPluginDef {
1105 schema: None,
1106 name: "all-plugin".to_string(),
1107 detection: Some(PluginDetection::All {
1108 conditions: vec![
1109 PluginDetection::Dependency {
1110 package: "pkg-a".to_string(),
1111 },
1112 PluginDetection::Dependency {
1113 package: "pkg-b".to_string(),
1114 },
1115 ],
1116 }),
1117 enablers: vec![],
1118 entry_points: vec![],
1119 config_patterns: vec![],
1120 always_used: vec![],
1121 tooling_dependencies: vec![],
1122 used_exports: vec![],
1123 };
1124 let registry = PluginRegistry::new(vec![ext]);
1125 let pkg = make_pkg(&["pkg-a"]);
1127 let result = registry.run(&pkg, Path::new("/project"), &[]);
1128 assert!(!result.active_plugins.contains(&"all-plugin".to_string()));
1129 }
1130
1131 #[test]
1132 fn external_plugin_used_exports_aggregated() {
1133 let ext = ExternalPluginDef {
1134 schema: None,
1135 name: "ue-plugin".to_string(),
1136 detection: None,
1137 enablers: vec!["ue-dep".to_string()],
1138 entry_points: vec![],
1139 config_patterns: vec![],
1140 always_used: vec![],
1141 tooling_dependencies: vec![],
1142 used_exports: vec![ExternalUsedExport {
1143 pattern: "pages/**/*.tsx".to_string(),
1144 exports: vec!["default".to_string(), "getServerSideProps".to_string()],
1145 }],
1146 };
1147 let registry = PluginRegistry::new(vec![ext]);
1148 let pkg = make_pkg(&["ue-dep"]);
1149 let result = registry.run(&pkg, Path::new("/project"), &[]);
1150 assert!(result.used_exports.iter().any(|(pat, exports)| {
1151 pat == "pages/**/*.tsx" && exports.contains(&"default".to_string())
1152 }));
1153 }
1154
1155 #[test]
1156 fn external_plugin_without_enablers_or_detection_stays_inactive() {
1157 let ext = ExternalPluginDef {
1158 schema: None,
1159 name: "orphan-plugin".to_string(),
1160 detection: None,
1161 enablers: vec![],
1162 entry_points: vec!["orphan/**/*.ts".to_string()],
1163 config_patterns: vec![],
1164 always_used: vec![],
1165 tooling_dependencies: vec![],
1166 used_exports: vec![],
1167 };
1168 let registry = PluginRegistry::new(vec![ext]);
1169 let pkg = make_pkg(&["anything"]);
1170 let result = registry.run(&pkg, Path::new("/project"), &[]);
1171 assert!(!result.active_plugins.contains(&"orphan-plugin".to_string()));
1172 }
1173
1174 #[test]
1177 fn is_enabled_with_deps_exact_match() {
1178 let plugin = nextjs::NextJsPlugin;
1179 let deps = vec!["next".to_string()];
1180 assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1181 }
1182
1183 #[test]
1184 fn is_enabled_with_deps_no_match() {
1185 let plugin = nextjs::NextJsPlugin;
1186 let deps = vec!["react".to_string()];
1187 assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1188 }
1189
1190 #[test]
1191 fn is_enabled_with_empty_deps() {
1192 let plugin = nextjs::NextJsPlugin;
1193 let deps: Vec<String> = vec![];
1194 assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1195 }
1196
1197 #[test]
1200 fn nuxt_contributes_virtual_module_prefixes() {
1201 let registry = PluginRegistry::default();
1202 let pkg = make_pkg(&["nuxt"]);
1203 let result = registry.run(&pkg, Path::new("/project"), &[]);
1204 assert!(
1205 result.virtual_module_prefixes.contains(&"#".to_string()),
1206 "nuxt should contribute '#' virtual module prefix"
1207 );
1208 }
1209
1210 #[test]
1213 fn plugin_result_is_empty_when_default() {
1214 let r = PluginResult::default();
1215 assert!(r.is_empty());
1216 }
1217
1218 #[test]
1219 fn plugin_result_not_empty_with_entry_patterns() {
1220 let r = PluginResult {
1221 entry_patterns: vec!["*.ts".to_string()],
1222 ..Default::default()
1223 };
1224 assert!(!r.is_empty());
1225 }
1226
1227 #[test]
1228 fn plugin_result_not_empty_with_referenced_deps() {
1229 let r = PluginResult {
1230 referenced_dependencies: vec!["lodash".to_string()],
1231 ..Default::default()
1232 };
1233 assert!(!r.is_empty());
1234 }
1235
1236 #[test]
1237 fn plugin_result_not_empty_with_setup_files() {
1238 let r = PluginResult {
1239 setup_files: vec![PathBuf::from("/setup.ts")],
1240 ..Default::default()
1241 };
1242 assert!(!r.is_empty());
1243 }
1244
1245 #[test]
1248 fn precompile_config_matchers_returns_entries() {
1249 let registry = PluginRegistry::default();
1250 let matchers = registry.precompile_config_matchers();
1251 assert!(
1253 !matchers.is_empty(),
1254 "precompile_config_matchers should return entries for plugins with config patterns"
1255 );
1256 }
1257
1258 #[test]
1259 fn precompile_config_matchers_only_for_plugins_with_patterns() {
1260 let registry = PluginRegistry::default();
1261 let matchers = registry.precompile_config_matchers();
1262 for (plugin, _) in &matchers {
1263 assert!(
1264 !plugin.config_patterns().is_empty(),
1265 "plugin '{}' in matchers should have config patterns",
1266 plugin.name()
1267 );
1268 }
1269 }
1270}