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