Skip to main content

fallow_config/external_plugin/
mod.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5use std::sync::{Mutex, OnceLock};
6
7use rustc_hash::FxHashSet;
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
10
11use crate::config::UsedClassMemberRule;
12
13/// Supported plugin file extensions.
14/// The file extensions of external plugin files.
15pub const PLUGIN_EXTENSIONS: &[&str] = &["toml", "json", "jsonc"];
16
17/// How a plugin's discovered entry points contribute to coverage reachability.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema, Default)]
19#[serde(rename_all = "camelCase")]
20pub enum EntryPointRole {
21    /// Runtime/application roots that should count toward runtime reachability.
22    Runtime,
23    /// Test roots that should count toward test reachability.
24    Test,
25    /// Support/setup/config roots that should keep files alive but not count as runtime/test.
26    #[default]
27    Support,
28}
29
30/// Which export shape a convention auto-import credits when its name is
31/// referenced without an explicit `import` statement.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum AutoImportKind {
34    /// `import { name } from source` (named export, e.g. a Nuxt composable/util).
35    Named,
36    /// `import name from source` (default export).
37    Default,
38    /// SFC default export consumed by a template tag (Nuxt `components/`).
39    DefaultComponent,
40}
41
42/// A single convention-based auto-import: a bare identifier name that resolves
43/// to an export in `source` by framework convention, with no explicit `import`
44/// statement in the consuming file.
45///
46/// Built by `Plugin::auto_imports` from a filesystem scan (e.g. Nuxt scanning
47/// `components/`), and consumed at graph-build time: the resolver matches a
48/// file's captured `auto_import_candidates` against these rules and synthesizes
49/// an edge to `source`. The table is a function of which files exist on disk,
50/// not of any single file's bytes, so it is computed fresh per run and never
51/// cached as part of per-file extraction.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct AutoImportRule {
54    /// Bare identifier name (e.g. `useCounter`, `Card001`, `BaseButton`,
55    /// `LazyCard001`). Component names are canonical PascalCase; the consuming
56    /// scanner normalizes kebab-case tags before matching.
57    pub name: String,
58    /// Absolute path to the source file providing the export.
59    pub source: PathBuf,
60    /// Which export to credit when the name is referenced.
61    pub kind: AutoImportKind,
62    /// Absolute roots whose files can reference the name: the root that
63    /// declared the rule, plus the roots that share its names, such as a Nuxt
64    /// app and the layers it extends. A file outside every root gets no edge.
65    /// Empty means every file, and the plugin run fills it with its own root.
66    pub scope: Vec<PathBuf>,
67}
68
69impl AutoImportRule {
70    /// A rule with no scope yet. The plugin run scopes it to its own root.
71    #[must_use]
72    pub const fn new(name: String, source: PathBuf, kind: AutoImportKind) -> Self {
73        Self {
74            name,
75            source,
76            kind,
77            scope: Vec::new(),
78        }
79    }
80}
81
82/// A JSX import source that a bundler or test config sets for a group of files.
83///
84/// With the automatic JSX runtime, the transform adds an import of
85/// `<source>/jsx-dev-runtime` to each file with JSX, and no import statement
86/// shows that edge. A per-file `@jsxImportSource` pragma overrides the config,
87/// so the resolver applies a rule only to a module with
88/// `jsx_runtime_from_config` set. Built from the config each run and never
89/// cached with per-file extraction.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct JsxImportSourceRule {
92    /// The `importSource` value as written, for example `./src/jsx` or
93    /// `preact`.
94    pub source: String,
95    /// Absolute directory of the config file. The `include` globs match paths
96    /// relative to it, and a relative `source` that does not resolve from the
97    /// file resolves from it.
98    pub config_dir: PathBuf,
99    /// Glob patterns, relative to `config_dir`, of the files that the config
100    /// transforms.
101    pub include: Vec<String>,
102    /// Glob patterns, relative to `config_dir`, of the files that the config
103    /// does not transform, also when `include` matches them.
104    pub exclude: Vec<String>,
105}
106
107/// How to detect if a plugin should be activated.
108///
109/// When set on an `ExternalPluginDef`, this takes priority over `enablers`.
110/// Supports dependency checks, file existence checks, and boolean combinators.
111#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
112#[serde(tag = "type", rename_all = "camelCase")]
113pub enum PluginDetection {
114    /// Plugin detected if this package is in dependencies.
115    Dependency {
116        /// Exact package name looked up in the project's declared dependencies.
117        package: String,
118    },
119    /// Plugin detected if this file pattern matches.
120    FileExists {
121        /// Project-root-relative glob; the plugin activates when any
122        /// discovered file matches it. Validated at load like other user
123        /// globs (no absolute paths or `..` segments).
124        /// A single `*` stays within one path segment; use `**` to match across directories.
125        pattern: String,
126    },
127    /// All conditions must be true.
128    All {
129        /// Sub-conditions combined with logical AND.
130        conditions: Vec<Self>,
131    },
132    /// Any condition must be true.
133    Any {
134        /// Sub-conditions combined with logical OR.
135        conditions: Vec<Self>,
136    },
137}
138
139/// A declarative plugin definition loaded from a standalone file or inline config.
140///
141/// External plugins provide the same static pattern capabilities as built-in
142/// plugins (entry points, always-used files, used exports, tooling dependencies),
143/// but are defined in standalone files or inline in the fallow config rather than
144/// compiled Rust code.
145///
146/// They cannot do AST-based config parsing (`resolve_config()`), but cover the
147/// vast majority of framework integration use cases.
148///
149/// Supports JSONC, JSON, and TOML formats. All use camelCase field names.
150///
151/// ```json
152/// {
153///   "$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/plugin-schema.json",
154///   "name": "my-framework",
155///   "enablers": ["my-framework", "@my-framework/core"],
156///   "entryPoints": ["src/routes/**/*.{ts,tsx}"],
157///   "configPatterns": ["my-framework.config.{ts,js}"],
158///   "alwaysUsed": ["src/setup.ts"],
159///   "toolingDependencies": ["my-framework-cli"],
160///   "usedExports": [
161///     { "pattern": "src/routes/**/*.{ts,tsx}", "exports": ["default", "loader", "action"] }
162///   ]
163/// }
164/// ```
165#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
166#[serde(rename_all = "camelCase")]
167pub struct ExternalPluginDef {
168    /// JSON Schema reference (ignored during deserialization).
169    #[serde(rename = "$schema", default, skip_serializing)]
170    #[schemars(skip)]
171    pub schema: Option<String>,
172
173    /// Unique name for this plugin.
174    pub name: String,
175
176    /// Rich detection logic (dependency checks, file existence, boolean combinators).
177    /// Takes priority over `enablers` when set.
178    #[serde(default)]
179    pub detection: Option<PluginDetection>,
180
181    /// Package names that activate this plugin when found in package.json.
182    /// Supports exact matches and prefix patterns (ending with `/`).
183    /// Only used when `detection` is not set. A plugin with neither `detection`
184    /// nor `enablers` never activates, and config load warns.
185    #[serde(default)]
186    pub enablers: Vec<String>,
187
188    /// Glob patterns for entry point files.
189    #[serde(default)]
190    pub entry_points: Vec<String>,
191
192    /// Coverage role for `entryPoints`.
193    ///
194    /// Defaults to `support`. Set to `runtime` for application entry points
195    /// or `test` for test framework entry points. In production mode, a file
196    /// that only entries with an explicit `support` role match takes no part
197    /// in dead-code analysis.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    #[schemars(with = "EntryPointRole", default = "schema_default_entry_point_role")]
200    pub entry_point_role: Option<EntryPointRole>,
201
202    /// Entry points derived from framework manifest files.
203    ///
204    /// Unlike `entryPoints` (static globs), each rule finds manifest files by a
205    /// recursive glob, parses them, and seeds sibling entries resolved relative
206    /// to each manifest's directory, gated on the manifest's own fields. Seeded
207    /// entries use this plugin's `entryPointRole`.
208    #[serde(default)]
209    pub manifest_entries: Vec<ManifestEntryRule>,
210
211    /// Glob patterns for config files (marked as always-used when active).
212    #[serde(default)]
213    pub config_patterns: Vec<String>,
214
215    /// Entries of `configPatterns` whose files do not get the `default`
216    /// export credit under `includeEntryExports`. Use it when the tool reads
217    /// named exports, or when the pattern also matches ordinary source files.
218    /// Write each entry exactly as in `configPatterns`. Other entries have
219    /// no effect.
220    #[serde(default)]
221    pub config_default_export_opt_out: Vec<String>,
222
223    /// Files that are always considered "used" when this plugin is active.
224    #[serde(default)]
225    pub always_used: Vec<String>,
226
227    /// Dependencies that are tooling (used via CLI/config, not source imports).
228    /// These should not be flagged as unused devDependencies.
229    #[serde(default)]
230    pub tooling_dependencies: Vec<String>,
231
232    /// Exports that are always considered used for matching file patterns.
233    #[serde(default)]
234    pub used_exports: Vec<ExternalUsedExport>,
235
236    /// Class member method/property rules the framework invokes at runtime.
237    /// Supports plain member names for global suppression and scoped objects
238    /// with `extends` / `implements` constraints when the method name is too
239    /// common to suppress across the whole workspace.
240    #[serde(default)]
241    pub used_class_members: Vec<UsedClassMemberRule>,
242}
243
244/// Exports considered used for files matching a pattern.
245#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
246pub struct ExternalUsedExport {
247    /// Glob pattern for files.
248    /// A single `*` stays within one path segment; use `**` to match across directories.
249    pub pattern: String,
250    /// Export names always considered used.
251    pub exports: Vec<String>,
252}
253
254/// Format of the manifest files a [`ManifestEntryRule`] reads.
255///
256/// `jsonc` (the default) also parses plain JSON, so it is the tolerant choice.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema, Default)]
258#[serde(rename_all = "lowercase")]
259pub enum ManifestFormat {
260    /// JSONC (comments + trailing commas). Also accepts plain JSON.
261    #[default]
262    Jsonc,
263    /// Strict JSON.
264    Json,
265}
266
267/// A validated field path into a manifest document.
268///
269/// Field paths use dotted object keys and an exact `[*]` segment for array
270/// traversal. The parsed segments are retained so evaluators do not repeatedly
271/// interpret user-authored path strings.
272#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
273pub struct ManifestFieldPath {
274    raw: String,
275    segments: Vec<ManifestFieldSegment>,
276}
277
278/// One validated traversal step in a [`ManifestFieldPath`].
279#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
280pub enum ManifestFieldSegment {
281    /// Read one named key from each current JSON object.
282    Key(String),
283    /// Visit every item in each current JSON array.
284    Each,
285}
286
287impl ManifestFieldPath {
288    /// The original validated path, used in diagnostics and serialization.
289    #[must_use]
290    pub fn as_str(&self) -> &str {
291        &self.raw
292    }
293
294    /// Parsed object-key and array traversal segments in source order.
295    #[must_use]
296    pub fn segments(&self) -> &[ManifestFieldSegment] {
297        &self.segments
298    }
299
300    fn parse(raw: String) -> Result<Self, String> {
301        if raw.is_empty() {
302            return Err("manifest field path must not be empty".to_string());
303        }
304
305        let mut segments = Vec::new();
306        for component in raw.split('.') {
307            if component.is_empty() {
308                return Err(format!(
309                    "manifest field path '{raw}' contains an empty segment"
310                ));
311            }
312
313            let key_end = component.find('[').unwrap_or(component.len());
314            let key = &component[..key_end];
315            if key.is_empty() || key.contains(['{', '}', ']']) {
316                return Err(format!(
317                    "manifest field path '{raw}' contains unsupported bracket syntax"
318                ));
319            }
320            segments.push(ManifestFieldSegment::Key(key.to_string()));
321
322            let mut suffix = &component[key_end..];
323            while !suffix.is_empty() {
324                let Some(rest) = suffix.strip_prefix("[*]") else {
325                    return Err(format!(
326                        "manifest field path '{raw}' only supports exact '[*]' array traversal"
327                    ));
328                };
329                segments.push(ManifestFieldSegment::Each);
330                suffix = rest;
331            }
332        }
333
334        Ok(Self { raw, segments })
335    }
336}
337
338impl FromStr for ManifestFieldPath {
339    type Err = String;
340
341    fn from_str(raw: &str) -> Result<Self, Self::Err> {
342        Self::parse(raw.to_string())
343    }
344}
345
346impl fmt::Display for ManifestFieldPath {
347    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348        f.write_str(&self.raw)
349    }
350}
351
352impl Serialize for ManifestFieldPath {
353    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
354    where
355        S: Serializer,
356    {
357        serializer.serialize_str(&self.raw)
358    }
359}
360
361impl<'de> Deserialize<'de> for ManifestFieldPath {
362    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
363    where
364        D: Deserializer<'de>,
365    {
366        let raw = String::deserialize(deserializer)?;
367        Self::parse(raw).map_err(|e| D::Error::custom(crate::parse_error::own_message(e)))
368    }
369}
370
371/// One parsed part of a manifest entry path template.
372#[derive(Debug, Clone, PartialEq, Eq)]
373pub enum ManifestPathPart {
374    /// Literal path text copied without interpretation.
375    Literal(String),
376    /// A manifest field whose scalar values are interpolated.
377    Field(ManifestFieldPath),
378}
379
380/// A validated manifest-relative entry path with parsed `${field.path}` parts.
381#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct ManifestPathTemplate {
383    raw: String,
384    parts: Vec<ManifestPathPart>,
385}
386
387impl ManifestPathTemplate {
388    /// The original template used for serialization and diagnostics.
389    #[must_use]
390    pub fn as_str(&self) -> &str {
391        &self.raw
392    }
393
394    /// Parsed literal and field parts in source order.
395    #[must_use]
396    pub fn parts(&self) -> &[ManifestPathPart] {
397        &self.parts
398    }
399
400    /// Replace field interpolations with a safe segment for glob validation.
401    #[must_use]
402    pub fn validation_pattern(&self) -> String {
403        let mut pattern = String::with_capacity(self.raw.len());
404        for part in &self.parts {
405            match part {
406                ManifestPathPart::Literal(literal) => pattern.push_str(literal),
407                ManifestPathPart::Field(_) => pattern.push_str("fallowinterp"),
408            }
409        }
410        pattern
411    }
412
413    fn parse(raw: String) -> Result<Self, String> {
414        let mut parts = Vec::new();
415        let mut rest = raw.as_str();
416
417        while let Some(start) = rest.find("${") {
418            if start > 0 {
419                parts.push(ManifestPathPart::Literal(rest[..start].to_string()));
420            }
421
422            let after = &rest[start + 2..];
423            let Some(end) = after.find('}') else {
424                return Err(format!(
425                    "manifest entry path '{raw}' contains an unterminated interpolation"
426                ));
427            };
428            let field = after[..end].parse::<ManifestFieldPath>()?;
429            parts.push(ManifestPathPart::Field(field));
430            rest = &after[end + 1..];
431        }
432
433        if !rest.is_empty() {
434            parts.push(ManifestPathPart::Literal(rest.to_string()));
435        }
436        if parts.is_empty() {
437            parts.push(ManifestPathPart::Literal(String::new()));
438        }
439
440        Ok(Self { raw, parts })
441    }
442}
443
444impl FromStr for ManifestPathTemplate {
445    type Err = String;
446
447    fn from_str(raw: &str) -> Result<Self, Self::Err> {
448        Self::parse(raw.to_string())
449    }
450}
451
452impl fmt::Display for ManifestPathTemplate {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        f.write_str(&self.raw)
455    }
456}
457
458impl Serialize for ManifestPathTemplate {
459    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
460    where
461        S: Serializer,
462    {
463        serializer.serialize_str(&self.raw)
464    }
465}
466
467impl<'de> Deserialize<'de> for ManifestPathTemplate {
468    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
469    where
470        D: Deserializer<'de>,
471    {
472        let raw = String::deserialize(deserializer)?;
473        Self::parse(raw).map_err(|e| D::Error::custom(crate::parse_error::own_message(e)))
474    }
475}
476
477/// A typed condition used by a manifest entry gate.
478///
479/// Plain JSON values retain strict equality semantics. The reserved
480/// `{ "exists": bool }` object tests field presence without truthiness.
481#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
482#[serde(untagged)]
483pub enum ManifestCondition {
484    /// Require the field path to resolve (`true`) or not resolve (`false`).
485    Exists(ManifestExistsPredicate),
486    /// Require at least one yielded value to equal this JSON value exactly.
487    Equals(serde_json::Value),
488}
489
490/// The explicit field-presence predicate accepted by [`ManifestCondition`].
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
492#[serde(deny_unknown_fields)]
493pub struct ManifestExistsPredicate {
494    /// Whether the field path must resolve to at least one value.
495    pub exists: bool,
496}
497
498/// A rule that seeds entry points derived from framework manifest files.
499///
500/// For every file matching `manifests` (a recursive glob) that passes the
501/// manifest-level `when` gate, each rule in `entries` is resolved relative to
502/// the manifest's directory (with `${dotted.field}` interpolation) into an entry
503/// point. Seeded entries use the owning plugin's `entryPointRole`.
504///
505/// ```jsonc
506/// {
507///   "manifests": "**/kibana.jsonc",
508///   "when": { "type": "plugin" },
509///   "entries": [
510///     { "path": "public/index.{ts,tsx}", "when": { "plugin.browser": true } },
511///     { "path": "server/index.{ts,tsx}", "when": { "plugin.server": true } },
512///     { "path": "${plugin.extraPublicDirs}/index.{ts,tsx}" }
513///   ]
514/// }
515/// ```
516#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
517#[serde(rename_all = "camelCase")]
518pub struct ManifestEntryRule {
519    /// Recursive glob selecting the manifest files to read (e.g. `**/kibana.jsonc`).
520    /// A single `*` stays within one path segment; use `**` to match across directories.
521    pub manifests: String,
522
523    /// Manifest format. Defaults to `jsonc` (which also parses plain JSON).
524    #[serde(default)]
525    pub format: ManifestFormat,
526
527    /// Manifest-level gate: a map of field path to an equality expectation or
528    /// an explicit `exists` predicate. Paths use dotted object keys and may
529    /// traverse arrays with `[*]`. ALL entries must match; a wildcard equality
530    /// matches when any yielded value equals the expectation. An empty map
531    /// matches every manifest.
532    #[serde(default)]
533    #[schemars(with = "BTreeMap<String, ManifestCondition>")]
534    pub when: BTreeMap<ManifestFieldPath, ManifestCondition>,
535
536    /// Entry rules seeded per matching manifest.
537    pub entries: Vec<ManifestSeedRule>,
538}
539
540/// A single entry seeded by a [`ManifestEntryRule`], resolved relative to the
541/// manifest's directory.
542#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
543#[serde(rename_all = "camelCase")]
544pub struct ManifestSeedRule {
545    /// Entry glob relative to the manifest directory. May contain
546    /// `${dotted.field}` interpolation that fans out over string / array
547    /// manifest field values; `[*]` traverses object arrays. A missing or empty
548    /// field seeds nothing. The glob must encode its own extension, such as
549    /// `public/index.{ts,tsx}`. Glob entry patterns are matched literally
550    /// against discovered files without
551    /// source-extension probing.
552    #[schemars(with = "String")]
553    pub path: ManifestPathTemplate,
554
555    /// Per-entry gate, using the same strict equality and `[*]` traversal as the
556    /// manifest-level gate. An empty map always passes.
557    #[serde(default)]
558    #[schemars(with = "BTreeMap<String, ManifestCondition>")]
559    pub when: BTreeMap<ManifestFieldPath, ManifestCondition>,
560}
561
562fn default_external_entry_point_role() -> EntryPointRole {
563    EntryPointRole::Support
564}
565
566#[expect(
567    clippy::unnecessary_wraps,
568    reason = "the schema default must have the field type"
569)]
570fn schema_default_entry_point_role() -> Option<EntryPointRole> {
571    Some(default_external_entry_point_role())
572}
573
574impl ExternalPluginDef {
575    /// The role of `entryPoints`: the configured role, else `support`.
576    #[must_use]
577    pub fn effective_entry_point_role(&self) -> EntryPointRole {
578        self.entry_point_role
579            .unwrap_or_else(default_external_entry_point_role)
580    }
581
582    /// Whether the config sets `"entryPointRole": "support"` explicitly.
583    /// Production mode leaves out only these support entries.
584    #[must_use]
585    pub fn has_explicit_support_role(&self) -> bool {
586        self.entry_point_role == Some(EntryPointRole::Support)
587    }
588
589    /// The reason for a plugin with no activation condition. Config load and
590    /// `fallow plugin-check` both use it, so one state has one phrase.
591    pub const NEVER_ACTIVATES_REASON: &str =
592        "no detection or enablers declared, so the plugin can never activate";
593
594    /// Whether the plugin declares something that can activate it. An empty
595    /// `enablers` list counts as no condition.
596    #[must_use]
597    pub fn has_activation_condition(&self) -> bool {
598        self.detection.is_some() || !self.enablers.is_empty()
599    }
600
601    /// Generate JSON Schema for the external plugin format.
602    #[must_use]
603    pub fn json_schema() -> serde_json::Value {
604        serde_json::to_value(schemars::schema_for!(ExternalPluginDef)).unwrap_or_default()
605    }
606
607    /// Validate all user-supplied glob patterns on this plugin definition,
608    /// including patterns nested inside `detection` combinators (`all` / `any`).
609    ///
610    /// Pattern names use the same `framework[].<field>` notation used by
611    /// inline plugin definitions in `FallowConfig::validate_user_globs` so the
612    /// user sees consistent field paths whether the plugin is inline or
613    /// loaded from `.fallow/plugins/` / `fallow-plugin-*.{toml,json,jsonc}`.
614    ///
615    /// # Errors
616    ///
617    /// Returns a non-empty `Vec` of
618    /// [`GlobValidationError`](crate::config::glob_validation::GlobValidationError)
619    /// when any pattern is rejected.
620    pub fn validate_user_globs(
621        &self,
622    ) -> Result<(), Vec<crate::config::glob_validation::GlobValidationError>> {
623        use crate::config::glob_validation::{compile_user_glob, validate_user_globs};
624
625        let mut errors = Vec::new();
626        validate_user_globs(&self.entry_points, "framework[].entryPoints", &mut errors);
627        validate_user_globs(&self.always_used, "framework[].alwaysUsed", &mut errors);
628        validate_user_globs(
629            &self.config_patterns,
630            "framework[].configPatterns",
631            &mut errors,
632        );
633        for used in &self.used_exports {
634            if let Err(e) = compile_user_glob(&used.pattern, "framework[].usedExports[].pattern") {
635                errors.push(e);
636            }
637        }
638        for rule in &self.manifest_entries {
639            if let Err(e) =
640                compile_user_glob(&rule.manifests, "framework[].manifestEntries[].manifests")
641            {
642                errors.push(e);
643            }
644            for seed in &rule.entries {
645                // Substitute `${...}` interpolation with a placeholder segment so
646                // the surrounding glob (e.g. `${x}/index.{ts,tsx}`) validates.
647                let probe = seed.path.validation_pattern();
648                if let Err(e) =
649                    compile_user_glob(&probe, "framework[].manifestEntries[].entries[].path")
650                {
651                    errors.push(e);
652                }
653            }
654        }
655        if let Some(detection) = &self.detection {
656            validate_detection_user_globs(detection, "framework[].detection", &mut errors);
657        }
658        if errors.is_empty() {
659            Ok(())
660        } else {
661            Err(errors)
662        }
663    }
664}
665
666/// Recursively validate `FileExists.pattern` fields inside a `PluginDetection`
667/// tree. `All` and `Any` combinators recurse into their nested conditions.
668fn validate_detection_user_globs(
669    detection: &PluginDetection,
670    field: &'static str,
671    errors: &mut Vec<crate::config::glob_validation::GlobValidationError>,
672) {
673    match detection {
674        PluginDetection::Dependency { .. } => {}
675        PluginDetection::FileExists { pattern } => {
676            if let Err(e) = crate::config::glob_validation::compile_user_glob(pattern, field) {
677                errors.push(e);
678            }
679        }
680        PluginDetection::All { conditions } | PluginDetection::Any { conditions } => {
681            for condition in conditions {
682                validate_detection_user_globs(condition, field, errors);
683            }
684        }
685    }
686}
687
688/// Discover external plugin definitions AND validate their user-supplied glob
689/// patterns. Accumulates all errors across all loaded plugins so the user sees
690/// every problem in one run.
691///
692/// Discovery is identical to [`discover_external_plugins`]; this wrapper adds
693/// the per-plugin glob validation step required for security
694/// (see issue #463: `framework[].detection.fileExists.pattern` reaches
695/// `glob::glob` on disk via `root.join(pattern)`, so a `..` segment loaded
696/// from `.fallow/plugins/` would be a real path traversal).
697///
698/// # Errors
699///
700/// Returns the list of validation errors when any discovered plugin contains
701/// a rejected pattern. The CLI surfaces these with exit code 2.
702pub fn discover_and_validate_external_plugins(
703    root: &Path,
704    config_plugin_paths: &[String],
705) -> Result<Vec<ExternalPluginDef>, Vec<crate::config::glob_validation::GlobValidationError>> {
706    let plugins = discover_external_plugins(root, config_plugin_paths);
707    let mut errors = Vec::new();
708    for plugin in &plugins {
709        if let Err(mut plugin_errors) = plugin.validate_user_globs() {
710            errors.append(&mut plugin_errors);
711        }
712    }
713    if errors.is_empty() {
714        Ok(plugins)
715    } else {
716        Err(errors)
717    }
718}
719
720/// Detect plugin format from file extension.
721enum PluginFormat {
722    Toml,
723    Json,
724    Jsonc,
725}
726
727impl PluginFormat {
728    fn from_path(path: &Path) -> Option<Self> {
729        match path.extension().and_then(|e| e.to_str()) {
730            Some("toml") => Some(Self::Toml),
731            Some("json") => Some(Self::Json),
732            Some("jsonc") => Some(Self::Jsonc),
733            _ => None,
734        }
735    }
736}
737
738/// Check if a file has a supported plugin extension.
739/// The name of the plugin directory under `.fallow/` that the loader reads.
740const DEFAULT_PLUGINS_DIR_NAME: &str = "plugins";
741
742/// The name prefix of the plugin files in the project root that the loader
743/// reads.
744pub const ROOT_PLUGIN_FILE_PREFIX: &str = "fallow-plugin-";
745
746fn is_plugin_file(path: &Path) -> bool {
747    path.extension()
748        .and_then(|e| e.to_str())
749        .is_some_and(|ext| PLUGIN_EXTENSIONS.contains(&ext))
750}
751
752/// Parse a plugin definition from file content based on format.
753fn parse_plugin(content: &str, format: &PluginFormat, path: &Path) -> Option<ExternalPluginDef> {
754    match plugin_parse_error(content, format) {
755        Ok(plugin) => Some(plugin),
756        Err(e) => {
757            tracing::warn!("failed to parse external plugin {}: {e}", path.display());
758            None
759        }
760    }
761}
762
763/// The plugin definition in `content`, or the text of the parse error.
764fn plugin_parse_error(content: &str, format: &PluginFormat) -> Result<ExternalPluginDef, String> {
765    match format {
766        PluginFormat::Toml => crate::toml_input::from_str::<ExternalPluginDef>(content)
767            .map_err(|e| crate::parse_error::describe_toml(&e, content)),
768        PluginFormat::Json => serde_json::from_str::<ExternalPluginDef>(content)
769            .map_err(|e| crate::parse_error::describe_json(&e)),
770        PluginFormat::Jsonc => crate::jsonc::parse_to_value::<ExternalPluginDef>(content)
771            .map_err(|e| crate::parse_error::describe_jsonc(&e)),
772    }
773}
774
775/// Why an explicitly configured external-plugin resource could not be loaded.
776#[derive(Debug, Clone, Copy, PartialEq, Eq)]
777#[non_exhaustive]
778pub enum ConfiguredPluginDiagnosticKind {
779    /// The configured path does not exist.
780    Missing,
781    /// The configured path resolves outside the project root.
782    OutsideProjectRoot,
783    /// The configured file does not use a supported plugin extension.
784    UnsupportedFormat,
785    /// The configured file or directory could not be read.
786    Unreadable,
787    /// The configured plugin file could not be parsed into a usable definition.
788    InvalidDefinition,
789    /// The configured directory contains no supported plugin definitions.
790    NoPluginFiles,
791}
792
793/// Typed readiness diagnostic for an explicitly configured plugin resource.
794#[derive(Debug, Clone, PartialEq, Eq)]
795#[non_exhaustive]
796pub struct ConfiguredPluginDiagnostic {
797    /// Failure classification suitable for programmatic branching.
798    pub kind: ConfiguredPluginDiagnosticKind,
799    /// Resolved path that was inspected. Callers must apply their own privacy policy.
800    pub path: PathBuf,
801}
802
803/// Inspect only paths named explicitly by the `plugins` config field.
804///
805/// Automatic plugin discovery deliberately retains its existing best-effort
806/// behavior. This API exists for readiness surfaces that must distinguish an
807/// absent plugin configuration from an explicitly configured resource that
808/// could not be loaded.
809#[must_use]
810pub fn diagnose_configured_external_plugins(
811    root: &Path,
812    config_plugin_paths: &[String],
813) -> Vec<ConfiguredPluginDiagnostic> {
814    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
815    let mut diagnostics = Vec::new();
816
817    for path_str in config_plugin_paths {
818        let path = root.join(path_str);
819        if !plugin_path_text_allowed(root, &canonical_root, &path) {
820            diagnostics.push(ConfiguredPluginDiagnostic {
821                kind: ConfiguredPluginDiagnosticKind::OutsideProjectRoot,
822                path,
823            });
824            continue;
825        }
826        let metadata = match std::fs::metadata(&path) {
827            Ok(metadata) => metadata,
828            Err(error) => {
829                diagnostics.push(ConfiguredPluginDiagnostic {
830                    kind: if error.kind() == std::io::ErrorKind::NotFound {
831                        ConfiguredPluginDiagnosticKind::Missing
832                    } else {
833                        ConfiguredPluginDiagnosticKind::Unreadable
834                    },
835                    path,
836                });
837                continue;
838            }
839        };
840
841        if !is_within_root(&path, &canonical_root) {
842            diagnostics.push(ConfiguredPluginDiagnostic {
843                kind: ConfiguredPluginDiagnosticKind::OutsideProjectRoot,
844                path,
845            });
846            continue;
847        }
848
849        if metadata.is_dir() {
850            diagnose_configured_plugin_dir(&path, &canonical_root, &mut diagnostics);
851        } else if metadata.is_file() {
852            diagnose_configured_plugin_file(&path, &canonical_root, &mut diagnostics);
853        } else {
854            diagnostics.push(ConfiguredPluginDiagnostic {
855                kind: ConfiguredPluginDiagnosticKind::UnsupportedFormat,
856                path,
857            });
858        }
859    }
860
861    diagnostics
862}
863
864fn diagnose_configured_plugin_dir(
865    dir: &Path,
866    canonical_root: &Path,
867    diagnostics: &mut Vec<ConfiguredPluginDiagnostic>,
868) {
869    let Ok(entries) = std::fs::read_dir(dir) else {
870        diagnostics.push(ConfiguredPluginDiagnostic {
871            kind: ConfiguredPluginDiagnosticKind::Unreadable,
872            path: dir.to_path_buf(),
873        });
874        return;
875    };
876    let mut plugin_files = Vec::new();
877    let mut entry_failed = false;
878    for entry in entries {
879        match entry {
880            Ok(entry) => {
881                let path = entry.path();
882                if path.is_file() && is_plugin_file(&path) {
883                    plugin_files.push(path);
884                }
885            }
886            Err(_) => {
887                entry_failed = true;
888                diagnostics.push(ConfiguredPluginDiagnostic {
889                    kind: ConfiguredPluginDiagnosticKind::Unreadable,
890                    path: dir.to_path_buf(),
891                });
892            }
893        }
894    }
895    if plugin_files.is_empty() && !entry_failed {
896        diagnostics.push(ConfiguredPluginDiagnostic {
897            kind: ConfiguredPluginDiagnosticKind::NoPluginFiles,
898            path: dir.to_path_buf(),
899        });
900        return;
901    }
902    plugin_files.sort();
903    for path in plugin_files {
904        diagnose_configured_plugin_file(&path, canonical_root, diagnostics);
905    }
906}
907
908fn diagnose_configured_plugin_file(
909    path: &Path,
910    canonical_root: &Path,
911    diagnostics: &mut Vec<ConfiguredPluginDiagnostic>,
912) {
913    let kind = if !is_within_root(path, canonical_root) {
914        Some(ConfiguredPluginDiagnosticKind::OutsideProjectRoot)
915    } else if let Some(format) = PluginFormat::from_path(path) {
916        match fallow_types::read_guard::read_to_string_inside(
917            canonical_root,
918            path,
919            fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
920        ) {
921            Ok(content) => match parse_plugin(&content, &format, path) {
922                Some(plugin) if !plugin.name.is_empty() => None,
923                Some(_) | None => Some(ConfiguredPluginDiagnosticKind::InvalidDefinition),
924            },
925            Err(_) => Some(ConfiguredPluginDiagnosticKind::Unreadable),
926        }
927    } else {
928        Some(ConfiguredPluginDiagnosticKind::UnsupportedFormat)
929    };
930    if let Some(kind) = kind {
931        diagnostics.push(ConfiguredPluginDiagnostic {
932            kind,
933            path: path.to_path_buf(),
934        });
935    }
936}
937
938/// Merge the discovered plugins with the inline `framework` entries, and warn
939/// about each plugin that can never activate.
940pub fn resolve_external_plugins(
941    root: &Path,
942    config_plugin_paths: &[String],
943    framework: Vec<ExternalPluginDef>,
944) -> Vec<ExternalPluginDef> {
945    let mut plugins = discover_external_plugins(root, config_plugin_paths);
946    plugins.extend(framework);
947    // A caller that skipped the validation of the config load still never
948    // gets a plugin whose globs are absolute or have a `..` segment.
949    plugins.retain(|plugin| match plugin.validate_user_globs() {
950        Ok(()) => true,
951        Err(errors) => {
952            for error in errors {
953                tracing::warn!("skipping external plugin '{}': {error}", plugin.name);
954            }
955            false
956        }
957    });
958    warn_on_plugins_that_never_activate(&plugins);
959    plugins
960}
961
962/// Warn once per process for each plugin name with no activation condition.
963/// Bare `fallow`, watch and the LSP resolve the config more than once.
964fn warn_on_plugins_that_never_activate(plugins: &[ExternalPluginDef]) {
965    static WARNED: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
966    let warned = WARNED.get_or_init(|| Mutex::new(FxHashSet::default()));
967
968    for plugin in plugins {
969        if plugin.has_activation_condition() {
970            continue;
971        }
972        if let Ok(mut set) = warned.lock()
973            && !set.insert(plugin.name.clone())
974        {
975            continue;
976        }
977        tracing::warn!(
978            "plugin '{}': {}. Add one of them, then run `fallow plugin-check`.",
979            plugin.name,
980            ExternalPluginDef::NEVER_ACTIVATES_REASON,
981        );
982    }
983}
984
985/// Discover and load external plugin definitions for a project.
986///
987/// Discovery order (first occurrence of a plugin name wins):
988/// 1. Paths from the `plugins` config field (files or directories)
989/// 2. `.fallow/plugins/` directory (auto-discover `*.toml`, `*.json`, `*.jsonc` files)
990/// 3. Project root `fallow-plugin-*` files (`.toml`, `.json`, `.jsonc`)
991pub fn discover_external_plugins(
992    root: &Path,
993    config_plugin_paths: &[String],
994) -> Vec<ExternalPluginDef> {
995    let mut plugins = Vec::new();
996    let mut seen_names = rustc_hash::FxHashSet::default();
997
998    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
999
1000    load_configured_plugin_paths(
1001        root,
1002        config_plugin_paths,
1003        &canonical_root,
1004        &mut plugins,
1005        &mut seen_names,
1006    );
1007    load_default_plugins_dir(root, &canonical_root, &mut plugins, &mut seen_names);
1008    load_root_plugin_files(root, &canonical_root, &mut plugins, &mut seen_names);
1009
1010    plugins
1011}
1012
1013fn load_configured_plugin_paths(
1014    root: &Path,
1015    config_plugin_paths: &[String],
1016    canonical_root: &Path,
1017    plugins: &mut Vec<ExternalPluginDef>,
1018    seen_names: &mut rustc_hash::FxHashSet<String>,
1019) {
1020    for path_str in config_plugin_paths {
1021        let path = root.join(path_str);
1022        match crate::project_read::project_entry(canonical_root, Path::new(path_str)) {
1023            crate::project_read::ProjectEntry::Missing => continue,
1024            crate::project_read::ProjectEntry::Outside => {
1025                tracing::warn!("plugin path '{path_str}' resolves outside project root, skipping");
1026                continue;
1027            }
1028            crate::project_read::ProjectEntry::Inside => {}
1029        }
1030        if path.is_dir() {
1031            load_plugins_from_dir(&path, canonical_root, plugins, seen_names);
1032        } else if path.is_file() {
1033            load_plugin_file(&path, canonical_root, plugins, seen_names);
1034        }
1035    }
1036}
1037
1038fn load_default_plugins_dir(
1039    root: &Path,
1040    canonical_root: &Path,
1041    plugins: &mut Vec<ExternalPluginDef>,
1042    seen_names: &mut rustc_hash::FxHashSet<String>,
1043) {
1044    let plugins_dir = root.join(".fallow").join(DEFAULT_PLUGINS_DIR_NAME);
1045    if plugins_dir.is_dir() && is_within_root(&plugins_dir, canonical_root) {
1046        load_plugins_from_dir(&plugins_dir, canonical_root, plugins, seen_names);
1047    }
1048}
1049
1050fn load_root_plugin_files(
1051    root: &Path,
1052    canonical_root: &Path,
1053    plugins: &mut Vec<ExternalPluginDef>,
1054    seen_names: &mut rustc_hash::FxHashSet<String>,
1055) {
1056    for path in root_plugin_files(root) {
1057        load_plugin_file(&path, canonical_root, plugins, seen_names);
1058    }
1059}
1060
1061/// The `fallow-plugin-*` files in the project root, sorted.
1062fn root_plugin_files(root: &Path) -> Vec<PathBuf> {
1063    let Ok(entries) = std::fs::read_dir(root) else {
1064        return Vec::new();
1065    };
1066    let mut plugin_files: Vec<PathBuf> = entries
1067        .filter_map(Result::ok)
1068        .map(|e| e.path())
1069        .filter(|p| {
1070            is_file_or_link(p)
1071                && p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
1072                    n.starts_with(ROOT_PLUGIN_FILE_PREFIX) && is_plugin_file(Path::new(n))
1073                })
1074        })
1075        .collect();
1076    plugin_files.sort();
1077    plugin_files
1078}
1079
1080/// The plugin files in a plugin directory, sorted.
1081fn plugin_files_in_dir(dir: &Path) -> Vec<PathBuf> {
1082    let Ok(entries) = std::fs::read_dir(dir) else {
1083        return Vec::new();
1084    };
1085    let mut plugin_files: Vec<PathBuf> = entries
1086        .filter_map(Result::ok)
1087        .map(|e| e.path())
1088        .filter(|p| is_file_or_link(p) && is_plugin_file(p))
1089        .collect();
1090    plugin_files.sort();
1091    plugin_files
1092}
1093
1094/// Whether the loader reads `path` from one of its default plugin
1095/// locations: a `fallow-plugin-*` file, or a file in a `.fallow/plugins/`
1096/// directory. A file that the `plugins` config key names can have any name.
1097#[must_use]
1098pub fn is_default_external_plugin_file(path: &Path) -> bool {
1099    if !is_plugin_file(path) {
1100        return false;
1101    }
1102    let name_matches = path
1103        .file_name()
1104        .and_then(|name| name.to_str())
1105        .is_some_and(|name| name.starts_with(ROOT_PLUGIN_FILE_PREFIX));
1106    let parent = path.parent();
1107    let in_plugins_dir = parent
1108        .and_then(Path::file_name)
1109        .is_some_and(|name| name == DEFAULT_PLUGINS_DIR_NAME)
1110        && parent
1111            .and_then(Path::parent)
1112            .and_then(Path::file_name)
1113            .is_some_and(|name| name == ".fallow");
1114    name_matches || in_plugins_dir
1115}
1116
1117/// The files that [`discover_external_plugins`] can read for a project, in
1118/// the order it reads them. A `plugins` entry that is not a directory is
1119/// listed also when it does not exist, so that a caller can see it appear.
1120/// The list does not apply the project-root check of the loader, so it can
1121/// hold a file that the loader skips.
1122#[must_use]
1123pub fn external_plugin_source_files(root: &Path, config_plugin_paths: &[String]) -> Vec<PathBuf> {
1124    let mut files = Vec::new();
1125    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
1126    for path_str in config_plugin_paths {
1127        let path = root.join(path_str);
1128        if !plugin_path_text_allowed(root, &canonical_root, &path) {
1129            continue;
1130        }
1131        if path.is_dir() {
1132            files.extend(plugin_files_in_dir(&path));
1133        } else {
1134            files.push(path);
1135        }
1136    }
1137    files.extend(plugin_files_in_dir(
1138        &root.join(".fallow").join(DEFAULT_PLUGINS_DIR_NAME),
1139    ));
1140    files.extend(root_plugin_files(root));
1141    files
1142}
1143
1144/// Whether the configured plugin path `path`, joined to `root`, may reach a
1145/// file system call. An absolute path must name a place below the root by
1146/// its text, see [`crate::project_read::absolute_path_text_inside`].
1147fn plugin_path_text_allowed(root: &Path, canonical_root: &Path, path: &Path) -> bool {
1148    // A Windows prefix without a root, such as `Z:x`, names a place relative
1149    // to the current directory of that drive: refuse it.
1150    let has_prefix = matches!(
1151        path.components().next(),
1152        Some(std::path::Component::Prefix(_))
1153    );
1154    if has_prefix && !path.is_absolute() {
1155        return false;
1156    }
1157    !path.is_absolute()
1158        || crate::project_read::absolute_path_text_inside(path, canonical_root, root)
1159}
1160
1161/// True when `path` is a regular file, or a link that does not resolve to
1162/// something other than a regular file. A dangling link and a link to a
1163/// file outside the root both reach the root check of the loader and get
1164/// the same warning. A link to a directory, a pipe or a device is not a
1165/// plugin file.
1166fn is_file_or_link(path: &Path) -> bool {
1167    path.symlink_metadata().is_ok_and(|meta| {
1168        meta.is_file()
1169            || (meta.file_type().is_symlink()
1170                && std::fs::metadata(path).map_or(true, |target| target.is_file()))
1171    })
1172}
1173
1174/// Check if a path resolves within the canonical root (follows symlinks).
1175/// A path that does not resolve counts as outside.
1176fn is_within_root(path: &Path, canonical_root: &Path) -> bool {
1177    dunce::canonicalize(path).is_ok_and(|canonical| canonical.starts_with(canonical_root))
1178}
1179
1180fn load_plugins_from_dir(
1181    dir: &Path,
1182    canonical_root: &Path,
1183    plugins: &mut Vec<ExternalPluginDef>,
1184    seen: &mut rustc_hash::FxHashSet<String>,
1185) {
1186    for path in plugin_files_in_dir(dir) {
1187        load_plugin_file(&path, canonical_root, plugins, seen);
1188    }
1189}
1190
1191fn load_plugin_file(
1192    path: &Path,
1193    canonical_root: &Path,
1194    plugins: &mut Vec<ExternalPluginDef>,
1195    seen: &mut rustc_hash::FxHashSet<String>,
1196) {
1197    if !is_within_root(path, canonical_root) {
1198        tracing::warn!(
1199            "plugin file '{}' resolves outside project root (symlink?), skipping",
1200            path.display()
1201        );
1202        return;
1203    }
1204
1205    let Some(format) = PluginFormat::from_path(path) else {
1206        tracing::warn!(
1207            "unsupported plugin file extension for {}, expected .toml, .json, or .jsonc",
1208            path.display()
1209        );
1210        return;
1211    };
1212
1213    let Some(content) = read_plugin_file(path, canonical_root) else {
1214        return;
1215    };
1216
1217    if let Some(plugin) = parse_plugin(&content, &format, path) {
1218        push_plugin_if_unique(plugin, path, plugins, seen);
1219    }
1220}
1221
1222fn read_plugin_file(path: &Path, canonical_root: &Path) -> Option<String> {
1223    match fallow_types::read_guard::read_to_string_inside(
1224        canonical_root,
1225        path,
1226        fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
1227    ) {
1228        Ok(content) => Some(content),
1229        Err(e) => {
1230            tracing::warn!("failed to read external plugin file: {e}");
1231            None
1232        }
1233    }
1234}
1235
1236fn push_plugin_if_unique(
1237    plugin: ExternalPluginDef,
1238    path: &Path,
1239    plugins: &mut Vec<ExternalPluginDef>,
1240    seen: &mut rustc_hash::FxHashSet<String>,
1241) {
1242    if plugin.name.is_empty() {
1243        tracing::warn!(
1244            "external plugin in {} has an empty name, skipping",
1245            path.display()
1246        );
1247        return;
1248    }
1249
1250    if seen.insert(plugin.name.clone()) {
1251        plugins.push(plugin);
1252    } else {
1253        tracing::warn!(
1254            "duplicate external plugin '{}' in {}, skipping",
1255            plugin.name,
1256            path.display()
1257        );
1258    }
1259}
1260
1261#[cfg(test)]
1262mod tests;