fallow_config/config/mod.rs
1mod boundaries;
2mod dependency_ignore;
3mod duplicates_config;
4mod entry_effect;
5mod entry_span;
6mod finding_ignore;
7mod flags;
8mod format;
9pub mod glob_validation;
10mod health;
11mod ignore_list_effect;
12mod ignore_patterns;
13mod keep_export_tags;
14mod legacy_glob;
15mod markup_extensions;
16mod mutation;
17mod outside_root;
18mod outside_values;
19#[cfg(all(test, unix))]
20pub use outside_root::test_tracked_link_probe;
21pub use outside_root::{OutsideKeys, TrackedLinkProbe, set_tracked_link_probe};
22pub use outside_values::{outside_value_error, outside_value_files};
23mod override_effect;
24mod parsing;
25mod resolution;
26mod resolve;
27mod rules;
28mod run_plan;
29mod similar_code;
30mod used_class_members;
31mod workspace_settings;
32
33pub use boundaries::{
34 AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
35 BoundaryRule, BoundaryZone, DEEP_MODULES_ROOT_CANDIDATES, ForbiddenCallRule, ForbiddenCallee,
36 InvalidForbiddenCallee, LogicalGroup, LogicalGroupStatus, PresetLayout, RedundantRootPrefix,
37 ResolvedBoundaryConfig, ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone,
38 UnknownZoneRef, ZoneReferenceKind, ZoneValidationError,
39};
40#[expect(
41 clippy::redundant_pub_crate,
42 reason = "this module is glob re-exported from lib.rs, so `pub` would leak the helper into the public API; pub(crate) keeps it internal to the crate"
43)]
44pub(crate) use boundaries::{expand_boundary_preset, wildcard_placement_error};
45pub use dependency_ignore::{IgnoreDependencyMatcher, is_dependency_glob};
46pub use duplicates_config::{
47 DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
48};
49pub use entry_effect::EntryEffectRecord;
50pub use entry_span::ConfigEntrySpan;
51pub use finding_ignore::FindingIgnoreMatcher;
52pub use flags::{FlagsConfig, SdkPattern};
53pub use format::OutputFormat;
54pub use glob_validation::compile_path_glob;
55pub use health::{
56 ChangeCouplingConfig, CyclomaticPolicy, EmailMode, HealthConfig, HealthThresholdOverride,
57 OwnershipConfig, ShallowDirectoriesConfig,
58};
59pub use ignore_list_effect::{IgnoreExportName, IgnoreListEffect, OverrideGlob};
60pub use ignore_patterns::{IgnorePatternSet, UNLIFTABLE_IGNORE_SEGMENTS};
61pub use keep_export_tags::{KeepExportTag, KeepExportTags};
62pub use legacy_glob::{
63 LegacyGlobGroup, LegacyGlobNarrowing, find_legacy_glob_narrowings, has_single_segment_wildcard,
64 suggest_cross_directory_rewrite,
65};
66pub use markup_extensions::{
67 DEFAULT_MARKUP_EXTENSIONS, resolve_markup_extensions, template_markup_extension,
68};
69pub use mutation::{MutationConfig, MutationOperatorName, MutationRunner};
70pub use override_effect::{IneffectiveOverrideRule, project_level_override_rules};
71pub use parsing::{
72 CONFIG_FILE_NAMES, ConfigLoadOptions, UNRECOGNIZED_CONFIG_FILE_NAMES, config_file_name,
73 extends_timeout_from_env_value,
74};
75pub use resolution::{
76 AnalysisSnapshot, CACHE_DIR_ENV, CACHE_MAX_SIZE_ENV, CompiledIgnoreCatalogReferenceRule,
77 CompiledIgnoreDependencyOverrideRule, CompiledIgnoreExportRule, ConfigOverride,
78 DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_FILE_SIZE_BYTES, DEFAULT_MAX_FILE_SIZE_MB,
79 IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule, IgnoreExportRule,
80 PACKAGE_BASELINES_ENV, ResolvedConfig, ResolvedOverride, cache_config_hash,
81 cache_dir_from_env_value, cache_max_size_env_override, cache_max_size_from_env_value,
82 config_cache_dir, package_baselines_disabled_by_env_value, resolve_max_file_size_bytes,
83};
84pub use resolve::ResolveConfig;
85pub use rules::{
86 KNOWN_RULE_NAMES, PartialRulesConfig, RulesConfig, SEMANTIC_REFINABLE_KINDS,
87 SYMBOL_USE_REFINABLE_KINDS, Severity, any_symbol_use_rule_active, closest_known_rule_name,
88 default_severity_for_kind, is_opt_in_kind,
89};
90pub use run_plan::{
91 AnalysisRequest, AnalysisSelection, ConfigKey, PlanSections, PlannedAnalysis, RunCommand,
92 RunPlan, RunRequest, SkipReason, plan_run,
93};
94pub use similar_code::SimilarCodeConfig;
95pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
96pub use workspace_settings::ResolvedWorkspaceSettings;
97
98use schemars::JsonSchema;
99use serde::{Deserialize, Deserializer, Serialize};
100use std::ops::Not;
101use std::path::PathBuf;
102
103use crate::external_plugin::ExternalPluginDef;
104use crate::workspace::WorkspaceConfig;
105
106/// Value of the `ignoreExportsUsedInFile` config key: whether an export
107/// referenced elsewhere in its own file is suppressed from `unused-export`.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
109#[serde(untagged, rename_all = "camelCase")]
110pub enum IgnoreExportsUsedInFileConfig {
111 /// Blanket toggle: `true` suppresses any export with a same-file use,
112 /// regardless of kind. The default is `false`.
113 Bool(bool),
114 /// Object form that restricts the suppression to type-only exports.
115 ByKind(IgnoreExportsUsedInFileByKind),
116}
117
118/// A derived untagged deserializer gives only "did not match any variant",
119/// so an unknown key in the object form would not be named.
120impl<'de> Deserialize<'de> for IgnoreExportsUsedInFileConfig {
121 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122 where
123 D: Deserializer<'de>,
124 {
125 struct IgnoreExportsVisitor;
126
127 impl<'de> serde::de::Visitor<'de> for IgnoreExportsVisitor {
128 type Value = IgnoreExportsUsedInFileConfig;
129
130 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 formatter.write_str("a boolean or an object with `type` and `interface`")
132 }
133
134 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
135 where
136 E: serde::de::Error,
137 {
138 Ok(IgnoreExportsUsedInFileConfig::Bool(value))
139 }
140
141 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
142 where
143 A: serde::de::MapAccess<'de>,
144 {
145 IgnoreExportsUsedInFileByKind::deserialize(
146 serde::de::value::MapAccessDeserializer::new(map),
147 )
148 .map(IgnoreExportsUsedInFileConfig::ByKind)
149 }
150 }
151
152 deserializer.deserialize_any(IgnoreExportsVisitor)
153 }
154}
155
156impl Default for IgnoreExportsUsedInFileConfig {
157 fn default() -> Self {
158 Self::Bool(false)
159 }
160}
161
162impl From<bool> for IgnoreExportsUsedInFileConfig {
163 fn from(value: bool) -> Self {
164 Self::Bool(value)
165 }
166}
167
168impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
169 fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
170 Self::ByKind(value)
171 }
172}
173
174impl IgnoreExportsUsedInFileConfig {
175 /// Whether any form of the same-file-use suppression is active (the bool
176 /// form is `true`, or either by-kind field is set).
177 #[must_use]
178 pub const fn is_enabled(self) -> bool {
179 match self {
180 Self::Bool(value) => value,
181 Self::ByKind(kind) => kind.type_ || kind.interface,
182 }
183 }
184
185 /// Whether an export with a same-file use should be suppressed, given
186 /// whether fallow classified it as type-only. The bool form suppresses
187 /// regardless of kind; the by-kind form suppresses type-only exports only.
188 #[must_use]
189 pub const fn suppresses(self, is_type_only: bool) -> bool {
190 match self {
191 Self::Bool(value) => value,
192 Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
193 }
194 }
195}
196
197/// Object form of `ignoreExportsUsedInFile` (`{ "type": ..., "interface": ... }`),
198/// restricting the same-file-use suppression to type-only exports.
199#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
200#[serde(deny_unknown_fields, rename_all = "camelCase")]
201pub struct IgnoreExportsUsedInFileByKind {
202 /// When `true`, enables the same-file-use suppression for type-only exports (serialized as `type`; part of the object form of `ignoreExportsUsedInFile`). Because fallow groups type aliases and interfaces under one issue kind, setting either `type` or `interface` enables the identical type-only suppression, applied only to exports fallow classifies as type-only.
203 #[serde(default, rename = "type")]
204 pub type_: bool,
205 /// When `true`, enables the same-file-use suppression for type-only exports (part of the object form of `ignoreExportsUsedInFile`). Fallow does not distinguish interfaces from type aliases in this issue kind, so `interface` behaves identically to `type`: setting either one turns on the type-only same-file suppression.
206 #[serde(default)]
207 pub interface: bool,
208}
209
210/// Options for the `unused-component-props` rule.
211///
212/// Lets a project exempt component props whose local destructure binding name
213/// matches a regex from `unused-component-props`, honoring the
214/// "accepted-but-intentionally-unused" leading-underscore convention (Svelte 5
215/// `$props()`, React destructure) that mirrors TypeScript `noUnusedParameters`
216/// and ESLint `@typescript-eslint/no-unused-vars` `varsIgnorePattern` /
217/// `argsIgnorePattern`. Opt-in; an unset `ignorePattern` leaves the rule's
218/// behavior unchanged.
219#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
220#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
221pub struct UnusedComponentPropsConfig {
222 /// Regex matched against each declared prop's local destructure binding name
223 /// (e.g. `_stage` in `let { stage: _stage } = $props()`), which falls back
224 /// to the public prop name when there is no alias. A prop whose local name
225 /// matches is treated as intentionally unused and never reported as
226 /// `unused-component-props`. Matching is unanchored (substring), like
227 /// ESLint's `RegExp.test`, so anchor with `^_` to match a leading
228 /// underscore. Compiled and validated at config load (an invalid regex fails
229 /// load). Applies to Vue, Svelte, Astro, and React/Preact props.
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub ignore_pattern: Option<String>,
232}
233
234impl UnusedComponentPropsConfig {
235 /// True when no option is set, so serialization can omit the section.
236 #[must_use]
237 pub fn is_default(&self) -> bool {
238 self.ignore_pattern.is_none()
239 }
240}
241
242/// Options for the `circular-dependencies` rule.
243///
244/// The default leaves the rule unchanged: every runtime import edge takes
245/// part in cycle detection, and only type-only edges are skipped.
246#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
247#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
248pub struct CircularDependenciesConfig {
249 /// Skip import edges that load their target on demand or on another
250 /// thread when fallow looks for cycles. A literal `import()` inside a
251 /// function, a template `import()`, a lazy `import.meta.glob`, a worker
252 /// URL and a webpack worker loader request (`worker-loader!./work.js`)
253 /// are lazy edges. A top-level `await import()`, `require()` and an
254 /// eager `import.meta.glob` load before the module finishes, so they stay.
255 /// An edge that also carries a static import stays. Default `false`.
256 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
257 pub ignore_lazy_imports: bool,
258 /// Accepted cycles. Each entry is the list of files of one cycle, in
259 /// import order, without the repeat of the first file at the end. An
260 /// entry accepts a cycle that has exactly these files in this order, from
261 /// any start file: `["src/a.ts", "src/b.ts", "src/c.ts"]` also accepts
262 /// `src/b.ts -> src/c.ts -> src/a.ts`. A cycle with another set of files
263 /// stays reported, also when it shares an import with an accepted cycle.
264 ///
265 /// Each path is relative to the project root, also in a monorepo: write
266 /// `packages/app/src/a.ts`, not a path relative to the workspace. The
267 /// match is case-sensitive on every platform. Globs are not supported.
268 /// An entry needs at least 2 files and lists each file once.
269 ///
270 /// An entry that matches no cycle in a run gives a
271 /// `circular-dependencies-allow-unmatched` diagnostic. The detector lists
272 /// at most 20 cycles per group of files that import each other, and no
273 /// cycle with more than 12 files. An accepted cycle does not count toward
274 /// the 20. An entry with more than 12 files, or with all files in a group
275 /// that reached the limit, gives no diagnostic, because the detector
276 /// cannot prove that it matches no cycle.
277 ///
278 /// A `fallow-ignore-next-line circular-dependency` comment on an accepted
279 /// cycle becomes a stale suppression: remove the comment when you add the
280 /// entry. Default `[]`.
281 #[serde(default, skip_serializing_if = "Vec::is_empty")]
282 #[schemars(inner(length(min = 2)))]
283 pub allow: Vec<Vec<String>>,
284}
285
286impl CircularDependenciesConfig {
287 /// True when no option is set, so serialization can omit the section.
288 #[must_use]
289 pub const fn is_default(&self) -> bool {
290 !self.ignore_lazy_imports && self.allow.is_empty()
291 }
292
293 /// The `allow` entries that can never match a cycle: an entry with fewer
294 /// than 2 files, and an entry that lists one file more than once. A
295 /// leading `./` does not make two paths different.
296 #[must_use]
297 pub fn allow_errors(&self) -> Vec<String> {
298 let mut errors = Vec::new();
299 for (index, entry) in self.allow.iter().enumerate() {
300 if entry.len() < 2 {
301 let noun = if entry.len() == 1 { "file" } else { "files" };
302 errors.push(format!(
303 "circularDependencies.allow[{index}] lists {} {noun}; an entry lists the 2 or \
304 more files of one cycle",
305 entry.len()
306 ));
307 continue;
308 }
309 let mut seen = rustc_hash::FxHashSet::default();
310 if let Some(repeated) = entry
311 .iter()
312 .map(|file| file.trim_start_matches("./"))
313 .find(|file| !seen.insert(*file))
314 {
315 errors.push(format!(
316 "circularDependencies.allow[{index}] lists '{repeated}' more than once; a \
317 cycle has each file once"
318 ));
319 }
320 }
321 errors
322 }
323}
324
325/// Options for projects that use the Effect library.
326///
327/// The default changes nothing: each Effect export is reported like any
328/// other export.
329#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
330#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
331pub struct EffectConfig {
332 /// Report an unused exported Effect schema as an unused type, under the
333 /// `unused-types` rule, and not as an unused export. An Effect schema
334 /// defines a runtime value and a type (`typeof User.Type`), so a team
335 /// that keeps exported types as contracts can keep schemas too. With
336 /// `"unused-types": "off"`, fallow does not report them. A schema is a
337 /// class that extends a `Schema` class factory (`Schema.Class`,
338 /// `Schema.TaggedClass`, `Schema.TaggedError`, `Schema.TaggedRequest`,
339 /// `Schema.Error`, `Schema.Opaque`), or a const whose
340 /// value is a `Schema` constructor, member or pipe chain
341 /// (`Schema.Struct({...})`, `Schema.String.pipe(Schema.brand("Id"))`).
342 /// Each `pipe` argument must be a `Schema` transform, or a call of an
343 /// `HttpApiSchema` transform such as `HttpApiSchema.status(201)`.
344 /// A const whose value is a call of a function is a schema when each
345 /// `return` of the function is a schema (`const makeUser = () =>
346 /// Schema.Struct({...})`, then `export const User = makeUser()`). The
347 /// function can be in the same module or in an imported module. The
348 /// export of the function itself stays an unused export. A conditional
349 /// expression whose two branches are schemas, a member of a namespace
350 /// import, a call of a function that returns a schema argument, a member
351 /// of a local `const` object or array literal, and a destructured export
352 /// of such a member also count. A lowercase `Schema` member counts when
353 /// its declared return type is a schema in effect 3 or effect 4
354 /// (`Schema.optional(...)`, `Schema.mutable(...)`), and only as a call.
355 /// Decoders, encoders, guards, filters and annotation ids do not count.
356 /// `Schema` must come from `effect`, `effect/Schema` or `@effect/schema`.
357 /// Default `false`.
358 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
359 #[schemars(extend("default" = false))]
360 pub schema_exports_as_types: bool,
361}
362
363impl EffectConfig {
364 /// True when no option is set, so serialization can omit the section.
365 #[must_use]
366 pub const fn is_default(&self) -> bool {
367 !self.schema_exports_as_types
368 }
369}
370
371/// The `fix` config section: settings for `fallow fix` apply behavior.
372#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
373#[serde(deny_unknown_fields, rename_all = "camelCase")]
374pub struct FixConfig {
375 /// Groups `fallow fix` settings for pnpm workspace catalog cleanup. Its only key, `deletePrecedingComments` (`auto` default, `always`, `never`), controls whether a comment block directly above a removed unused `pnpm-workspace.yaml` catalog entry is deleted with the entry.
376 #[serde(default)]
377 pub catalog: CatalogFixConfig,
378}
379
380/// The `fix.catalog` section: how `fallow fix` cleans up unused
381/// `pnpm-workspace.yaml` catalog entries.
382#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
383#[serde(deny_unknown_fields, rename_all = "camelCase")]
384pub struct CatalogFixConfig {
385 /// Controls whether comment lines immediately above an unused `pnpm-workspace.yaml` catalog entry are removed when `fallow fix` deletes that entry: `auto` (default: delete only when the comment block is preceded by a blank line or sits directly under the parent catalog header, and never when it is a section banner like `# ====`), `always` (always remove the adjacent comment block), or `never` (leave all preceding comments). A `fallow-keep` marker anywhere in the block always preserves it regardless of this setting. Set `never` for teams that keep hand-authored notes above catalog pins.
386 #[serde(default)]
387 pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
388}
389
390/// Value of `fix.catalog.deletePrecedingComments`: what happens to comment
391/// lines directly above a catalog entry that `fallow fix` removes. A
392/// `fallow-keep` marker in the block always preserves it regardless of policy.
393#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
394#[serde(rename_all = "lowercase")]
395pub enum CatalogPrecedingCommentPolicy {
396 /// Delete the adjacent comment block only when heuristics attribute it to
397 /// the entry (preceded by a blank line or directly under the catalog
398 /// header) and it is not a section banner. The default.
399 #[default]
400 Auto,
401 /// Always delete the adjacent comment block with the entry.
402 Always,
403 /// Never delete preceding comments.
404 Never,
405}
406
407/// Completeness policy for opt-in TypeScript semantic analysis.
408#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
409#[serde(rename_all = "kebab-case")]
410pub enum TypeAwareRequire {
411 /// Keep conservative findings and report semantic gaps without failing.
412 #[default]
413 BestEffort,
414 /// Fail the quality gate when any requested semantic query is incomplete.
415 Complete,
416}
417
418impl TypeAwareRequire {
419 /// The policy of a `FALLOW_TYPE_AWARE_REQUIRE` value: `best-effort` or
420 /// `complete`, without case and outer spaces. `None` for another value.
421 #[must_use]
422 pub fn from_env_value(value: &str) -> Option<Self> {
423 match value.trim().to_ascii_lowercase().as_str() {
424 "best-effort" => Some(Self::BestEffort),
425 "complete" => Some(Self::Complete),
426 _ => None,
427 }
428 }
429}
430
431impl From<TypeAwareRequire> for fallow_types::semantic::SemanticCompletenessRequirement {
432 fn from(value: TypeAwareRequire) -> Self {
433 match value {
434 TypeAwareRequire::BestEffort => Self::BestEffort,
435 TypeAwareRequire::Complete => Self::Complete,
436 }
437 }
438}
439
440/// Shared opt-in configuration for TypeScript semantic analysis.
441#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
442#[serde(deny_unknown_fields, rename_all = "camelCase")]
443pub struct TypeAwareConfig {
444 /// Enable the optional TypeScript semantic pass. Disabled by default.
445 #[serde(default)]
446 pub enabled: bool,
447 /// TypeScript project config paths, resolved relative to the project root.
448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
449 pub projects: Vec<String>,
450 /// Decide whether partial semantic analysis is advisory or gating.
451 #[serde(default, skip_serializing_if = "is_default_type_aware_require")]
452 pub require: TypeAwareRequire,
453}
454
455#[expect(
456 clippy::trivially_copy_pass_by_ref,
457 reason = "serde skip_serializing_if callbacks receive field values by reference"
458)]
459fn is_default_type_aware_require(value: &TypeAwareRequire) -> bool {
460 matches!(value, TypeAwareRequire::BestEffort)
461}
462
463impl TypeAwareConfig {
464 /// True when the section equals its default (disabled, no projects,
465 /// best-effort), so serialization can omit it.
466 #[must_use]
467 pub fn is_default(&self) -> bool {
468 !self.enabled && self.projects.is_empty() && self.require == TypeAwareRequire::BestEffort
469 }
470}
471
472/// Schema for `extends`. The loader accepts one string or an array of strings
473/// and normalizes both to a list before it deserializes the config (#3351).
474fn extends_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
475 schemars::json_schema!({
476 "anyOf": [
477 { "type": "string" },
478 { "type": "array", "items": { "type": "string" } }
479 ]
480 })
481}
482
483/// The user-facing fallow configuration as authored in `.fallowrc.json` /
484/// `.fallowrc.jsonc` / `fallow.toml` / `.fallow.toml`.
485///
486/// Every field documents its serialized meaning, default, and precedence
487/// against CLI flags and environment variables where they exist.
488/// `FallowConfig::resolve` compiles the loaded config (globs, regexes,
489/// plugin and rule-pack discovery) into a [`ResolvedConfig`] for analysis.
490/// Unknown keys are rejected at load so typos fail loud.
491#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
492#[serde(deny_unknown_fields, rename_all = "camelCase")]
493// Both `.fallowrc.json` and `.fallowrc.jsonc` are read with the JSONC dialect
494// from `crate::jsonc::parse_options`, so the schema declares the same dialect.
495// JSON language service clients (VS Code, Zed) read these two keywords off the
496// root object and otherwise flag syntax the loader accepts. They are
497// annotations only: nothing in fallow reads them back.
498#[schemars(extend("allowComments" = true, "allowTrailingCommas" = true))]
499pub struct FallowConfig {
500 /// A string pointing at fallow's JSON Schema URL, used only by editors for autocomplete and validation of the config file; it has no effect on analysis, and fallow does not write it back when it saves a config. Set it to `./node_modules/fallow/schema.json` for npm installs (version-aligned, offline, avoids VS Code's untrusted-remote-schema prompt), or `https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json` for non-npm installs; any other value is ignored by fallow.
501 #[serde(rename = "$schema", default, skip_serializing)]
502 pub schema: Option<String>,
503
504 /// The lowest fallow version this config is written for, as `MAJOR.MINOR.PATCH`. An older binary stops with a message naming both versions instead of failing on the first field it does not recognize, so a config committed to a shared repository says which upgrade it needs rather than reading like a typo. Optional and unset by default; set it in the same change that adds a field introduced in a newer version. Only digits are accepted: a pre-release suffix such as `-beta.1` is a config error. A parent config of `extends` can set it too. It gates nothing on its own: an unknown key still fails on a binary at or above this version, because there the key really is a typo. A value of `3.34.0` or higher also says that the config is written for the rule where a single `*` or `?` matches in one folder level only, so fallow prints no single-segment glob warning for the globs of the config. The globs of plugins and rule packs keep that warning.
505 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub minimum_version: Option<String>,
507
508 /// A single parent config source, or an ordered array of them, to inherit before this file's own keys apply; each source is a file-relative path, an `npm:<package>` specifier, or an `https://` URL (`http://` is rejected), deep-merged in order so objects merge field-by-field while arrays and scalars in this file replace the parent's, with a cycle guard and a depth limit of 10 levels. An `https://` source loads only with `--allow-remote-extends`; fallow waits 5 seconds for it (`FALLOW_EXTENDS_TIMEOUT_SECS` changes this) and refuses a response over 1 MB. Set it to share a base config across a monorepo or team; fallow reads it at load and does not write it back when it saves a config.
509 #[serde(default, skip_serializing)]
510 #[schemars(schema_with = "extends_schema")]
511 pub extends: Vec<String>,
512
513 /// An array of project-root-relative glob patterns whose matching files are seeded as manual entry points, on top of the framework and package.json entries fallow discovers automatically, so their transitive imports are not reported as unused. Set it (e.g. `["src/main.ts"]`) when a file is a real runtime root that no plugin or manifest declares; patterns are validated at load and matched against discovered files. For a script that does not run in production, use `supportEntry` and leave its glob out of `entry`: a file that also matches `entry` stays a runtime root. A single `*` stays within one path segment; use `**` to match across directories.
514 #[serde(default)]
515 pub entry: Vec<String>,
516
517 /// An array of project-root-relative glob patterns for files to exclude from analysis entirely; entries are unioned with fallow's built-in defaults (**/node_modules/**, **/dist/**, **/build/**, **/.git/**, **/coverage/**, **/*.min.js, **/*.min.mjs, **/*.min.cjs, **/*.bundle.js, and the root fallow-viz.html that fallow viz writes), so custom globs add to rather than replace them. Set it (e.g. `["generated/**"]`) to drop generated or vendored trees from every detector; patterns are validated at load. A `!`-prefixed entry is an exception that applies after the defaults and the positive patterns: `"!src/policy/coverage/**"` brings back hand-written source under a built-in default such as `**/coverage/**`, and `"!.config/**"` adds a hidden directory to discovery. Paths under `node_modules` or `.git` can not be lifted, and a `!` entry that names one of these segments is a config error. A single `*` stays within one path segment; use `**` to match across directories.
518 #[serde(default)]
519 pub ignore_patterns: Vec<String>,
520
521 /// An array of project-root-relative glob patterns whose matching files are support entry points: dev scripts, tooling and setup files that run outside production. In default mode a support entry keeps its file and its imports reachable, the same as `entry`. In `--production` mode (or `production` for dead-code analysis), fallow leaves a file that only a support entry matches out of the analysis, so its imports credit no export, file or dependency. A file that also matches `entry`, a framework plugin or a package.json field stays an entry point, and a support file that production code imports stays a normal module. Use `entry` for the files that run in production. A single `*` stays within one path segment; use `**` to match across directories.
522 #[serde(default, skip_serializing_if = "Vec::is_empty")]
523 #[schemars(extend("default" = []))]
524 pub support_entry: Vec<String>,
525
526 /// An array of project-root-relative glob patterns whose source-owned dead-code findings are hidden after analysis without excluding matching files from discovery, parsing, resolution, or the module graph. Use `/` as the path separator on every platform. The human output names each pattern that matched no finding in the run. Positive patterns select paths to hide; `!`-prefixed patterns keep matching paths reportable, and a negated-only array reports only those exception paths. A finding with multiple source owners is hidden only when every owner matches, so a cycle, duplicate-export group, or unlisted dependency with any reportable location remains visible. Architecture, policy, suppression-hygiene, and framework-correctness findings remain visible even when a referenced path matches, as do manifest-owned findings that no source file owns: unused dependencies, unused dev and optional dependencies, catalog entries, and dependency overrides. Use `ignorePatterns` instead when a generated or vendored file must not be analyzed at all. A matching file that parses with errors reports no `source-parse-degraded` diagnostic, and its partial parse does not mark other findings as incomplete; use this only for files that are broken on purpose, such as syntax-error test fixtures. A single `*` stays within one path segment; use `**` to match across directories.
527 #[serde(default, skip_serializing_if = "Vec::is_empty")]
528 #[schemars(extend("default" = []))]
529 pub ignore_findings: Vec<String>,
530
531 /// Declares inline external framework plugins as data (array of plugin objects), each with `name` plus optional `enablers` (package names that activate it) or richer `detection` (dependency/file-existence/`all`/`any` checks, taking priority over `enablers`); an entry with neither never activates, and config load warns. Each entry can also have `entryPoints` (+ `entryPointRole` runtime/support/test), `configPatterns`, `alwaysUsed`, `toolingDependencies`, `usedExports` (`{ pattern, exports }`), and `usedClassMembers`. Set it to keep a custom or in-house framework's entry points, config files, and conventions reachable without a Rust plugin; these definitions are appended to plugins discovered via `plugins`, `.fallow/plugins/`, and root `fallow-plugin-*` files (first occurrence of a name wins), and cannot do AST-based config parsing.
532 #[serde(default)]
533 pub framework: Vec<ExternalPluginDef>,
534
535 /// Monorepo workspace configuration. `patterns` adds workspace package roots beyond manifest discovery; `changedSince` maps exact project-root-relative workspace roots to Git baseline refs. A global changed-since request overrides those per-package baselines.
536 #[serde(default)]
537 pub workspaces: Option<WorkspaceConfig>,
538
539 /// A list of package names or package-name globs excluded from both unused-dependency and unlisted-dependency detection, so a runtime-provided or otherwise-untracked package (e.g. `bun:sqlite`, a peer supplied at deploy time) is never flagged as unused when declared nor as unlisted when imported. Set it for packages fallow cannot observe being used and cannot observe being declared. An entry without glob characters matches the package name exactly; an entry with `*`, `?`, `[` or `{` is a glob matched against the package name. In this glob, `*` also matches `/`, so `@acme/*` and `@acme*` both cover every package in the `@acme` scope. The human output names each entry that hid no dependency finding and each glob that matched no declared dependency in the run.
540 #[serde(default)]
541 pub ignore_dependencies: Vec<String>,
542
543 /// A list of binary names or name globs that the `unlisted-binaries` rule does not report. Set it for a binary that the operating system, the CI image, or a tool outside `node_modules` provides (e.g. `["gnome-extensions", "tailscale"]`). An entry without glob characters matches the binary name exactly; an entry with `*`, `?`, `[` or `{` is a glob matched against the binary name, so `xcrun*` covers every name that starts with `xcrun`. Fallow already skips shell builtins and a fixed list of common operating-system tools (such as `git`, `ssh-keygen`, `curl`, and `ffmpeg`).
544 #[serde(default, skip_serializing_if = "Vec::is_empty")]
545 #[schemars(extend("default" = []))]
546 pub ignore_binaries: Vec<String>,
547
548 /// A list of command names whose file arguments fallow does not make entry points. Fallow reads commands in package.json scripts (root and workspace packages), CI files (GitHub Actions and GitLab CI), Dockerfiles, Procfiles, and fly.toml files, and a file that a command names (such as `node scripts/seed.ts`) normally becomes an entry point. A listed command still counts as a used dependency, and its `--config` file is still tracked. Formatters and linters (ESLint, Prettier, Oxlint, Oxfmt, Biome, Stylelint, and similar tools) never make their targets entry points, so they do not need to be listed. Set it for a command whose file arguments are data, not code that runs (e.g. `["my-codegen"]`), or use `["*"]` to turn off entry points from all commands and declare real entries in `entry`. A name matches the command after environment, package-manager, and wrapper prefixes (`npx`, `pnpm exec`, `yarn run`, `varlock run --`), by exact file name; `*` is the only wildcard.
549 #[serde(default, skip_serializing_if = "Vec::is_empty")]
550 #[schemars(extend("default" = []))]
551 pub ignore_command_entries: Vec<String>,
552
553 /// A list of glob patterns that suppress only `unresolved-import` findings whose raw import specifier matches; it does not change dependency usage accounting or resolver behavior. Patterns match the import string as written (not a filesystem path), so list both `@example/icons` and `@example/icons/**` to cover a bare package and its subpaths; parent-relative generated specifiers like `../generated/**` are valid, and broad values like `**` can hide real missing modules. An invalid glob is a config error.
554 #[serde(default)]
555 pub ignore_unresolved_imports: Vec<String>,
556
557 /// A list of per-file rules that exempt named exports from `unused-export` and from duplicate-exports grouping for files matching a glob. Each entry is `{ file: <glob>, exports: [<name>, ...] }` where `exports: ["*"]` exempts every export in the file and a name list exempts only those names; built for component-library barrels (shadcn/Radix/bits-ui `index.ts`) that intentionally re-export the same short names across many files. A single `*` stays within one path segment; use `**` to match across directories. An invalid `file` glob is a config error. `fallow fix` can add an entry for a duplicate export.
558 #[serde(default)]
559 pub ignore_exports: Vec<IgnoreExportRule>,
560
561 /// A list of rules that suppress `unresolved-catalog-reference` findings (a workspace `package.json` referencing a `catalog:` or `catalog:<name>` that the catalog does not declare); config-only because `package.json` has no inline-suppression comment surface. Each entry needs a `package` (exact match) plus optional `catalog` (exact catalog-name match) and `consumer` (glob on the consuming package.json path); use it for staged catalog migrations where the catalog edit lands in a separate change. An invalid `consumer` glob is a config error.
562 #[serde(default, skip_serializing_if = "Vec::is_empty")]
563 #[schemars(extend("default" = []))]
564 pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
565
566 /// A list of rules that suppress `unused-dependency-override` and `misconfigured-dependency-override` findings for override entries: pnpm `overrides` in `pnpm-workspace.yaml` or `package.json`, npm and bun `overrides`, and bun `resolutions`; config-only, matched against the override's target package. Each entry needs a `package` (exact match) plus an optional `source` to scope the suppression to `"pnpm-workspace.yaml"` or `"package.json"`.
567 #[serde(default, skip_serializing_if = "Vec::is_empty")]
568 #[schemars(extend("default" = []))]
569 pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
570
571 /// Controls whether an export referenced only by another symbol in the same file is treated as used (suppressed from `unused-export`) until it becomes completely unreferenced; references inside an export specifier itself (`export { foo }`, `export default foo`) do not count as same-file uses. Accepts `true`/`false` (default `false`, suppress nothing) or the knip-parity object `{ "type": true, "interface": true }`, which restricts the suppression to type-only exports; fallow groups type aliases and interfaces under one kind, so both object fields behave identically.
572 #[serde(default)]
573 pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
574
575 /// The JSDoc visibility tags that keep an export out of `unused-export`: `public` (also `@api public`), `internal`, `alpha` and `beta`, with or without a leading `@`. The default lists all four, so a tagged export never gets an `unused-export` finding and counts as public API for the re-exports that forward it. A tag that is not in the list has no effect: fallow checks the export like an untagged one. Set `["public"]` when `@internal`, `@alpha` and `@beta` mark code that no consumer outside the project uses, for example `/** @internal Exported for tests. */`. `[]` also checks `@public` exports. `@expected-unused` is not configurable.
576 #[serde(default)]
577 pub keep_export_tags: KeepExportTags,
578
579 /// A list of decorator names that no longer grant a class member automatic exemption from `unused-class-member`: a member whose every decorator is in this set is checked normally, while a member carrying any decorator NOT listed here stays skipped (frameworks consume decorated members reflectively). Dotted entries match the full decorator path (`ns.foo`) and bare entries match the leftmost segment (so `"decorators"` collapses every `@decorators.*`); both `"@step"` and `"step"` are accepted (leading `@` stripped), and an unmatched entry emits a one-time warning.
580 #[serde(default, skip_serializing_if = "Vec::is_empty")]
581 #[schemars(extend("default" = []))]
582 pub ignore_decorators: Vec<String>,
583
584 /// A list of class-member names or glob patterns treated as framework-used, so a method a library invokes reflectively (ag-Grid `agInit`/`refresh`, Web Component `connectedCallback`) is not reported as `unused-class-member`; it applies to class members only, not enum members. Each entry is either a plain string/glob (`"agInit"`, `"enter*"`, `"*"`) applied to every class, or a scoped object `{ extends?, implements?, members: [...] }` that applies only when the class matches that heritage clause (a scoped rule requires `extends` or `implements`). A scoped rule with `"extends": "Base"` applies to the subclasses of `Base`, not to `Base` itself; to keep the members of one class, put `// fallow-ignore-file unused-class-member` in its file. Patterns matching zero members warn once.
585 #[serde(default)]
586 pub used_class_members: Vec<UsedClassMemberRule>,
587
588 /// Configures clone detection: `enabled` (default true), `mode` (`strict`, `mild` default, `weak`, `semantic`, from least to most identifier/literal blinding; `strict` and `mild` are equivalent under fallow's AST tokenizer, `weak` blinds string literals, `semantic` blinds all identifiers and literals for Type-2 renamed-variable detection), `near` (false, add bounded function-scoped near-miss detection), `minTokens` (50), `minLines` (5), `minOccurrences` (integer >= 2, deserialization fails below 2), `threshold` (max duplication percentage; the default 0 turns the gate off and is not zero tolerance), `ignore` globs, `ignoredClones` (reviewed clone keys to hide until their content or occurrence count changes), `ignoreDefaults` (true, merge built-in ignores for generated output and test and mock files), `skipLocal` (only report cross-directory clones), `ignoreSymlinks` (false, omit clone instances whose path is a symlink or lies under a symlinked directory), `crossLanguage` (strip TS type annotations to match .ts against .js), `ignoreImports` (true, strip ES import/re-export/top-level require wiring from the token stream), and `normalization` (per-flag `ignoreIdentifiers`/`ignoreStringValues`/`ignoreNumericValues` overrides on top of `mode`, plus `consistentIdentifiers`, which with `ignoreIdentifiers` requires a one-to-one name mapping between clone instances). Raise `minOccurrences` to focus on widespread copy-paste, enable `near` for gapped structural clones, or set `mode` to `semantic` to catch renamed-variable exact clones.
589 #[serde(default)]
590 pub duplicates: DuplicatesConfig,
591
592 /// Configures the explicit local `similar-code` candidate workflow:
593 /// `threshold` (0.80, model-specific cosine floor), `minLines` (3), and
594 /// additional `ignore` globs. Provider identity, setup, executables,
595 /// endpoints, credentials, and consent cannot be set by project config.
596 #[serde(default)]
597 pub similar_code: SimilarCodeConfig,
598
599 /// Configures the explicit `fallow mutation` workflow: `runner` (`auto`
600 /// or `vitest`), `operators` (kebab-case names, default the default set),
601 /// `minScore` (0 to 100; a lower score exits with code 1), and
602 /// `concurrency` (half the logical cores). No key starts a run, and the
603 /// side-effect override is a CLI flag only.
604 #[serde(default, skip_serializing_if = "MutationConfig::is_default")]
605 pub mutation: MutationConfig,
606
607 /// Sets complexity and health thresholds for `fallow health` (also applied in combined `fallow` and `fallow audit`): `maxCyclomatic` (20), `maxCognitive` (15), `maxCrap` (30.0, findings at or above this are reported), `crapRefactorBand` (5, cyclomatic band below `maxCyclomatic` where a secondary refactor action is added), `maxUnitSize` (max function lines before a large-function finding, 60), `maxFileLines` (max physical lines per file before a file-level finding, 0 means off), `coverage`/`coverageRoot` (Istanbul coverage path and path-prefix strip for accurate CRAP), `ignore` globs (remove files from findings AND the health score), `tailwindIgnorePatterns` (regexes on normalized `prefix-[value]` Tailwind arbitrary-value tokens to exclude from `--css` findings and analytics), `thresholdOverrides` (per-file/per-function ceilings via `files`/`functions`/`maxCyclomatic`/`maxCognitive`/`maxCrap`/`maxUnitSize`/`maxFileLines`/`reason`), `ownership` (`botPatterns` and `emailMode` for `--ownership`), and `suggestInlineSuppression` (true, emit `suppress-line` action hints in JSON). Raise thresholds to relax which functions are flagged, wire `coverage` for real CRAP scores, or exempt generated/test files via `ignore` (drops them from the score too) or `thresholdOverrides` (keeps them visible under a higher ceiling). The `max*` thresholds govern findings only and never move `health_score`: its penalties use fixed calibration so grades stay comparable across projects, and `ignore` is the lever that removes files from the score.
608 #[serde(default)]
609 pub health: HealthConfig,
610
611 /// Opts into TypeScript semantic analysis for project-wide symbol use,
612 /// provenance, API surface, symbol impact, and public-signature coupling.
613 /// This does not surface compiler diagnostics or typed lint rules.
614 #[serde(default, skip_serializing_if = "TypeAwareConfig::is_default")]
615 pub type_aware: TypeAwareConfig,
616
617 /// Sets per-issue-type severity, keyed by kebab-case rule id: `error` reports and fails CI (non-zero exit), `warn` reports without failing, `off` disables detection and reporting entirely (e.g. `{ "unused-files": "error", "unused-exports": "warn", "private-type-leaks": "off" }`). Set a rule `off` to silence it, `warn` to demote below CI gating, or `error` to promote a warn/off-default rule to gating; most rules default to `error`, dev/optional-dependency and component/store/inject/CSS/catalog rules default to `warn`, and opt-in rules (`private-type-leaks`, `deprecated-exports-in-use`, `security-*`, `prop-drilling`, `thin-wrapper`, `duplicate-prop-shape`, `coverage-gaps`, `feature-flags`, `require-suppression-reason`) default to `off`. Singular aliases (`unused-file`) and `warning`/`none` severity spellings are accepted.
618 #[serde(default)]
619 pub rules: RulesConfig,
620
621 #[serde(
622 default,
623 skip_serializing_if = "UnusedComponentPropsConfig::is_default"
624 )]
625 /// Options for the `unused-component-props` rule. It has one key, `ignorePattern`: a regex matched against each declared prop's local destructure binding name (falling back to the public prop name when unaliased) to exempt intentionally-unused props such as the leading-underscore convention. Set `{ "ignorePattern": "^_" }` to skip props like `_stage`; matching is unanchored (substring, like ESLint's `RegExp.test`) so anchor with `^`, the pattern is validated at config load (invalid regex fails load), and it applies to Vue, Svelte, Astro, and React/Preact props (unset leaves the rule unchanged).
626 pub unused_component_props: UnusedComponentPropsConfig,
627
628 #[serde(
629 default,
630 skip_serializing_if = "CircularDependenciesConfig::is_default"
631 )]
632 /// Options for the `circular-dependencies` rule: `ignoreLazyImports` and `allow`, a list of accepted cycles. Set `{ "ignoreLazyImports": true }` to skip import edges that load on demand or on another thread (an `import()` inside a function, a template `import()`, a lazy `import.meta.glob`, a worker URL, a webpack worker loader request such as `worker-loader!./work.js`) when fallow looks for cycles. A top-level `await import()`, `require()`, an eager glob, and an edge that also has a static import stay in the cycle graph. Default `false` leaves the rule unchanged.
633 pub circular_dependencies: CircularDependenciesConfig,
634
635 #[serde(default, skip_serializing_if = "EffectConfig::is_default")]
636 /// Options for projects that use the Effect library. Its one key is `schemaExportsAsTypes`. Set `{ "schemaExportsAsTypes": true }` to report an unused exported Effect schema (a class that extends `Schema.Class`, `Schema.TaggedClass`, `Schema.TaggedError` and the other `Schema` class factories, or a const such as `Schema.Struct({...})` or `Schema.String.pipe(Schema.brand("Id"))`) as an unused type under the `unused-types` rule, not as an unused export, so `"unused-types": "off"` hides it. `Schema` must come from `effect`, `effect/Schema` or `@effect/schema`. A re-export of a schema from another module also counts. In a module that imports Effect, a chain on an imported schema (`Imported.pipe(Schema.brand("Id"))`, `Imported.annotations({...})`) and an alias (`export const Copy = Imported`) also count. A call of a function whose each `return` is a schema also counts (`export const User = makeUser()`), for a function of the same module or of an imported module. A conditional expression whose two branches are schemas (`flag ? Schema.String : Schema.Number`), a member of a namespace import (`Imported.makeUser()`), a call of a function that returns its schema argument (`identity(Schema.String)`), a member of a local `const` object or array literal (`schemas[0]`, `factories.make()`) and a destructured export of such a member also count. A call of a lowercase `Schema` member counts when its declared return type is a schema in effect 3 or effect 4 (`Schema.optional(...)`); decoders, encoders, guards and annotation ids such as `Schema.BrandSchemaId` do not. Default `false` leaves every report unchanged.
637 pub effect: EffectConfig,
638
639 /// Configures architecture boundary enforcement: which source directories belong to which named zone and which zones may import which others, reported as boundary-violation, boundary-coverage-violation, and boundary-call-violation findings (severity via rules.boundary-violation, default error). Set to enforce a layered/module architecture; the object holds `preset` (one of layered, hexagonal, feature-sliced, bulletproof, whose default zones/rules are merged in with the user-declared zones/rules taking precedence), `zones` (each with `name`, `patterns`, `autoDiscover`, optional `root`), `rules` (each with `from`, `allow`, `allowTypeOnly` target-zone lists), `coverage` (`requireAllFiles` plus `allowUnmatched` globs for files matching no zone), and `calls` (a `forbidden` list of `{from, callee}` banned-call rules per zone).
640 #[serde(default)]
641 pub boundaries: BoundaryConfig,
642
643 /// Configures feature-flag detection: `sdkPatterns` (custom flag-evaluating call signatures, each `{ function, nameArg (zero-based arg index of the flag name, default 0), provider? }`, merged with built-ins for LaunchDarkly, Statsig, Unleash, GrowthBook, Split, PostHog, Vercel Flags, ConfigCat, Flagsmith, Optimizely, and Eppo), `envPrefixes` (env-var prefixes marking `process.env.*` and `import.meta.env.*` accesses as flags, merged with built-ins), and `configObjectHeuristics` (default false; when true, property accesses on objects whose name contains `feature`/`flag`/`toggle` are reported as low-confidence flags). Set `sdkPatterns`/`envPrefixes` to teach fallow a proprietary flag SDK or naming convention, or enable `configObjectHeuristics` for projects that read flags off config objects (higher false-positive rate). Feature-flag findings surface only when the `feature-flags` rule is enabled (default `off`).
644 #[serde(default)]
645 pub flags: FlagsConfig,
646 /// Global slots that `fallow architecture --shared-state` leaves out of its inventory. Each entry is an exact pair of a global root (`window`, `globalThis`, `self` or `global`) and a direct slot, for example `["window", "analyticsQueue"]`.
647 #[serde(default, skip_serializing_if = "Vec::is_empty")]
648 #[schemars(extend("default" = []))]
649 pub shared_state_allowlist: Vec<[String; 2]>,
650
651 /// Scopes the opt-in `fallow security` catalogue: which candidate categories run and which extra local identifiers count as HTTP request objects. Set when tuning security-candidate detection; the object holds `categories` (an object with `include` and/or `exclude` string arrays of catalogue category ids, where `include` restricts to a whitelist and `exclude` removes from the admitted set, both unset admits all ordinary categories) and `requestReceivers` (a string array of project-local names that extend, not replace, the built-in `*.query`/`*.params`/`*.body` source-receiver allowlist). The `hardcoded-secret` and `secret-to-network` categories are include-required: they fire only when explicitly listed in `categories.include`, even when no include list is otherwise set. The valid category ids are enumerated (with title, CWE, and include-required flag) in the `security_categories` block of `fallow schema`, and also listed by `fallow security --help`; they are not in this config-schema.
652 #[serde(default)]
653 pub security: SecurityConfig,
654
655 /// Configures `fallow fix` behavior. It holds one nested section, `catalog`, whose only key `deletePrecedingComments` (`auto` default, `always`, `never`) governs whether comment lines directly above a removed unused `pnpm-workspace.yaml` catalog entry are deleted with it.
656 #[serde(default)]
657 pub fix: FixConfig,
658
659 /// Configures the module resolver. Its one key `conditions` is a list of additional package.json `exports`/`imports` condition names to honor, matched at higher priority than fallow's built-ins (`development`, `import`, `require`, `default`, `types`, `node`, plus `react-native`/`browser` when the React Native or Expo plugin is active). Set it when a package's `exports` map has custom branches (e.g. `worker`, `deno`, `edge`) that fallow should follow instead of the default branch.
660 #[serde(default)]
661 pub resolve: ResolveConfig,
662
663 /// Enables production mode, which excludes test/spec/story/dev files from discovery and forces `unused-dev-dependencies` and `unused-optional-dependencies` to `off`. Accepts a boolean (default false) applied to all analyses, or a per-analysis object `{ deadCode?, health?, dupes?, ignore? }` that scopes production mode to individual analyses: `deadCode` applies to `fallow dead-code`, `health` to `fallow health` and `dupes` to `fallow dupes`, and each applies to its part of combined `fallow` and `fallow audit` (each analysis key a boolean, default false). The object key `ignore` is a glob array of extra paths that discovery drops in production mode only. Set it to analyze only shipped code; the `--production`/`--no-production` and `--production-{dead-code,health,dupes}` CLI flags and `FALLOW_PRODUCTION*` env vars override this value (CLI flags win, then per-analysis env, then global env, then config).
664 #[serde(default)]
665 pub production: ProductionConfig,
666
667 /// List of paths (relative to the project root, must resolve within it) to external plugin definition files or directories in JSONC/JSON/TOML, loaded in addition to the auto-discovered `.fallow/plugins/` directory and root `fallow-plugin-*` files. Set it to load plugin definitions kept outside those default locations; a path resolving outside the project root is skipped with a warning, and paths listed here are searched before the auto-discovered locations (first occurrence of a plugin name wins).
668 #[serde(default)]
669 pub plugins: Vec<String>,
670
671 /// Paths to declarative rule-pack files (JSON or JSONC), relative to the
672 /// project root. Each pack declares `banned-call`, `banned-import`, or
673 /// `banned-effect` rules that report as `policy-violation` findings. Packs
674 /// are pure data: no project code is executed. Invalid or missing packs
675 /// fail config load.
676 #[serde(default, skip_serializing_if = "Vec::is_empty")]
677 #[schemars(extend("default" = []))]
678 pub rule_packs: Vec<String>,
679
680 /// An array of project-root-relative glob patterns for files loaded at runtime by a mechanism the static graph cannot see (dynamic path resolution, config-driven loading); matching files are seeded as entry points so they and their imports stay reachable. Empty by default; set it (e.g. `["plugins/**/*.ts", "locales/**/*.json"]`) for plugin or locale trees pulled in dynamically. A single `*` stays within one path segment; use `**` to match across directories.
681 #[serde(default)]
682 pub dynamically_loaded: Vec<String>,
683
684 /// An array of file extensions, without the leading dot, for server-side template files whose text counts as CSS class references for the `unreferenced-css-class` finding of `fallow health --css`. These files are read as text only: they do not join source discovery or the module graph, so they never become unused files and their imports are not followed. Templates are more lenient than Markdown: the whole text of a template file counts as a dynamic class reference, so any class-like word in it counts as used, also a common word such as `hidden` or `title` in prose or a template tag. A Markdown file joins the reference text only when it has dynamic class syntax. The extensions `liquid`, `njk`, `hbs`, `handlebars`, `twig`, and `blade.php` are always read; set this (e.g. `["tpl", "erb"]`) for other template languages. An extension matches the end of a file name, ignoring case, so `blade.php` matches `welcome.blade.php`. Values may contain only letters, digits, `.`, `-`, and `_`. A value whose last segment is a script, stylesheet, data or asset extension (`js`, `ts`, `css`, `json`, `svg`, `xml`, `map`, and similar, so also `module.css` or `d.ts`), or a compound value that ends in a markup extension that fallow already reads (`page.html`), is a config error. The walk uses the ignore files of source discovery (`.gitignore`, `.ignore`), skips `ignorePatterns`, `health.ignore`, `node_modules`, `vendor`, and build output directories, reads only regular files, and skips files over the `--max-file-size` limit. In `extends`, a child list replaces the parent list.
685 #[serde(
686 default,
687 skip_serializing_if = "Vec::is_empty",
688 deserialize_with = "markup_extensions::deserialize_markup_extensions"
689 )]
690 #[schemars(extend("default" = []))]
691 pub markup_extensions: Vec<String>,
692
693 /// An ordered list of per-file rule-severity overrides: each entry re-severities specific analysis rules for files its globs match, layered on top of the top-level `rules` defaults. Set to relax or tighten a rule for a subset of paths (e.g. downgrade unused-exports to warn under a generated directory); each entry has `files` (glob-pattern array) and `rules` (a partial per-rule severity map of error/warn/off). Entries apply in list order and a file matched by several entries takes every matching entry's overrides (later entries win on conflict). For most rules, an override cannot start a detector for a rule that is off at top level, so set the top-level rule on and use an override to set `off` for the other paths. Project-level rules ignore overrides: unused-dependencies, unused-dev-dependencies, unused-optional-dependencies, unlisted-dependencies, unlisted-binaries, type-only-dependencies, test-only-dependencies, dev-dependencies-in-production, duplicate-exports, re-export-cycle and unused-catalog-entries. Fallow reports each such entry as an `override-rule-ineffective` diagnostic that names the mechanism that works. A single `*` stays within one path segment; use `**` to match across directories.
694 #[serde(default)]
695 pub overrides: Vec<ConfigOverride>,
696
697 /// A path to a CODEOWNERS file, relative to the project root or absolute, that must resolve inside the project scope base (the git top level of the root), used by `--group-by owner` and `--group-by section` to group findings, and by `fallow health --hotspots --ownership` to attribute declared owners and compute unowned/drifting ownership state; setting it overrides the default probe order (CODEOWNERS, .github/CODEOWNERS, .gitlab/CODEOWNERS, docs/CODEOWNERS). String, defaults to null (auto-probe the standard locations); set it only when the CODEOWNERS file lives at a non-standard location.
698 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub codeowners: Option<String>,
700
701 /// An array of internal workspace package names (or globs matched against workspace package names) whose public API is intentionally consumed outside the analyzed graph; their entry points and re-export surface become reachability roots, so their exported files, the exports on that surface, and the class and enum members of a class or enum on that surface are not reported as unused. Exports and members that the surface cannot reach are still reported. Set it (e.g. `["@myorg/shared-lib", "@myorg/*"]`) for library packages in a monorepo that ship an API to external consumers; only meaningful when workspaces are present (an empty list or no workspaces is a no-op).
702 #[serde(default)]
703 pub public_packages: Vec<String>,
704
705 /// Holds a saved issue-count baseline that the `--fail-on-regression` gate compares the current run against, failing only when counts grow beyond tolerance relative to the baseline. Usually written by `--save-baseline` rather than hand-authored; the object has a single `baseline` sub-key holding per-issue-type counts (total_issues plus per-kind fields like unused_exports, boundary_violations, policy_violations, each defaulting to 0). Absent means no baseline is embedded in config.
706 #[serde(default, skip_serializing_if = "Option::is_none")]
707 pub regression: Option<RegressionConfig>,
708
709 /// Sets in-repo defaults for `fallow audit` (the changed-files quality gate) so CLI flags need not repeat per run. Set to pin audit behavior; the object holds `gate` (`new-only` or `all`, which findings drive the verdict), `css`/`cssDeep` (booleans toggling styling analysis and the project-wide CSS reachability pass), `deadCodeBaseline`/`healthBaseline`/`dupesBaseline` (per-sub-analysis baseline file paths), and `cacheMaxAgeDays` (the age in days after which fallow removes an entry of the reusable base-snapshot worktree cache). The matching CLI flag overrides each field.
710 #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
711 pub audit: AuditConfig,
712
713 /// When true, restricts this config's extends entries to file-relative paths that resolve inside the config file's own directory; any https:// URL, npm: package, or relative path escaping that directory is rejected at load with a hard error. Boolean, defaults to false (URL, npm, and any-relative extends are permitted); set it to true to harden a config against pulling in remote or out-of-tree bases.
714 #[serde(default)]
715 pub sealed: bool,
716
717 /// When true, fallow checks the exports of every entry-point file for unused exports. When false, fallow credits all exports of an entry file as used, unless a plugin `usedExports` rule matches the file: then fallow checks the other exports of that file, so a stray export in a framework route (for example a misspelled `meatdata` in place of `metadata`) is flagged without this setting. The setting extends the check to package entries and other entry files that no plugin rule matches; the names in plugin `usedExports` lists stay credited. A name that an entry file re-exports with `export *` needs an importer too: fallow reports an unused one at its declaration, and an `ignoreExports` rule on the entry file covers the names behind its `export *` lines. The setting also turns on the unused enum member, class member and namespace member checks for the exports that an entry file declares, and the unused enum member check for an enum that a public package entry re-exports. Boolean, defaults to false; the CLI flag --include-entry-exports applies the same behavior for one run.
718 #[serde(default)]
719 pub include_entry_exports: bool,
720
721 /// When true, the report keeps the unused exports, unused types, unused class members and unused enum members of a file that is an unused file. Boolean, defaults to false: deleting an unused file removes these findings, so the report hides them and counts them in cascade_hidden. The CLI flag --show-cascade applies the same behavior for one run.
722 #[serde(default)]
723 pub show_cascade: bool,
724
725 /// When true, drops Nuxt convention-based entry-pattern fallbacks so genuinely-unreferenced convention files surface as unused-file. Component fallbacks are kept when nuxt.config customizes components: in a way fallow does not model, and composable/util fallbacks are kept when it customizes imports:; a config that scans no more than the Nuxt defaults (components: false, components: [], components: { dirs: [] }, components: true, imports: { scan: false }, imports: {}, imports: { dirs: [] }) is treated like the default and its fallbacks are dropped; imports: { autoImport: false } on its own is not, because it only switches the injection off while the same directories stay registered behind #imports. A nuxt.config that carries any top-level key fallow cannot read statically, a computed key, an accessor, or a spread such as { ...base, devtools: {} }, keeps both surfaces' fallbacks for that root, because the spread may hold the keys that decide. Only top-level keys count when the config object is readable: a nested key such as a routeRules path ending in components does not keep a fallback. Nested components or imports keys in $production, $development, $test or `$env.<name>`, and components or imports hooks (a components:* key or a nested components object in hooks, also inside those overrides), count as that surface's key; such an override object or hooks object that fallow cannot read statically falls back to a text match for the keys. Each root is classified on its own config plus the configs of its local layers, so one custom nuxt.config in a monorepo does not keep every other workspace's fallbacks. A local layer is a directory named in extends, or a `layers/<name>` directory, that holds a nuxt.config; its convention files are entry points with the flag off and auto-import sources with it on, and `#layers/<name>/` resolves to it by its $meta.name (a `layers/<name>` directory without one uses its directory name). A remote or package layer is only a dependency reference. Component names follow Nuxt: a component under components/global or components/islands is named after its own directory (components/global/Foo.vue is `<Foo>`), and .client, .server, .global and .island suffixes are stripped. A name imported or re-exported by hand from #components or #imports credits its convention file just like a template tag or a bare call; a namespace import names nothing and credits nothing. Boolean, defaults to false; set it for a Nuxt project that has explicitly configured its auto-import directories. Synthesis of auto-import graph edges (resolving `<Card />` or `useUserStore()` to their convention files) happens regardless of this flag.
726 #[serde(default)]
727 pub auto_imports: bool,
728
729 /// When true, the run fails with exit code 1 if fallow could not parse a source file cleanly (a `source-parse-degraded` or `source-nesting-too-deep` entry in `workspace_diagnostics[]`), and the `parse-error` entry of `gate_outcomes` names each such file. Boolean, defaults to false, so a file the parser rejects only warns. Applies to `fallow dead-code`, `fallow health`, `fallow audit` and the bare `fallow` run; the CLI flag `--fail-on-parse-error` arms the same gate for one run. Older fallow versions reject this key as unknown, so pair it with `minimumVersion` set to the release that added it.
730 #[serde(default)]
731 pub fail_on_parse_error: bool,
732
733 /// Overrides the location and size ceiling of fallow's persistent extraction cache (default `.fallow/cache.bin` under the project root). Set to relocate the cache or cap its footprint; the object holds `dir` (cache directory, relative paths resolve from the project root) and `maxSizeMb` (extraction-cache size limit in megabytes). The `FALLOW_CACHE_MAX_SIZE` environment variable overrides `maxSizeMb`.
734 #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
735 pub cache: CacheConfig,
736
737 /// The keys whose value can come from a local config file outside the
738 /// project, set by the load. Checks after the load name these keys
739 /// without their values. It is not part of the config file format.
740 #[serde(skip)]
741 #[schemars(skip)]
742 #[doc(hidden)]
743 pub outside_keys: OutsideKeys,
744}
745
746/// Scopes `fallow security` catalogue behavior. An absent category block admits
747/// every catalogue category. `hardcoded-secret` is include-required and only
748/// runs when explicitly listed in `security.categories.include`.
749#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
750#[serde(deny_unknown_fields, rename_all = "camelCase")]
751pub struct SecurityConfig {
752 /// Include/exclude filter over category ids (e.g. `dangerous-html`).
753 #[serde(default, skip_serializing_if = "Option::is_none")]
754 pub categories: Option<SecurityCategories>,
755 /// Additional project-local names for HTTP request objects. These names
756 /// extend the built-in receiver allowlist for `*.query`, `*.params`, and
757 /// `*.body` source patterns. They do not replace the built-ins and do not
758 /// gate `*.searchParams`, which intentionally stays ungated.
759 #[serde(default, skip_serializing_if = "Vec::is_empty")]
760 pub request_receivers: Vec<String>,
761}
762
763impl SecurityConfig {
764 /// The configured `requestReceivers` trimmed, lowercased, and deduplicated
765 /// in first-seen order, with empty entries dropped; the form the matcher
766 /// compares receiver names against (matching is case-insensitive).
767 #[must_use]
768 pub fn normalized_request_receivers(&self) -> Vec<String> {
769 let mut receivers = Vec::new();
770 for receiver in &self.request_receivers {
771 let normalized = receiver.trim().to_ascii_lowercase();
772 if !normalized.is_empty() && !receivers.contains(&normalized) {
773 receivers.push(normalized);
774 }
775 }
776 receivers
777 }
778
779 /// False when any configured receiver is empty or whitespace-only, which
780 /// config validation reports as an error instead of silently dropping it.
781 #[must_use]
782 pub fn request_receivers_are_valid(&self) -> bool {
783 self.request_receivers
784 .iter()
785 .all(|receiver| !receiver.trim().is_empty())
786 }
787}
788
789/// Include/exclude lists scoping the active security categories. When `include`
790/// is set, only those categories are active; `exclude` removes categories from
791/// the admitted set. Both unset admits catalogue categories. `hardcoded-secret`
792/// still requires explicit inclusion.
793#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
794#[serde(deny_unknown_fields, rename_all = "camelCase")]
795pub struct SecurityCategories {
796 /// Catalogue category ids to admit. When set, all others are excluded.
797 #[serde(default, skip_serializing_if = "Option::is_none")]
798 pub include: Option<Vec<String>>,
799 /// Catalogue category ids to remove from the admitted set.
800 #[serde(default, skip_serializing_if = "Option::is_none")]
801 pub exclude: Option<Vec<String>>,
802}
803
804/// The `cache` config section: location and size ceiling of fallow's
805/// persistent caches (default directory `<root>/.fallow`).
806#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
807#[serde(deny_unknown_fields, rename_all = "camelCase")]
808pub struct CacheConfig {
809 /// Directory for fallow's persistent analysis cache. Relative paths resolve
810 /// from the project root. The directory must be inside the project: an
811 /// absolute path or a path that leaves the root is ignored with a
812 /// warning. Use `FALLOW_CACHE_DIR` to put the cache outside the project.
813 #[serde(default, skip_serializing_if = "Option::is_none")]
814 pub dir: Option<PathBuf>,
815 /// Maximum size of the persistent extraction cache, in megabytes.
816 /// Default 256.
817 #[serde(default, skip_serializing_if = "Option::is_none")]
818 #[schemars(extend("default" = 256))]
819 pub max_size_mb: Option<u32>,
820}
821
822impl CacheConfig {
823 /// True when neither field is set, so serialization can omit the section.
824 #[must_use]
825 pub fn is_default(&self) -> bool {
826 self.dir.is_none() && self.max_size_mb.is_none()
827 }
828}
829
830/// The analysis families production mode can be scoped to independently via
831/// the object form of the `production` config key.
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833pub enum ProductionAnalysis {
834 /// Unused files/exports/dependencies detection.
835 DeadCode,
836 /// Complexity and health scoring.
837 Health,
838 /// Clone detection.
839 Dupes,
840}
841
842/// Value of the `production` config key: excludes test/spec/story/dev files
843/// from discovery, either globally or per analysis family.
844#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
845#[serde(untagged)]
846pub enum ProductionConfig {
847 /// Boolean form applying to every analysis. The default is `false`.
848 Global(bool),
849 /// Object form (`{ deadCode?, health?, dupes?, ignore? }`) scoping
850 /// production mode per analysis family.
851 PerAnalysis(PerAnalysisProductionConfig),
852}
853
854impl<'de> Deserialize<'de> for ProductionConfig {
855 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
856 where
857 D: Deserializer<'de>,
858 {
859 struct ProductionConfigVisitor;
860
861 impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
862 type Value = ProductionConfig;
863
864 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865 formatter.write_str("a boolean or per-analysis production config object")
866 }
867
868 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
869 where
870 E: serde::de::Error,
871 {
872 Ok(ProductionConfig::Global(value))
873 }
874
875 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
876 where
877 A: serde::de::MapAccess<'de>,
878 {
879 PerAnalysisProductionConfig::deserialize(
880 serde::de::value::MapAccessDeserializer::new(map),
881 )
882 .map(ProductionConfig::PerAnalysis)
883 }
884 }
885
886 deserializer.deserialize_any(ProductionConfigVisitor)
887 }
888}
889
890impl Default for ProductionConfig {
891 fn default() -> Self {
892 Self::Global(false)
893 }
894}
895
896impl From<bool> for ProductionConfig {
897 fn from(value: bool) -> Self {
898 Self::Global(value)
899 }
900}
901
902impl Not for ProductionConfig {
903 type Output = bool;
904
905 fn not(self) -> Self::Output {
906 !self.any_enabled()
907 }
908}
909
910impl Not for &ProductionConfig {
911 type Output = bool;
912
913 fn not(self) -> Self::Output {
914 !self.any_enabled()
915 }
916}
917
918impl ProductionConfig {
919 /// Whether production mode applies to `analysis` under this config.
920 #[must_use]
921 pub const fn for_analysis(&self, analysis: ProductionAnalysis) -> bool {
922 match self {
923 Self::Global(value) => *value,
924 Self::PerAnalysis(config) => match analysis {
925 ProductionAnalysis::DeadCode => config.dead_code,
926 ProductionAnalysis::Health => config.health,
927 ProductionAnalysis::Dupes => config.dupes,
928 },
929 }
930 }
931
932 /// The boolean form's value. The per-analysis form counts as global
933 /// production mode only when it turns on every analysis family.
934 #[must_use]
935 pub const fn global(&self) -> bool {
936 match self {
937 Self::Global(value) => *value,
938 Self::PerAnalysis(config) => config.dead_code && config.health && config.dupes,
939 }
940 }
941
942 /// Whether production mode is enabled for at least one analysis family.
943 #[must_use]
944 pub const fn any_enabled(&self) -> bool {
945 match self {
946 Self::Global(value) => *value,
947 Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
948 }
949 }
950
951 /// The `ignore` globs of the object form. The boolean form has none.
952 #[must_use]
953 pub fn ignore(&self) -> &[String] {
954 match self {
955 Self::Global(_) => &[],
956 Self::PerAnalysis(config) => &config.ignore,
957 }
958 }
959
960 /// The config of one run, with production mode set to `enabled` for every
961 /// analysis family. The `ignore` globs stay, so a run in production mode
962 /// still drops them when a CLI flag or one analysis selects the mode.
963 #[must_use]
964 pub fn for_run(&self, enabled: bool) -> Self {
965 let ignore = self.ignore();
966 if ignore.is_empty() {
967 return Self::Global(enabled);
968 }
969 Self::PerAnalysis(PerAnalysisProductionConfig {
970 dead_code: enabled,
971 health: enabled,
972 dupes: enabled,
973 ignore: ignore.to_vec(),
974 })
975 }
976}
977
978/// Object form of the `production` config key, scoping production mode to
979/// individual analysis families in combined `fallow` and `fallow audit`.
980#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
981#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
982pub struct PerAnalysisProductionConfig {
983 /// When `production` is a per-analysis object, enables production mode for dead-code analysis only (boolean, default false): unused-files/exports/dependencies detection excludes test/spec/story/dev files and forces `unused-dev-dependencies`/`unused-optional-dependencies` to `off`, while health and dupes stay on the full tree. Set it to scope production analysis to dead code independently.
984 pub dead_code: bool,
985 /// When `production` is a per-analysis object, enables production mode for the health/complexity analysis only (boolean, default false), so `fallow health` in combined `fallow` and `fallow audit` scores only shipped code (test/spec/story/dev files excluded) while dead-code and dupes stay on the full tree. Set it to scope production analysis to health independently.
986 pub health: bool,
987 /// When `production` is a per-analysis object, enables production mode for duplication analysis only (boolean, default false), so clone detection runs on shipped code only (test/spec/story/dev files excluded) while dead-code and health stay on the full tree. Set it to scope production analysis to dupes independently.
988 pub dupes: bool,
989 /// When `production` is a per-analysis object, an array of project-root-relative glob patterns for paths that discovery drops in production mode only, in addition to the built-in test/spec/story/dev patterns (default empty). The default run keeps these paths. The globs apply to each analysis that runs in production mode, also when the `--production` flag or a `FALLOW_PRODUCTION*` env var selects the mode. Set it for tooling, CI scripts, seeds and test harnesses that never ship (e.g. `["scripts/**"]`). A single `*` stays within one path segment; use `**` to match across directories.
990 #[serde(default, skip_serializing_if = "Vec::is_empty")]
991 pub ignore: Vec<String>,
992}
993
994/// The `audit` config section: in-repo defaults for `fallow audit`, each
995/// overridable by its matching CLI flag.
996#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
997#[serde(deny_unknown_fields, rename_all = "camelCase")]
998pub struct AuditConfig {
999 /// Selects which findings affect the `fallow audit` verdict: `new-only` (default) fails only on findings introduced by the current changeset (running a base-snapshot attribution pass), while `all` fails on every finding in changed files and skips that pass. Set to `all` to gate the full backlog in changed files; the `--gate` CLI flag overrides this.
1000 #[serde(default, skip_serializing_if = "AuditGate::is_default")]
1001 pub gate: AuditGate,
1002
1003 /// Selects how a worsened complexity finding affects the `fallow audit` verdict under `gate: new-only`. A worsened finding was already in the base snapshot, and a measured value is higher now. Any growth of cyclomatic, cognitive or CRAP counts. The line count must grow by at least 5 lines, and it includes comments and blank lines. `warn` (default) makes the verdict at least `warn` and does not fail the run. `error` counts a worsened finding like an introduced finding. `off` reports only the growth of a metric that the finding exceeds as worsened, which gives at least `warn`. A finding whose exceeded metric grew is worsened when it stays in its severity tier (`moderate`, `high`, `critical`), and introduced when it moves to a higher tier or exceeds a metric that the base finding did not exceed. The `--worsened` CLI flag overrides this.
1004 #[serde(default, skip_serializing_if = "AuditWorsened::is_default")]
1005 pub worsened: AuditWorsened,
1006
1007 /// Toggles the dead-code sub-analysis in `fallow audit` (unused files, exports, types, members and dependencies, plus boundary violations and circular dependencies, which come from the same pass). Defaults to on when unset; set `false` to leave it out of the verdict, summary and attribution, on the head and on the base snapshot. `fallow audit --skip dead-code` turns it off for one run and `--only` replaces this selection. The review brief (`--brief`, `fallow review`) keeps every sub-analysis because it reads the module graph.
1008 #[serde(default, skip_serializing_if = "Option::is_none")]
1009 pub dead_code: Option<bool>,
1010
1011 /// Toggles the health sub-analysis in `fallow audit` (complexity and CRAP findings, plus styling findings, which come from the same pass). Defaults to on when unset; set `false` to leave it out of the verdict, summary and attribution, on the head and on the base snapshot. `fallow audit --skip health` turns it off for one run and `--only` replaces this selection.
1012 #[serde(default, skip_serializing_if = "Option::is_none")]
1013 pub health: Option<bool>,
1014
1015 /// Toggles the duplication sub-analysis in `fallow audit`. Defaults to the value of `duplicates.enabled` when unset, which is on by default; set `false` to leave clone groups out of the verdict, summary and attribution, on the head and on the base snapshot. `fallow audit --skip dupes` turns it off for one run and `--only` replaces this selection.
1016 #[serde(default, skip_serializing_if = "Option::is_none")]
1017 pub dupes: Option<bool>,
1018
1019 /// Toggles styling analytics (CSS and CSS-in-JS) in the `fallow audit` health sub-pass; these findings are descriptive and verdict-neutral by default (they change the exit code only when a css-* rule is set to error). Defaults to on when unset; set `false` to skip styling analysis. The `--no-css` CLI flag forces it off regardless.
1020 #[serde(default, skip_serializing_if = "Option::is_none")]
1021 pub css: Option<bool>,
1022
1023 /// Toggles the project-wide CSS reachability pass in `fallow audit`, whose cross-file findings are narrowed back to changed anchors. Defaults to on when unset and runs only when css analytics are enabled; set `false` to keep local styling analytics but skip the whole-project scan. The `--css-deep` flag re-enables it and `--no-css-deep` forces it off.
1024 #[serde(default, skip_serializing_if = "Option::is_none")]
1025 pub css_deep: Option<bool>,
1026
1027 /// Path to a saved dead-code baseline file (produced by `fallow dead-code --save-baseline`) that the audit's dead-code sub-analysis compares against, suppressing pre-existing dead-code issues. The `--dead-code-baseline` CLI flag overrides it and both resolve relative to the project root; each sub-analysis uses a distinct baseline format, so this is separate from `healthBaseline` and `dupesBaseline`.
1028 #[serde(default, skip_serializing_if = "Option::is_none")]
1029 pub dead_code_baseline: Option<String>,
1030
1031 /// Path to a saved health/complexity baseline file (produced by `fallow health --save-baseline`) that the audit's health sub-analysis compares against, suppressing pre-existing complexity/health findings. The `--health-baseline` CLI flag overrides it and both resolve relative to the project root; its baseline format is distinct from the dead-code and dupes baselines.
1032 #[serde(default, skip_serializing_if = "Option::is_none")]
1033 pub health_baseline: Option<String>,
1034
1035 /// Path to a saved duplication baseline file (produced by `fallow dupes --save-baseline`) that the audit's duplication sub-analysis compares clone groups against, suppressing pre-existing duplicate clones. The `--dupes-baseline` CLI flag overrides it and both resolve relative to the project root; its baseline format is distinct from the dead-code and health baselines.
1036 #[serde(default, skip_serializing_if = "Option::is_none")]
1037 pub dupes_baseline: Option<String>,
1038
1039 /// Garbage-collection threshold, in whole days, for the persistent reusable base-snapshot worktree caches `fallow audit` creates: entries older than this window are swept on each audit run. Set to control cache accumulation; `0` disables the sweep and unset defaults to 30 days. Each sweep also reclaims abandoned entries minted under other repo identities (deleted or moved repos, other git worktrees) once they age past this repo's threshold; entries whose recorded owner root still exists are skipped and stay governed by that repo's own setting. The same window applies to the base-snapshot files in the project cache directory, counted from their last use; independent of this window, audit keeps only the newest 32 of those files. The `FALLOW_AUDIT_CACHE_MAX_AGE_DAYS` environment variable overrides this field.
1040 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub cache_max_age_days: Option<u32>,
1042
1043 /// Overrides the top-level `typeAware.enabled` opt-in for `fallow audit` only: set `false` to keep persistent type-aware analysis on for cleanup commands (`dead-code`, `fix`, `health`) while the audit gate stays syntactic, or `true` to enable it for audit alone. Unset inherits `typeAware.enabled`. The `--type-aware`/`--no-type-aware` CLI flags and the `FALLOW_TYPE_AWARE` environment variable both take precedence over this field.
1044 #[serde(default, skip_serializing_if = "Option::is_none")]
1045 pub type_aware: Option<bool>,
1046}
1047
1048impl AuditConfig {
1049 /// True when every field is unset, so serialization can omit the section.
1050 #[must_use]
1051 pub fn is_empty(&self) -> bool {
1052 self.gate.is_default()
1053 && self.worsened.is_default()
1054 && self.dead_code.is_none()
1055 && self.health.is_none()
1056 && self.dupes.is_none()
1057 && self.css.is_none()
1058 && self.css_deep.is_none()
1059 && self.dead_code_baseline.is_none()
1060 && self.health_baseline.is_none()
1061 && self.dupes_baseline.is_none()
1062 && self.cache_max_age_days.is_none()
1063 && self.type_aware.is_none()
1064 }
1065}
1066
1067/// Value of `audit.gate`: which findings drive the `fallow audit` verdict.
1068#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1069#[serde(rename_all = "kebab-case")]
1070pub enum AuditGate {
1071 /// Fail only on findings the current changeset introduced, determined by
1072 /// a base-snapshot attribution pass. An unused file or unused export
1073 /// outside the changed files counts when the base does not report it.
1074 /// The default.
1075 #[default]
1076 NewOnly,
1077 /// Fail on every finding in changed files, skipping the attribution pass.
1078 All,
1079}
1080
1081impl AuditGate {
1082 /// True for the default `new-only` gate, so serialization can omit it.
1083 #[must_use]
1084 pub const fn is_default(&self) -> bool {
1085 matches!(self, Self::NewOnly)
1086 }
1087}
1088
1089/// Value of `audit.worsened`: how a worsened complexity finding affects the
1090/// `fallow audit` verdict.
1091#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1092#[serde(rename_all = "kebab-case")]
1093pub enum AuditWorsened {
1094 /// A worsened finding makes the verdict at least `warn` and does not fail
1095 /// the run. The default.
1096 #[default]
1097 Warn,
1098 /// A worsened finding counts like an introduced finding.
1099 Error,
1100 /// Growth only in metrics that the finding does not exceed stays
1101 /// inherited. Growth of an exceeded metric stays worsened and gives at
1102 /// least `warn`.
1103 Off,
1104}
1105
1106impl AuditWorsened {
1107 /// True for the default `warn` mode, so serialization can omit it.
1108 #[must_use]
1109 pub const fn is_default(&self) -> bool {
1110 matches!(self, Self::Warn)
1111 }
1112}
1113
1114/// The `regression` config section holding the saved issue-count baseline for
1115/// the `--fail-on-regression` gate.
1116#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
1117#[serde(deny_unknown_fields, rename_all = "camelCase")]
1118pub struct RegressionConfig {
1119 /// The saved per-issue-type issue counts that `--fail-on-regression` compares the current run against; the gate fails only when counts grow beyond the configured tolerance. Typically written by `--save-baseline` rather than hand-authored; each field (total_issues plus per-kind counts like unused_exports, boundary_violations, policy_violations) is an integer defaulting to 0 when omitted. Absent means no baseline is embedded.
1120 #[serde(default, skip_serializing_if = "Option::is_none")]
1121 pub baseline: Option<RegressionBaseline>,
1122}
1123
1124#[expect(
1125 clippy::trivially_copy_pass_by_ref,
1126 reason = "serde skip_serializing_if requires a reference"
1127)]
1128const fn is_zero_count(count: &usize) -> bool {
1129 *count == 0
1130}
1131
1132/// Saved per-issue-type counts written by `--save-baseline` and compared by
1133/// `--fail-on-regression`. Every count defaults to `0` when its key is missing,
1134/// so hand-trimmed baselines stay loadable.
1135#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
1136#[serde(rename_all = "camelCase")]
1137pub struct RegressionBaseline {
1138 /// Baseline count of optional component prop review candidates.
1139 #[serde(default)]
1140 pub absent_component_props: usize,
1141
1142 /// Baseline count of constant parameter review candidates. Absent while
1143 /// zero, so a baseline without the opt-in rule keeps its shape.
1144 #[serde(default, skip_serializing_if = "is_zero_count")]
1145 pub constant_parameters: usize,
1146
1147 /// Compatibility identity for the analysis that produced these counts.
1148 /// Missing values in existing configs are treated as syntactic.
1149 #[serde(default)]
1150 pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
1151 /// Baseline count across all issue types.
1152 #[serde(default)]
1153 pub total_issues: usize,
1154 /// Baseline count of `unused-files` findings.
1155 #[serde(default)]
1156 pub unused_files: usize,
1157 /// Baseline count of `unused-exports` findings.
1158 #[serde(default)]
1159 pub unused_exports: usize,
1160 /// Baseline count of `unused-types` findings.
1161 #[serde(default)]
1162 pub unused_types: usize,
1163 /// Baseline count of `unused-dependencies` findings.
1164 #[serde(default)]
1165 pub unused_dependencies: usize,
1166 /// Baseline count of `unused-dev-dependencies` findings.
1167 #[serde(default)]
1168 pub unused_dev_dependencies: usize,
1169 /// Baseline count of `unused-optional-dependencies` findings.
1170 #[serde(default)]
1171 pub unused_optional_dependencies: usize,
1172 /// Baseline count of `unused-enum-members` findings.
1173 #[serde(default)]
1174 pub unused_enum_members: usize,
1175 /// Baseline count of `unused-class-members` findings.
1176 #[serde(default)]
1177 pub unused_class_members: usize,
1178 /// Baseline count of `unresolved-imports` findings.
1179 #[serde(default)]
1180 pub unresolved_imports: usize,
1181 /// Baseline count of `unlisted-dependencies` findings.
1182 #[serde(default)]
1183 pub unlisted_dependencies: usize,
1184 /// Baseline count of `unlisted-binaries` findings.
1185 #[serde(default)]
1186 pub unlisted_binaries: usize,
1187 /// Baseline count of `duplicate-exports` findings.
1188 #[serde(default)]
1189 pub duplicate_exports: usize,
1190 /// Baseline count of `circular-dependencies` findings.
1191 #[serde(default)]
1192 pub circular_dependencies: usize,
1193 /// Baseline count of `re-export-cycle` findings.
1194 #[serde(default)]
1195 pub re_export_cycles: usize,
1196 /// Baseline count of `package-cycle` findings.
1197 #[serde(default)]
1198 pub package_cycles: usize,
1199 /// Baseline count of `type-only-dependencies` findings.
1200 #[serde(default)]
1201 pub type_only_dependencies: usize,
1202 /// Baseline count of `test-only-dependencies` findings.
1203 #[serde(default)]
1204 pub test_only_dependencies: usize,
1205 /// Baseline count of `dev-dependencies-in-production` findings.
1206 #[serde(default)]
1207 pub dev_dependencies_in_production: usize,
1208 /// Baseline count of `boundary-violation` findings.
1209 #[serde(default)]
1210 pub boundary_violations: usize,
1211 /// Baseline count of boundary-coverage-violation findings.
1212 #[serde(default)]
1213 pub boundary_coverage_violations: usize,
1214 /// Baseline count of boundary-call-violation findings.
1215 #[serde(default)]
1216 pub boundary_call_violations: usize,
1217 /// Baseline count of `policy-violation` findings.
1218 #[serde(default)]
1219 pub policy_violations: usize,
1220}
1221
1222#[cfg(test)]
1223mod tests {
1224 use super::*;
1225
1226 #[test]
1227 fn regression_baseline_preserves_absent_component_prop_count() {
1228 let baseline: RegressionBaseline =
1229 serde_json::from_value(serde_json::json!({"absentComponentProps":7})).unwrap();
1230 assert_eq!(
1231 serde_json::to_value(baseline).unwrap()["absentComponentProps"],
1232 7
1233 );
1234 }
1235
1236 #[test]
1237 fn default_config_has_empty_collections() {
1238 let config = FallowConfig::default();
1239 assert!(config.schema.is_none());
1240 assert!(config.extends.is_empty());
1241 assert!(config.entry.is_empty());
1242 assert!(config.ignore_patterns.is_empty());
1243 assert!(config.ignore_findings.is_empty());
1244 assert!(config.framework.is_empty());
1245 assert!(config.workspaces.is_none());
1246 assert!(config.ignore_dependencies.is_empty());
1247 assert!(config.ignore_exports.is_empty());
1248 assert!(config.used_class_members.is_empty());
1249 assert!(config.plugins.is_empty());
1250 assert!(config.dynamically_loaded.is_empty());
1251 assert!(config.overrides.is_empty());
1252 assert!(config.public_packages.is_empty());
1253 assert_eq!(
1254 config.fix.catalog.delete_preceding_comments,
1255 CatalogPrecedingCommentPolicy::Auto
1256 );
1257 assert!(!config.production);
1258 }
1259
1260 #[test]
1261 fn deserialize_empty_json_object() {
1262 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1263 assert!(config.entry.is_empty());
1264 assert!(!config.production);
1265 assert!(!config.type_aware.enabled);
1266 assert_eq!(config.type_aware.require, TypeAwareRequire::BestEffort);
1267 }
1268
1269 #[test]
1270 fn deserialize_type_aware_config() {
1271 let config: FallowConfig = serde_json::from_str(
1272 r#"{"typeAware":{"enabled":true,"projects":["tsconfig.app.json"],"require":"complete"}}"#,
1273 )
1274 .unwrap();
1275
1276 assert!(config.type_aware.enabled);
1277 assert_eq!(config.type_aware.projects, ["tsconfig.app.json"]);
1278 assert_eq!(config.type_aware.require, TypeAwareRequire::Complete);
1279 }
1280
1281 #[test]
1282 fn deserialize_type_aware_config_rejects_unknown_fields() {
1283 let result = serde_json::from_str::<FallowConfig>(
1284 r#"{"typeAware":{"enabled":true,"compilerDiagnostics":true}}"#,
1285 );
1286 assert!(result.is_err());
1287 }
1288
1289 #[test]
1290 fn deserialize_json_with_all_top_level_fields() {
1291 let json = r#"{
1292 "$schema": "./node_modules/fallow/schema.json",
1293 "entry": ["src/main.ts"],
1294 "ignorePatterns": ["generated/**"],
1295 "ignoreFindings": ["**/*.test.ts", "!src/public/**"],
1296 "ignoreDependencies": ["postcss"],
1297 "production": true,
1298 "plugins": ["custom-plugin.toml"],
1299 "rules": {"unused-files": "warn"},
1300 "duplicates": {"enabled": false},
1301 "health": {"maxCyclomatic": 30}
1302 }"#;
1303 let config: FallowConfig = serde_json::from_str(json).unwrap();
1304 assert_eq!(
1305 config.schema.as_deref(),
1306 Some("./node_modules/fallow/schema.json")
1307 );
1308 assert_eq!(config.entry, vec!["src/main.ts"]);
1309 assert_eq!(config.ignore_patterns, vec!["generated/**"]);
1310 assert_eq!(
1311 config.ignore_findings,
1312 vec!["**/*.test.ts", "!src/public/**"]
1313 );
1314 assert_eq!(config.ignore_dependencies, vec!["postcss"]);
1315 assert!(config.production);
1316 assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
1317 assert_eq!(config.rules.unused_files, Severity::Warn);
1318 assert!(!config.duplicates.enabled);
1319 assert_eq!(config.health.max_cyclomatic, 30);
1320 }
1321
1322 #[test]
1323 fn deserialize_json_deny_unknown_fields() {
1324 let json = r#"{"unknownField": true}"#;
1325 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1326 assert!(result.is_err(), "unknown fields should be rejected");
1327 }
1328
1329 #[test]
1330 fn ignore_findings_serialization_is_canonical_and_sparse() {
1331 let default_value = serde_json::to_value(FallowConfig::default()).unwrap();
1332 assert!(default_value.get("ignoreFindings").is_none());
1333
1334 let config = FallowConfig {
1335 ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
1336 ..Default::default()
1337 };
1338 let value = serde_json::to_value(config).unwrap();
1339 assert_eq!(
1340 value.get("ignoreFindings"),
1341 Some(&serde_json::json!(["**/*.test.ts", "!src/public/**"]))
1342 );
1343 }
1344
1345 #[test]
1346 fn ignore_findings_deserializes_from_toml() {
1347 let config: FallowConfig =
1348 toml::from_str(r#"ignoreFindings = ["**/*.test.ts", "!src/public/**"]"#).unwrap();
1349
1350 assert_eq!(
1351 config.ignore_findings,
1352 vec!["**/*.test.ts", "!src/public/**"]
1353 );
1354 }
1355
1356 #[test]
1357 fn generic_ignore_alias_is_rejected() {
1358 let result = serde_json::from_str::<FallowConfig>(r#"{"ignore": ["**/*.test.ts"]}"#);
1359
1360 assert!(result.is_err());
1361 }
1362
1363 #[test]
1364 fn deserialize_json_production_mode_default_false() {
1365 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1366 assert!(!config.production);
1367 }
1368
1369 #[test]
1370 fn deserialize_json_production_mode_true() {
1371 let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
1372 assert!(config.production);
1373 }
1374
1375 #[test]
1376 fn deserialize_json_per_analysis_production_mode() {
1377 let config: FallowConfig = serde_json::from_str(
1378 r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
1379 )
1380 .unwrap();
1381 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1382 assert!(config.production.for_analysis(ProductionAnalysis::Health));
1383 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1384 }
1385
1386 #[test]
1387 fn deserialize_json_production_ignore() {
1388 let config: FallowConfig =
1389 serde_json::from_str(r#"{"production": {"deadCode": true, "ignore": ["scripts/**"]}}"#)
1390 .unwrap();
1391 assert!(config.production.for_analysis(ProductionAnalysis::DeadCode));
1392 assert_eq!(config.production.ignore(), ["scripts/**".to_string()]);
1393 assert!(
1394 ProductionConfig::Global(true).ignore().is_empty(),
1395 "the boolean form has no ignore globs"
1396 );
1397 }
1398
1399 #[test]
1400 fn production_for_run_keeps_ignore_globs() {
1401 let config: FallowConfig =
1402 serde_json::from_str(r#"{"production": {"ignore": ["scripts/**"]}}"#).unwrap();
1403 let on = config.production.for_run(true);
1404 assert!(on.global());
1405 assert_eq!(on.ignore(), ["scripts/**".to_string()]);
1406 let off = config.production.for_run(false);
1407 assert!(!off.any_enabled());
1408 assert_eq!(off.ignore(), ["scripts/**".to_string()]);
1409 assert_eq!(
1410 ProductionConfig::Global(false).for_run(true),
1411 ProductionConfig::Global(true),
1412 "a config without ignore globs keeps the boolean form"
1413 );
1414 }
1415
1416 #[test]
1417 fn production_global_needs_every_analysis_in_the_object_form() {
1418 let partial: FallowConfig =
1419 serde_json::from_str(r#"{"production": {"deadCode": true, "health": true}}"#).unwrap();
1420 assert!(!partial.production.global());
1421 let all: FallowConfig = serde_json::from_str(
1422 r#"{"production": {"deadCode": true, "health": true, "dupes": true}}"#,
1423 )
1424 .unwrap();
1425 assert!(all.production.global());
1426 }
1427
1428 #[test]
1429 fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
1430 let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
1431 .unwrap_err();
1432 assert!(
1433 err.to_string().contains("healthTypo"),
1434 "error should name the unknown field: {err}"
1435 );
1436 }
1437
1438 #[test]
1439 fn deserialize_json_dynamically_loaded() {
1440 let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
1441 let config: FallowConfig = serde_json::from_str(json).unwrap();
1442 assert_eq!(
1443 config.dynamically_loaded,
1444 vec!["plugins/**/*.ts", "locales/**/*.json"]
1445 );
1446 }
1447
1448 #[test]
1449 fn deserialize_json_dynamically_loaded_defaults_empty() {
1450 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1451 assert!(config.dynamically_loaded.is_empty());
1452 }
1453
1454 #[test]
1455 fn deserialize_json_fix_catalog_delete_preceding_comments() {
1456 let config: FallowConfig =
1457 serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
1458 .unwrap();
1459 assert_eq!(
1460 config.fix.catalog.delete_preceding_comments,
1461 CatalogPrecedingCommentPolicy::Always
1462 );
1463 }
1464
1465 #[test]
1466 fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
1467 let err = serde_json::from_str::<FallowConfig>(
1468 r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
1469 )
1470 .unwrap_err();
1471 assert!(
1472 err.to_string().contains("sometimes"),
1473 "error should name the bad policy: {err}"
1474 );
1475 }
1476
1477 #[test]
1478 fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
1479 let json = r#"{
1480 "usedClassMembers": [
1481 "agInit",
1482 { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
1483 { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
1484 ]
1485 }"#;
1486 let config: FallowConfig = serde_json::from_str(json).unwrap();
1487 assert_eq!(
1488 config.used_class_members,
1489 vec![
1490 UsedClassMemberRule::from("agInit"),
1491 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1492 extends: None,
1493 implements: Some("ICellRendererAngularComp".to_string()),
1494 members: vec!["refresh".to_string()],
1495 }),
1496 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1497 extends: Some("BaseCommand".to_string()),
1498 implements: Some("CanActivate".to_string()),
1499 members: vec!["execute".to_string()],
1500 }),
1501 ]
1502 );
1503 }
1504
1505 #[test]
1506 fn deserialize_toml_minimal() {
1507 let toml_str = r#"
1508entry = ["src/index.ts"]
1509production = true
1510"#;
1511 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1512 assert_eq!(config.entry, vec!["src/index.ts"]);
1513 assert!(config.production);
1514 }
1515
1516 #[test]
1517 fn workspaces_packages_key_is_accepted_as_patterns_alias() {
1518 // An older `fallow init --toml` wrote `[workspaces]` with a `packages`
1519 // key; the back-compat serde alias keeps those existing configs scoping
1520 // instead of silently dropping the (unknown) key and losing the patterns.
1521 let config: FallowConfig =
1522 toml::from_str("[workspaces]\npackages = [\"packages/*\", \"apps/*\"]").unwrap();
1523 assert_eq!(
1524 config.workspaces.map(|w| w.patterns).unwrap_or_default(),
1525 vec!["packages/*".to_string(), "apps/*".to_string()],
1526 "the `packages` alias must populate `patterns`"
1527 );
1528 }
1529
1530 #[test]
1531 fn deserialize_toml_per_analysis_production_mode() {
1532 let toml_str = r"
1533[production]
1534deadCode = false
1535health = true
1536dupes = false
1537";
1538 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1539 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1540 assert!(config.production.for_analysis(ProductionAnalysis::Health));
1541 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1542 }
1543
1544 #[test]
1545 fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
1546 let err = toml::from_str::<FallowConfig>(
1547 r"
1548[production]
1549healthTypo = true
1550",
1551 )
1552 .unwrap_err();
1553 assert!(
1554 err.to_string().contains("healthTypo"),
1555 "error should name the unknown field: {err}"
1556 );
1557 }
1558
1559 #[test]
1560 fn deserialize_toml_with_inline_framework() {
1561 let toml_str = r#"
1562[[framework]]
1563name = "my-framework"
1564enablers = ["my-framework-pkg"]
1565entryPoints = ["src/routes/**/*.tsx"]
1566"#;
1567 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1568 assert_eq!(config.framework.len(), 1);
1569 assert_eq!(config.framework[0].name, "my-framework");
1570 assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
1571 assert_eq!(
1572 config.framework[0].entry_points,
1573 vec!["src/routes/**/*.tsx"]
1574 );
1575 }
1576
1577 #[test]
1578 fn deserialize_toml_fix_catalog_delete_preceding_comments() {
1579 let toml_str = r#"
1580[fix.catalog]
1581deletePrecedingComments = "never"
1582"#;
1583 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1584 assert_eq!(
1585 config.fix.catalog.delete_preceding_comments,
1586 CatalogPrecedingCommentPolicy::Never
1587 );
1588 }
1589
1590 #[test]
1591 fn deserialize_toml_with_workspace_config() {
1592 let toml_str = r#"
1593[workspaces]
1594patterns = ["packages/*", "apps/*"]
1595[workspaces.changedSince]
1596"packages/web" = "main"
1597"packages/legacy" = "release/2024.10"
1598"#;
1599 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1600 assert!(config.workspaces.is_some());
1601 let ws = config.workspaces.unwrap();
1602 assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
1603 assert_eq!(ws.changed_since["packages/web"], "main");
1604 assert_eq!(ws.changed_since["packages/legacy"], "release/2024.10");
1605 }
1606
1607 #[test]
1608 fn deserialize_toml_with_ignore_exports() {
1609 let toml_str = r#"
1610[[ignoreExports]]
1611file = "src/types/**/*.ts"
1612exports = ["*"]
1613"#;
1614 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1615 assert_eq!(config.ignore_exports.len(), 1);
1616 assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
1617 assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
1618 }
1619
1620 #[test]
1621 fn deserialize_toml_used_class_members_supports_scoped_rules() {
1622 let toml_str = r#"
1623usedClassMembers = [
1624 { implements = "ICellRendererAngularComp", members = ["refresh"] },
1625 { extends = "BaseCommand", members = ["execute"] },
1626]
1627"#;
1628 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1629 assert_eq!(
1630 config.used_class_members,
1631 vec![
1632 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1633 extends: None,
1634 implements: Some("ICellRendererAngularComp".to_string()),
1635 members: vec!["refresh".to_string()],
1636 }),
1637 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1638 extends: Some("BaseCommand".to_string()),
1639 implements: None,
1640 members: vec!["execute".to_string()],
1641 }),
1642 ]
1643 );
1644 }
1645
1646 #[test]
1647 fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
1648 let result = serde_json::from_str::<FallowConfig>(
1649 r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
1650 );
1651 assert!(
1652 result.is_err(),
1653 "unconstrained scoped rule should be rejected"
1654 );
1655 }
1656
1657 #[test]
1658 fn deserialize_ignore_exports_used_in_file_bool() {
1659 let config: FallowConfig =
1660 serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
1661
1662 assert!(config.ignore_exports_used_in_file.suppresses(false));
1663 assert!(config.ignore_exports_used_in_file.suppresses(true));
1664 }
1665
1666 #[test]
1667 fn deserialize_effect_schema_exports_as_types() {
1668 let default: FallowConfig = serde_json::from_str("{}").unwrap();
1669 assert!(!default.effect.schema_exports_as_types);
1670 assert!(
1671 !serde_json::to_string(&default)
1672 .unwrap()
1673 .contains("\"effect\""),
1674 "the default section is not serialized"
1675 );
1676
1677 let config: FallowConfig =
1678 serde_json::from_str(r#"{"effect":{"schemaExportsAsTypes":true}}"#).unwrap();
1679 assert!(config.effect.schema_exports_as_types);
1680
1681 let toml: FallowConfig = toml::from_str("[effect]\nschemaExportsAsTypes = true\n").unwrap();
1682 assert!(toml.effect.schema_exports_as_types);
1683
1684 let typo = serde_json::from_str::<FallowConfig>(r#"{"effect":{"schemaExports":true}}"#);
1685 assert!(typo.is_err(), "an unknown effect key fails the load");
1686 }
1687
1688 #[test]
1689 fn deserialize_ignore_exports_used_in_file_kind_form() {
1690 let config: FallowConfig =
1691 serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
1692
1693 assert!(!config.ignore_exports_used_in_file.suppresses(false));
1694 assert!(config.ignore_exports_used_in_file.suppresses(true));
1695 }
1696
1697 #[test]
1698 fn deserialize_toml_deny_unknown_fields() {
1699 let toml_str = r"bogus_field = true";
1700 let result: Result<FallowConfig, _> = toml::from_str(toml_str);
1701 assert!(result.is_err(), "unknown fields should be rejected");
1702 }
1703
1704 #[test]
1705 fn json_serialize_roundtrip() {
1706 let config = FallowConfig {
1707 entry: vec!["src/main.ts".to_string()],
1708 production: true.into(),
1709 ..FallowConfig::default()
1710 };
1711 let json = serde_json::to_string(&config).unwrap();
1712 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1713 assert_eq!(restored.entry, vec!["src/main.ts"]);
1714 assert!(restored.production);
1715 }
1716
1717 #[test]
1718 fn schema_field_not_serialized() {
1719 let config = FallowConfig {
1720 schema: Some("https://example.com/schema.json".to_string()),
1721 ..FallowConfig::default()
1722 };
1723 let json = serde_json::to_string(&config).unwrap();
1724 assert!(
1725 !json.contains("$schema"),
1726 "schema field should be skipped in serialization"
1727 );
1728 }
1729
1730 #[test]
1731 fn extends_field_not_serialized() {
1732 let config = FallowConfig {
1733 extends: vec!["base.json".to_string()],
1734 ..FallowConfig::default()
1735 };
1736 let json = serde_json::to_string(&config).unwrap();
1737 assert!(
1738 !json.contains("extends"),
1739 "extends field should be skipped in serialization"
1740 );
1741 }
1742
1743 #[test]
1744 fn regression_config_deserialize_json() {
1745 let json = r#"{
1746 "regression": {
1747 "baseline": {
1748 "totalIssues": 42,
1749 "unusedFiles": 10,
1750 "unusedExports": 5,
1751 "circularDependencies": 2
1752 }
1753 }
1754 }"#;
1755 let config: FallowConfig = serde_json::from_str(json).unwrap();
1756 let regression = config.regression.unwrap();
1757 let baseline = regression.baseline.unwrap();
1758 assert_eq!(baseline.total_issues, 42);
1759 assert_eq!(baseline.unused_files, 10);
1760 assert_eq!(baseline.unused_exports, 5);
1761 assert_eq!(baseline.circular_dependencies, 2);
1762 assert_eq!(baseline.unused_types, 0);
1763 assert_eq!(baseline.boundary_violations, 0);
1764 }
1765
1766 #[test]
1767 fn regression_config_defaults_to_none() {
1768 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1769 assert!(config.regression.is_none());
1770 }
1771
1772 #[test]
1773 fn regression_baseline_all_zeros_by_default() {
1774 let baseline = RegressionBaseline::default();
1775 assert_eq!(baseline.total_issues, 0);
1776 assert_eq!(baseline.unused_files, 0);
1777 assert_eq!(baseline.unused_exports, 0);
1778 assert_eq!(baseline.unused_types, 0);
1779 assert_eq!(baseline.unused_dependencies, 0);
1780 assert_eq!(baseline.unused_dev_dependencies, 0);
1781 assert_eq!(baseline.unused_optional_dependencies, 0);
1782 assert_eq!(baseline.unused_enum_members, 0);
1783 assert_eq!(baseline.unused_class_members, 0);
1784 assert_eq!(baseline.unresolved_imports, 0);
1785 assert_eq!(baseline.unlisted_dependencies, 0);
1786 assert_eq!(baseline.duplicate_exports, 0);
1787 assert_eq!(baseline.circular_dependencies, 0);
1788 assert_eq!(baseline.type_only_dependencies, 0);
1789 assert_eq!(baseline.test_only_dependencies, 0);
1790 assert_eq!(baseline.boundary_violations, 0);
1791 }
1792
1793 #[test]
1794 fn regression_config_serialize_roundtrip() {
1795 let baseline = RegressionBaseline {
1796 total_issues: 100,
1797 unused_files: 20,
1798 unused_exports: 30,
1799 ..RegressionBaseline::default()
1800 };
1801 let regression = RegressionConfig {
1802 baseline: Some(baseline),
1803 };
1804 let config = FallowConfig {
1805 regression: Some(regression),
1806 ..FallowConfig::default()
1807 };
1808 let json = serde_json::to_string(&config).unwrap();
1809 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1810 let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1811 assert_eq!(restored_baseline.total_issues, 100);
1812 assert_eq!(restored_baseline.unused_files, 20);
1813 assert_eq!(restored_baseline.unused_exports, 30);
1814 assert_eq!(restored_baseline.unused_types, 0);
1815 }
1816
1817 #[test]
1818 fn regression_config_empty_baseline_deserialize() {
1819 let json = r#"{"regression": {}}"#;
1820 let config: FallowConfig = serde_json::from_str(json).unwrap();
1821 let regression = config.regression.unwrap();
1822 assert!(regression.baseline.is_none());
1823 }
1824
1825 #[test]
1826 fn regression_baseline_not_serialized_when_none() {
1827 let config = FallowConfig {
1828 regression: None,
1829 ..FallowConfig::default()
1830 };
1831 let json = serde_json::to_string(&config).unwrap();
1832 assert!(
1833 !json.contains("regression"),
1834 "regression should be skipped when None"
1835 );
1836 }
1837
1838 #[test]
1839 fn deserialize_json_with_overrides() {
1840 let json = r#"{
1841 "overrides": [
1842 {
1843 "files": ["*.test.ts", "*.spec.ts"],
1844 "rules": {
1845 "unused-exports": "off",
1846 "unused-files": "warn"
1847 }
1848 }
1849 ]
1850 }"#;
1851 let config: FallowConfig = serde_json::from_str(json).unwrap();
1852 assert_eq!(config.overrides.len(), 1);
1853 assert_eq!(config.overrides[0].files.len(), 2);
1854 assert_eq!(
1855 config.overrides[0].rules.unused_exports,
1856 Some(Severity::Off)
1857 );
1858 assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1859 }
1860
1861 #[test]
1862 fn deserialize_json_with_boundaries() {
1863 let json = r#"{
1864 "boundaries": {
1865 "preset": "layered"
1866 }
1867 }"#;
1868 let config: FallowConfig = serde_json::from_str(json).unwrap();
1869 assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1870 }
1871
1872 #[test]
1873 fn deserialize_toml_with_regression_baseline() {
1874 let toml_str = r"
1875[regression.baseline]
1876totalIssues = 50
1877unusedFiles = 10
1878unusedExports = 15
1879";
1880 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1881 let baseline = config.regression.unwrap().baseline.unwrap();
1882 assert_eq!(baseline.total_issues, 50);
1883 assert_eq!(baseline.unused_files, 10);
1884 assert_eq!(baseline.unused_exports, 15);
1885 }
1886
1887 #[test]
1888 fn deserialize_toml_with_overrides() {
1889 let toml_str = r#"
1890[[overrides]]
1891files = ["*.test.ts"]
1892
1893[overrides.rules]
1894unused-exports = "off"
1895
1896[[overrides]]
1897files = ["*.stories.tsx"]
1898
1899[overrides.rules]
1900unused-files = "off"
1901"#;
1902 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1903 assert_eq!(config.overrides.len(), 2);
1904 assert_eq!(
1905 config.overrides[0].rules.unused_exports,
1906 Some(Severity::Off)
1907 );
1908 assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1909 }
1910
1911 #[test]
1912 fn regression_config_default_is_none_baseline() {
1913 let config = RegressionConfig::default();
1914 assert!(config.baseline.is_none());
1915 }
1916
1917 #[test]
1918 fn deserialize_json_multiple_ignore_export_rules() {
1919 let json = r#"{
1920 "ignoreExports": [
1921 {"file": "src/types/**/*.ts", "exports": ["*"]},
1922 {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1923 {"file": "src/index.ts", "exports": ["default"]}
1924 ]
1925 }"#;
1926 let config: FallowConfig = serde_json::from_str(json).unwrap();
1927 assert_eq!(config.ignore_exports.len(), 3);
1928 assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1929 }
1930
1931 #[test]
1932 fn deserialize_json_public_packages_camel_case() {
1933 let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1934 let config: FallowConfig = serde_json::from_str(json).unwrap();
1935 assert_eq!(
1936 config.public_packages,
1937 vec!["@myorg/shared-lib", "@myorg/utils"]
1938 );
1939 }
1940
1941 #[test]
1942 fn deserialize_json_public_packages_rejects_snake_case() {
1943 let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1944 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1945 assert!(
1946 result.is_err(),
1947 "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1948 );
1949 }
1950
1951 #[test]
1952 fn deserialize_json_public_packages_empty() {
1953 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1954 assert!(config.public_packages.is_empty());
1955 }
1956
1957 #[test]
1958 fn deserialize_toml_public_packages() {
1959 let toml_str = r#"
1960publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1961"#;
1962 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1963 assert_eq!(
1964 config.public_packages,
1965 vec!["@myorg/shared-lib", "@myorg/ui"]
1966 );
1967 }
1968
1969 #[test]
1970 fn public_packages_serialize_roundtrip() {
1971 let config = FallowConfig {
1972 public_packages: vec!["@myorg/shared-lib".to_string()],
1973 ..FallowConfig::default()
1974 };
1975 let json = serde_json::to_string(&config).unwrap();
1976 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1977 assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1978 }
1979}