Skip to main content

fallow_core/plugins/
mod.rs

1//! Plugin system for framework-aware codebase analysis.
2//!
3//! Plugins read JS, TS and JSON config files with the Oxc parser and walk the
4//! AST. They never run JavaScript. Each plugin implements the [`Plugin`] trait
5//! with static defaults (entry patterns, config file patterns, used exports)
6//! and reads config files for entries, dependencies and setup files.
7
8use std::path::{Path, PathBuf};
9
10use fallow_config::{
11    AutoImportRule, EntryPointRole, JsxImportSourceRule, PackageJson, UsedClassMemberRule,
12};
13use fallow_types::semantic::SemanticFrameworkContract;
14use regex::Regex;
15
16const TEST_ENTRY_POINT_PLUGINS: &[&str] = &[
17    "ava",
18    "bun",
19    "deno",
20    "cucumber",
21    "cypress",
22    "jasmine",
23    "jest",
24    "k6",
25    "mocha",
26    "playwright",
27    "rstest",
28    "tap",
29    "tsd",
30    "vitest",
31    "webdriverio",
32];
33
34const RUNTIME_ENTRY_POINT_PLUGINS: &[&str] = &[
35    "adonis",
36    "angular",
37    "astro",
38    "browser-extension",
39    "convex",
40    "docusaurus",
41    "egg",
42    "electron",
43    "ember",
44    "eve",
45    "expo",
46    "expo-router",
47    "flue",
48    "gatsby",
49    "hardhat",
50    "kibana",
51    "module-federation",
52    "nestjs",
53    "next-intl",
54    "nextjs",
55    "nitro",
56    "nuxt",
57    "obsidian",
58    "parcel",
59    "qwik",
60    "react-native",
61    "react-router",
62    "redwoodsdk",
63    "remix",
64    "rolldown",
65    "rollup",
66    "rsbuild",
67    "rspack",
68    "sanity",
69    "supabase",
70    "sveltekit",
71    "tanstack-router",
72    "tsdown",
73    "tsup",
74    "vercel",
75    "vite",
76    "vite-plus",
77    "vitepress",
78    "waku",
79    "webpack",
80    "wrangler",
81    "wxt",
82];
83
84/// Whether an entry rule of `result` matches the project-relative `path`, as
85/// entry point discovery compiles and matches the rules.
86#[cfg(test)]
87fn entry_rules_match(result: &PluginResult, path: &str) -> bool {
88    result
89        .entry_patterns
90        .iter()
91        .filter_map(|rule| CompiledPathRule::for_entry_rule(rule, "entry pattern"))
92        .any(|rule| rule.matches(path))
93}
94
95#[cfg(test)]
96const SUPPORT_ENTRY_POINT_PLUGINS: &[&str] = &[
97    "alchemy",
98    "content-collections",
99    "contentlayer",
100    "danger",
101    "drizzle",
102    "fumadocs",
103    "i18next",
104    "knex",
105    "kysely",
106    "mintlify",
107    "msw",
108    "opencode",
109    "prisma",
110    "storybook",
111    "stryker",
112    "typeorm",
113    "velite",
114];
115
116/// Which workspace diagnostic kind a plugin-stage advisory becomes.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum PluginConfigEffect {
119    /// The plugin could not read the key in full, so part of what it declares
120    /// never reached the analysis.
121    Unreadable,
122    /// The plugin read the key and does not model its effect, so a modeled
123    /// default the run would otherwise have applied stood down.
124    NotModeled,
125}
126
127/// One advisory about a config file a plugin read, before it becomes a
128/// [`fallow_config::WorkspaceDiagnostic`].
129///
130/// A plugin knows the fact (which config file, which key, why) but not the root
131/// the message renders against: in a workspace run its own `root` is the package
132/// root, while the diagnostic's path and message are project-root-relative. The
133/// conversion therefore happens once, where every plugin result has converged on
134/// the project root, and `config_path` is kept ABSOLUTE until then so the
135/// registry's canonical dedupe and the serialized root-relative form both work
136/// from one value (issue #2736).
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct PluginConfigDiagnostic {
139    /// Absolute path of the config file that was read.
140    pub config_path: PathBuf,
141    /// The plugin that read it, as it labels itself. Module Federation options
142    /// reach four bundler plugins inline, and each names itself rather than the
143    /// reader, because the config file the user must edit is the bundler's.
144    pub plugin: String,
145    /// The config key the advisory is about (`exposes`, `remotes`,
146    /// `components`, `imports`).
147    pub key: String,
148    /// Why, as a kebab-case token from the resulting kind's open set.
149    pub reason: String,
150    /// Which workspace diagnostic kind this becomes.
151    pub effect: PluginConfigEffect,
152}
153
154impl PluginConfigDiagnostic {
155    /// Build an advisory about a key a plugin could not read in full.
156    pub(super) fn unreadable(
157        config_path: &Path,
158        plugin: &str,
159        key: &str,
160        reason: &'static str,
161    ) -> Self {
162        Self {
163            config_path: config_path.to_path_buf(),
164            plugin: plugin.to_owned(),
165            key: key.to_owned(),
166            reason: reason.to_owned(),
167            effect: PluginConfigEffect::Unreadable,
168        }
169    }
170
171    /// Build an advisory about a key whose effect the plugin does not model.
172    pub(crate) fn not_modeled(
173        config_path: &Path,
174        plugin: &str,
175        key: &str,
176        reason: &'static str,
177    ) -> Self {
178        Self {
179            config_path: config_path.to_path_buf(),
180            plugin: plugin.to_owned(),
181            key: key.to_owned(),
182            reason: reason.to_owned(),
183            effect: PluginConfigEffect::NotModeled,
184        }
185    }
186
187    /// Render this advisory against the PROJECT root, which is the root every
188    /// consumer's paths are relative to.
189    #[must_use]
190    pub fn into_workspace_diagnostic(self, root: &Path) -> fallow_config::WorkspaceDiagnostic {
191        let Self {
192            config_path,
193            plugin,
194            key,
195            reason,
196            effect,
197        } = self;
198        let kind = match effect {
199            PluginConfigEffect::Unreadable => {
200                fallow_config::WorkspaceDiagnosticKind::PluginConfigUnreadable {
201                    plugin,
202                    key,
203                    reason,
204                }
205            }
206            PluginConfigEffect::NotModeled => {
207                fallow_config::WorkspaceDiagnosticKind::PluginEffectNotModeled {
208                    plugin,
209                    key,
210                    reason,
211                }
212            }
213        };
214        fallow_config::WorkspaceDiagnostic::new(root, config_path, kind)
215    }
216}
217
218/// Result of resolving a plugin's config file.
219#[derive(Debug, Default)]
220pub struct PluginResult {
221    /// Additional entry point glob patterns discovered from config.
222    entry_patterns: Vec<PathRule>,
223    /// When true, `entry_patterns` from config replace the plugin's static
224    /// `entry_patterns()` defaults instead of adding to them. Tools like Vitest
225    /// and Jest treat their config's include/testMatch as a replacement for built-in
226    /// defaults, so when the config is explicit the static patterns must be dropped.
227    replace_entry_patterns: bool,
228    /// When true, a replacing config removes only the static defaults, and the
229    /// replacing configs of one plugin run add their patterns together. When
230    /// false, the last replacing config of the plugin wins.
231    accumulate_config_entry_patterns: bool,
232    /// When true, `used_exports` from config replace the plugin's static
233    /// `used_export_rules()` defaults instead of adding to them.
234    replace_used_export_rules: bool,
235    /// Additional export-usage rules discovered from config.
236    used_exports: Vec<UsedExportRule>,
237    /// Exports that the tool reads from the files a config names. These rules
238    /// join the config-file export credit, so they count only under
239    /// `includeEntryExports`. Unlike `used_exports`, they never make an entry
240    /// point reportable when `includeEntryExports` is off.
241    entry_export_credits: Vec<UsedExportRule>,
242    /// Class member rules that should never be flagged as unused. Contributed
243    /// by plugins that know their framework invokes these methods at runtime
244    /// and may scope suppression via `extends` / `implements` constraints when
245    /// the method name is too common to allowlist globally.
246    used_class_members: Vec<UsedClassMemberRule>,
247    /// Dependencies referenced in config files (should not be flagged as unused).
248    referenced_dependencies: Vec<String>,
249    /// Dependencies a config credits only to the package that owns it, keyed
250    /// by the path of that package's `package.json`.
251    package_referenced_dependencies: Vec<(PathBuf, String)>,
252    /// Packages that a config needs installed. See [`RequiredDependency`].
253    required_dependencies: Vec<RequiredDependency>,
254    /// Additional files that are always considered used.
255    always_used_files: Vec<String>,
256    /// Path alias mappings discovered from config (prefix -> replacement directory).
257    path_aliases: Vec<(String, String)>,
258    /// Setup/helper files referenced from config.
259    setup_files: Vec<PathBuf>,
260    /// Test fixture glob patterns discovered from config.
261    fixture_patterns: Vec<String>,
262    /// Absolute directories to include when resolving SCSS/Sass `@import` and
263    /// `@use` specifiers. Contributed by framework plugins that read their
264    /// tool's equivalent of `includePaths` (e.g. Angular's
265    /// `stylePreprocessorOptions.includePaths` from `angular.json` /
266    /// `project.json`). Bare SCSS specifiers that fail to resolve relative to
267    /// the importing file retry against each include path using the SCSS
268    /// partial / directory-index conventions.
269    scss_include_paths: Vec<PathBuf>,
270    /// URL-to-filesystem static directory mappings discovered from tool config.
271    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
272    static_dir_mappings: Vec<(PathBuf, String)>,
273    framework_static_dir_mappings: Vec<(PathBuf, String)>,
274    /// File-scoped dependency providers. Matching imports are considered
275    /// available from the framework runtime and are not unlisted dependencies.
276    provided_dependencies: Vec<ProvidedDependencyRule>,
277    /// Advisories about the config file this result was read from. A plugin
278    /// records the fact here instead of printing it, so it reaches the report
279    /// and every consumer rather than only a stderr line.
280    config_diagnostics: Vec<PluginConfigDiagnostic>,
281    /// Where a Module Federation config exposes a file or declares a remote
282    /// alias, kept so a trace can name the config (issue #2796).
283    federation_sources: Vec<FederationSource>,
284    /// JSX import sources that the config sets for the files it transforms.
285    /// The resolver adds the runtime edge to each matching file without a
286    /// JSX pragma.
287    jsx_import_sources: Vec<JsxImportSourceRule>,
288    /// Runtime packages that the JSX transform of a config imports when the
289    /// config sets no import source. The analysis credits a package only when
290    /// a matching file has JSX and no pragma. These rules never add a graph
291    /// edge.
292    jsx_package_credits: Vec<JsxImportSourceRule>,
293    /// The directories of the tsconfig files that set the JSX runtime of
294    /// TypeScript files, through `jsxImportSource` or a `jsx` mode that adds
295    /// no automatic runtime import. Vite then does not use the default
296    /// `react` runtime for the TypeScript files below these directories.
297    tsconfig_jsx_dirs: Vec<PathBuf>,
298}
299
300/// What a Module Federation config declares, and where, for the trace output.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub struct FederationSource {
303    /// What the config names.
304    pub target: FederationSourceTarget,
305    /// The absolute path of the config file.
306    pub config_path: PathBuf,
307    /// The plugin that read the config, as it labels itself.
308    pub plugin: String,
309    /// The config key that names the target.
310    pub key: &'static str,
311}
312
313/// The thing a [`FederationSource`] names.
314#[derive(Debug, Clone, PartialEq, Eq)]
315pub enum FederationSourceTarget {
316    /// An `exposes` target, as the entry-point rule it became.
317    Exposed(PathRule),
318    /// A `remotes` alias.
319    Remote(String),
320}
321
322impl FederationSource {
323    #[must_use]
324    fn prefixed(&self, ws_prefix: &str) -> Self {
325        let target = match &self.target {
326            FederationSourceTarget::Exposed(rule) => {
327                FederationSourceTarget::Exposed(rule.prefixed(ws_prefix))
328            }
329            FederationSourceTarget::Remote(alias) => FederationSourceTarget::Remote(alias.clone()),
330        };
331        Self {
332            target,
333            config_path: self.config_path.clone(),
334            plugin: self.plugin.clone(),
335            key: self.key,
336        }
337    }
338}
339
340/// Match the Module Federation sources of one analysis against the discovered
341/// files, for the trace output.
342///
343/// Only a project with a Federation config pays for the match, and it runs
344/// once per analysis, so a trace reads plain data. A remote that a literal
345/// runtime call (`registerRemotes`, `loadRemote`, `init`, `createInstance`) names traces to the source
346/// file, with the function name as the key.
347#[must_use]
348fn federation_trace_provenance(
349    root: &Path,
350    files: &[crate::discover::DiscoveredFile],
351    sources: &[FederationSource],
352    modules: &[crate::extract::ModuleInfo],
353) -> fallow_types::trace::TraceProvenance {
354    let mut provenance = fallow_types::trace::TraceProvenance::default();
355    push_runtime_remote_sources(&mut provenance, root, files, modules);
356    if sources.is_empty() {
357        return provenance;
358    }
359    let mut exposed = Vec::new();
360    for source in sources {
361        let config = source
362            .config_path
363            .strip_prefix(root)
364            .unwrap_or(&source.config_path)
365            .to_path_buf();
366        let trace_source = fallow_types::trace::TraceSource {
367            kind: "module-federation".to_owned(),
368            plugin: source.plugin.clone(),
369            config,
370            key: source.key.to_owned(),
371        };
372        match &source.target {
373            FederationSourceTarget::Exposed(rule) => {
374                if let Some(compiled) =
375                    CompiledPathRule::for_entry_rule(rule, "Module Federation exposes target")
376                {
377                    exposed.push((compiled, trace_source));
378                }
379            }
380            FederationSourceTarget::Remote(alias) => {
381                provenance.push_dependency(alias.clone(), trace_source);
382            }
383        }
384    }
385    if exposed.is_empty() {
386        return provenance;
387    }
388    for file in files {
389        let Ok(relative) = file.path.strip_prefix(root) else {
390            continue;
391        };
392        let relative_str = relative.to_string_lossy().replace('\\', "/");
393        for (rule, source) in &exposed {
394            if rule.matches(&relative_str) {
395                provenance.push_file(relative.to_path_buf(), source.clone());
396            }
397        }
398    }
399    provenance
400}
401
402/// Export names that frameworks read as configuration, not as code.
403///
404/// A plugin `used_exports` rule can list these names next to real handlers
405/// (Next.js lists `dynamic` next to `GET` and `default`). Only a listed name
406/// with a literal value counts as configuration, so the review brief does not
407/// ask for a test of it. Extend this set when a new plugin adds a
408/// configuration-only export. Never add a name that holds behavior, such as
409/// `generateMetadata`, `loader` or a route handler.
410const CONFIG_ONLY_EXPORT_NAMES: &[&str] = &[
411    "dynamic",
412    "dynamicParams",
413    "revalidate",
414    "fetchCache",
415    "runtime",
416    "preferredRegion",
417    "maxDuration",
418    "prerender",
419    "config",
420    "metadata",
421    "viewport",
422];
423
424/// Record why the unused devDependency check credits each plugin tooling
425/// dependency, so `--trace-dependency` explains the credit instead of calling
426/// the dependency unused.
427fn push_tooling_trace_credits(
428    provenance: &mut fallow_types::trace::TraceProvenance,
429    root: &Path,
430    workspaces: &[fallow_config::WorkspaceInfo],
431    plugin_result: &AggregatedPluginResult,
432) {
433    for entry in &plugin_result.plugin_tooling {
434        let Some(evidence) = entry.evidence(&plugin_result.script_used_packages) else {
435            continue;
436        };
437        let credit = match evidence {
438            PluginToolingEvidence::OwnConfig(config) => fallow_types::trace::ToolingCredit {
439                reason: "plugin-config".to_owned(),
440                plugin: Some(entry.plugin.clone()),
441                config: Some(config.strip_prefix(root).unwrap_or(config).to_path_buf()),
442                reference: None,
443            },
444            PluginToolingEvidence::Reference(name) => fallow_types::trace::ToolingCredit {
445                reason: "plugin-reference".to_owned(),
446                plugin: Some(entry.plugin.clone()),
447                config: None,
448                reference: Some(name.to_owned()),
449            },
450        };
451        for dependency in &entry.dependencies {
452            provenance.push_tooling_credit(dependency.clone(), credit.clone());
453        }
454    }
455    push_types_trace_credits(provenance, plugin_result);
456    push_catalogue_trace_credits(provenance, root, workspaces, plugin_result);
457}
458
459/// Record why the unused devDependency check credits each catalogue entry in
460/// `devDependencies` that the trace would otherwise call unused: a library
461/// entry by name, a command-line tool by its own config file or its
462/// package.json key, and any entry that the same manifest lists in
463/// `peerDependencies`.
464///
465/// The check reads each declaring manifest on its own, so a credit here comes
466/// from a manifest that declares the name. A config in a sibling workspace
467/// gives no credit.
468fn push_catalogue_trace_credits(
469    provenance: &mut fallow_types::trace::TraceProvenance,
470    root: &Path,
471    workspaces: &[fallow_config::WorkspaceInfo],
472    plugin_result: &AggregatedPluginResult,
473) {
474    let manifests = read_trace_manifests(root, workspaces);
475    let mut names: Vec<&String> = plugin_result.dev_dependency_names.iter().collect();
476    names.sort_unstable();
477    for name in names {
478        let declaring: Vec<&(PathBuf, serde_json::Value)> = manifests
479            .iter()
480            .filter(|(_, manifest)| manifest_lists(manifest, "devDependencies", name))
481            .collect();
482        if let Some(credit) = catalogue_credit(name, root, &declaring) {
483            provenance.push_tooling_credit(name.clone(), credit);
484        }
485        if let Some((path, _)) = declaring
486            .iter()
487            .find(|(_, manifest)| manifest_lists(manifest, "peerDependencies", name))
488        {
489            provenance.push_tooling_credit(
490                name.clone(),
491                fallow_types::trace::ToolingCredit {
492                    reason: "own-peer".to_owned(),
493                    plugin: None,
494                    config: Some(path.strip_prefix(root).unwrap_or(path).to_path_buf()),
495                    reference: None,
496                },
497            );
498        }
499    }
500}
501
502/// The root manifest and each workspace manifest, parsed, root first.
503fn read_trace_manifests(
504    root: &Path,
505    workspaces: &[fallow_config::WorkspaceInfo],
506) -> Vec<(PathBuf, serde_json::Value)> {
507    std::iter::once(root)
508        .chain(
509            workspaces
510                .iter()
511                .map(|ws| ws.root.as_path())
512                .filter(|ws_root| *ws_root != root),
513        )
514        .filter_map(|package_root| {
515            let path = package_root.join("package.json");
516            let content = std::fs::read_to_string(&path).ok()?;
517            serde_json::from_str(&content)
518                .ok()
519                .map(|value| (path, value))
520        })
521        .collect()
522}
523
524fn manifest_lists(manifest: &serde_json::Value, section: &str, name: &str) -> bool {
525    manifest
526        .get(section)
527        .and_then(serde_json::Value::as_object)
528        .is_some_and(|deps| deps.contains_key(name))
529}
530
531/// The catalogue credit of `name` from the first declaring manifest that the
532/// unused devDependency check credits.
533fn catalogue_credit(
534    name: &str,
535    root: &Path,
536    declaring: &[&(PathBuf, serde_json::Value)],
537) -> Option<fallow_types::trace::ToolingCredit> {
538    if is_ambient_types_package(name) || types_package_target(name).is_some() {
539        return None;
540    }
541    let Some(patterns) = cli_tooling_config_patterns(name) else {
542        return is_known_tooling_dependency(name).then(|| fallow_types::trace::ToolingCredit {
543            reason: "known-tooling".to_owned(),
544            plugin: None,
545            config: None,
546            reference: None,
547        });
548    };
549    let config = declaring.iter().find_map(|(path, manifest)| {
550        crate::analyze::cli_tool_own_config(name, patterns, root, path, Some(manifest))
551    })?;
552    Some(fallow_types::trace::ToolingCredit {
553        reason: "known-tooling-config".to_owned(),
554        plugin: None,
555        config: Some(config.strip_prefix(root).unwrap_or(&config).to_path_buf()),
556        reference: None,
557    })
558}
559
560/// Record why the unused devDependency check credits each type package in
561/// `devDependencies`: ambient globals, a declared target package, or a
562/// tsconfig `types` entry. A target that the code imports is credited by the trace
563/// itself, which reads the module graph.
564fn push_types_trace_credits(
565    provenance: &mut fallow_types::trace::TraceProvenance,
566    plugin_result: &AggregatedPluginResult,
567) {
568    let declared = plugin_result.dependency_binaries.declared_packages();
569    let mut names: Vec<&String> = plugin_result.dev_dependency_names.iter().collect();
570    names.sort_unstable();
571    for name in names {
572        let credit = if is_ambient_types_package(name) {
573            fallow_types::trace::ToolingCredit {
574                reason: "ambient-types".to_owned(),
575                plugin: None,
576                config: None,
577                reference: None,
578            }
579        } else if let Some(target) = types_package_target(name) {
580            if declared.contains(&target) {
581                fallow_types::trace::ToolingCredit {
582                    reason: "types-target".to_owned(),
583                    plugin: None,
584                    config: None,
585                    reference: Some(target),
586                }
587            } else if plugin_result.referenced_dependencies.contains(name) {
588                fallow_types::trace::ToolingCredit {
589                    reason: "types-config".to_owned(),
590                    plugin: None,
591                    config: None,
592                    reference: None,
593                }
594            } else {
595                continue;
596            }
597        } else {
598            continue;
599        };
600        provenance.push_tooling_credit(name.clone(), credit);
601    }
602}
603
604/// Add a trace source for each remote that a literal runtime call names.
605fn push_runtime_remote_sources(
606    provenance: &mut fallow_types::trace::TraceProvenance,
607    root: &Path,
608    files: &[crate::discover::DiscoveredFile],
609    modules: &[crate::extract::ModuleInfo],
610) {
611    for module in modules {
612        let mut file = None;
613        for fact in module.semantic_facts.iter() {
614            let fallow_types::extract::SemanticFact::FederationRuntimeRemote(fact) = fact else {
615                continue;
616            };
617            let Some(remote) = &fact.remote else {
618                continue;
619            };
620            let Some(path) = file.get_or_insert_with(|| {
621                files.get(module.file_id.0 as usize).map(|file| {
622                    file.path
623                        .strip_prefix(root)
624                        .unwrap_or(&file.path)
625                        .to_path_buf()
626                })
627            }) else {
628                break;
629            };
630            provenance.push_dependency(
631                remote.clone(),
632                fallow_types::trace::TraceSource {
633                    kind: "module-federation".to_owned(),
634                    plugin: "module-federation".to_owned(),
635                    config: path.clone(),
636                    key: fact.call.name().to_owned(),
637                },
638            );
639        }
640    }
641}
642
643impl PluginResult {
644    /// Register `entry` values that a bundler reads relative to the directory
645    /// of its config file. The project root run and the workspace run can read
646    /// the same config, so each value is anchored at the config directory. A
647    /// value with a leading `!` excludes its matches from every other value.
648    fn extend_config_dir_entry_patterns(
649        &mut self,
650        values: Vec<String>,
651        config_path: &Path,
652        root: &Path,
653    ) {
654        let (negated, positive): (Vec<String>, Vec<String>) =
655            values.into_iter().partition(|value| value.starts_with('!'));
656        let excluded: Vec<String> = negated
657            .iter()
658            .filter_map(|value| value.strip_prefix('!'))
659            .filter_map(|value| config_parser::normalize_config_path(value, config_path, root))
660            .collect();
661        self.entry_patterns.extend(
662            positive
663                .iter()
664                .filter_map(|value| config_parser::normalize_config_path(value, config_path, root))
665                .map(|pattern| {
666                    PathRule::new(pattern).with_excluded_globs(excluded.iter().cloned())
667                }),
668        );
669    }
670
671    /// Register an entry pattern whose leading `../` segments are relative to
672    /// the plugin root. The workspace prefix resolves them.
673    fn push_parent_relative_entry_pattern(&mut self, pattern: String) {
674        let mut rule = PathRule::new(pattern);
675        rule.parent_relative = true;
676        self.entry_patterns.push(rule);
677    }
678
679    fn push_entry_pattern(&mut self, pattern: impl Into<String>) {
680        self.entry_patterns
681            .push(PathRule::new(normalize_entry_pattern(pattern.into())));
682    }
683
684    fn extend_entry_patterns<I, S>(&mut self, patterns: I)
685    where
686        I: IntoIterator<Item = S>,
687        S: Into<String>,
688    {
689        self.entry_patterns.extend(
690            patterns
691                .into_iter()
692                .map(|pat| PathRule::new(normalize_entry_pattern(pat.into()))),
693        );
694    }
695
696    /// Route each config value to the surface that can use it: a value naming a
697    /// module request credits its package, every other value becomes an entry
698    /// pattern.
699    ///
700    /// A bundler `entry` accepts a project file and a bare module request such as
701    /// `react-hot-loader/patch` in the same list. A module request names no file,
702    /// so a glob built from it matches nothing while the package still needs
703    /// dependency credit. Module Federation `exposes` targets already split the
704    /// two this way (issue #2706); bundler entries now do too (issue #2739).
705    ///
706    /// `resolve_path` maps a path value to its project-relative form, for
707    /// example against a `context` directory. It runs after the value is
708    /// classified, because a joined path such as `app/main` no longer carries
709    /// the `./` that marks it as a path.
710    fn extend_entry_patterns_or_dependencies<I, S>(
711        &mut self,
712        values: I,
713        resolve_path: impl Fn(String) -> String,
714    ) where
715        I: IntoIterator<Item = S>,
716        S: Into<String>,
717    {
718        for value in values {
719            let value = value.into();
720            if let Some(request) = module_request(&value) {
721                self.referenced_dependencies
722                    .push(crate::resolve::extract_package_name(request));
723                continue;
724            }
725            self.push_entry_path(resolve_path(value));
726        }
727    }
728
729    /// Route each value of a rollup-style `input` to both surfaces when it is
730    /// ambiguous.
731    ///
732    /// Rollup, rolldown and vite resolve an `input` value with no importer: a
733    /// resolve plugin can read it as a module request, and without one it is a
734    /// path relative to the working directory. A value without `./`, `../` or
735    /// `/`, without a source extension and without glob syntax can therefore
736    /// name either one. It keeps the entry pattern, and it credits the package
737    /// unless the value names a file under `root`. A value that names a
738    /// project file is a path, so it must not hide an unused package that has
739    /// the same first segment (issue #2753).
740    fn extend_entry_patterns_and_dependencies<I, S>(&mut self, values: I, root: &Path)
741    where
742        I: IntoIterator<Item = S>,
743        S: Into<String>,
744    {
745        for value in values {
746            let value = value.into();
747            if let Some(request) = module_request(&value)
748                && !names_project_file(root, request)
749            {
750                self.referenced_dependencies
751                    .push(crate::resolve::extract_package_name(request));
752            }
753            self.push_entry_path(value);
754        }
755    }
756
757    /// Register each value as a bundler entry path.
758    fn extend_entry_paths<I, S>(&mut self, values: I)
759    where
760        I: IntoIterator<Item = S>,
761        S: Into<String>,
762    {
763        for value in values {
764            self.push_entry_path(value.into());
765        }
766    }
767
768    /// Register a bundler entry path.
769    ///
770    /// A bundler resolves an entry without a source extension the way it
771    /// resolves an import: first as a file with each extension, then as a
772    /// directory through its index file. `./lib` therefore names
773    /// `lib/index.ts`, and `./src/app` names `src/app.ts`. The value as written
774    /// stays a pattern too, so a file without an extension still matches.
775    fn push_entry_path(&mut self, value: String) {
776        if has_glob_syntax(&value) || has_source_extension(&value) {
777            self.push_entry_pattern(value);
778            return;
779        }
780        let base = value.trim_end_matches('/').to_owned();
781        self.push_entry_pattern(value);
782        self.push_entry_pattern(format!("{base}.{REQUEST_EXTENSIONS}"));
783        self.push_entry_pattern(format!("{base}/index.{REQUEST_EXTENSIONS}"));
784    }
785
786    /// Whether this result contributes nothing, which lets the registry skip a
787    /// config file entirely.
788    ///
789    /// A config that yields only a diagnostic is NOT empty: an unreadable
790    /// `exposes` in a config that declares nothing else is exactly the case the
791    /// advisory exists for, and skipping the result would drop it.
792    #[must_use]
793    const fn is_empty(&self) -> bool {
794        self.config_diagnostics.is_empty()
795            && self.entry_patterns.is_empty()
796            && self.used_exports.is_empty()
797            && self.entry_export_credits.is_empty()
798            && self.used_class_members.is_empty()
799            && self.referenced_dependencies.is_empty()
800            && self.package_referenced_dependencies.is_empty()
801            && self.required_dependencies.is_empty()
802            && self.always_used_files.is_empty()
803            && self.path_aliases.is_empty()
804            && self.setup_files.is_empty()
805            && self.fixture_patterns.is_empty()
806            && self.scss_include_paths.is_empty()
807            && self.static_dir_mappings.is_empty()
808            && self.framework_static_dir_mappings.is_empty()
809            && self.provided_dependencies.is_empty()
810            && self.federation_sources.is_empty()
811            && self.jsx_import_sources.is_empty()
812            && self.jsx_package_credits.is_empty()
813            && self.tsconfig_jsx_dirs.is_empty()
814    }
815}
816
817/// Whether an extensionless value names a file under `root`: the value itself,
818/// the value with a source extension, or the index file of the directory it
819/// names. This is the order in which a bundler resolves a path.
820fn names_project_file(root: &Path, value: &str) -> bool {
821    let base = root.join(value);
822    base.is_file()
823        || crate::discover::SOURCE_EXTENSIONS.iter().any(|extension| {
824            let mut candidate = base.clone().into_os_string();
825            candidate.push(".");
826            candidate.push(extension);
827            Path::new(&candidate).is_file() || base.join(format!("index.{extension}")).is_file()
828        })
829}
830
831/// Brace list of the extensions a bundler tries for a request that names no
832/// extension. Entry patterns are plain globs with no extension expansion, so a
833/// bare `src/Button` would match no file.
834const REQUEST_EXTENSIONS: &str = "{ts,tsx,mts,cts,gts,js,jsx,mjs,cjs,gjs,vue,svelte,astro,mdx}";
835
836fn normalize_entry_pattern(pattern: String) -> String {
837    pattern
838        .strip_prefix("./")
839        .map(str::to_owned)
840        .unwrap_or(pattern)
841}
842
843/// The module request a config value names, or `None` when the value names a
844/// file or a pattern over project files.
845///
846/// A bundler resolves a value without a leading `./`, `../` or `/` and without a
847/// source extension through module resolution, so it names a package. Both
848/// Module Federation `exposes` targets and bundler `entry` values are read this
849/// way. A value carrying glob syntax is a path in every case: no module
850/// resolution accepts a glob, so `src/pages/**` stays an entry pattern. A
851/// resource query is not part of the request, so it is dropped before both
852/// tests and before the package name is taken.
853fn module_request(value: &str) -> Option<&str> {
854    let request = strip_resource_query(value);
855    (config_parser::is_package_specifier(request)
856        && !has_glob_syntax(request)
857        && !has_source_extension(request))
858    .then_some(request)
859}
860
861/// Drop a trailing resource query from a config value.
862///
863/// A bundler hands everything after the first `?` to the loader, so the standard
864/// hot-reload entry `webpack-hot-middleware/client?reload=true` names the
865/// package's `client` module. A `?` is also the single-character glob wildcard,
866/// so what follows it decides: `reload=true` is a query, the `.ts` of
867/// `src/pag?.ts` is not.
868fn strip_resource_query(value: &str) -> &str {
869    match value.split_once('?') {
870        Some((request, query)) if is_resource_query(query) => request,
871        _ => value,
872    }
873}
874
875/// Whether a string is an `&`-separated list of `key` or `key=value` pairs whose
876/// keys read like identifiers.
877fn is_resource_query(query: &str) -> bool {
878    !query.is_empty()
879        && query.split('&').all(|pair| {
880            let key = pair.split_once('=').map_or(pair, |(key, _)| key);
881            key.starts_with(|first: char| first.is_ascii_alphanumeric() || first == '_')
882                && key
883                    .chars()
884                    .all(|char| char.is_ascii_alphanumeric() || matches!(char, '_' | '-' | '.'))
885        })
886}
887
888/// Whether a config value carries glob metacharacters, which makes it a pattern
889/// over project files rather than a single path or module request.
890fn has_glob_syntax(value: &str) -> bool {
891    value.contains('*') || value.contains('?') || value.contains('[') || value.contains('{')
892}
893
894/// Whether a config value carries an extension discovery analyzes. Discovery's
895/// own extension set decides, so a value naming a file type discovery does not
896/// analyze stays a module request.
897fn has_source_extension(value: &str) -> bool {
898    Path::new(value)
899        .extension()
900        .and_then(|ext| ext.to_str())
901        .is_some_and(|ext| {
902            crate::discover::SOURCE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())
903        })
904}
905
906/// A file-pattern rule with optional exclusion globs plus path-level or
907/// segment-level regex filters.
908///
909/// Exclusion regexes are matched against the project-relative path and should be
910/// anchored when generated dynamically so they can be safely workspace-prefixed.
911#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
912pub struct PathRule {
913    pub pattern: String,
914    pub exclude_globs: Vec<String>,
915    pub exclude_regexes: Vec<String>,
916    /// Regexes matched against individual path segments. These are not prefixed
917    /// for workspaces because they intentionally operate on segment names rather
918    /// than the full project-relative path.
919    pub exclude_segment_regexes: Vec<String>,
920    /// Whether the leading `../` segments of `pattern` are relative to the
921    /// plugin root, so the workspace prefix resolves them. Only the Module
922    /// Federation reader sets it, for an `exposes` target in a sibling
923    /// workspace. Other plugins emit patterns relative to a config directory,
924    /// such as the Storybook `../src/**`, which must not climb out of the
925    /// workspace.
926    pub parent_relative: bool,
927}
928
929impl PathRule {
930    #[must_use]
931    pub(crate) fn new(pattern: impl Into<String>) -> Self {
932        Self {
933            pattern: pattern.into(),
934            exclude_globs: Vec::new(),
935            exclude_regexes: Vec::new(),
936            exclude_segment_regexes: Vec::new(),
937            parent_relative: false,
938        }
939    }
940
941    #[must_use]
942    fn from_static(pattern: &'static str) -> Self {
943        Self::new(pattern)
944    }
945
946    /// A rule for a tool glob with extglob groups, such as `!(*.spec)`. The
947    /// rule matches at least the paths that the tool matches. Each negated
948    /// group becomes an excluded glob.
949    #[must_use]
950    fn from_extglob(pattern: &str) -> Self {
951        let rewritten = fallow_config::extglob::rewrite_include(pattern);
952        Self::new(rewritten.include).with_excluded_globs(rewritten.excludes)
953    }
954
955    /// Exclude the paths of tool globs with extglob groups. An excluded glob
956    /// never removes more paths than the tool does, so a glob with a negated
957    /// group excludes nothing.
958    #[must_use]
959    fn with_excluded_extglobs<I, S>(self, patterns: I) -> Self
960    where
961        I: IntoIterator<Item = S>,
962        S: AsRef<str>,
963    {
964        let excluded: Vec<String> = patterns
965            .into_iter()
966            .filter_map(|pattern| fallow_config::extglob::rewrite_exclude(pattern.as_ref()))
967            .collect();
968        self.with_excluded_globs(excluded)
969    }
970
971    #[must_use]
972    pub(crate) fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
973    where
974        I: IntoIterator<Item = S>,
975        S: Into<String>,
976    {
977        self.exclude_globs
978            .extend(patterns.into_iter().map(Into::into));
979        self
980    }
981
982    #[must_use]
983    fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
984    where
985        I: IntoIterator<Item = S>,
986        S: Into<String>,
987    {
988        self.exclude_regexes
989            .extend(patterns.into_iter().map(Into::into));
990        self
991    }
992
993    #[must_use]
994    fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
995    where
996        I: IntoIterator<Item = S>,
997        S: Into<String>,
998    {
999        self.exclude_segment_regexes
1000            .extend(patterns.into_iter().map(Into::into));
1001        self
1002    }
1003
1004    #[must_use]
1005    fn prefixed(&self, ws_prefix: &str) -> Self {
1006        let prefix = |pattern: &str| {
1007            if self.parent_relative && pattern.starts_with("../") {
1008                resolve_parent_relative_pattern(pattern, ws_prefix)
1009            } else {
1010                prefix_workspace_pattern(pattern, ws_prefix)
1011            }
1012        };
1013        Self {
1014            pattern: prefix(&self.pattern),
1015            exclude_globs: self
1016                .exclude_globs
1017                .iter()
1018                .map(|pattern| prefix(pattern))
1019                .collect(),
1020            exclude_regexes: self
1021                .exclude_regexes
1022                .iter()
1023                .map(|pattern| prefix_workspace_regex(pattern, ws_prefix))
1024                .collect(),
1025            exclude_segment_regexes: self.exclude_segment_regexes.clone(),
1026            parent_relative: false,
1027        }
1028    }
1029}
1030
1031/// A file-scoped dependency provider rule contributed by a framework plugin.
1032#[derive(Debug, Clone, Default, PartialEq, Eq)]
1033pub struct ProvidedDependencyRule {
1034    pub(crate) path: PathRule,
1035    exact_specifiers: Vec<String>,
1036    specifier_prefixes: Vec<String>,
1037}
1038
1039impl ProvidedDependencyRule {
1040    #[must_use]
1041    fn new(
1042        pattern: impl Into<String>,
1043        exact_specifiers: impl IntoIterator<Item = impl Into<String>>,
1044        specifier_prefixes: impl IntoIterator<Item = impl Into<String>>,
1045    ) -> Self {
1046        Self {
1047            path: PathRule::new(pattern),
1048            exact_specifiers: exact_specifiers.into_iter().map(Into::into).collect(),
1049            specifier_prefixes: specifier_prefixes.into_iter().map(Into::into).collect(),
1050        }
1051    }
1052
1053    #[must_use]
1054    fn prefixed(&self, ws_prefix: &str) -> Self {
1055        Self {
1056            path: self.path.prefixed(ws_prefix),
1057            exact_specifiers: self.exact_specifiers.clone(),
1058            specifier_prefixes: self.specifier_prefixes.clone(),
1059        }
1060    }
1061
1062    #[must_use]
1063    pub(crate) fn may_cover_package(&self, package_name: &str) -> bool {
1064        self.exact_specifiers
1065            .iter()
1066            .chain(self.specifier_prefixes.iter())
1067            .any(|specifier| crate::resolve::extract_package_name(specifier) == package_name)
1068    }
1069
1070    #[must_use]
1071    pub(crate) fn covers_specifier(&self, specifier: &str) -> bool {
1072        self.exact_specifiers
1073            .iter()
1074            .any(|allowed| allowed == specifier)
1075            || self
1076                .specifier_prefixes
1077                .iter()
1078                .any(|prefix| specifier.starts_with(prefix))
1079    }
1080}
1081
1082/// Compile the include glob of an entry rule. Its `*` stays in one path
1083/// segment, and it accepts an empty alternative, such as `{,m}js`, because
1084/// the rewrite of an extglob `?(m)` group gives one.
1085pub(crate) fn entry_rule_glob(pattern: &str) -> Result<globset::Glob, globset::Error> {
1086    globset::GlobBuilder::new(pattern)
1087        .literal_separator(true)
1088        .empty_alternates(true)
1089        .build()
1090}
1091
1092/// A compiled path rule matcher shared by entry-point and used-export matching.
1093///
1094/// Every glob accepts an empty alternative, such as `{,m}js`, because the
1095/// rewrite of an extglob `?(m)` group gives one.
1096#[derive(Debug, Clone)]
1097pub(crate) struct CompiledPathRule {
1098    include: globset::GlobMatcher,
1099    exclude_globs: Vec<globset::GlobMatcher>,
1100    exclude_regexes: Vec<Regex>,
1101    exclude_segment_regexes: Vec<Regex>,
1102}
1103
1104impl CompiledPathRule {
1105    pub(crate) fn for_entry_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
1106        let include = match entry_rule_glob(&rule.pattern) {
1107            Ok(glob) => glob.compile_matcher(),
1108            Err(err) => {
1109                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
1110                return None;
1111            }
1112        };
1113        Some(Self {
1114            include,
1115            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
1116            exclude_regexes: compile_excluded_regexes(
1117                &rule.exclude_regexes,
1118                rule_kind,
1119                &rule.pattern,
1120            ),
1121            exclude_segment_regexes: compile_excluded_segment_regexes(
1122                &rule.exclude_segment_regexes,
1123                rule_kind,
1124                &rule.pattern,
1125            ),
1126        })
1127    }
1128
1129    pub(crate) fn for_used_export_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
1130        Self::for_entry_rule(rule, rule_kind)
1131    }
1132
1133    #[must_use]
1134    pub(crate) fn matches(&self, path: &str) -> bool {
1135        self.include.is_match(path)
1136            && !self.exclude_globs.iter().any(|glob| glob.is_match(path))
1137            && !self
1138                .exclude_regexes
1139                .iter()
1140                .any(|regex| regex.is_match(path))
1141            && !matches_segment_regex(path, &self.exclude_segment_regexes)
1142    }
1143}
1144
1145fn prefix_workspace_pattern(pattern: &str, ws_prefix: &str) -> String {
1146    if pattern.starts_with(ws_prefix) || pattern.starts_with('/') {
1147        pattern.to_string()
1148    } else {
1149        format!("{ws_prefix}/{pattern}")
1150    }
1151}
1152
1153/// Resolve the leading `../` segments of a parent-relative pattern against the
1154/// workspace prefix, so a pattern that names a file in a sibling workspace
1155/// matches from the project root. A pattern that climbs past the project root,
1156/// or a prefix that is not project-relative, keeps the pattern as written,
1157/// which matches no project file.
1158fn resolve_parent_relative_pattern(pattern: &str, ws_prefix: &str) -> String {
1159    if ws_prefix.starts_with('/') || Path::new(ws_prefix).is_absolute() {
1160        return pattern.to_string();
1161    }
1162    // The workspace prefix comes from a native path, so on Windows its
1163    // segments are separated by backslashes.
1164    let mut base: Vec<&str> = ws_prefix
1165        .split(['/', '\\'])
1166        .filter(|segment| !segment.is_empty())
1167        .collect();
1168    let mut rest = pattern;
1169    while let Some(stripped) = rest.strip_prefix("../") {
1170        if base.pop().is_none() {
1171            return pattern.to_string();
1172        }
1173        rest = stripped;
1174    }
1175    if base.is_empty() {
1176        rest.to_string()
1177    } else {
1178        format!("{}/{rest}", base.join("/"))
1179    }
1180}
1181
1182fn prefix_workspace_regex(pattern: &str, ws_prefix: &str) -> String {
1183    if let Some(pattern) = pattern.strip_prefix('^') {
1184        format!("^{}/{}", regex::escape(ws_prefix), pattern)
1185    } else {
1186        format!("^{}/(?:{})", regex::escape(ws_prefix), pattern)
1187    }
1188}
1189
1190fn compile_excluded_globs(
1191    patterns: &[String],
1192    rule_kind: &str,
1193    rule_pattern: &str,
1194) -> Vec<globset::GlobMatcher> {
1195    patterns
1196        .iter()
1197        .filter_map(|pattern| {
1198            match globset::GlobBuilder::new(pattern)
1199                .literal_separator(true)
1200                .empty_alternates(true)
1201                .build()
1202            {
1203                Ok(glob) => Some(glob.compile_matcher()),
1204                Err(err) => {
1205                    tracing::warn!(
1206                        "skipping invalid excluded glob '{}' for {} '{}': {err}",
1207                        pattern,
1208                        rule_kind,
1209                        rule_pattern
1210                    );
1211                    None
1212                }
1213            }
1214        })
1215        .collect()
1216}
1217
1218fn compile_excluded_regexes(
1219    patterns: &[String],
1220    rule_kind: &str,
1221    rule_pattern: &str,
1222) -> Vec<Regex> {
1223    patterns
1224        .iter()
1225        .filter_map(|pattern| match Regex::new(pattern) {
1226            Ok(regex) => Some(regex),
1227            Err(err) => {
1228                tracing::warn!(
1229                    "skipping invalid excluded regex '{}' for {} '{}': {err}",
1230                    pattern,
1231                    rule_kind,
1232                    rule_pattern
1233                );
1234                None
1235            }
1236        })
1237        .collect()
1238}
1239
1240fn compile_excluded_segment_regexes(
1241    patterns: &[String],
1242    rule_kind: &str,
1243    rule_pattern: &str,
1244) -> Vec<Regex> {
1245    patterns
1246        .iter()
1247        .filter_map(|pattern| match Regex::new(pattern) {
1248            Ok(regex) => Some(regex),
1249            Err(err) => {
1250                tracing::warn!(
1251                    "skipping invalid excluded segment regex '{}' for {} '{}': {err}",
1252                    pattern,
1253                    rule_kind,
1254                    rule_pattern
1255                );
1256                None
1257            }
1258        })
1259        .collect()
1260}
1261
1262/// Whether a segment of `path` matches one of `regexes`. The path can use the
1263/// native separator: on Windows a caller can pass `src\pages\x.tsx`.
1264fn matches_segment_regex(path: &str, regexes: &[Regex]) -> bool {
1265    path.split(std::path::is_separator)
1266        .any(|segment| regexes.iter().any(|regex| regex.is_match(segment)))
1267}
1268
1269impl From<String> for PathRule {
1270    fn from(pattern: String) -> Self {
1271        Self::new(pattern)
1272    }
1273}
1274
1275impl From<&str> for PathRule {
1276    fn from(pattern: &str) -> Self {
1277        Self::new(pattern)
1278    }
1279}
1280
1281impl std::ops::Deref for PathRule {
1282    type Target = str;
1283
1284    fn deref(&self) -> &Self::Target {
1285        &self.pattern
1286    }
1287}
1288
1289impl PartialEq<&str> for PathRule {
1290    fn eq(&self, other: &&str) -> bool {
1291        self.pattern == *other
1292    }
1293}
1294
1295impl PartialEq<str> for PathRule {
1296    fn eq(&self, other: &str) -> bool {
1297        self.pattern == other
1298    }
1299}
1300
1301impl PartialEq<String> for PathRule {
1302    fn eq(&self, other: &String) -> bool {
1303        &self.pattern == other
1304    }
1305}
1306
1307/// A framework/tool plugin that contributes to dead code analysis.
1308pub trait Plugin: Send + Sync {
1309    /// Human-readable plugin name.
1310    fn name(&self) -> &'static str;
1311
1312    /// Package names that activate this plugin when found in package.json.
1313    /// Supports exact matches and prefix patterns (ending with `/`).
1314    fn enablers(&self) -> &'static [&'static str] {
1315        &[]
1316    }
1317
1318    /// Calls `is_enabled_with_deps`. The registry does not call this method, so do not override it.
1319    fn is_enabled(&self, pkg: &PackageJson, root: &Path) -> bool {
1320        let deps = pkg.all_dependency_names();
1321        self.is_enabled_with_deps(&deps, root)
1322    }
1323
1324    /// Fast variant of `is_enabled` that accepts a pre-computed deps list.
1325    /// Avoids repeated `all_dependency_names()` allocation when checking many plugins.
1326    fn is_enabled_with_deps(&self, deps: &[String], _root: &Path) -> bool {
1327        let enablers = self.enablers();
1328        if enablers.is_empty() {
1329            return false;
1330        }
1331        enablers.iter().any(|enabler| {
1332            if enabler.ends_with('/') {
1333                // Prefix match (e.g., "@storybook/" matches "@storybook/react")
1334                deps.iter().any(|d| d.starts_with(enabler))
1335            } else {
1336                deps.iter().any(|d| d == enabler)
1337            }
1338        })
1339    }
1340
1341    /// Check whether this plugin should be active with source discovery available.
1342    ///
1343    /// Most plugins only need dependency/config activation. Convention-only tools
1344    /// can override this to activate from discovered source filenames without
1345    /// forcing a separate filesystem walk.
1346    ///
1347    /// `candidate_index` is the discovery walk's in-memory listing of source +
1348    /// non-source config-candidate files (`Some` outside production mode, `None`
1349    /// in production). A plugin that activates on a non-source sentinel file
1350    /// (`manifest.json`, `.env.schema`) can consult it to avoid a per-directory
1351    /// filesystem probe; when it is `None`, the plugin falls back to the
1352    /// filesystem.
1353    fn is_enabled_with_files(
1354        &self,
1355        deps: &[String],
1356        root: &Path,
1357        _discovered_files: &[PathBuf],
1358        _candidate_index: Option<&registry::ConfigCandidateIndex>,
1359    ) -> bool {
1360        self.is_enabled_with_deps(deps, root)
1361    }
1362
1363    /// Package-script binary/package names that can activate this plugin.
1364    fn script_enablers(&self) -> &'static [&'static str] {
1365        &[]
1366    }
1367
1368    /// Check whether this plugin should be active from package.json scripts.
1369    fn is_enabled_with_scripts(
1370        &self,
1371        script_packages: &rustc_hash::FxHashSet<String>,
1372        _root: &Path,
1373    ) -> bool {
1374        let enablers = self.script_enablers();
1375        if enablers.is_empty() {
1376            return false;
1377        }
1378        enablers.iter().any(|enabler| {
1379            if enabler.ends_with('/') {
1380                script_packages
1381                    .iter()
1382                    .any(|package| package.starts_with(enabler))
1383            } else {
1384                script_packages.contains(*enabler)
1385            }
1386        })
1387    }
1388
1389    /// Default glob patterns for entry point files.
1390    fn entry_patterns(&self) -> &'static [&'static str] {
1391        &[]
1392    }
1393
1394    /// Entry point rules with optional exclusions.
1395    fn entry_pattern_rules(&self) -> Vec<PathRule> {
1396        self.entry_patterns()
1397            .iter()
1398            .map(|pattern| PathRule::from_static(pattern))
1399            .collect()
1400    }
1401
1402    /// How this plugin's entry patterns should contribute to coverage reachability.
1403    ///
1404    /// `Support` roots keep files alive for dead-code analysis but do not count
1405    /// as runtime or test reachability for static coverage gaps.
1406    fn entry_point_role(&self) -> EntryPointRole {
1407        builtin_entry_point_role(self.name())
1408    }
1409
1410    /// Glob patterns for config files this plugin can parse.
1411    fn config_patterns(&self) -> &'static [&'static str] {
1412        &[]
1413    }
1414
1415    /// Config patterns whose files do not get the `default` export credit.
1416    ///
1417    /// Under `includeEntryExports`, the `default` export of a file that one of
1418    /// [`Self::config_patterns`] matches counts as used, because the tool loads
1419    /// the config file and reads its default export. List a pattern here when
1420    /// the tool reads named exports instead, or when the pattern also matches
1421    /// ordinary source files. Each entry must be identical to an entry of
1422    /// [`Self::config_patterns`].
1423    fn config_default_export_opt_out(&self) -> &'static [&'static str] {
1424        &[]
1425    }
1426
1427    /// Tool config files and the export names that the tool reads from them.
1428    ///
1429    /// Under `includeEntryExports`, these exports of a matching file count as
1430    /// used. `"*"` credits every export. Use this for a config file that is not
1431    /// in [`Self::config_patterns`], or for a tool that reads named exports.
1432    /// Each pattern is anchored: it gets the workspace prefix but no `**/`
1433    /// prefix, so it matches only at the project or workspace package root.
1434    /// This credit never changes the output without `includeEntryExports`.
1435    fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] {
1436        &[]
1437    }
1438
1439    /// Files that are always considered "used" when this plugin is active.
1440    fn always_used(&self) -> &'static [&'static str] {
1441        &[]
1442    }
1443
1444    /// Exports that are always considered used for matching file patterns.
1445    fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1446        vec![]
1447    }
1448
1449    /// Used-export rules with optional exclusions.
1450    fn used_export_rules(&self) -> Vec<UsedExportRule> {
1451        self.used_exports()
1452            .into_iter()
1453            .map(|(pattern, exports)| UsedExportRule::from_static(pattern, exports))
1454            .collect()
1455    }
1456
1457    /// Class member names the framework invokes at runtime. Matching members
1458    /// are skipped during `unused-class-members` analysis. Intended for
1459    /// interface/contract patterns where the library calls methods on consumer
1460    /// classes (e.g. ag-Grid's `agInit`, Web Components' `connectedCallback`).
1461    fn used_class_members(&self) -> &'static [&'static str] {
1462        &[]
1463    }
1464
1465    /// Heritage-scoped class member rules. Each rule applies only to classes
1466    /// matching its `extends` and/or `implements` clause. Used for frameworks
1467    /// where lifecycle members are runtime-invoked only on classes that extend
1468    /// a known base (e.g. Lit's `render`/`updated` on classes extending
1469    /// `LitElement`, native Web Components' `connectedCallback` on classes
1470    /// extending `HTMLElement`). Default: empty. Plugins override when they
1471    /// need scoping; flat names should still come from `used_class_members`.
1472    fn used_class_member_rules(&self) -> Vec<UsedClassMemberRule> {
1473        Vec::new()
1474    }
1475
1476    /// Exact package-backed framework contracts that type-aware analysis may
1477    /// verify for latent class-member candidates.
1478    fn framework_class_member_contracts(&self) -> Vec<SemanticFrameworkContract> {
1479        Vec::new()
1480    }
1481
1482    /// Glob patterns for test fixture files consumed by this framework.
1483    /// These files are implicitly used by the test runner and should not be
1484    /// flagged as unused. Unlike `always_used()`, this carries semantic intent
1485    /// for reporting purposes.
1486    fn fixture_glob_patterns(&self) -> &'static [&'static str] {
1487        &[]
1488    }
1489
1490    /// Hidden directory names that should be traversed when this plugin is active.
1491    ///
1492    /// These are consulted before normal plugin execution because source discovery
1493    /// runs first. Keep entries static and package-convention scoped.
1494    fn discovery_hidden_dirs(&self) -> &'static [&'static str] {
1495        &[]
1496    }
1497
1498    /// Dependencies that are tooling (used via CLI/config, not source imports).
1499    /// These should not be flagged as unused devDependencies.
1500    fn tooling_dependencies(&self) -> &'static [&'static str] {
1501        &[]
1502    }
1503
1504    /// Import prefixes that are virtual modules provided by this framework at build time.
1505    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
1506    /// Each entry is matched as a prefix against the extracted package name
1507    /// (e.g., `"@theme/"` matches `@theme/Layout`).
1508    fn virtual_module_prefixes(&self) -> &'static [&'static str] {
1509        &[]
1510    }
1511
1512    /// Package name suffixes that are virtual modules provided by this framework
1513    /// at build time (e.g., test runner mock conventions).
1514    /// Imports matching these suffixes should not be flagged as unlisted dependencies.
1515    /// Each entry is matched as a suffix against the extracted package name
1516    /// (e.g., `"/__mocks__"` matches `@aws-sdk/__mocks__` and `some-pkg/__mocks__`).
1517    fn virtual_package_suffixes(&self) -> &'static [&'static str] {
1518        &[]
1519    }
1520
1521    /// Import suffixes for build-time generated relative imports.
1522    ///
1523    /// Unresolved relative imports whose specifier ends with one of these suffixes
1524    /// will not be flagged as unresolved. For example, SvelteKit generates
1525    /// `./$types` imports in route files, returning `"/$types"` suppresses those.
1526    fn generated_import_patterns(&self) -> &'static [&'static str] {
1527        &[]
1528    }
1529
1530    /// Import prefixes for generated type-only relative imports.
1531    ///
1532    /// Unresolved type-only imports whose specifier starts with one of these prefixes
1533    /// will not be flagged as unresolved. Runtime imports are still reported.
1534    fn generated_type_import_prefixes(&self) -> &'static [&'static str] {
1535        &[]
1536    }
1537
1538    /// Path alias mappings provided by this framework at build time.
1539    ///
1540    /// Returns a list of `(prefix, replacement_dir)` tuples. When an import starting
1541    /// with `prefix` fails to resolve, the resolver will substitute the prefix with
1542    /// `replacement_dir` (relative to the project root) and retry.
1543    ///
1544    /// Called once when plugins are activated. The project `root` is provided so
1545    /// plugins can inspect the filesystem (e.g., Nuxt checks whether `app/` exists
1546    /// to determine the `srcDir`).
1547    fn path_aliases(&self, _root: &Path) -> Vec<(&'static str, String)> {
1548        vec![]
1549    }
1550
1551    /// Directories this framework serves at a URL mount by convention, so a
1552    /// root-absolute reference in ANY HTML document in the project names a file
1553    /// inside one.
1554    ///
1555    /// Called once when plugins are activated, with the project `root`, so a
1556    /// plugin can require the directory to exist before claiming it.
1557    ///
1558    /// Distinct from the config-file mounts a tool declares from
1559    /// `resolve_config` (Storybook `staticDirs`), which stay scoped to that
1560    /// tool's own documents. A convention here describes how the whole project
1561    /// is served, so it is not scoped that way.
1562    fn static_dir_mappings(&self, _root: &Path) -> Vec<(std::path::PathBuf, String)> {
1563        vec![]
1564    }
1565
1566    /// Convention-based auto-imports provided by this framework.
1567    ///
1568    /// Returns the names this framework exposes to user code by filesystem
1569    /// convention with no explicit `import` statement (e.g. Nuxt `components/`
1570    /// resolved by `<Card001 />` template tags), each mapped to the source file
1571    /// providing the export. When a file references one of these names without an
1572    /// import, the resolver synthesizes a graph edge to `source`.
1573    ///
1574    /// Called once when plugins are activated. The project `root` is provided so
1575    /// plugins can scan the convention directories on the filesystem. The table is
1576    /// a function of which files exist on disk, so it is rebuilt every run and is
1577    /// never folded into per-file extraction caching. See issue #704.
1578    ///
1579    /// A rule with an empty `scope` is visible to the files under `root` only.
1580    /// A plugin can set `scope` itself to make a rule visible to more roots.
1581    /// After the plugin runs, a shared step links a Nuxt app and each layer
1582    /// outside it in both directions. See issue #2752.
1583    fn auto_imports(&self, _root: &Path) -> Vec<AutoImportRule> {
1584        Vec::new()
1585    }
1586
1587    /// File-scoped dependency providers contributed by this framework.
1588    fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> {
1589        Vec::new()
1590    }
1591
1592    /// Check whether parsed package.json metadata activates this plugin.
1593    fn is_enabled_with_package_json(&self, _pkg: &PackageJson, _root: &Path) -> bool {
1594        false
1595    }
1596
1597    /// Resolve parsed package.json metadata into dynamic plugin facts.
1598    fn resolve_package_json(&self, _pkg: &PackageJson, _root: &Path) -> PluginResult {
1599        PluginResult::default()
1600    }
1601
1602    /// Dependencies referenced by the package's own package.json metadata.
1603    ///
1604    /// Unlike config-derived dependencies, these credits apply only to the
1605    /// package.json that produced them.
1606    fn package_json_referenced_dependencies(
1607        &self,
1608        _pkg: &PackageJson,
1609        _root: &Path,
1610    ) -> Vec<String> {
1611        Vec::new()
1612    }
1613
1614    /// Parse a config file's AST to discover additional entries, dependencies, etc.
1615    ///
1616    /// Called for each config file matching `config_patterns()`. The source code
1617    /// and parsed AST are provided, use [`config_parser`] utilities to extract values.
1618    fn resolve_config(&self, _config_path: &Path, _source: &str, _root: &Path) -> PluginResult {
1619        PluginResult::default()
1620    }
1621
1622    /// Parse a config file with the project root known.
1623    ///
1624    /// `root` is the package root that [`Plugin::resolve_config`] receives. In
1625    /// a workspace run it is the workspace package directory. `project_root`
1626    /// is the analysis root. A plugin that reads more files from paths that
1627    /// the config names must keep each read inside `project_root`, because the
1628    /// config comes from the analyzed repository. The default ignores
1629    /// `project_root`.
1630    fn resolve_config_in_project(
1631        &self,
1632        config_path: &Path,
1633        source: &str,
1634        root: &Path,
1635        _project_root: &Path,
1636    ) -> PluginResult {
1637        self.resolve_config(config_path, source, root)
1638    }
1639
1640    /// Parse a config file that a package script passes with `--config` or
1641    /// `-c`. The script runs the tool in `root`, also for a config in a
1642    /// subdirectory. The default is [`Plugin::resolve_config_in_project`].
1643    fn resolve_script_config(
1644        &self,
1645        config_path: &Path,
1646        source: &str,
1647        root: &Path,
1648        project_root: &Path,
1649    ) -> PluginResult {
1650        self.resolve_config_in_project(config_path, source, root, project_root)
1651    }
1652
1653    /// Binaries whose `--config` / `-c` argument in a package script names a
1654    /// config file of this plugin.
1655    ///
1656    /// A script such as `vitest run --config vitest.e2e.config.ts` points the
1657    /// tool at a file that no `config_patterns()` entry matches. The plugin
1658    /// system sends that file to `resolve_config` and credits its default
1659    /// export as used.
1660    fn script_config_binaries(&self) -> &'static [&'static str] {
1661        &[]
1662    }
1663
1664    /// The key name in package.json that holds inline configuration for this tool.
1665    /// When set (e.g., `"jest"` for the `"jest"` key in package.json), the plugin
1666    /// system will extract that key's value and call `resolve_config` with its
1667    /// JSON content if no standalone config file was found.
1668    fn package_json_config_key(&self) -> Option<&'static str> {
1669        None
1670    }
1671}
1672
1673fn builtin_entry_point_role(name: &str) -> EntryPointRole {
1674    if TEST_ENTRY_POINT_PLUGINS.contains(&name) {
1675        EntryPointRole::Test
1676    } else if RUNTIME_ENTRY_POINT_PLUGINS.contains(&name) {
1677        EntryPointRole::Runtime
1678    } else {
1679        EntryPointRole::Support
1680    }
1681}
1682
1683/// Macro to eliminate boilerplate in plugin implementations.
1684///
1685/// Generates a struct and a `Plugin` trait impl with the standard static methods
1686/// (`name`, `enablers`, `entry_patterns`, `config_patterns`, `always_used`, `tooling_dependencies`,
1687/// `fixture_glob_patterns`, `virtual_module_prefixes`, `virtual_package_suffixes`,
1688/// `generated_type_import_prefixes`, `used_exports`).
1689///
1690/// For plugins that need custom `resolve_config()` or `is_enabled()`, keep those as
1691/// manual `impl Plugin for ...` blocks instead of using this macro.
1692///
1693/// # Usage
1694///
1695/// ```ignore
1696/// // Simple plugin (most common):
1697/// define_plugin! {
1698///     struct VitePlugin => "vite",
1699///     enablers: ENABLERS,
1700///     entry_patterns: ENTRY_PATTERNS,
1701///     config_patterns: CONFIG_PATTERNS,
1702///     always_used: ALWAYS_USED,
1703///     tooling_dependencies: TOOLING_DEPENDENCIES,
1704/// }
1705///
1706/// // Plugin with used_exports:
1707/// define_plugin! {
1708///     struct RemixPlugin => "remix",
1709///     enablers: ENABLERS,
1710///     entry_patterns: ENTRY_PATTERNS,
1711///     always_used: ALWAYS_USED,
1712///     tooling_dependencies: TOOLING_DEPENDENCIES,
1713///     used_exports: [("app/routes/**/*.{ts,tsx}", ROUTE_EXPORTS)],
1714/// }
1715///
1716/// // Plugin with imports-only resolve_config (extracts imports from config as deps):
1717/// define_plugin! {
1718///     struct CypressPlugin => "cypress",
1719///     enablers: ENABLERS,
1720///     entry_patterns: ENTRY_PATTERNS,
1721///     config_patterns: CONFIG_PATTERNS,
1722///     always_used: ALWAYS_USED,
1723///     tooling_dependencies: TOOLING_DEPENDENCIES,
1724///     resolve_config: imports_only,
1725/// }
1726///
1727/// // Plugin with custom resolve_config body:
1728/// define_plugin! {
1729///     struct RollupPlugin => "rollup",
1730///     enablers: ENABLERS,
1731///     config_patterns: CONFIG_PATTERNS,
1732///     always_used: ALWAYS_USED,
1733///     tooling_dependencies: TOOLING_DEPENDENCIES,
1734///     resolve_config(config_path, source, _root) {
1735///         let mut result = PluginResult::default();
1736///         // custom config parsing...
1737///         result
1738///     }
1739/// }
1740/// ```
1741///
1742/// All fields except `struct` and `enablers` are optional and default to `&[]` / `vec![]`.
1743macro_rules! define_plugin {
1744    (
1745        struct $name:ident => $display:expr,
1746        enablers: $enablers:expr
1747        $(, entry_patterns: $entry:expr)?
1748        $(, config_patterns: $config:expr)?
1749        $(, config_default_export_opt_out: $config_opt_out:expr)?
1750        $(, config_file_exports: $config_exports:expr)?
1751        $(, always_used: $always:expr)?
1752        $(, tooling_dependencies: $tooling:expr)?
1753        $(, fixture_glob_patterns: $fixtures:expr)?
1754        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1755        $(, virtual_module_prefixes: $virtual:expr)?
1756        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1757        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1758        $(, provided_dependencies: $provided_dependencies:expr)?
1759        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1760        , resolve_config: imports_only
1761        $(,)?
1762    ) => {
1763        pub struct $name;
1764
1765        impl Plugin for $name {
1766            fn name(&self) -> &'static str {
1767                $display
1768            }
1769
1770            fn enablers(&self) -> &'static [&'static str] {
1771                $enablers
1772            }
1773
1774            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1775            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1776            $( fn config_default_export_opt_out(&self) -> &'static [&'static str] { $config_opt_out } )?
1777            $( fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] { $config_exports } )?
1778            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1779            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1780            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1781            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1782            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1783            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1784            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1785            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1786
1787            $(
1788                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1789                    vec![$( ($pat, $exports) ),*]
1790                }
1791            )?
1792
1793            fn resolve_config(
1794                &self,
1795                config_path: &std::path::Path,
1796                source: &str,
1797                _root: &std::path::Path,
1798            ) -> PluginResult {
1799                let mut result = PluginResult::default();
1800                crate::plugins::add_import_referenced_dependencies(
1801                    &mut result,
1802                    source,
1803                    config_path,
1804                );
1805                result
1806            }
1807        }
1808    };
1809
1810    (
1811        struct $name:ident => $display:expr,
1812        enablers: $enablers:expr
1813        $(, entry_patterns: $entry:expr)?
1814        $(, config_patterns: $config:expr)?
1815        $(, config_default_export_opt_out: $config_opt_out:expr)?
1816        $(, config_file_exports: $config_exports:expr)?
1817        $(, always_used: $always:expr)?
1818        $(, tooling_dependencies: $tooling:expr)?
1819        $(, fixture_glob_patterns: $fixtures:expr)?
1820        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1821        $(, virtual_module_prefixes: $virtual:expr)?
1822        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1823        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1824        $(, provided_dependencies: $provided_dependencies:expr)?
1825        $(, package_json_config_key: $pkg_key:expr)?
1826        $(, script_config_binaries: $script_binaries:expr)?
1827        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1828        , resolve_config($cp:ident, $src:ident, $root:ident) $body:block
1829        $(, resolve_config_in_project($pcp:ident, $psrc:ident, $proot:ident, $pproj:ident) $pbody:block)?
1830        $(,)?
1831    ) => {
1832        pub struct $name;
1833
1834        impl Plugin for $name {
1835            fn name(&self) -> &'static str {
1836                $display
1837            }
1838
1839            fn enablers(&self) -> &'static [&'static str] {
1840                $enablers
1841            }
1842
1843            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1844            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1845            $( fn config_default_export_opt_out(&self) -> &'static [&'static str] { $config_opt_out } )?
1846            $( fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] { $config_exports } )?
1847            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1848            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1849            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1850            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1851            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1852            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1853            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1854            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1855
1856            $(
1857                fn package_json_config_key(&self) -> Option<&'static str> {
1858                    Some($pkg_key)
1859                }
1860            )?
1861
1862            $(
1863                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1864                    vec![$( ($pat, $exports) ),*]
1865                }
1866            )?
1867
1868            $( fn script_config_binaries(&self) -> &'static [&'static str] { $script_binaries } )?
1869
1870            fn resolve_config(
1871                &self,
1872                $cp: &std::path::Path,
1873                $src: &str,
1874                $root: &std::path::Path,
1875            ) -> PluginResult
1876            $body
1877
1878            $(
1879                fn resolve_config_in_project(
1880                    &self,
1881                    $pcp: &std::path::Path,
1882                    $psrc: &str,
1883                    $proot: &std::path::Path,
1884                    $pproj: &std::path::Path,
1885                ) -> PluginResult
1886                $pbody
1887            )?
1888        }
1889    };
1890
1891    (
1892        struct $name:ident => $display:expr,
1893        enablers: $enablers:expr
1894        $(, entry_patterns: $entry:expr)?
1895        $(, config_patterns: $config:expr)?
1896        $(, config_default_export_opt_out: $config_opt_out:expr)?
1897        $(, config_file_exports: $config_exports:expr)?
1898        $(, always_used: $always:expr)?
1899        $(, tooling_dependencies: $tooling:expr)?
1900        $(, fixture_glob_patterns: $fixtures:expr)?
1901        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1902        $(, virtual_module_prefixes: $virtual:expr)?
1903        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1904        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1905        $(, provided_dependencies: $provided_dependencies:expr)?
1906        $(, package_json_config_key: $pkg_key:expr)?
1907        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1908        $(,)?
1909    ) => {
1910        pub struct $name;
1911
1912        impl Plugin for $name {
1913            fn name(&self) -> &'static str {
1914                $display
1915            }
1916
1917            fn enablers(&self) -> &'static [&'static str] {
1918                $enablers
1919            }
1920
1921            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1922            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1923            $( fn config_default_export_opt_out(&self) -> &'static [&'static str] { $config_opt_out } )?
1924            $( fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] { $config_exports } )?
1925            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1926            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1927            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1928            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1929            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1930            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1931            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1932            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1933
1934            $(
1935                fn package_json_config_key(&self) -> Option<&'static str> {
1936                    Some($pkg_key)
1937                }
1938            )?
1939
1940            $(
1941                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1942                    vec![$( ($pat, $exports) ),*]
1943                }
1944            )?
1945        }
1946    };
1947}
1948
1949mod config_dependencies;
1950pub mod config_parser;
1951mod config_value_credits;
1952mod flue;
1953mod jasmine;
1954mod manifest;
1955pub mod manifest_entries;
1956mod mise;
1957mod osls;
1958mod project_glob;
1959mod railway;
1960pub mod registry;
1961mod rstest;
1962mod serverless_framework;
1963mod textlint;
1964mod tooling;
1965pub(crate) mod trace_provenance;
1966mod used_export_names;
1967mod used_export_rule;
1968
1969pub use config_dependencies::RequiredDependency;
1970use config_dependencies::add_import_referenced_dependencies;
1971pub(crate) use module_federation::runtime_remotes;
1972pub use registry::{
1973    AggregatedPluginResult, PluginRegistry, PluginToolingDependencies, PluginToolingEvidence,
1974};
1975pub use tooling::types_package_target;
1976pub(crate) use tooling::{
1977    cli_tooling_config_patterns, is_ambient_types_package, is_known_tooling_dependency,
1978};
1979pub use trace_provenance::ExportCredits;
1980pub use used_export_names::UsedExportNames;
1981pub(crate) use used_export_rule::{ConfigExportCredit, is_export_ignored};
1982pub use used_export_rule::{PluginUsedExportRule, UsedExportRule};
1983
1984/// Credit the optional peer dependencies a test environment loads at runtime.
1985///
1986/// The rules are data: see the `test-environment-optional-peer` rows in
1987/// `crates/core/data/config_value_credits.toml`. `jsdom` requires its optional
1988/// peer `canvas` lazily when it is installed, so a project installing it for
1989/// real canvas support has no import of it anywhere and would see the
1990/// dependency reported as unused (issue #2005). Environments without such a
1991/// peer, like `happy-dom`, have no row.
1992///
1993/// Only names already declared in the manifest can be credited, so this never
1994/// invents an unlisted dependency.
1995fn credit_environment_optional_peers(environment: &str, result: &mut PluginResult) {
1996    credit_config_value(
1997        config_value_credits::CreditSurface::TestEnvironmentOptionalPeer,
1998        canonical_test_environment(environment),
1999        result,
2000    );
2001}
2002
2003/// Record the catalogue credits for a config value, if any.
2004///
2005/// Returns whether a rule matched, which callers use when the credited packages
2006/// replace the dependencies derived from the value itself.
2007fn credit_config_value(
2008    surface: config_value_credits::CreditSurface,
2009    value: &str,
2010    result: &mut PluginResult,
2011) -> bool {
2012    let Some(packages) = config_value_credits::credited_packages(surface, value) else {
2013        return false;
2014    };
2015    result
2016        .referenced_dependencies
2017        .extend(packages.iter().cloned());
2018    true
2019}
2020
2021/// Strip the runner prefix from a test environment specifier.
2022///
2023/// Both runners accept the bare name and the package it resolves to, so
2024/// `testEnvironment: "jest-environment-jsdom"` and `environment: "jsdom"` select
2025/// the same environment. A match on the short name only missed the fully
2026/// qualified form that the Jest docs use, so that form lost its credit.
2027fn canonical_test_environment(environment: &str) -> &str {
2028    environment
2029        .strip_prefix("jest-environment-")
2030        .or_else(|| environment.strip_prefix("vitest-environment-"))
2031        .unwrap_or(environment)
2032}
2033
2034mod adonis;
2035mod ag_ui;
2036mod alchemy;
2037mod alias_replacement;
2038mod angular;
2039mod astro;
2040mod ava;
2041mod babel;
2042mod biome;
2043mod browser_extension;
2044mod bun;
2045mod c8;
2046mod capacitor;
2047mod changesets;
2048mod commit_and_tag_version;
2049mod commitizen;
2050mod commitlint;
2051mod content_collections;
2052mod contentlayer;
2053mod convex;
2054mod cspell;
2055mod cucumber;
2056mod cypress;
2057mod danger;
2058mod deno;
2059mod dependency_cruiser;
2060mod docusaurus;
2061mod dotenv;
2062mod drizzle;
2063mod egg;
2064mod electron;
2065mod ember;
2066mod eslint;
2067mod eve;
2068mod expo;
2069mod expo_router;
2070mod firebase;
2071mod fumadocs;
2072mod gatsby;
2073mod github_action;
2074mod graphql_codegen;
2075mod graphql_config;
2076mod hardhat;
2077mod husky;
2078mod i18next;
2079mod ionic;
2080mod jest;
2081mod k6;
2082mod karma;
2083mod kibana;
2084mod knex;
2085mod kysely;
2086mod lefthook;
2087mod lexical;
2088mod lint_staged;
2089mod lit;
2090mod markdownlint;
2091mod mintlify;
2092mod mocha;
2093mod module_federation;
2094mod msw;
2095mod napi_rs;
2096mod nest_commander;
2097mod nestjs;
2098mod nestjs_trpc;
2099mod next_intl;
2100mod nextjs;
2101mod nitro;
2102mod nodemon;
2103pub(crate) mod nuxt;
2104mod nx;
2105mod nyc;
2106mod obsidian;
2107mod openapi_ts;
2108mod opencode;
2109mod opennext_cloudflare;
2110mod opentelemetry;
2111mod oxfmt;
2112mod oxlint;
2113mod pandacss;
2114mod parcel;
2115mod pinia;
2116mod pkg_utils;
2117mod playwright;
2118mod plop;
2119mod pm2;
2120mod pnpm;
2121mod postcss;
2122mod prettier;
2123mod prisma;
2124mod qwik;
2125mod react_compiler;
2126mod react_native;
2127mod react_router;
2128mod redwoodsdk;
2129mod relay;
2130mod release_it;
2131mod remark;
2132mod remix;
2133mod rolldown;
2134mod rollup;
2135mod rsbuild;
2136mod rspack;
2137mod rspress;
2138mod sanity;
2139mod semantic_release;
2140mod sentry;
2141mod simple_git_hooks;
2142mod size_limit;
2143mod storybook;
2144mod stryker;
2145mod stylelint;
2146mod supabase;
2147mod sveltekit;
2148mod svgo;
2149mod svgr;
2150mod swc;
2151mod syncpack;
2152mod tailwind;
2153mod tanstack_router;
2154mod tap;
2155mod test_alias;
2156#[cfg(test)]
2157mod tests;
2158mod tsd;
2159mod tsdown;
2160mod tsup;
2161mod turborepo;
2162mod typedoc;
2163mod typeorm;
2164mod typescript;
2165mod typescript_content_mapper;
2166mod unocss;
2167mod varlock;
2168mod velite;
2169mod vercel;
2170mod vite;
2171pub(crate) mod vite_plus;
2172mod vitepress;
2173mod vitest;
2174mod vscode;
2175mod waku;
2176mod webdriverio;
2177mod webpack;
2178mod wrangler;
2179mod wuchale;
2180mod wxt;