Skip to main content

fallow_core/plugins/
mod.rs

1//! Plugin system for framework-aware codebase analysis.
2//!
3//! Unlike knip's JavaScript plugin system that evaluates config files at runtime,
4//! fallow's plugin system uses Oxc's parser to extract configuration values from
5//! JS/TS/JSON config files via AST walking — no JavaScript evaluation needed.
6//!
7//! Each plugin implements the [`Plugin`] trait with:
8//! - **Static defaults**: Entry patterns, config file patterns, used exports
9//! - **Dynamic resolution**: Parse tool config files to discover additional entries,
10//!   referenced dependencies, and setup files
11
12use std::path::{Path, PathBuf};
13
14use fallow_config::{AutoImportRule, EntryPointRole, PackageJson, UsedClassMemberRule};
15use regex::Regex;
16
17const TEST_ENTRY_POINT_PLUGINS: &[&str] = &[
18    "ava",
19    "bun",
20    "cucumber",
21    "cypress",
22    "jest",
23    "k6",
24    "mocha",
25    "playwright",
26    "tap",
27    "tsd",
28    "vitest",
29    "webdriverio",
30];
31
32const RUNTIME_ENTRY_POINT_PLUGINS: &[&str] = &[
33    "adonis",
34    "angular",
35    "astro",
36    "browser-extension",
37    "convex",
38    "docusaurus",
39    "electron",
40    "ember",
41    "expo",
42    "expo-router",
43    "gatsby",
44    "hardhat",
45    "nestjs",
46    "next-intl",
47    "nextjs",
48    "nitro",
49    "nuxt",
50    "obsidian",
51    "parcel",
52    "qwik",
53    "react-native",
54    "react-router",
55    "redwoodsdk",
56    "remix",
57    "rolldown",
58    "rollup",
59    "rsbuild",
60    "rspack",
61    "sanity",
62    "supabase",
63    "sveltekit",
64    "tanstack-router",
65    "tsdown",
66    "tsup",
67    "vite",
68    "vitepress",
69    "webpack",
70    "wrangler",
71    "wxt",
72];
73
74#[cfg(test)]
75const SUPPORT_ENTRY_POINT_PLUGINS: &[&str] = &[
76    "content-collections",
77    "contentlayer",
78    "danger",
79    "drizzle",
80    "fumadocs",
81    "i18next",
82    "knex",
83    "kysely",
84    "mintlify",
85    "msw",
86    "opencode",
87    "prisma",
88    "storybook",
89    "stryker",
90    "typeorm",
91    "velite",
92];
93
94/// Result of resolving a plugin's config file.
95#[derive(Debug, Default)]
96pub struct PluginResult {
97    /// Additional entry point glob patterns discovered from config.
98    pub entry_patterns: Vec<PathRule>,
99    /// When true, `entry_patterns` from config replace the plugin's static
100    /// `entry_patterns()` defaults instead of adding to them. Tools like Vitest
101    /// and Jest treat their config's include/testMatch as a replacement for built-in
102    /// defaults, so when the config is explicit the static patterns must be dropped.
103    pub replace_entry_patterns: bool,
104    /// When true, `used_exports` from config replace the plugin's static
105    /// `used_export_rules()` defaults instead of adding to them.
106    pub replace_used_export_rules: bool,
107    /// Additional export-usage rules discovered from config.
108    pub used_exports: Vec<UsedExportRule>,
109    /// Class member rules that should never be flagged as unused. Contributed
110    /// by plugins that know their framework invokes these methods at runtime
111    /// and may scope suppression via `extends` / `implements` constraints when
112    /// the method name is too common to allowlist globally.
113    pub used_class_members: Vec<UsedClassMemberRule>,
114    /// Dependencies referenced in config files (should not be flagged as unused).
115    pub referenced_dependencies: Vec<String>,
116    /// Additional files that are always considered used.
117    pub always_used_files: Vec<String>,
118    /// Path alias mappings discovered from config (prefix -> replacement directory).
119    pub path_aliases: Vec<(String, String)>,
120    /// Setup/helper files referenced from config.
121    pub setup_files: Vec<PathBuf>,
122    /// Test fixture glob patterns discovered from config.
123    pub fixture_patterns: Vec<String>,
124    /// Absolute directories to include when resolving SCSS/Sass `@import` and
125    /// `@use` specifiers. Contributed by framework plugins that read their
126    /// tool's equivalent of `includePaths` (e.g. Angular's
127    /// `stylePreprocessorOptions.includePaths` from `angular.json` /
128    /// `project.json`). Bare SCSS specifiers that fail to resolve relative to
129    /// the importing file retry against each include path using the SCSS
130    /// partial / directory-index conventions.
131    pub scss_include_paths: Vec<PathBuf>,
132    /// URL-to-filesystem static directory mappings discovered from tool config.
133    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
134    pub static_dir_mappings: Vec<(PathBuf, String)>,
135    /// File-scoped dependency providers. Matching imports are considered
136    /// available from the framework runtime and are not unlisted dependencies.
137    pub provided_dependencies: Vec<ProvidedDependencyRule>,
138}
139
140impl PluginResult {
141    pub fn push_entry_pattern(&mut self, pattern: impl Into<String>) {
142        self.entry_patterns
143            .push(PathRule::new(normalize_entry_pattern(pattern.into())));
144    }
145
146    pub fn extend_entry_patterns<I, S>(&mut self, patterns: I)
147    where
148        I: IntoIterator<Item = S>,
149        S: Into<String>,
150    {
151        self.entry_patterns.extend(
152            patterns
153                .into_iter()
154                .map(|pat| PathRule::new(normalize_entry_pattern(pat.into()))),
155        );
156    }
157
158    pub fn push_used_export_rule(
159        &mut self,
160        pattern: impl Into<String>,
161        exports: impl IntoIterator<Item = impl Into<String>>,
162    ) {
163        self.used_exports
164            .push(UsedExportRule::new(pattern, exports));
165    }
166
167    #[must_use]
168    pub const fn is_empty(&self) -> bool {
169        self.entry_patterns.is_empty()
170            && self.used_exports.is_empty()
171            && self.used_class_members.is_empty()
172            && self.referenced_dependencies.is_empty()
173            && self.always_used_files.is_empty()
174            && self.path_aliases.is_empty()
175            && self.setup_files.is_empty()
176            && self.fixture_patterns.is_empty()
177            && self.scss_include_paths.is_empty()
178            && self.static_dir_mappings.is_empty()
179            && self.provided_dependencies.is_empty()
180    }
181}
182
183fn normalize_entry_pattern(pattern: String) -> String {
184    pattern
185        .strip_prefix("./")
186        .map(str::to_owned)
187        .unwrap_or(pattern)
188}
189
190/// A file-pattern rule with optional exclusion globs plus path-level or
191/// segment-level regex filters.
192///
193/// Exclusion regexes are matched against the project-relative path and should be
194/// anchored when generated dynamically so they can be safely workspace-prefixed.
195#[derive(Debug, Clone, Default, PartialEq, Eq)]
196pub struct PathRule {
197    pub pattern: String,
198    pub exclude_globs: Vec<String>,
199    pub exclude_regexes: Vec<String>,
200    /// Regexes matched against individual path segments. These are not prefixed
201    /// for workspaces because they intentionally operate on segment names rather
202    /// than the full project-relative path.
203    pub exclude_segment_regexes: Vec<String>,
204}
205
206impl PathRule {
207    #[must_use]
208    pub fn new(pattern: impl Into<String>) -> Self {
209        Self {
210            pattern: pattern.into(),
211            exclude_globs: Vec::new(),
212            exclude_regexes: Vec::new(),
213            exclude_segment_regexes: Vec::new(),
214        }
215    }
216
217    #[must_use]
218    pub fn from_static(pattern: &'static str) -> Self {
219        Self::new(pattern)
220    }
221
222    #[must_use]
223    pub fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
224    where
225        I: IntoIterator<Item = S>,
226        S: Into<String>,
227    {
228        self.exclude_globs
229            .extend(patterns.into_iter().map(Into::into));
230        self
231    }
232
233    #[must_use]
234    pub fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
235    where
236        I: IntoIterator<Item = S>,
237        S: Into<String>,
238    {
239        self.exclude_regexes
240            .extend(patterns.into_iter().map(Into::into));
241        self
242    }
243
244    #[must_use]
245    pub fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
246    where
247        I: IntoIterator<Item = S>,
248        S: Into<String>,
249    {
250        self.exclude_segment_regexes
251            .extend(patterns.into_iter().map(Into::into));
252        self
253    }
254
255    #[must_use]
256    pub fn prefixed(&self, ws_prefix: &str) -> Self {
257        Self {
258            pattern: prefix_workspace_pattern(&self.pattern, ws_prefix),
259            exclude_globs: self
260                .exclude_globs
261                .iter()
262                .map(|pattern| prefix_workspace_pattern(pattern, ws_prefix))
263                .collect(),
264            exclude_regexes: self
265                .exclude_regexes
266                .iter()
267                .map(|pattern| prefix_workspace_regex(pattern, ws_prefix))
268                .collect(),
269            exclude_segment_regexes: self.exclude_segment_regexes.clone(),
270        }
271    }
272}
273
274/// A used-export rule bound to a file-pattern rule.
275#[derive(Debug, Clone, Default, PartialEq, Eq)]
276pub struct UsedExportRule {
277    pub path: PathRule,
278    pub exports: Vec<String>,
279}
280
281impl UsedExportRule {
282    #[must_use]
283    pub fn new(
284        pattern: impl Into<String>,
285        exports: impl IntoIterator<Item = impl Into<String>>,
286    ) -> Self {
287        Self {
288            path: PathRule::new(pattern),
289            exports: exports.into_iter().map(Into::into).collect(),
290        }
291    }
292
293    #[must_use]
294    pub fn from_static(pattern: &'static str, exports: &'static [&'static str]) -> Self {
295        Self::new(pattern, exports.iter().copied())
296    }
297
298    #[must_use]
299    pub fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
300    where
301        I: IntoIterator<Item = S>,
302        S: Into<String>,
303    {
304        self.path = self.path.with_excluded_globs(patterns);
305        self
306    }
307
308    #[must_use]
309    pub fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
310    where
311        I: IntoIterator<Item = S>,
312        S: Into<String>,
313    {
314        self.path = self.path.with_excluded_regexes(patterns);
315        self
316    }
317
318    #[must_use]
319    pub fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
320    where
321        I: IntoIterator<Item = S>,
322        S: Into<String>,
323    {
324        self.path = self.path.with_excluded_segment_regexes(patterns);
325        self
326    }
327
328    #[must_use]
329    pub fn prefixed(&self, ws_prefix: &str) -> Self {
330        Self {
331            path: self.path.prefixed(ws_prefix),
332            exports: self.exports.clone(),
333        }
334    }
335}
336
337/// A used-export rule tagged with the plugin that contributed it.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct PluginUsedExportRule {
340    pub plugin_name: String,
341    pub rule: UsedExportRule,
342}
343
344impl PluginUsedExportRule {
345    #[must_use]
346    pub fn new(plugin_name: impl Into<String>, rule: UsedExportRule) -> Self {
347        Self {
348            plugin_name: plugin_name.into(),
349            rule,
350        }
351    }
352
353    #[must_use]
354    pub fn prefixed(&self, ws_prefix: &str) -> Self {
355        Self {
356            plugin_name: self.plugin_name.clone(),
357            rule: self.rule.prefixed(ws_prefix),
358        }
359    }
360}
361
362/// A file-scoped dependency provider rule contributed by a framework plugin.
363#[derive(Debug, Clone, Default, PartialEq, Eq)]
364pub struct ProvidedDependencyRule {
365    pub path: PathRule,
366    pub exact_specifiers: Vec<String>,
367    pub specifier_prefixes: Vec<String>,
368}
369
370impl ProvidedDependencyRule {
371    #[must_use]
372    pub fn new(
373        pattern: impl Into<String>,
374        exact_specifiers: impl IntoIterator<Item = impl Into<String>>,
375        specifier_prefixes: impl IntoIterator<Item = impl Into<String>>,
376    ) -> Self {
377        Self {
378            path: PathRule::new(pattern),
379            exact_specifiers: exact_specifiers.into_iter().map(Into::into).collect(),
380            specifier_prefixes: specifier_prefixes.into_iter().map(Into::into).collect(),
381        }
382    }
383
384    #[must_use]
385    pub fn prefixed(&self, ws_prefix: &str) -> Self {
386        Self {
387            path: self.path.prefixed(ws_prefix),
388            exact_specifiers: self.exact_specifiers.clone(),
389            specifier_prefixes: self.specifier_prefixes.clone(),
390        }
391    }
392
393    #[must_use]
394    pub fn may_cover_package(&self, package_name: &str) -> bool {
395        self.exact_specifiers
396            .iter()
397            .chain(self.specifier_prefixes.iter())
398            .any(|specifier| crate::resolve::extract_package_name(specifier) == package_name)
399    }
400
401    #[must_use]
402    pub fn covers_specifier(&self, specifier: &str) -> bool {
403        self.exact_specifiers
404            .iter()
405            .any(|allowed| allowed == specifier)
406            || self
407                .specifier_prefixes
408                .iter()
409                .any(|prefix| specifier.starts_with(prefix))
410    }
411}
412
413/// A compiled path rule matcher shared by entry-point and used-export matching.
414#[derive(Debug, Clone)]
415pub(crate) struct CompiledPathRule {
416    include: globset::GlobMatcher,
417    exclude_globs: Vec<globset::GlobMatcher>,
418    exclude_regexes: Vec<Regex>,
419    exclude_segment_regexes: Vec<Regex>,
420}
421
422impl CompiledPathRule {
423    pub(crate) fn for_entry_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
424        let include = match globset::GlobBuilder::new(&rule.pattern)
425            .literal_separator(true)
426            .build()
427        {
428            Ok(glob) => glob.compile_matcher(),
429            Err(err) => {
430                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
431                return None;
432            }
433        };
434        Some(Self {
435            include,
436            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
437            exclude_regexes: compile_excluded_regexes(
438                &rule.exclude_regexes,
439                rule_kind,
440                &rule.pattern,
441            ),
442            exclude_segment_regexes: compile_excluded_segment_regexes(
443                &rule.exclude_segment_regexes,
444                rule_kind,
445                &rule.pattern,
446            ),
447        })
448    }
449
450    pub(crate) fn for_used_export_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
451        let include = match globset::Glob::new(&rule.pattern) {
452            Ok(glob) => glob.compile_matcher(),
453            Err(err) => {
454                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
455                return None;
456            }
457        };
458        Some(Self {
459            include,
460            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
461            exclude_regexes: compile_excluded_regexes(
462                &rule.exclude_regexes,
463                rule_kind,
464                &rule.pattern,
465            ),
466            exclude_segment_regexes: compile_excluded_segment_regexes(
467                &rule.exclude_segment_regexes,
468                rule_kind,
469                &rule.pattern,
470            ),
471        })
472    }
473
474    #[must_use]
475    pub(crate) fn matches(&self, path: &str) -> bool {
476        self.include.is_match(path)
477            && !self.exclude_globs.iter().any(|glob| glob.is_match(path))
478            && !self
479                .exclude_regexes
480                .iter()
481                .any(|regex| regex.is_match(path))
482            && !matches_segment_regex(path, &self.exclude_segment_regexes)
483    }
484}
485
486fn prefix_workspace_pattern(pattern: &str, ws_prefix: &str) -> String {
487    if pattern.starts_with(ws_prefix) || pattern.starts_with('/') {
488        pattern.to_string()
489    } else {
490        format!("{ws_prefix}/{pattern}")
491    }
492}
493
494fn prefix_workspace_regex(pattern: &str, ws_prefix: &str) -> String {
495    if let Some(pattern) = pattern.strip_prefix('^') {
496        format!("^{}/{}", regex::escape(ws_prefix), pattern)
497    } else {
498        format!("^{}/(?:{})", regex::escape(ws_prefix), pattern)
499    }
500}
501
502fn compile_excluded_globs(
503    patterns: &[String],
504    rule_kind: &str,
505    rule_pattern: &str,
506) -> Vec<globset::GlobMatcher> {
507    patterns
508        .iter()
509        .filter_map(|pattern| {
510            match globset::GlobBuilder::new(pattern)
511                .literal_separator(true)
512                .build()
513            {
514                Ok(glob) => Some(glob.compile_matcher()),
515                Err(err) => {
516                    tracing::warn!(
517                        "skipping invalid excluded glob '{}' for {} '{}': {err}",
518                        pattern,
519                        rule_kind,
520                        rule_pattern
521                    );
522                    None
523                }
524            }
525        })
526        .collect()
527}
528
529fn compile_excluded_regexes(
530    patterns: &[String],
531    rule_kind: &str,
532    rule_pattern: &str,
533) -> Vec<Regex> {
534    patterns
535        .iter()
536        .filter_map(|pattern| match Regex::new(pattern) {
537            Ok(regex) => Some(regex),
538            Err(err) => {
539                tracing::warn!(
540                    "skipping invalid excluded regex '{}' for {} '{}': {err}",
541                    pattern,
542                    rule_kind,
543                    rule_pattern
544                );
545                None
546            }
547        })
548        .collect()
549}
550
551fn compile_excluded_segment_regexes(
552    patterns: &[String],
553    rule_kind: &str,
554    rule_pattern: &str,
555) -> Vec<Regex> {
556    patterns
557        .iter()
558        .filter_map(|pattern| match Regex::new(pattern) {
559            Ok(regex) => Some(regex),
560            Err(err) => {
561                tracing::warn!(
562                    "skipping invalid excluded segment regex '{}' for {} '{}': {err}",
563                    pattern,
564                    rule_kind,
565                    rule_pattern
566                );
567                None
568            }
569        })
570        .collect()
571}
572
573fn matches_segment_regex(path: &str, regexes: &[Regex]) -> bool {
574    path.split('/')
575        .any(|segment| regexes.iter().any(|regex| regex.is_match(segment)))
576}
577
578impl From<String> for PathRule {
579    fn from(pattern: String) -> Self {
580        Self::new(pattern)
581    }
582}
583
584impl From<&str> for PathRule {
585    fn from(pattern: &str) -> Self {
586        Self::new(pattern)
587    }
588}
589
590impl std::ops::Deref for PathRule {
591    type Target = str;
592
593    fn deref(&self) -> &Self::Target {
594        &self.pattern
595    }
596}
597
598impl PartialEq<&str> for PathRule {
599    fn eq(&self, other: &&str) -> bool {
600        self.pattern == *other
601    }
602}
603
604impl PartialEq<str> for PathRule {
605    fn eq(&self, other: &str) -> bool {
606        self.pattern == other
607    }
608}
609
610impl PartialEq<String> for PathRule {
611    fn eq(&self, other: &String) -> bool {
612        &self.pattern == other
613    }
614}
615
616/// A framework/tool plugin that contributes to dead code analysis.
617pub trait Plugin: Send + Sync {
618    /// Human-readable plugin name.
619    fn name(&self) -> &'static str;
620
621    /// Package names that activate this plugin when found in package.json.
622    /// Supports exact matches and prefix patterns (ending with `/`).
623    fn enablers(&self) -> &'static [&'static str] {
624        &[]
625    }
626
627    /// Check if this plugin should be active for the given project.
628    /// Default implementation checks `enablers()` against package.json dependencies.
629    fn is_enabled(&self, pkg: &PackageJson, root: &Path) -> bool {
630        let deps = pkg.all_dependency_names();
631        self.is_enabled_with_deps(&deps, root)
632    }
633
634    /// Fast variant of `is_enabled` that accepts a pre-computed deps list.
635    /// Avoids repeated `all_dependency_names()` allocation when checking many plugins.
636    fn is_enabled_with_deps(&self, deps: &[String], _root: &Path) -> bool {
637        let enablers = self.enablers();
638        if enablers.is_empty() {
639            return false;
640        }
641        enablers.iter().any(|enabler| {
642            if enabler.ends_with('/') {
643                // Prefix match (e.g., "@storybook/" matches "@storybook/react")
644                deps.iter().any(|d| d.starts_with(enabler))
645            } else {
646                deps.iter().any(|d| d == enabler)
647            }
648        })
649    }
650
651    /// Check whether this plugin should be active with source discovery available.
652    ///
653    /// Most plugins only need dependency/config activation. Convention-only tools
654    /// can override this to activate from discovered source filenames without
655    /// forcing a separate filesystem walk.
656    fn is_enabled_with_files(
657        &self,
658        deps: &[String],
659        root: &Path,
660        _discovered_files: &[PathBuf],
661    ) -> bool {
662        self.is_enabled_with_deps(deps, root)
663    }
664
665    /// Package-script binary/package names that can activate this plugin.
666    fn script_enablers(&self) -> &'static [&'static str] {
667        &[]
668    }
669
670    /// Check whether this plugin should be active from package.json scripts.
671    fn is_enabled_with_scripts(
672        &self,
673        script_packages: &rustc_hash::FxHashSet<String>,
674        _root: &Path,
675    ) -> bool {
676        let enablers = self.script_enablers();
677        if enablers.is_empty() {
678            return false;
679        }
680        enablers.iter().any(|enabler| {
681            if enabler.ends_with('/') {
682                script_packages
683                    .iter()
684                    .any(|package| package.starts_with(enabler))
685            } else {
686                script_packages.contains(*enabler)
687            }
688        })
689    }
690
691    /// Default glob patterns for entry point files.
692    fn entry_patterns(&self) -> &'static [&'static str] {
693        &[]
694    }
695
696    /// Entry point rules with optional exclusions.
697    fn entry_pattern_rules(&self) -> Vec<PathRule> {
698        self.entry_patterns()
699            .iter()
700            .map(|pattern| PathRule::from_static(pattern))
701            .collect()
702    }
703
704    /// How this plugin's entry patterns should contribute to coverage reachability.
705    ///
706    /// `Support` roots keep files alive for dead-code analysis but do not count
707    /// as runtime or test reachability for static coverage gaps.
708    fn entry_point_role(&self) -> EntryPointRole {
709        builtin_entry_point_role(self.name())
710    }
711
712    /// Glob patterns for config files this plugin can parse.
713    fn config_patterns(&self) -> &'static [&'static str] {
714        &[]
715    }
716
717    /// Files that are always considered "used" when this plugin is active.
718    fn always_used(&self) -> &'static [&'static str] {
719        &[]
720    }
721
722    /// Exports that are always considered used for matching file patterns.
723    fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
724        vec![]
725    }
726
727    /// Used-export rules with optional exclusions.
728    fn used_export_rules(&self) -> Vec<UsedExportRule> {
729        self.used_exports()
730            .into_iter()
731            .map(|(pattern, exports)| UsedExportRule::from_static(pattern, exports))
732            .collect()
733    }
734
735    /// Class member names the framework invokes at runtime. Matching members
736    /// are skipped during `unused-class-members` analysis. Intended for
737    /// interface/contract patterns where the library calls methods on consumer
738    /// classes (e.g. ag-Grid's `agInit`, Web Components' `connectedCallback`).
739    fn used_class_members(&self) -> &'static [&'static str] {
740        &[]
741    }
742
743    /// Heritage-scoped class member rules. Each rule applies only to classes
744    /// matching its `extends` and/or `implements` clause. Used for frameworks
745    /// where lifecycle members are runtime-invoked only on classes that extend
746    /// a known base (e.g. Lit's `render`/`updated` on classes extending
747    /// `LitElement`, native Web Components' `connectedCallback` on classes
748    /// extending `HTMLElement`). Default: empty. Plugins override when they
749    /// need scoping; flat names should still come from `used_class_members`.
750    fn used_class_member_rules(&self) -> Vec<UsedClassMemberRule> {
751        Vec::new()
752    }
753
754    /// Glob patterns for test fixture files consumed by this framework.
755    /// These files are implicitly used by the test runner and should not be
756    /// flagged as unused. Unlike `always_used()`, this carries semantic intent
757    /// for reporting purposes.
758    fn fixture_glob_patterns(&self) -> &'static [&'static str] {
759        &[]
760    }
761
762    /// Hidden directory names that should be traversed when this plugin is active.
763    ///
764    /// These are consulted before normal plugin execution because source discovery
765    /// runs first. Keep entries static and package-convention scoped.
766    fn discovery_hidden_dirs(&self) -> &'static [&'static str] {
767        &[]
768    }
769
770    /// Dependencies that are tooling (used via CLI/config, not source imports).
771    /// These should not be flagged as unused devDependencies.
772    fn tooling_dependencies(&self) -> &'static [&'static str] {
773        &[]
774    }
775
776    /// Import prefixes that are virtual modules provided by this framework at build time.
777    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
778    /// Each entry is matched as a prefix against the extracted package name
779    /// (e.g., `"@theme/"` matches `@theme/Layout`).
780    fn virtual_module_prefixes(&self) -> &'static [&'static str] {
781        &[]
782    }
783
784    /// Package name suffixes that are virtual modules provided by this framework
785    /// at build time (e.g., test runner mock conventions).
786    /// Imports matching these suffixes should not be flagged as unlisted dependencies.
787    /// Each entry is matched as a suffix against the extracted package name
788    /// (e.g., `"/__mocks__"` matches `@aws-sdk/__mocks__` and `some-pkg/__mocks__`).
789    fn virtual_package_suffixes(&self) -> &'static [&'static str] {
790        &[]
791    }
792
793    /// Import suffixes for build-time generated relative imports.
794    ///
795    /// Unresolved relative imports whose specifier ends with one of these suffixes
796    /// will not be flagged as unresolved. For example, SvelteKit generates
797    /// `./$types` imports in route files — returning `"/$types"` suppresses those.
798    fn generated_import_patterns(&self) -> &'static [&'static str] {
799        &[]
800    }
801
802    /// Import prefixes for generated type-only relative imports.
803    ///
804    /// Unresolved type-only imports whose specifier starts with one of these prefixes
805    /// will not be flagged as unresolved. Runtime imports are still reported.
806    fn generated_type_import_prefixes(&self) -> &'static [&'static str] {
807        &[]
808    }
809
810    /// Path alias mappings provided by this framework at build time.
811    ///
812    /// Returns a list of `(prefix, replacement_dir)` tuples. When an import starting
813    /// with `prefix` fails to resolve, the resolver will substitute the prefix with
814    /// `replacement_dir` (relative to the project root) and retry.
815    ///
816    /// Called once when plugins are activated. The project `root` is provided so
817    /// plugins can inspect the filesystem (e.g., Nuxt checks whether `app/` exists
818    /// to determine the `srcDir`).
819    fn path_aliases(&self, _root: &Path) -> Vec<(&'static str, String)> {
820        vec![]
821    }
822
823    /// Convention-based auto-imports provided by this framework.
824    ///
825    /// Returns the names this framework exposes to user code by filesystem
826    /// convention with no explicit `import` statement (e.g. Nuxt `components/`
827    /// resolved by `<Card001 />` template tags), each mapped to the source file
828    /// providing the export. When a file references one of these names without an
829    /// import, the resolver synthesizes a graph edge to `source`.
830    ///
831    /// Called once when plugins are activated. The project `root` is provided so
832    /// plugins can scan the convention directories on the filesystem. The table is
833    /// a function of which files exist on disk, so it is rebuilt every run and is
834    /// never folded into per-file extraction caching. See issue #704.
835    fn auto_imports(&self, _root: &Path) -> Vec<AutoImportRule> {
836        Vec::new()
837    }
838
839    /// File-scoped dependency providers contributed by this framework.
840    fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> {
841        Vec::new()
842    }
843
844    /// Parse a config file's AST to discover additional entries, dependencies, etc.
845    ///
846    /// Called for each config file matching `config_patterns()`. The source code
847    /// and parsed AST are provided — use [`config_parser`] utilities to extract values.
848    fn resolve_config(&self, _config_path: &Path, _source: &str, _root: &Path) -> PluginResult {
849        PluginResult::default()
850    }
851
852    /// The key name in package.json that holds inline configuration for this tool.
853    /// When set (e.g., `"jest"` for the `"jest"` key in package.json), the plugin
854    /// system will extract that key's value and call `resolve_config` with its
855    /// JSON content if no standalone config file was found.
856    fn package_json_config_key(&self) -> Option<&'static str> {
857        None
858    }
859}
860
861fn builtin_entry_point_role(name: &str) -> EntryPointRole {
862    if TEST_ENTRY_POINT_PLUGINS.contains(&name) {
863        EntryPointRole::Test
864    } else if RUNTIME_ENTRY_POINT_PLUGINS.contains(&name) {
865        EntryPointRole::Runtime
866    } else {
867        EntryPointRole::Support
868    }
869}
870
871/// Macro to eliminate boilerplate in plugin implementations.
872///
873/// Generates a struct and a `Plugin` trait impl with the standard static methods
874/// (`name`, `enablers`, `entry_patterns`, `config_patterns`, `always_used`, `tooling_dependencies`,
875/// `fixture_glob_patterns`, `virtual_module_prefixes`, `virtual_package_suffixes`,
876/// `generated_type_import_prefixes`, `used_exports`).
877///
878/// For plugins that need custom `resolve_config()` or `is_enabled()`, keep those as
879/// manual `impl Plugin for ...` blocks instead of using this macro.
880///
881/// # Usage
882///
883/// ```ignore
884/// // Simple plugin (most common):
885/// define_plugin! {
886///     struct VitePlugin => "vite",
887///     enablers: ENABLERS,
888///     entry_patterns: ENTRY_PATTERNS,
889///     config_patterns: CONFIG_PATTERNS,
890///     always_used: ALWAYS_USED,
891///     tooling_dependencies: TOOLING_DEPENDENCIES,
892/// }
893///
894/// // Plugin with used_exports:
895/// define_plugin! {
896///     struct RemixPlugin => "remix",
897///     enablers: ENABLERS,
898///     entry_patterns: ENTRY_PATTERNS,
899///     always_used: ALWAYS_USED,
900///     tooling_dependencies: TOOLING_DEPENDENCIES,
901///     used_exports: [("app/routes/**/*.{ts,tsx}", ROUTE_EXPORTS)],
902/// }
903///
904/// // Plugin with imports-only resolve_config (extracts imports from config as deps):
905/// define_plugin! {
906///     struct CypressPlugin => "cypress",
907///     enablers: ENABLERS,
908///     entry_patterns: ENTRY_PATTERNS,
909///     config_patterns: CONFIG_PATTERNS,
910///     always_used: ALWAYS_USED,
911///     tooling_dependencies: TOOLING_DEPENDENCIES,
912///     resolve_config: imports_only,
913/// }
914///
915/// // Plugin with custom resolve_config body:
916/// define_plugin! {
917///     struct RollupPlugin => "rollup",
918///     enablers: ENABLERS,
919///     config_patterns: CONFIG_PATTERNS,
920///     always_used: ALWAYS_USED,
921///     tooling_dependencies: TOOLING_DEPENDENCIES,
922///     resolve_config(config_path, source, _root) {
923///         let mut result = PluginResult::default();
924///         // custom config parsing...
925///         result
926///     }
927/// }
928/// ```
929///
930/// All fields except `struct` and `enablers` are optional and default to `&[]` / `vec![]`.
931macro_rules! define_plugin {
932    (
933        struct $name:ident => $display:expr,
934        enablers: $enablers:expr
935        $(, entry_patterns: $entry:expr)?
936        $(, config_patterns: $config:expr)?
937        $(, always_used: $always:expr)?
938        $(, tooling_dependencies: $tooling:expr)?
939        $(, fixture_glob_patterns: $fixtures:expr)?
940        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
941        $(, virtual_module_prefixes: $virtual:expr)?
942        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
943        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
944        $(, provided_dependencies: $provided_dependencies:expr)?
945        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
946        , resolve_config: imports_only
947        $(,)?
948    ) => {
949        pub struct $name;
950
951        impl Plugin for $name {
952            fn name(&self) -> &'static str {
953                $display
954            }
955
956            fn enablers(&self) -> &'static [&'static str] {
957                $enablers
958            }
959
960            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
961            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
962            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
963            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
964            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
965            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
966            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
967            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
968            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
969            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
970
971            $(
972                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
973                    vec![$( ($pat, $exports) ),*]
974                }
975            )?
976
977            fn resolve_config(
978                &self,
979                config_path: &std::path::Path,
980                source: &str,
981                _root: &std::path::Path,
982            ) -> PluginResult {
983                let mut result = PluginResult::default();
984                let imports = crate::plugins::config_parser::extract_imports(source, config_path);
985                for imp in &imports {
986                    let dep = crate::resolve::extract_package_name(imp);
987                    result.referenced_dependencies.push(dep);
988                }
989                result
990            }
991        }
992    };
993
994    (
995        struct $name:ident => $display:expr,
996        enablers: $enablers:expr
997        $(, entry_patterns: $entry:expr)?
998        $(, config_patterns: $config:expr)?
999        $(, always_used: $always:expr)?
1000        $(, tooling_dependencies: $tooling:expr)?
1001        $(, fixture_glob_patterns: $fixtures:expr)?
1002        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1003        $(, virtual_module_prefixes: $virtual:expr)?
1004        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1005        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1006        $(, provided_dependencies: $provided_dependencies:expr)?
1007        $(, package_json_config_key: $pkg_key:expr)?
1008        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1009        , resolve_config($cp:ident, $src:ident, $root:ident) $body:block
1010        $(,)?
1011    ) => {
1012        pub struct $name;
1013
1014        impl Plugin for $name {
1015            fn name(&self) -> &'static str {
1016                $display
1017            }
1018
1019            fn enablers(&self) -> &'static [&'static str] {
1020                $enablers
1021            }
1022
1023            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1024            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1025            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1026            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1027            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1028            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1029            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1030            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1031            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1032            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1033
1034            $(
1035                fn package_json_config_key(&self) -> Option<&'static str> {
1036                    Some($pkg_key)
1037                }
1038            )?
1039
1040            $(
1041                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1042                    vec![$( ($pat, $exports) ),*]
1043                }
1044            )?
1045
1046            fn resolve_config(
1047                &self,
1048                $cp: &std::path::Path,
1049                $src: &str,
1050                $root: &std::path::Path,
1051            ) -> PluginResult
1052            $body
1053        }
1054    };
1055
1056    (
1057        struct $name:ident => $display:expr,
1058        enablers: $enablers:expr
1059        $(, entry_patterns: $entry:expr)?
1060        $(, config_patterns: $config:expr)?
1061        $(, always_used: $always:expr)?
1062        $(, tooling_dependencies: $tooling:expr)?
1063        $(, fixture_glob_patterns: $fixtures:expr)?
1064        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1065        $(, virtual_module_prefixes: $virtual:expr)?
1066        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1067        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1068        $(, provided_dependencies: $provided_dependencies:expr)?
1069        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1070        $(,)?
1071    ) => {
1072        pub struct $name;
1073
1074        impl Plugin for $name {
1075            fn name(&self) -> &'static str {
1076                $display
1077            }
1078
1079            fn enablers(&self) -> &'static [&'static str] {
1080                $enablers
1081            }
1082
1083            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1084            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1085            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1086            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1087            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1088            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1089            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1090            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1091            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1092            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1093
1094            $(
1095                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1096                    vec![$( ($pat, $exports) ),*]
1097                }
1098            )?
1099        }
1100    };
1101}
1102
1103pub mod config_parser;
1104pub mod registry;
1105mod tooling;
1106
1107pub use registry::{AggregatedPluginResult, PluginRegistry};
1108pub use tooling::is_known_tooling_dependency;
1109
1110mod adonis;
1111mod angular;
1112mod astro;
1113mod ava;
1114mod babel;
1115mod biome;
1116mod browser_extension;
1117mod bun;
1118mod c8;
1119mod capacitor;
1120mod changesets;
1121mod commitizen;
1122mod commitlint;
1123mod content_collections;
1124mod contentlayer;
1125mod convex;
1126mod cspell;
1127mod cucumber;
1128mod cypress;
1129mod danger;
1130mod dependency_cruiser;
1131mod docusaurus;
1132mod drizzle;
1133mod electron;
1134mod ember;
1135mod eslint;
1136mod expo;
1137mod expo_router;
1138mod firebase;
1139mod fumadocs;
1140mod gatsby;
1141mod graphql_codegen;
1142mod hardhat;
1143mod husky;
1144mod i18next;
1145mod ionic;
1146mod jest;
1147mod k6;
1148mod karma;
1149mod knex;
1150mod kysely;
1151mod lefthook;
1152mod lexical;
1153mod lint_staged;
1154mod lit;
1155mod markdownlint;
1156mod mintlify;
1157mod mocha;
1158mod msw;
1159mod nestjs;
1160mod next_intl;
1161mod nextjs;
1162mod nitro;
1163mod nodemon;
1164pub(crate) mod nuxt;
1165mod nx;
1166mod nyc;
1167mod obsidian;
1168mod openapi_ts;
1169mod opencode;
1170mod opennext_cloudflare;
1171mod oxlint;
1172mod pandacss;
1173mod parcel;
1174mod pinia;
1175mod pkg_utils;
1176mod playwright;
1177mod plop;
1178mod pm2;
1179mod pnpm;
1180mod postcss;
1181mod prettier;
1182mod prisma;
1183mod qwik;
1184mod react_compiler;
1185mod react_native;
1186mod react_router;
1187mod redwoodsdk;
1188mod relay;
1189mod remark;
1190mod remix;
1191mod rolldown;
1192mod rollup;
1193mod rsbuild;
1194mod rspack;
1195mod rspress;
1196mod sanity;
1197mod semantic_release;
1198mod sentry;
1199mod simple_git_hooks;
1200mod storybook;
1201mod stryker;
1202mod stylelint;
1203mod supabase;
1204mod sveltekit;
1205mod svgo;
1206mod svgr;
1207mod swc;
1208mod syncpack;
1209mod tailwind;
1210mod tanstack_router;
1211mod tap;
1212mod test_alias;
1213mod tsd;
1214mod tsdown;
1215mod tsup;
1216mod turborepo;
1217mod typedoc;
1218mod typeorm;
1219mod typescript;
1220mod unocss;
1221mod varlock;
1222mod velite;
1223mod vercel;
1224mod vite;
1225mod vitepress;
1226mod vitest;
1227mod vscode;
1228mod webdriverio;
1229mod webpack;
1230mod wrangler;
1231mod wuchale;
1232mod wxt;
1233
1234#[cfg(test)]
1235mod tests {
1236    use super::*;
1237    use std::path::Path;
1238
1239    #[test]
1240    fn is_enabled_with_deps_exact_match() {
1241        let plugin = nextjs::NextJsPlugin;
1242        let deps = vec!["next".to_string()];
1243        assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1244    }
1245
1246    #[test]
1247    fn is_enabled_with_deps_no_match() {
1248        let plugin = nextjs::NextJsPlugin;
1249        let deps = vec!["react".to_string()];
1250        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1251    }
1252
1253    #[test]
1254    fn is_enabled_with_deps_empty_deps() {
1255        let plugin = nextjs::NextJsPlugin;
1256        let deps: Vec<String> = vec![];
1257        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1258    }
1259
1260    #[test]
1261    fn entry_point_role_defaults_are_centralized() {
1262        assert_eq!(vite::VitePlugin.entry_point_role(), EntryPointRole::Runtime);
1263        assert_eq!(
1264            vitest::VitestPlugin.entry_point_role(),
1265            EntryPointRole::Test
1266        );
1267        assert_eq!(
1268            storybook::StorybookPlugin.entry_point_role(),
1269            EntryPointRole::Support
1270        );
1271        assert_eq!(
1272            obsidian::ObsidianPlugin.entry_point_role(),
1273            EntryPointRole::Runtime
1274        );
1275        assert_eq!(knex::KnexPlugin.entry_point_role(), EntryPointRole::Support);
1276    }
1277
1278    #[test]
1279    fn plugins_with_entry_patterns_have_explicit_role_intent() {
1280        let runtime_or_test_or_support: rustc_hash::FxHashSet<&'static str> =
1281            TEST_ENTRY_POINT_PLUGINS
1282                .iter()
1283                .chain(RUNTIME_ENTRY_POINT_PLUGINS.iter())
1284                .chain(SUPPORT_ENTRY_POINT_PLUGINS.iter())
1285                .copied()
1286                .collect();
1287
1288        for plugin in crate::plugins::registry::builtin::create_builtin_plugins() {
1289            if plugin.entry_patterns().is_empty() {
1290                continue;
1291            }
1292            assert!(
1293                runtime_or_test_or_support.contains(plugin.name()),
1294                "plugin '{}' exposes entry patterns but is missing from the entry-point role map",
1295                plugin.name()
1296            );
1297        }
1298    }
1299
1300    #[test]
1301    fn plugin_result_is_empty_when_default() {
1302        let r = PluginResult::default();
1303        assert!(r.is_empty());
1304    }
1305
1306    #[test]
1307    fn plugin_result_not_empty_with_entry_patterns() {
1308        let r = PluginResult {
1309            entry_patterns: vec!["*.ts".into()],
1310            ..Default::default()
1311        };
1312        assert!(!r.is_empty());
1313    }
1314
1315    #[test]
1316    fn plugin_result_not_empty_with_referenced_deps() {
1317        let r = PluginResult {
1318            referenced_dependencies: vec!["lodash".to_string()],
1319            ..Default::default()
1320        };
1321        assert!(!r.is_empty());
1322    }
1323
1324    #[test]
1325    fn plugin_result_not_empty_with_setup_files() {
1326        let r = PluginResult {
1327            setup_files: vec![PathBuf::from("/setup.ts")],
1328            ..Default::default()
1329        };
1330        assert!(!r.is_empty());
1331    }
1332
1333    #[test]
1334    fn plugin_result_not_empty_with_always_used_files() {
1335        let r = PluginResult {
1336            always_used_files: vec!["**/*.stories.tsx".to_string()],
1337            ..Default::default()
1338        };
1339        assert!(!r.is_empty());
1340    }
1341
1342    #[test]
1343    fn plugin_result_not_empty_with_fixture_patterns() {
1344        let r = PluginResult {
1345            fixture_patterns: vec!["**/__fixtures__/**/*".to_string()],
1346            ..Default::default()
1347        };
1348        assert!(!r.is_empty());
1349    }
1350
1351    #[test]
1352    fn is_enabled_with_deps_prefix_match() {
1353        let plugin = storybook::StorybookPlugin;
1354        let deps = vec!["@storybook/react".to_string()];
1355        assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1356    }
1357
1358    #[test]
1359    fn is_enabled_with_deps_prefix_no_match_without_slash() {
1360        let plugin = storybook::StorybookPlugin;
1361        let deps = vec!["@storybookish".to_string()];
1362        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1363    }
1364
1365    #[test]
1366    fn is_enabled_with_deps_multiple_enablers() {
1367        let plugin = vitest::VitestPlugin;
1368        let deps_vitest = vec!["vitest".to_string()];
1369        let deps_none = vec!["mocha".to_string()];
1370        assert!(plugin.is_enabled_with_deps(&deps_vitest, Path::new("/project")));
1371        assert!(!plugin.is_enabled_with_deps(&deps_none, Path::new("/project")));
1372    }
1373
1374    #[test]
1375    fn plugin_default_methods_return_empty() {
1376        let plugin = commitizen::CommitizenPlugin;
1377        assert!(
1378            plugin.tooling_dependencies().is_empty() || !plugin.tooling_dependencies().is_empty()
1379        );
1380        assert!(plugin.virtual_module_prefixes().is_empty());
1381        assert!(plugin.virtual_package_suffixes().is_empty());
1382        assert!(plugin.path_aliases(Path::new("/project")).is_empty());
1383        assert!(
1384            plugin.package_json_config_key().is_none()
1385                || plugin.package_json_config_key().is_some()
1386        );
1387    }
1388
1389    #[test]
1390    fn plugin_resolve_config_default_returns_empty() {
1391        let plugin = commitizen::CommitizenPlugin;
1392        let result = plugin.resolve_config(
1393            Path::new("/project/config.js"),
1394            "const x = 1;",
1395            Path::new("/project"),
1396        );
1397        assert!(result.is_empty());
1398    }
1399
1400    #[test]
1401    fn is_enabled_with_deps_exact_and_prefix_both_work() {
1402        let plugin = storybook::StorybookPlugin;
1403        let deps_exact = vec!["storybook".to_string()];
1404        assert!(plugin.is_enabled_with_deps(&deps_exact, Path::new("/project")));
1405        let deps_prefix = vec!["@storybook/vue3".to_string()];
1406        assert!(plugin.is_enabled_with_deps(&deps_prefix, Path::new("/project")));
1407    }
1408
1409    #[test]
1410    fn is_enabled_with_deps_multiple_enablers_remix() {
1411        let plugin = remix::RemixPlugin;
1412        let deps_node = vec!["@remix-run/node".to_string()];
1413        assert!(plugin.is_enabled_with_deps(&deps_node, Path::new("/project")));
1414        let deps_react = vec!["@remix-run/react".to_string()];
1415        assert!(plugin.is_enabled_with_deps(&deps_react, Path::new("/project")));
1416        let deps_cf = vec!["@remix-run/cloudflare".to_string()];
1417        assert!(plugin.is_enabled_with_deps(&deps_cf, Path::new("/project")));
1418    }
1419
1420    struct MinimalPlugin;
1421    impl Plugin for MinimalPlugin {
1422        fn name(&self) -> &'static str {
1423            "minimal"
1424        }
1425    }
1426
1427    #[test]
1428    fn default_enablers_is_empty() {
1429        assert!(MinimalPlugin.enablers().is_empty());
1430    }
1431
1432    #[test]
1433    fn default_entry_patterns_is_empty() {
1434        assert!(MinimalPlugin.entry_patterns().is_empty());
1435    }
1436
1437    #[test]
1438    fn default_config_patterns_is_empty() {
1439        assert!(MinimalPlugin.config_patterns().is_empty());
1440    }
1441
1442    #[test]
1443    fn default_always_used_is_empty() {
1444        assert!(MinimalPlugin.always_used().is_empty());
1445    }
1446
1447    #[test]
1448    fn default_used_exports_is_empty() {
1449        assert!(MinimalPlugin.used_exports().is_empty());
1450    }
1451
1452    #[test]
1453    fn default_tooling_dependencies_is_empty() {
1454        assert!(MinimalPlugin.tooling_dependencies().is_empty());
1455    }
1456
1457    #[test]
1458    fn default_fixture_glob_patterns_is_empty() {
1459        assert!(MinimalPlugin.fixture_glob_patterns().is_empty());
1460    }
1461
1462    #[test]
1463    fn default_virtual_module_prefixes_is_empty() {
1464        assert!(MinimalPlugin.virtual_module_prefixes().is_empty());
1465    }
1466
1467    #[test]
1468    fn default_virtual_package_suffixes_is_empty() {
1469        assert!(MinimalPlugin.virtual_package_suffixes().is_empty());
1470    }
1471
1472    #[test]
1473    fn default_path_aliases_is_empty() {
1474        assert!(MinimalPlugin.path_aliases(Path::new("/")).is_empty());
1475    }
1476
1477    #[test]
1478    fn default_resolve_config_returns_empty() {
1479        let r = MinimalPlugin.resolve_config(
1480            Path::new("config.js"),
1481            "export default {}",
1482            Path::new("/"),
1483        );
1484        assert!(r.is_empty());
1485    }
1486
1487    #[test]
1488    fn default_package_json_config_key_is_none() {
1489        assert!(MinimalPlugin.package_json_config_key().is_none());
1490    }
1491
1492    #[test]
1493    fn default_is_enabled_returns_false_when_no_enablers() {
1494        let deps = vec!["anything".to_string()];
1495        assert!(!MinimalPlugin.is_enabled_with_deps(&deps, Path::new("/")));
1496    }
1497
1498    #[test]
1499    fn all_builtin_plugin_names_are_unique() {
1500        let plugins = registry::builtin::create_builtin_plugins();
1501        let mut seen = std::collections::BTreeSet::new();
1502        for p in &plugins {
1503            let name = p.name();
1504            assert!(seen.insert(name), "duplicate plugin name: {name}");
1505        }
1506    }
1507
1508    #[test]
1509    fn all_builtin_plugins_have_enablers() {
1510        let plugins = registry::builtin::create_builtin_plugins();
1511        for p in &plugins {
1512            assert!(
1513                !p.enablers().is_empty(),
1514                "plugin '{}' has no enablers",
1515                p.name()
1516            );
1517        }
1518    }
1519
1520    #[test]
1521    fn plugins_with_config_patterns_have_always_used() {
1522        let plugins = registry::builtin::create_builtin_plugins();
1523        for p in &plugins {
1524            if !p.config_patterns().is_empty() {
1525                assert!(
1526                    !p.always_used().is_empty(),
1527                    "plugin '{}' has config_patterns but no always_used",
1528                    p.name()
1529                );
1530            }
1531        }
1532    }
1533
1534    #[test]
1535    fn framework_plugins_enablers() {
1536        let cases: Vec<(&dyn Plugin, &[&str])> = vec![
1537            (&nextjs::NextJsPlugin, &["next"]),
1538            (&nuxt::NuxtPlugin, &["nuxt"]),
1539            (&angular::AngularPlugin, &["@angular/core"]),
1540            (&ionic::IonicPlugin, &["@ionic/angular"]),
1541            (&sveltekit::SvelteKitPlugin, &["@sveltejs/kit"]),
1542            (&gatsby::GatsbyPlugin, &["gatsby"]),
1543        ];
1544        for (plugin, expected_enablers) in cases {
1545            let enablers = plugin.enablers();
1546            for expected in expected_enablers {
1547                assert!(
1548                    enablers.contains(expected),
1549                    "plugin '{}' should have '{}'",
1550                    plugin.name(),
1551                    expected
1552                );
1553            }
1554        }
1555    }
1556
1557    #[test]
1558    fn testing_plugins_enablers() {
1559        let cases: Vec<(&dyn Plugin, &str)> = vec![
1560            (&jest::JestPlugin, "jest"),
1561            (&vitest::VitestPlugin, "vitest"),
1562            (&playwright::PlaywrightPlugin, "@playwright/test"),
1563            (&cypress::CypressPlugin, "cypress"),
1564            (&mocha::MochaPlugin, "mocha"),
1565            (&stryker::StrykerPlugin, "@stryker-mutator/core"),
1566        ];
1567        for (plugin, enabler) in cases {
1568            assert!(
1569                plugin.enablers().contains(&enabler),
1570                "plugin '{}' should have '{}'",
1571                plugin.name(),
1572                enabler
1573            );
1574        }
1575    }
1576
1577    #[test]
1578    fn bundler_plugins_enablers() {
1579        let cases: Vec<(&dyn Plugin, &str)> = vec![
1580            (&vite::VitePlugin, "vite"),
1581            (&webpack::WebpackPlugin, "webpack"),
1582            (&rollup::RollupPlugin, "rollup"),
1583        ];
1584        for (plugin, enabler) in cases {
1585            assert!(
1586                plugin.enablers().contains(&enabler),
1587                "plugin '{}' should have '{}'",
1588                plugin.name(),
1589                enabler
1590            );
1591        }
1592    }
1593
1594    #[test]
1595    fn test_plugins_have_test_entry_patterns() {
1596        let test_plugins: Vec<&dyn Plugin> = vec![
1597            &bun::BunPlugin,
1598            &jest::JestPlugin,
1599            &vitest::VitestPlugin,
1600            &mocha::MochaPlugin,
1601            &tap::TapPlugin,
1602            &tsd::TsdPlugin,
1603        ];
1604        for plugin in test_plugins {
1605            let patterns = plugin.entry_patterns();
1606            assert!(
1607                !patterns.is_empty(),
1608                "test plugin '{}' should have entry patterns",
1609                plugin.name()
1610            );
1611            assert!(
1612                patterns
1613                    .iter()
1614                    .any(|p| p.contains("test") || p.contains("spec") || p.contains("__tests__")),
1615                "test plugin '{}' should have test/spec patterns",
1616                plugin.name()
1617            );
1618        }
1619    }
1620
1621    #[test]
1622    fn framework_plugins_have_entry_patterns() {
1623        let plugins: Vec<&dyn Plugin> = vec![
1624            &nextjs::NextJsPlugin,
1625            &nuxt::NuxtPlugin,
1626            &angular::AngularPlugin,
1627            &sveltekit::SvelteKitPlugin,
1628        ];
1629        for plugin in plugins {
1630            assert!(
1631                !plugin.entry_patterns().is_empty(),
1632                "framework plugin '{}' should have entry patterns",
1633                plugin.name()
1634            );
1635        }
1636    }
1637
1638    #[test]
1639    fn plugins_with_resolve_config_have_config_patterns() {
1640        let plugins: Vec<&dyn Plugin> = vec![
1641            &jest::JestPlugin,
1642            &vitest::VitestPlugin,
1643            &babel::BabelPlugin,
1644            &eslint::EslintPlugin,
1645            &webpack::WebpackPlugin,
1646            &storybook::StorybookPlugin,
1647            &typescript::TypeScriptPlugin,
1648            &postcss::PostCssPlugin,
1649            &nextjs::NextJsPlugin,
1650            &nuxt::NuxtPlugin,
1651            &angular::AngularPlugin,
1652            &nx::NxPlugin,
1653            &stryker::StrykerPlugin,
1654            &wuchale::WuchalePlugin,
1655            &rollup::RollupPlugin,
1656            &sveltekit::SvelteKitPlugin,
1657            &prettier::PrettierPlugin,
1658            &contentlayer::ContentlayerPlugin,
1659        ];
1660        for plugin in plugins {
1661            assert!(
1662                !plugin.config_patterns().is_empty(),
1663                "plugin '{}' with resolve_config should have config_patterns",
1664                plugin.name()
1665            );
1666        }
1667    }
1668
1669    #[test]
1670    fn plugin_tooling_deps_include_enabler_package() {
1671        let plugins: Vec<&dyn Plugin> = vec![
1672            &jest::JestPlugin,
1673            &vitest::VitestPlugin,
1674            &webpack::WebpackPlugin,
1675            &typescript::TypeScriptPlugin,
1676            &eslint::EslintPlugin,
1677            &prettier::PrettierPlugin,
1678            &danger::DangerPlugin,
1679            &stryker::StrykerPlugin,
1680            &wuchale::WuchalePlugin,
1681            &contentlayer::ContentlayerPlugin,
1682        ];
1683        for plugin in plugins {
1684            let tooling = plugin.tooling_dependencies();
1685            let enablers = plugin.enablers();
1686            assert!(
1687                enablers
1688                    .iter()
1689                    .any(|e| !e.ends_with('/') && tooling.contains(e)),
1690                "plugin '{}': at least one non-prefix enabler should be in tooling_dependencies",
1691                plugin.name()
1692            );
1693        }
1694    }
1695
1696    #[test]
1697    fn nextjs_has_used_exports_for_pages() {
1698        let plugin = nextjs::NextJsPlugin;
1699        let exports = plugin.used_exports();
1700        assert!(!exports.is_empty());
1701        assert!(exports.iter().any(|(_, names)| names.contains(&"default")));
1702    }
1703
1704    #[test]
1705    fn remix_has_used_exports_for_routes() {
1706        let plugin = remix::RemixPlugin;
1707        let exports = plugin.used_exports();
1708        assert!(!exports.is_empty());
1709        let route_entry = exports.iter().find(|(pat, _)| pat.contains("routes"));
1710        assert!(route_entry.is_some());
1711        let (_, names) = route_entry.unwrap();
1712        assert!(names.contains(&"loader"));
1713        assert!(names.contains(&"action"));
1714        assert!(names.contains(&"default"));
1715    }
1716
1717    #[test]
1718    fn sveltekit_has_used_exports_for_routes() {
1719        let plugin = sveltekit::SvelteKitPlugin;
1720        let exports = plugin.used_exports();
1721        assert!(!exports.is_empty());
1722        assert!(exports.iter().any(|(_, names)| names.contains(&"GET")));
1723    }
1724
1725    #[test]
1726    fn nuxt_has_hash_virtual_prefix() {
1727        assert!(nuxt::NuxtPlugin.virtual_module_prefixes().contains(&"#"));
1728    }
1729
1730    #[test]
1731    fn sveltekit_has_dollar_virtual_prefixes() {
1732        let prefixes = sveltekit::SvelteKitPlugin.virtual_module_prefixes();
1733        assert!(prefixes.contains(&"$app/"));
1734        assert!(prefixes.contains(&"$env/"));
1735        assert!(prefixes.contains(&"$lib/"));
1736    }
1737
1738    #[test]
1739    fn sveltekit_has_lib_path_alias() {
1740        let aliases = sveltekit::SvelteKitPlugin.path_aliases(Path::new("/project"));
1741        assert!(aliases.iter().any(|(prefix, _)| *prefix == "$lib/"));
1742    }
1743
1744    #[test]
1745    fn nuxt_has_tilde_path_alias() {
1746        let aliases = nuxt::NuxtPlugin.path_aliases(Path::new("/nonexistent"));
1747        assert!(aliases.iter().any(|(prefix, _)| *prefix == "~/"));
1748        assert!(aliases.iter().any(|(prefix, _)| *prefix == "~~/"));
1749    }
1750
1751    #[test]
1752    fn jest_has_package_json_config_key() {
1753        assert_eq!(jest::JestPlugin.package_json_config_key(), Some("jest"));
1754    }
1755
1756    #[test]
1757    fn tsd_has_package_json_config_key() {
1758        assert_eq!(tsd::TsdPlugin.package_json_config_key(), Some("tsd"));
1759    }
1760
1761    #[test]
1762    fn babel_has_package_json_config_key() {
1763        assert_eq!(babel::BabelPlugin.package_json_config_key(), Some("babel"));
1764    }
1765
1766    #[test]
1767    fn eslint_has_package_json_config_key() {
1768        assert_eq!(
1769            eslint::EslintPlugin.package_json_config_key(),
1770            Some("eslintConfig")
1771        );
1772    }
1773
1774    #[test]
1775    fn prettier_has_package_json_config_key() {
1776        assert_eq!(
1777            prettier::PrettierPlugin.package_json_config_key(),
1778            Some("prettier")
1779        );
1780    }
1781
1782    #[test]
1783    fn macro_generated_plugin_basic_properties() {
1784        let plugin = msw::MswPlugin;
1785        assert_eq!(plugin.name(), "msw");
1786        assert!(plugin.enablers().contains(&"msw"));
1787        assert!(!plugin.entry_patterns().is_empty());
1788        assert!(plugin.config_patterns().is_empty());
1789        assert!(!plugin.always_used().is_empty());
1790        assert!(!plugin.tooling_dependencies().is_empty());
1791    }
1792
1793    #[test]
1794    fn macro_generated_plugin_with_used_exports() {
1795        let plugin = remix::RemixPlugin;
1796        assert_eq!(plugin.name(), "remix");
1797        assert!(!plugin.used_exports().is_empty());
1798    }
1799
1800    #[test]
1801    fn macro_passes_through_virtual_package_suffixes() {
1802        define_plugin! {
1803            struct MacroSuffixSmokePlugin => "macro-suffix-smoke",
1804            enablers: &["macro-suffix-smoke"],
1805            virtual_package_suffixes: &["/__macro_smoke__"],
1806        }
1807
1808        let plugin = MacroSuffixSmokePlugin;
1809        assert_eq!(
1810            plugin.virtual_package_suffixes(),
1811            &["/__macro_smoke__"],
1812            "macro-declared virtual_package_suffixes must propagate to the trait method"
1813        );
1814    }
1815
1816    #[test]
1817    fn macro_generated_plugin_imports_only_resolve_config() {
1818        let plugin = cypress::CypressPlugin;
1819        let source = r"
1820            import { defineConfig } from 'cypress';
1821            import coveragePlugin from '@cypress/code-coverage';
1822            export default defineConfig({});
1823        ";
1824        let result = plugin.resolve_config(
1825            Path::new("cypress.config.ts"),
1826            source,
1827            Path::new("/project"),
1828        );
1829        assert!(
1830            result
1831                .referenced_dependencies
1832                .contains(&"cypress".to_string())
1833        );
1834        assert!(
1835            result
1836                .referenced_dependencies
1837                .contains(&"@cypress/code-coverage".to_string())
1838        );
1839    }
1840
1841    #[test]
1842    fn builtin_plugin_count_is_expected() {
1843        let plugins = registry::builtin::create_builtin_plugins();
1844        assert!(
1845            plugins.len() >= 80,
1846            "expected at least 80 built-in plugins, got {}",
1847            plugins.len()
1848        );
1849    }
1850}