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_patterns;
12mod legacy_glob;
13mod markup_extensions;
14mod mutation;
15mod override_effect;
16mod parsing;
17mod resolution;
18mod resolve;
19mod rules;
20mod run_plan;
21mod similar_code;
22mod used_class_members;
23mod workspace_settings;
24
25#[expect(
26 clippy::redundant_pub_crate,
27 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"
28)]
29pub(crate) use boundaries::wildcard_placement_error;
30pub use boundaries::{
31 AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
32 BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
33 LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
34 ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
35 ZoneReferenceKind, ZoneValidationError,
36};
37pub use dependency_ignore::{IgnoreDependencyMatcher, is_dependency_glob};
38pub use duplicates_config::{
39 DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
40};
41pub use entry_effect::EntryEffectRecord;
42pub use entry_span::ConfigEntrySpan;
43pub use finding_ignore::FindingIgnoreMatcher;
44pub use flags::{FlagsConfig, SdkPattern};
45pub use format::OutputFormat;
46pub use glob_validation::compile_path_glob;
47pub use health::{
48 ChangeCouplingConfig, CyclomaticPolicy, EmailMode, HealthConfig, HealthThresholdOverride,
49 OwnershipConfig,
50};
51pub use ignore_patterns::{IgnorePatternSet, UNLIFTABLE_IGNORE_SEGMENTS};
52pub use legacy_glob::{
53 LegacyGlobGroup, LegacyGlobNarrowing, find_legacy_glob_narrowings, has_single_segment_wildcard,
54 suggest_cross_directory_rewrite,
55};
56pub use markup_extensions::{
57 DEFAULT_MARKUP_EXTENSIONS, resolve_markup_extensions, template_markup_extension,
58};
59pub use mutation::{MutationConfig, MutationOperatorName, MutationRunner};
60pub use override_effect::{IneffectiveOverrideRule, project_level_override_rules};
61pub use parsing::{CONFIG_FILE_NAMES, ConfigLoadOptions, extends_timeout_from_env_value};
62pub use resolution::{
63 AnalysisSnapshot, CACHE_DIR_ENV, CACHE_MAX_SIZE_ENV, CompiledIgnoreCatalogReferenceRule,
64 CompiledIgnoreDependencyOverrideRule, CompiledIgnoreExportRule, ConfigOverride,
65 DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_FILE_SIZE_BYTES, DEFAULT_MAX_FILE_SIZE_MB,
66 IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule, IgnoreExportRule,
67 PACKAGE_BASELINES_ENV, ResolvedConfig, ResolvedOverride, cache_config_hash,
68 cache_dir_from_env_value, cache_max_size_env_override, cache_max_size_from_env_value,
69 config_cache_dir, package_baselines_disabled_by_env_value, resolve_max_file_size_bytes,
70};
71pub use resolve::ResolveConfig;
72pub use rules::{
73 KNOWN_RULE_NAMES, PartialRulesConfig, RulesConfig, SEMANTIC_REFINABLE_KINDS,
74 SYMBOL_USE_REFINABLE_KINDS, Severity, any_symbol_use_rule_active, closest_known_rule_name,
75 default_severity_for_kind, is_opt_in_kind,
76};
77pub use run_plan::{
78 AnalysisRequest, AnalysisSelection, ConfigKey, PlanSections, PlannedAnalysis, RunCommand,
79 RunPlan, RunRequest, SkipReason, plan_run,
80};
81pub use similar_code::SimilarCodeConfig;
82pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
83pub use workspace_settings::ResolvedWorkspaceSettings;
84
85use schemars::JsonSchema;
86use serde::{Deserialize, Deserializer, Serialize};
87use std::ops::Not;
88use std::path::PathBuf;
89
90use crate::external_plugin::ExternalPluginDef;
91use crate::workspace::WorkspaceConfig;
92
93/// Value of the `ignoreExportsUsedInFile` config key: whether an export
94/// referenced elsewhere in its own file is suppressed from `unused-export`.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
96#[serde(untagged, rename_all = "camelCase")]
97pub enum IgnoreExportsUsedInFileConfig {
98 /// Blanket toggle: `true` suppresses any export with a same-file use,
99 /// regardless of kind. The default is `false`.
100 Bool(bool),
101 /// Object form that restricts the suppression to type-only exports.
102 ByKind(IgnoreExportsUsedInFileByKind),
103}
104
105impl Default for IgnoreExportsUsedInFileConfig {
106 fn default() -> Self {
107 Self::Bool(false)
108 }
109}
110
111impl From<bool> for IgnoreExportsUsedInFileConfig {
112 fn from(value: bool) -> Self {
113 Self::Bool(value)
114 }
115}
116
117impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
118 fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
119 Self::ByKind(value)
120 }
121}
122
123impl IgnoreExportsUsedInFileConfig {
124 /// Whether any form of the same-file-use suppression is active (the bool
125 /// form is `true`, or either by-kind field is set).
126 #[must_use]
127 pub const fn is_enabled(self) -> bool {
128 match self {
129 Self::Bool(value) => value,
130 Self::ByKind(kind) => kind.type_ || kind.interface,
131 }
132 }
133
134 /// Whether an export with a same-file use should be suppressed, given
135 /// whether fallow classified it as type-only. The bool form suppresses
136 /// regardless of kind; the by-kind form suppresses type-only exports only.
137 #[must_use]
138 pub const fn suppresses(self, is_type_only: bool) -> bool {
139 match self {
140 Self::Bool(value) => value,
141 Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
142 }
143 }
144}
145
146/// Object form of `ignoreExportsUsedInFile` (`{ "type": ..., "interface": ... }`),
147/// restricting the same-file-use suppression to type-only exports.
148#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
149#[serde(rename_all = "camelCase")]
150pub struct IgnoreExportsUsedInFileByKind {
151 /// 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.
152 #[serde(default, rename = "type")]
153 pub type_: bool,
154 /// 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.
155 #[serde(default)]
156 pub interface: bool,
157}
158
159/// Options for the `unused-component-props` rule.
160///
161/// Lets a project exempt component props whose local destructure binding name
162/// matches a regex from `unused-component-props`, honoring the
163/// "accepted-but-intentionally-unused" leading-underscore convention (Svelte 5
164/// `$props()`, React destructure) that mirrors TypeScript `noUnusedParameters`
165/// and ESLint `@typescript-eslint/no-unused-vars` `varsIgnorePattern` /
166/// `argsIgnorePattern`. Opt-in; an unset `ignorePattern` leaves the rule's
167/// behavior unchanged.
168#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
169#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
170pub struct UnusedComponentPropsConfig {
171 /// Regex matched against each declared prop's local destructure binding name
172 /// (e.g. `_stage` in `let { stage: _stage } = $props()`), which falls back
173 /// to the public prop name when there is no alias. A prop whose local name
174 /// matches is treated as intentionally unused and never reported as
175 /// `unused-component-props`. Matching is unanchored (substring), like
176 /// ESLint's `RegExp.test`, so anchor with `^_` to match a leading
177 /// underscore. Compiled and validated at config load (an invalid regex fails
178 /// load). Applies to Vue, Svelte, Astro, and React/Preact props.
179 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub ignore_pattern: Option<String>,
181}
182
183impl UnusedComponentPropsConfig {
184 /// True when no option is set, so serialization can omit the section.
185 #[must_use]
186 pub fn is_default(&self) -> bool {
187 self.ignore_pattern.is_none()
188 }
189}
190
191/// Options for the `circular-dependencies` rule.
192///
193/// The default leaves the rule unchanged: every runtime import edge takes
194/// part in cycle detection, and only type-only edges are skipped.
195#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
196#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
197pub struct CircularDependenciesConfig {
198 /// Skip import edges that load their target on demand or on another
199 /// thread when fallow looks for cycles. A literal `import()` inside a
200 /// function, a template `import()`, a lazy `import.meta.glob`, a worker
201 /// URL and a webpack worker loader request (`worker-loader!./work.js`)
202 /// are lazy edges. A top-level `await import()`, `require()` and an
203 /// eager `import.meta.glob` load before the module finishes, so they stay.
204 /// An edge that also carries a static import stays. Default `false`.
205 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
206 pub ignore_lazy_imports: bool,
207 /// Accepted cycles. Each entry is the list of files of one cycle, in
208 /// import order, without the repeat of the first file at the end. An
209 /// entry accepts a cycle that has exactly these files in this order, from
210 /// any start file: `["src/a.ts", "src/b.ts", "src/c.ts"]` also accepts
211 /// `src/b.ts -> src/c.ts -> src/a.ts`. A cycle with another set of files
212 /// stays reported, also when it shares an import with an accepted cycle.
213 ///
214 /// Each path is relative to the project root, also in a monorepo: write
215 /// `packages/app/src/a.ts`, not a path relative to the workspace. The
216 /// match is case-sensitive on every platform. Globs are not supported.
217 /// An entry needs at least 2 files and lists each file once.
218 ///
219 /// An entry that matches no cycle in a run gives a
220 /// `circular-dependencies-allow-unmatched` diagnostic. The detector lists
221 /// at most 20 cycles per group of files that import each other, and no
222 /// cycle with more than 12 files. An accepted cycle does not count toward
223 /// the 20. An entry with more than 12 files, or with all files in a group
224 /// that reached the limit, gives no diagnostic, because the detector
225 /// cannot prove that it matches no cycle.
226 ///
227 /// A `fallow-ignore-next-line circular-dependency` comment on an accepted
228 /// cycle becomes a stale suppression: remove the comment when you add the
229 /// entry. Default `[]`.
230 #[serde(default, skip_serializing_if = "Vec::is_empty")]
231 #[schemars(inner(length(min = 2)))]
232 pub allow: Vec<Vec<String>>,
233}
234
235impl CircularDependenciesConfig {
236 /// True when no option is set, so serialization can omit the section.
237 #[must_use]
238 pub const fn is_default(&self) -> bool {
239 !self.ignore_lazy_imports && self.allow.is_empty()
240 }
241
242 /// The `allow` entries that can never match a cycle: an entry with fewer
243 /// than 2 files, and an entry that lists one file more than once. A
244 /// leading `./` does not make two paths different.
245 #[must_use]
246 pub fn allow_errors(&self) -> Vec<String> {
247 let mut errors = Vec::new();
248 for (index, entry) in self.allow.iter().enumerate() {
249 if entry.len() < 2 {
250 let noun = if entry.len() == 1 { "file" } else { "files" };
251 errors.push(format!(
252 "circularDependencies.allow[{index}] lists {} {noun}; an entry lists the 2 or \
253 more files of one cycle",
254 entry.len()
255 ));
256 continue;
257 }
258 let mut seen = rustc_hash::FxHashSet::default();
259 if let Some(repeated) = entry
260 .iter()
261 .map(|file| file.trim_start_matches("./"))
262 .find(|file| !seen.insert(*file))
263 {
264 errors.push(format!(
265 "circularDependencies.allow[{index}] lists '{repeated}' more than once; a \
266 cycle has each file once"
267 ));
268 }
269 }
270 errors
271 }
272}
273
274/// Options for projects that use the Effect library.
275///
276/// The default changes nothing: each Effect export is reported like any
277/// other export.
278#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
279#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
280pub struct EffectConfig {
281 /// Report an unused exported Effect schema as an unused type, under the
282 /// `unused-types` rule, and not as an unused export. An Effect schema
283 /// defines a runtime value and a type (`typeof User.Type`), so a team
284 /// that keeps exported types as contracts can keep schemas too. With
285 /// `"unused-types": "off"`, fallow does not report them. A schema is a
286 /// class that extends a `Schema` class factory (`Schema.Class`,
287 /// `Schema.TaggedClass`, `Schema.TaggedError`, `Schema.TaggedRequest`,
288 /// `Schema.Error`, `Schema.Opaque`), or a const whose
289 /// value is a `Schema` constructor, member or pipe chain
290 /// (`Schema.Struct({...})`, `Schema.String.pipe(Schema.brand("Id"))`).
291 /// Each `pipe` argument must be a `Schema` transform, or a call of an
292 /// `HttpApiSchema` transform such as `HttpApiSchema.status(201)`.
293 /// A const whose value is a call of a function is a schema when each
294 /// `return` of the function is a schema (`const makeUser = () =>
295 /// Schema.Struct({...})`, then `export const User = makeUser()`). The
296 /// function can be in the same module or in an imported module. The
297 /// export of the function itself stays an unused export.
298 /// `Schema` must come from `effect`, `effect/Schema` or `@effect/schema`.
299 /// Default `false`.
300 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
301 #[schemars(extend("default" = false))]
302 pub schema_exports_as_types: bool,
303}
304
305impl EffectConfig {
306 /// True when no option is set, so serialization can omit the section.
307 #[must_use]
308 pub const fn is_default(&self) -> bool {
309 !self.schema_exports_as_types
310 }
311}
312
313/// The `fix` config section: settings for `fallow fix` apply behavior.
314#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
315#[serde(rename_all = "camelCase")]
316pub struct FixConfig {
317 /// 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.
318 #[serde(default)]
319 pub catalog: CatalogFixConfig,
320}
321
322/// The `fix.catalog` section: how `fallow fix` cleans up unused
323/// `pnpm-workspace.yaml` catalog entries.
324#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
325#[serde(rename_all = "camelCase")]
326pub struct CatalogFixConfig {
327 /// 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.
328 #[serde(default)]
329 pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
330}
331
332/// Value of `fix.catalog.deletePrecedingComments`: what happens to comment
333/// lines directly above a catalog entry that `fallow fix` removes. A
334/// `fallow-keep` marker in the block always preserves it regardless of policy.
335#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
336#[serde(rename_all = "lowercase")]
337pub enum CatalogPrecedingCommentPolicy {
338 /// Delete the adjacent comment block only when heuristics attribute it to
339 /// the entry (preceded by a blank line or directly under the catalog
340 /// header) and it is not a section banner. The default.
341 #[default]
342 Auto,
343 /// Always delete the adjacent comment block with the entry.
344 Always,
345 /// Never delete preceding comments.
346 Never,
347}
348
349/// Completeness policy for opt-in TypeScript semantic analysis.
350#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
351#[serde(rename_all = "kebab-case")]
352pub enum TypeAwareRequire {
353 /// Keep conservative findings and report semantic gaps without failing.
354 #[default]
355 BestEffort,
356 /// Fail the quality gate when any requested semantic query is incomplete.
357 Complete,
358}
359
360impl TypeAwareRequire {
361 /// The policy of a `FALLOW_TYPE_AWARE_REQUIRE` value: `best-effort` or
362 /// `complete`, without case and outer spaces. `None` for another value.
363 #[must_use]
364 pub fn from_env_value(value: &str) -> Option<Self> {
365 match value.trim().to_ascii_lowercase().as_str() {
366 "best-effort" => Some(Self::BestEffort),
367 "complete" => Some(Self::Complete),
368 _ => None,
369 }
370 }
371}
372
373impl From<TypeAwareRequire> for fallow_types::semantic::SemanticCompletenessRequirement {
374 fn from(value: TypeAwareRequire) -> Self {
375 match value {
376 TypeAwareRequire::BestEffort => Self::BestEffort,
377 TypeAwareRequire::Complete => Self::Complete,
378 }
379 }
380}
381
382/// Shared opt-in configuration for TypeScript semantic analysis.
383#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
384#[serde(deny_unknown_fields, rename_all = "camelCase")]
385pub struct TypeAwareConfig {
386 /// Enable the optional TypeScript semantic pass. Disabled by default.
387 #[serde(default)]
388 pub enabled: bool,
389 /// TypeScript project config paths, resolved relative to the project root.
390 #[serde(default, skip_serializing_if = "Vec::is_empty")]
391 pub projects: Vec<String>,
392 /// Decide whether partial semantic analysis is advisory or gating.
393 #[serde(default, skip_serializing_if = "is_default_type_aware_require")]
394 pub require: TypeAwareRequire,
395}
396
397#[expect(
398 clippy::trivially_copy_pass_by_ref,
399 reason = "serde skip_serializing_if callbacks receive field values by reference"
400)]
401fn is_default_type_aware_require(value: &TypeAwareRequire) -> bool {
402 matches!(value, TypeAwareRequire::BestEffort)
403}
404
405impl TypeAwareConfig {
406 /// True when the section equals its default (disabled, no projects,
407 /// best-effort), so serialization can omit it.
408 #[must_use]
409 pub fn is_default(&self) -> bool {
410 !self.enabled && self.projects.is_empty() && self.require == TypeAwareRequire::BestEffort
411 }
412}
413
414/// Schema for `extends`. The loader accepts one string or an array of strings
415/// and normalizes both to a list before it deserializes the config (#3351).
416fn extends_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
417 schemars::json_schema!({
418 "anyOf": [
419 { "type": "string" },
420 { "type": "array", "items": { "type": "string" } }
421 ]
422 })
423}
424
425/// The user-facing fallow configuration as authored in `.fallowrc.json` /
426/// `.fallowrc.jsonc` / `fallow.toml` / `.fallow.toml`.
427///
428/// Every field documents its serialized meaning, default, and precedence
429/// against CLI flags and environment variables where they exist.
430/// `FallowConfig::resolve` compiles the loaded config (globs, regexes,
431/// plugin and rule-pack discovery) into a [`ResolvedConfig`] for analysis.
432/// Unknown keys are rejected at load so typos fail loud.
433#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
434#[serde(deny_unknown_fields, rename_all = "camelCase")]
435// Both `.fallowrc.json` and `.fallowrc.jsonc` are read with the JSONC dialect
436// from `crate::jsonc::parse_options`, so the schema declares the same dialect.
437// JSON language service clients (VS Code, Zed) read these two keywords off the
438// root object and otherwise flag syntax the loader accepts. They are
439// annotations only: nothing in fallow reads them back.
440#[schemars(extend("allowComments" = true, "allowTrailingCommas" = true))]
441pub struct FallowConfig {
442 /// 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.
443 #[serde(rename = "$schema", default, skip_serializing)]
444 pub schema: Option<String>,
445
446 /// 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.
447 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub minimum_version: Option<String>,
449
450 /// 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.
451 #[serde(default, skip_serializing)]
452 #[schemars(schema_with = "extends_schema")]
453 pub extends: Vec<String>,
454
455 /// 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.
456 #[serde(default)]
457 pub entry: Vec<String>,
458
459 /// 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.
460 #[serde(default)]
461 pub ignore_patterns: Vec<String>,
462
463 /// 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.
464 #[serde(default, skip_serializing_if = "Vec::is_empty")]
465 #[schemars(extend("default" = []))]
466 pub support_entry: Vec<String>,
467
468 /// 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.
469 #[serde(default, skip_serializing_if = "Vec::is_empty")]
470 #[schemars(extend("default" = []))]
471 pub ignore_findings: Vec<String>,
472
473 /// 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.
474 #[serde(default)]
475 pub framework: Vec<ExternalPluginDef>,
476
477 /// 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.
478 #[serde(default)]
479 pub workspaces: Option<WorkspaceConfig>,
480
481 /// 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.
482 #[serde(default)]
483 pub ignore_dependencies: Vec<String>,
484
485 /// 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`).
486 #[serde(default, skip_serializing_if = "Vec::is_empty")]
487 #[schemars(extend("default" = []))]
488 pub ignore_binaries: Vec<String>,
489
490 /// 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.
491 #[serde(default, skip_serializing_if = "Vec::is_empty")]
492 #[schemars(extend("default" = []))]
493 pub ignore_command_entries: Vec<String>,
494
495 /// 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.
496 #[serde(default)]
497 pub ignore_unresolved_imports: Vec<String>,
498
499 /// 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.
500 #[serde(default)]
501 pub ignore_exports: Vec<IgnoreExportRule>,
502
503 /// 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.
504 #[serde(default, skip_serializing_if = "Vec::is_empty")]
505 #[schemars(extend("default" = []))]
506 pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
507
508 /// 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"`.
509 #[serde(default, skip_serializing_if = "Vec::is_empty")]
510 #[schemars(extend("default" = []))]
511 pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
512
513 /// 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.
514 #[serde(default)]
515 pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
516
517 /// 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.
518 #[serde(default, skip_serializing_if = "Vec::is_empty")]
519 #[schemars(extend("default" = []))]
520 pub ignore_decorators: Vec<String>,
521
522 /// 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`); patterns matching zero members warn once.
523 #[serde(default)]
524 pub used_class_members: Vec<UsedClassMemberRule>,
525
526 /// 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, 0 = no limit), `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.
527 #[serde(default)]
528 pub duplicates: DuplicatesConfig,
529
530 /// Configures the explicit local `similar-code` candidate workflow:
531 /// `threshold` (0.80, model-specific cosine floor), `minLines` (3), and
532 /// additional `ignore` globs. Provider identity, setup, executables,
533 /// endpoints, credentials, and consent cannot be set by project config.
534 #[serde(default)]
535 pub similar_code: SimilarCodeConfig,
536
537 /// Configures the explicit `fallow mutation` workflow: `runner` (`auto`
538 /// or `vitest`), `operators` (kebab-case names, default the default set),
539 /// `minScore` (0 to 100; a lower score exits with code 1), and
540 /// `concurrency` (half the logical cores). No key starts a run, and the
541 /// side-effect override is a CLI flag only.
542 #[serde(default, skip_serializing_if = "MutationConfig::is_default")]
543 pub mutation: MutationConfig,
544
545 /// 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.
546 #[serde(default)]
547 pub health: HealthConfig,
548
549 /// Opts into TypeScript semantic analysis for project-wide symbol use,
550 /// provenance, API surface, symbol impact, and public-signature coupling.
551 /// This does not surface compiler diagnostics or typed lint rules.
552 #[serde(default, skip_serializing_if = "TypeAwareConfig::is_default")]
553 pub type_aware: TypeAwareConfig,
554
555 /// 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.
556 #[serde(default)]
557 pub rules: RulesConfig,
558
559 #[serde(
560 default,
561 skip_serializing_if = "UnusedComponentPropsConfig::is_default"
562 )]
563 /// 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).
564 pub unused_component_props: UnusedComponentPropsConfig,
565
566 #[serde(
567 default,
568 skip_serializing_if = "CircularDependenciesConfig::is_default"
569 )]
570 /// 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.
571 pub circular_dependencies: CircularDependenciesConfig,
572
573 #[serde(default, skip_serializing_if = "EffectConfig::is_default")]
574 /// 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. Default `false` leaves every report unchanged.
575 pub effect: EffectConfig,
576
577 /// 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).
578 #[serde(default)]
579 pub boundaries: BoundaryConfig,
580
581 /// 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`).
582 #[serde(default)]
583 pub flags: FlagsConfig,
584 /// 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"]`.
585 #[serde(default, skip_serializing_if = "Vec::is_empty")]
586 #[schemars(extend("default" = []))]
587 pub shared_state_allowlist: Vec<[String; 2]>,
588
589 /// 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.
590 #[serde(default)]
591 pub security: SecurityConfig,
592
593 /// 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.
594 #[serde(default)]
595 pub fix: FixConfig,
596
597 /// 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.
598 #[serde(default)]
599 pub resolve: ResolveConfig,
600
601 /// 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).
602 #[serde(default)]
603 pub production: ProductionConfig,
604
605 /// 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).
606 #[serde(default)]
607 pub plugins: Vec<String>,
608
609 /// Paths to declarative rule-pack files (JSON or JSONC), relative to the
610 /// project root. Each pack declares `banned-call`, `banned-import`, or
611 /// `banned-effect` rules that report as `policy-violation` findings. Packs
612 /// are pure data: no project code is executed. Invalid or missing packs
613 /// fail config load.
614 #[serde(default, skip_serializing_if = "Vec::is_empty")]
615 #[schemars(extend("default" = []))]
616 pub rule_packs: Vec<String>,
617
618 /// 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.
619 #[serde(default)]
620 pub dynamically_loaded: Vec<String>,
621
622 /// 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.
623 #[serde(
624 default,
625 skip_serializing_if = "Vec::is_empty",
626 deserialize_with = "markup_extensions::deserialize_markup_extensions"
627 )]
628 #[schemars(extend("default" = []))]
629 pub markup_extensions: Vec<String>,
630
631 /// 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.
632 #[serde(default)]
633 pub overrides: Vec<ConfigOverride>,
634
635 /// A project-root-relative path to a CODEOWNERS file, 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.
636 #[serde(default, skip_serializing_if = "Option::is_none")]
637 pub codeowners: Option<String>,
638
639 /// 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).
640 #[serde(default)]
641 pub public_packages: Vec<String>,
642
643 /// 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.
644 #[serde(default, skip_serializing_if = "Option::is_none")]
645 pub regression: Option<RegressionConfig>,
646
647 /// 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.
648 #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
649 pub audit: AuditConfig,
650
651 /// 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.
652 #[serde(default)]
653 pub sealed: bool,
654
655 /// 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. Boolean, defaults to false; the CLI flag --include-entry-exports applies the same behavior for one run.
656 #[serde(default)]
657 pub include_entry_exports: bool,
658
659 /// 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.
660 #[serde(default)]
661 pub show_cascade: bool,
662
663 /// 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.
664 #[serde(default)]
665 pub auto_imports: bool,
666
667 /// 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.
668 #[serde(default)]
669 pub fail_on_parse_error: bool,
670
671 /// 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`.
672 #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
673 pub cache: CacheConfig,
674}
675
676/// Scopes `fallow security` catalogue behavior. An absent category block admits
677/// every catalogue category. `hardcoded-secret` is include-required and only
678/// runs when explicitly listed in `security.categories.include`.
679#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
680#[serde(deny_unknown_fields, rename_all = "camelCase")]
681pub struct SecurityConfig {
682 /// Include/exclude filter over category ids (e.g. `dangerous-html`).
683 #[serde(default, skip_serializing_if = "Option::is_none")]
684 pub categories: Option<SecurityCategories>,
685 /// Additional project-local names for HTTP request objects. These names
686 /// extend the built-in receiver allowlist for `*.query`, `*.params`, and
687 /// `*.body` source patterns. They do not replace the built-ins and do not
688 /// gate `*.searchParams`, which intentionally stays ungated.
689 #[serde(default, skip_serializing_if = "Vec::is_empty")]
690 pub request_receivers: Vec<String>,
691}
692
693impl SecurityConfig {
694 /// The configured `requestReceivers` trimmed, lowercased, and deduplicated
695 /// in first-seen order, with empty entries dropped; the form the matcher
696 /// compares receiver names against (matching is case-insensitive).
697 #[must_use]
698 pub fn normalized_request_receivers(&self) -> Vec<String> {
699 let mut receivers = Vec::new();
700 for receiver in &self.request_receivers {
701 let normalized = receiver.trim().to_ascii_lowercase();
702 if !normalized.is_empty() && !receivers.contains(&normalized) {
703 receivers.push(normalized);
704 }
705 }
706 receivers
707 }
708
709 /// False when any configured receiver is empty or whitespace-only, which
710 /// config validation reports as an error instead of silently dropping it.
711 #[must_use]
712 pub fn request_receivers_are_valid(&self) -> bool {
713 self.request_receivers
714 .iter()
715 .all(|receiver| !receiver.trim().is_empty())
716 }
717}
718
719/// Include/exclude lists scoping the active security categories. When `include`
720/// is set, only those categories are active; `exclude` removes categories from
721/// the admitted set. Both unset admits catalogue categories. `hardcoded-secret`
722/// still requires explicit inclusion.
723#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
724#[serde(deny_unknown_fields, rename_all = "camelCase")]
725pub struct SecurityCategories {
726 /// Catalogue category ids to admit. When set, all others are excluded.
727 #[serde(default, skip_serializing_if = "Option::is_none")]
728 pub include: Option<Vec<String>>,
729 /// Catalogue category ids to remove from the admitted set.
730 #[serde(default, skip_serializing_if = "Option::is_none")]
731 pub exclude: Option<Vec<String>>,
732}
733
734/// The `cache` config section: location and size ceiling of fallow's
735/// persistent caches (default directory `<root>/.fallow`).
736#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
737#[serde(deny_unknown_fields, rename_all = "camelCase")]
738pub struct CacheConfig {
739 /// Directory for fallow's persistent analysis cache. Relative paths resolve
740 /// from the project root. The directory must be inside the project: an
741 /// absolute path or a path that leaves the root is ignored with a
742 /// warning. Use `FALLOW_CACHE_DIR` to put the cache outside the project.
743 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub dir: Option<PathBuf>,
745 /// Maximum size of the persistent extraction cache, in megabytes.
746 /// Default 256.
747 #[serde(default, skip_serializing_if = "Option::is_none")]
748 #[schemars(extend("default" = 256))]
749 pub max_size_mb: Option<u32>,
750}
751
752impl CacheConfig {
753 /// True when neither field is set, so serialization can omit the section.
754 #[must_use]
755 pub fn is_default(&self) -> bool {
756 self.dir.is_none() && self.max_size_mb.is_none()
757 }
758}
759
760/// The analysis families production mode can be scoped to independently via
761/// the object form of the `production` config key.
762#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub enum ProductionAnalysis {
764 /// Unused files/exports/dependencies detection.
765 DeadCode,
766 /// Complexity and health scoring.
767 Health,
768 /// Clone detection.
769 Dupes,
770}
771
772/// Value of the `production` config key: excludes test/spec/story/dev files
773/// from discovery, either globally or per analysis family.
774#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
775#[serde(untagged)]
776pub enum ProductionConfig {
777 /// Boolean form applying to every analysis. The default is `false`.
778 Global(bool),
779 /// Object form (`{ deadCode?, health?, dupes?, ignore? }`) scoping
780 /// production mode per analysis family.
781 PerAnalysis(PerAnalysisProductionConfig),
782}
783
784impl<'de> Deserialize<'de> for ProductionConfig {
785 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
786 where
787 D: Deserializer<'de>,
788 {
789 struct ProductionConfigVisitor;
790
791 impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
792 type Value = ProductionConfig;
793
794 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
795 formatter.write_str("a boolean or per-analysis production config object")
796 }
797
798 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
799 where
800 E: serde::de::Error,
801 {
802 Ok(ProductionConfig::Global(value))
803 }
804
805 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
806 where
807 A: serde::de::MapAccess<'de>,
808 {
809 PerAnalysisProductionConfig::deserialize(
810 serde::de::value::MapAccessDeserializer::new(map),
811 )
812 .map(ProductionConfig::PerAnalysis)
813 }
814 }
815
816 deserializer.deserialize_any(ProductionConfigVisitor)
817 }
818}
819
820impl Default for ProductionConfig {
821 fn default() -> Self {
822 Self::Global(false)
823 }
824}
825
826impl From<bool> for ProductionConfig {
827 fn from(value: bool) -> Self {
828 Self::Global(value)
829 }
830}
831
832impl Not for ProductionConfig {
833 type Output = bool;
834
835 fn not(self) -> Self::Output {
836 !self.any_enabled()
837 }
838}
839
840impl Not for &ProductionConfig {
841 type Output = bool;
842
843 fn not(self) -> Self::Output {
844 !self.any_enabled()
845 }
846}
847
848impl ProductionConfig {
849 /// Whether production mode applies to `analysis` under this config.
850 #[must_use]
851 pub const fn for_analysis(&self, analysis: ProductionAnalysis) -> bool {
852 match self {
853 Self::Global(value) => *value,
854 Self::PerAnalysis(config) => match analysis {
855 ProductionAnalysis::DeadCode => config.dead_code,
856 ProductionAnalysis::Health => config.health,
857 ProductionAnalysis::Dupes => config.dupes,
858 },
859 }
860 }
861
862 /// The boolean form's value. The per-analysis form counts as global
863 /// production mode only when it turns on every analysis family.
864 #[must_use]
865 pub const fn global(&self) -> bool {
866 match self {
867 Self::Global(value) => *value,
868 Self::PerAnalysis(config) => config.dead_code && config.health && config.dupes,
869 }
870 }
871
872 /// Whether production mode is enabled for at least one analysis family.
873 #[must_use]
874 pub const fn any_enabled(&self) -> bool {
875 match self {
876 Self::Global(value) => *value,
877 Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
878 }
879 }
880
881 /// The `ignore` globs of the object form. The boolean form has none.
882 #[must_use]
883 pub fn ignore(&self) -> &[String] {
884 match self {
885 Self::Global(_) => &[],
886 Self::PerAnalysis(config) => &config.ignore,
887 }
888 }
889
890 /// The config of one run, with production mode set to `enabled` for every
891 /// analysis family. The `ignore` globs stay, so a run in production mode
892 /// still drops them when a CLI flag or one analysis selects the mode.
893 #[must_use]
894 pub fn for_run(&self, enabled: bool) -> Self {
895 let ignore = self.ignore();
896 if ignore.is_empty() {
897 return Self::Global(enabled);
898 }
899 Self::PerAnalysis(PerAnalysisProductionConfig {
900 dead_code: enabled,
901 health: enabled,
902 dupes: enabled,
903 ignore: ignore.to_vec(),
904 })
905 }
906}
907
908/// Object form of the `production` config key, scoping production mode to
909/// individual analysis families in combined `fallow` and `fallow audit`.
910#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
911#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
912pub struct PerAnalysisProductionConfig {
913 /// 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.
914 pub dead_code: bool,
915 /// 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.
916 pub health: bool,
917 /// 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.
918 pub dupes: bool,
919 /// 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.
920 #[serde(default, skip_serializing_if = "Vec::is_empty")]
921 pub ignore: Vec<String>,
922}
923
924/// The `audit` config section: in-repo defaults for `fallow audit`, each
925/// overridable by its matching CLI flag.
926#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
927#[serde(rename_all = "camelCase")]
928pub struct AuditConfig {
929 /// 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.
930 #[serde(default, skip_serializing_if = "AuditGate::is_default")]
931 pub gate: AuditGate,
932
933 /// 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.
934 #[serde(default, skip_serializing_if = "AuditWorsened::is_default")]
935 pub worsened: AuditWorsened,
936
937 /// 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.
938 #[serde(default, skip_serializing_if = "Option::is_none")]
939 pub dead_code: Option<bool>,
940
941 /// 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.
942 #[serde(default, skip_serializing_if = "Option::is_none")]
943 pub health: Option<bool>,
944
945 /// 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.
946 #[serde(default, skip_serializing_if = "Option::is_none")]
947 pub dupes: Option<bool>,
948
949 /// 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.
950 #[serde(default, skip_serializing_if = "Option::is_none")]
951 pub css: Option<bool>,
952
953 /// 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.
954 #[serde(default, skip_serializing_if = "Option::is_none")]
955 pub css_deep: Option<bool>,
956
957 /// 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`.
958 #[serde(default, skip_serializing_if = "Option::is_none")]
959 pub dead_code_baseline: Option<String>,
960
961 /// 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.
962 #[serde(default, skip_serializing_if = "Option::is_none")]
963 pub health_baseline: Option<String>,
964
965 /// 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.
966 #[serde(default, skip_serializing_if = "Option::is_none")]
967 pub dupes_baseline: Option<String>,
968
969 /// 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.
970 #[serde(default, skip_serializing_if = "Option::is_none")]
971 pub cache_max_age_days: Option<u32>,
972
973 /// 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.
974 #[serde(default, skip_serializing_if = "Option::is_none")]
975 pub type_aware: Option<bool>,
976}
977
978impl AuditConfig {
979 /// True when every field is unset, so serialization can omit the section.
980 #[must_use]
981 pub fn is_empty(&self) -> bool {
982 self.gate.is_default()
983 && self.worsened.is_default()
984 && self.dead_code.is_none()
985 && self.health.is_none()
986 && self.dupes.is_none()
987 && self.css.is_none()
988 && self.css_deep.is_none()
989 && self.dead_code_baseline.is_none()
990 && self.health_baseline.is_none()
991 && self.dupes_baseline.is_none()
992 && self.cache_max_age_days.is_none()
993 && self.type_aware.is_none()
994 }
995}
996
997/// Value of `audit.gate`: which findings drive the `fallow audit` verdict.
998#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
999#[serde(rename_all = "kebab-case")]
1000pub enum AuditGate {
1001 /// Fail only on findings the current changeset introduced, determined by
1002 /// a base-snapshot attribution pass. An unused file or unused export
1003 /// outside the changed files counts when the base does not report it.
1004 /// The default.
1005 #[default]
1006 NewOnly,
1007 /// Fail on every finding in changed files, skipping the attribution pass.
1008 All,
1009}
1010
1011impl AuditGate {
1012 /// True for the default `new-only` gate, so serialization can omit it.
1013 #[must_use]
1014 pub const fn is_default(&self) -> bool {
1015 matches!(self, Self::NewOnly)
1016 }
1017}
1018
1019/// Value of `audit.worsened`: how a worsened complexity finding affects the
1020/// `fallow audit` verdict.
1021#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
1022#[serde(rename_all = "kebab-case")]
1023pub enum AuditWorsened {
1024 /// A worsened finding makes the verdict at least `warn` and does not fail
1025 /// the run. The default.
1026 #[default]
1027 Warn,
1028 /// A worsened finding counts like an introduced finding.
1029 Error,
1030 /// Growth only in metrics that the finding does not exceed stays
1031 /// inherited. Growth of an exceeded metric stays worsened and gives at
1032 /// least `warn`.
1033 Off,
1034}
1035
1036impl AuditWorsened {
1037 /// True for the default `warn` mode, so serialization can omit it.
1038 #[must_use]
1039 pub const fn is_default(&self) -> bool {
1040 matches!(self, Self::Warn)
1041 }
1042}
1043
1044/// The `regression` config section holding the saved issue-count baseline for
1045/// the `--fail-on-regression` gate.
1046#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
1047#[serde(rename_all = "camelCase")]
1048pub struct RegressionConfig {
1049 /// 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.
1050 #[serde(default, skip_serializing_if = "Option::is_none")]
1051 pub baseline: Option<RegressionBaseline>,
1052}
1053
1054#[expect(
1055 clippy::trivially_copy_pass_by_ref,
1056 reason = "serde skip_serializing_if requires a reference"
1057)]
1058const fn is_zero_count(count: &usize) -> bool {
1059 *count == 0
1060}
1061
1062/// Saved per-issue-type counts written by `--save-baseline` and compared by
1063/// `--fail-on-regression`. Every count defaults to `0` when its key is missing,
1064/// so hand-trimmed baselines stay loadable.
1065#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
1066#[serde(rename_all = "camelCase")]
1067pub struct RegressionBaseline {
1068 /// Baseline count of optional component prop review candidates.
1069 #[serde(default)]
1070 pub absent_component_props: usize,
1071
1072 /// Baseline count of constant parameter review candidates. Absent while
1073 /// zero, so a baseline without the opt-in rule keeps its shape.
1074 #[serde(default, skip_serializing_if = "is_zero_count")]
1075 pub constant_parameters: usize,
1076
1077 /// Compatibility identity for the analysis that produced these counts.
1078 /// Missing values in existing configs are treated as syntactic.
1079 #[serde(default)]
1080 pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
1081 /// Baseline count across all issue types.
1082 #[serde(default)]
1083 pub total_issues: usize,
1084 /// Baseline count of `unused-files` findings.
1085 #[serde(default)]
1086 pub unused_files: usize,
1087 /// Baseline count of `unused-exports` findings.
1088 #[serde(default)]
1089 pub unused_exports: usize,
1090 /// Baseline count of `unused-types` findings.
1091 #[serde(default)]
1092 pub unused_types: usize,
1093 /// Baseline count of `unused-dependencies` findings.
1094 #[serde(default)]
1095 pub unused_dependencies: usize,
1096 /// Baseline count of `unused-dev-dependencies` findings.
1097 #[serde(default)]
1098 pub unused_dev_dependencies: usize,
1099 /// Baseline count of `unused-optional-dependencies` findings.
1100 #[serde(default)]
1101 pub unused_optional_dependencies: usize,
1102 /// Baseline count of `unused-enum-members` findings.
1103 #[serde(default)]
1104 pub unused_enum_members: usize,
1105 /// Baseline count of `unused-class-members` findings.
1106 #[serde(default)]
1107 pub unused_class_members: usize,
1108 /// Baseline count of `unresolved-imports` findings.
1109 #[serde(default)]
1110 pub unresolved_imports: usize,
1111 /// Baseline count of `unlisted-dependencies` findings.
1112 #[serde(default)]
1113 pub unlisted_dependencies: usize,
1114 /// Baseline count of `unlisted-binaries` findings.
1115 #[serde(default)]
1116 pub unlisted_binaries: usize,
1117 /// Baseline count of `duplicate-exports` findings.
1118 #[serde(default)]
1119 pub duplicate_exports: usize,
1120 /// Baseline count of `circular-dependencies` findings.
1121 #[serde(default)]
1122 pub circular_dependencies: usize,
1123 /// Baseline count of `re-export-cycle` findings.
1124 #[serde(default)]
1125 pub re_export_cycles: usize,
1126 /// Baseline count of `package-cycle` findings.
1127 #[serde(default)]
1128 pub package_cycles: usize,
1129 /// Baseline count of `type-only-dependencies` findings.
1130 #[serde(default)]
1131 pub type_only_dependencies: usize,
1132 /// Baseline count of `test-only-dependencies` findings.
1133 #[serde(default)]
1134 pub test_only_dependencies: usize,
1135 /// Baseline count of `dev-dependencies-in-production` findings.
1136 #[serde(default)]
1137 pub dev_dependencies_in_production: usize,
1138 /// Baseline count of `boundary-violation` findings.
1139 #[serde(default)]
1140 pub boundary_violations: usize,
1141 /// Baseline count of boundary-coverage-violation findings.
1142 #[serde(default)]
1143 pub boundary_coverage_violations: usize,
1144 /// Baseline count of boundary-call-violation findings.
1145 #[serde(default)]
1146 pub boundary_call_violations: usize,
1147 /// Baseline count of `policy-violation` findings.
1148 #[serde(default)]
1149 pub policy_violations: usize,
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154 use super::*;
1155
1156 #[test]
1157 fn regression_baseline_preserves_absent_component_prop_count() {
1158 let baseline: RegressionBaseline =
1159 serde_json::from_value(serde_json::json!({"absentComponentProps":7})).unwrap();
1160 assert_eq!(
1161 serde_json::to_value(baseline).unwrap()["absentComponentProps"],
1162 7
1163 );
1164 }
1165
1166 #[test]
1167 fn default_config_has_empty_collections() {
1168 let config = FallowConfig::default();
1169 assert!(config.schema.is_none());
1170 assert!(config.extends.is_empty());
1171 assert!(config.entry.is_empty());
1172 assert!(config.ignore_patterns.is_empty());
1173 assert!(config.ignore_findings.is_empty());
1174 assert!(config.framework.is_empty());
1175 assert!(config.workspaces.is_none());
1176 assert!(config.ignore_dependencies.is_empty());
1177 assert!(config.ignore_exports.is_empty());
1178 assert!(config.used_class_members.is_empty());
1179 assert!(config.plugins.is_empty());
1180 assert!(config.dynamically_loaded.is_empty());
1181 assert!(config.overrides.is_empty());
1182 assert!(config.public_packages.is_empty());
1183 assert_eq!(
1184 config.fix.catalog.delete_preceding_comments,
1185 CatalogPrecedingCommentPolicy::Auto
1186 );
1187 assert!(!config.production);
1188 }
1189
1190 #[test]
1191 fn deserialize_empty_json_object() {
1192 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1193 assert!(config.entry.is_empty());
1194 assert!(!config.production);
1195 assert!(!config.type_aware.enabled);
1196 assert_eq!(config.type_aware.require, TypeAwareRequire::BestEffort);
1197 }
1198
1199 #[test]
1200 fn deserialize_type_aware_config() {
1201 let config: FallowConfig = serde_json::from_str(
1202 r#"{"typeAware":{"enabled":true,"projects":["tsconfig.app.json"],"require":"complete"}}"#,
1203 )
1204 .unwrap();
1205
1206 assert!(config.type_aware.enabled);
1207 assert_eq!(config.type_aware.projects, ["tsconfig.app.json"]);
1208 assert_eq!(config.type_aware.require, TypeAwareRequire::Complete);
1209 }
1210
1211 #[test]
1212 fn deserialize_type_aware_config_rejects_unknown_fields() {
1213 let result = serde_json::from_str::<FallowConfig>(
1214 r#"{"typeAware":{"enabled":true,"compilerDiagnostics":true}}"#,
1215 );
1216 assert!(result.is_err());
1217 }
1218
1219 #[test]
1220 fn deserialize_json_with_all_top_level_fields() {
1221 let json = r#"{
1222 "$schema": "./node_modules/fallow/schema.json",
1223 "entry": ["src/main.ts"],
1224 "ignorePatterns": ["generated/**"],
1225 "ignoreFindings": ["**/*.test.ts", "!src/public/**"],
1226 "ignoreDependencies": ["postcss"],
1227 "production": true,
1228 "plugins": ["custom-plugin.toml"],
1229 "rules": {"unused-files": "warn"},
1230 "duplicates": {"enabled": false},
1231 "health": {"maxCyclomatic": 30}
1232 }"#;
1233 let config: FallowConfig = serde_json::from_str(json).unwrap();
1234 assert_eq!(
1235 config.schema.as_deref(),
1236 Some("./node_modules/fallow/schema.json")
1237 );
1238 assert_eq!(config.entry, vec!["src/main.ts"]);
1239 assert_eq!(config.ignore_patterns, vec!["generated/**"]);
1240 assert_eq!(
1241 config.ignore_findings,
1242 vec!["**/*.test.ts", "!src/public/**"]
1243 );
1244 assert_eq!(config.ignore_dependencies, vec!["postcss"]);
1245 assert!(config.production);
1246 assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
1247 assert_eq!(config.rules.unused_files, Severity::Warn);
1248 assert!(!config.duplicates.enabled);
1249 assert_eq!(config.health.max_cyclomatic, 30);
1250 }
1251
1252 #[test]
1253 fn deserialize_json_deny_unknown_fields() {
1254 let json = r#"{"unknownField": true}"#;
1255 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1256 assert!(result.is_err(), "unknown fields should be rejected");
1257 }
1258
1259 #[test]
1260 fn ignore_findings_serialization_is_canonical_and_sparse() {
1261 let default_value = serde_json::to_value(FallowConfig::default()).unwrap();
1262 assert!(default_value.get("ignoreFindings").is_none());
1263
1264 let config = FallowConfig {
1265 ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
1266 ..Default::default()
1267 };
1268 let value = serde_json::to_value(config).unwrap();
1269 assert_eq!(
1270 value.get("ignoreFindings"),
1271 Some(&serde_json::json!(["**/*.test.ts", "!src/public/**"]))
1272 );
1273 }
1274
1275 #[test]
1276 fn ignore_findings_deserializes_from_toml() {
1277 let config: FallowConfig =
1278 toml::from_str(r#"ignoreFindings = ["**/*.test.ts", "!src/public/**"]"#).unwrap();
1279
1280 assert_eq!(
1281 config.ignore_findings,
1282 vec!["**/*.test.ts", "!src/public/**"]
1283 );
1284 }
1285
1286 #[test]
1287 fn generic_ignore_alias_is_rejected() {
1288 let result = serde_json::from_str::<FallowConfig>(r#"{"ignore": ["**/*.test.ts"]}"#);
1289
1290 assert!(result.is_err());
1291 }
1292
1293 #[test]
1294 fn deserialize_json_production_mode_default_false() {
1295 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1296 assert!(!config.production);
1297 }
1298
1299 #[test]
1300 fn deserialize_json_production_mode_true() {
1301 let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
1302 assert!(config.production);
1303 }
1304
1305 #[test]
1306 fn deserialize_json_per_analysis_production_mode() {
1307 let config: FallowConfig = serde_json::from_str(
1308 r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
1309 )
1310 .unwrap();
1311 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1312 assert!(config.production.for_analysis(ProductionAnalysis::Health));
1313 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1314 }
1315
1316 #[test]
1317 fn deserialize_json_production_ignore() {
1318 let config: FallowConfig =
1319 serde_json::from_str(r#"{"production": {"deadCode": true, "ignore": ["scripts/**"]}}"#)
1320 .unwrap();
1321 assert!(config.production.for_analysis(ProductionAnalysis::DeadCode));
1322 assert_eq!(config.production.ignore(), ["scripts/**".to_string()]);
1323 assert!(
1324 ProductionConfig::Global(true).ignore().is_empty(),
1325 "the boolean form has no ignore globs"
1326 );
1327 }
1328
1329 #[test]
1330 fn production_for_run_keeps_ignore_globs() {
1331 let config: FallowConfig =
1332 serde_json::from_str(r#"{"production": {"ignore": ["scripts/**"]}}"#).unwrap();
1333 let on = config.production.for_run(true);
1334 assert!(on.global());
1335 assert_eq!(on.ignore(), ["scripts/**".to_string()]);
1336 let off = config.production.for_run(false);
1337 assert!(!off.any_enabled());
1338 assert_eq!(off.ignore(), ["scripts/**".to_string()]);
1339 assert_eq!(
1340 ProductionConfig::Global(false).for_run(true),
1341 ProductionConfig::Global(true),
1342 "a config without ignore globs keeps the boolean form"
1343 );
1344 }
1345
1346 #[test]
1347 fn production_global_needs_every_analysis_in_the_object_form() {
1348 let partial: FallowConfig =
1349 serde_json::from_str(r#"{"production": {"deadCode": true, "health": true}}"#).unwrap();
1350 assert!(!partial.production.global());
1351 let all: FallowConfig = serde_json::from_str(
1352 r#"{"production": {"deadCode": true, "health": true, "dupes": true}}"#,
1353 )
1354 .unwrap();
1355 assert!(all.production.global());
1356 }
1357
1358 #[test]
1359 fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
1360 let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
1361 .unwrap_err();
1362 assert!(
1363 err.to_string().contains("healthTypo"),
1364 "error should name the unknown field: {err}"
1365 );
1366 }
1367
1368 #[test]
1369 fn deserialize_json_dynamically_loaded() {
1370 let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
1371 let config: FallowConfig = serde_json::from_str(json).unwrap();
1372 assert_eq!(
1373 config.dynamically_loaded,
1374 vec!["plugins/**/*.ts", "locales/**/*.json"]
1375 );
1376 }
1377
1378 #[test]
1379 fn deserialize_json_dynamically_loaded_defaults_empty() {
1380 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1381 assert!(config.dynamically_loaded.is_empty());
1382 }
1383
1384 #[test]
1385 fn deserialize_json_fix_catalog_delete_preceding_comments() {
1386 let config: FallowConfig =
1387 serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
1388 .unwrap();
1389 assert_eq!(
1390 config.fix.catalog.delete_preceding_comments,
1391 CatalogPrecedingCommentPolicy::Always
1392 );
1393 }
1394
1395 #[test]
1396 fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
1397 let err = serde_json::from_str::<FallowConfig>(
1398 r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
1399 )
1400 .unwrap_err();
1401 assert!(
1402 err.to_string().contains("sometimes"),
1403 "error should name the bad policy: {err}"
1404 );
1405 }
1406
1407 #[test]
1408 fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
1409 let json = r#"{
1410 "usedClassMembers": [
1411 "agInit",
1412 { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
1413 { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
1414 ]
1415 }"#;
1416 let config: FallowConfig = serde_json::from_str(json).unwrap();
1417 assert_eq!(
1418 config.used_class_members,
1419 vec![
1420 UsedClassMemberRule::from("agInit"),
1421 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1422 extends: None,
1423 implements: Some("ICellRendererAngularComp".to_string()),
1424 members: vec!["refresh".to_string()],
1425 }),
1426 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1427 extends: Some("BaseCommand".to_string()),
1428 implements: Some("CanActivate".to_string()),
1429 members: vec!["execute".to_string()],
1430 }),
1431 ]
1432 );
1433 }
1434
1435 #[test]
1436 fn deserialize_toml_minimal() {
1437 let toml_str = r#"
1438entry = ["src/index.ts"]
1439production = true
1440"#;
1441 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1442 assert_eq!(config.entry, vec!["src/index.ts"]);
1443 assert!(config.production);
1444 }
1445
1446 #[test]
1447 fn workspaces_packages_key_is_accepted_as_patterns_alias() {
1448 // An older `fallow init --toml` wrote `[workspaces]` with a `packages`
1449 // key; the back-compat serde alias keeps those existing configs scoping
1450 // instead of silently dropping the (unknown) key and losing the patterns.
1451 let config: FallowConfig =
1452 toml::from_str("[workspaces]\npackages = [\"packages/*\", \"apps/*\"]").unwrap();
1453 assert_eq!(
1454 config.workspaces.map(|w| w.patterns).unwrap_or_default(),
1455 vec!["packages/*".to_string(), "apps/*".to_string()],
1456 "the `packages` alias must populate `patterns`"
1457 );
1458 }
1459
1460 #[test]
1461 fn deserialize_toml_per_analysis_production_mode() {
1462 let toml_str = r"
1463[production]
1464deadCode = false
1465health = true
1466dupes = false
1467";
1468 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1469 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1470 assert!(config.production.for_analysis(ProductionAnalysis::Health));
1471 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1472 }
1473
1474 #[test]
1475 fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
1476 let err = toml::from_str::<FallowConfig>(
1477 r"
1478[production]
1479healthTypo = true
1480",
1481 )
1482 .unwrap_err();
1483 assert!(
1484 err.to_string().contains("healthTypo"),
1485 "error should name the unknown field: {err}"
1486 );
1487 }
1488
1489 #[test]
1490 fn deserialize_toml_with_inline_framework() {
1491 let toml_str = r#"
1492[[framework]]
1493name = "my-framework"
1494enablers = ["my-framework-pkg"]
1495entryPoints = ["src/routes/**/*.tsx"]
1496"#;
1497 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1498 assert_eq!(config.framework.len(), 1);
1499 assert_eq!(config.framework[0].name, "my-framework");
1500 assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
1501 assert_eq!(
1502 config.framework[0].entry_points,
1503 vec!["src/routes/**/*.tsx"]
1504 );
1505 }
1506
1507 #[test]
1508 fn deserialize_toml_fix_catalog_delete_preceding_comments() {
1509 let toml_str = r#"
1510[fix.catalog]
1511deletePrecedingComments = "never"
1512"#;
1513 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1514 assert_eq!(
1515 config.fix.catalog.delete_preceding_comments,
1516 CatalogPrecedingCommentPolicy::Never
1517 );
1518 }
1519
1520 #[test]
1521 fn deserialize_toml_with_workspace_config() {
1522 let toml_str = r#"
1523[workspaces]
1524patterns = ["packages/*", "apps/*"]
1525[workspaces.changedSince]
1526"packages/web" = "main"
1527"packages/legacy" = "release/2024.10"
1528"#;
1529 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1530 assert!(config.workspaces.is_some());
1531 let ws = config.workspaces.unwrap();
1532 assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
1533 assert_eq!(ws.changed_since["packages/web"], "main");
1534 assert_eq!(ws.changed_since["packages/legacy"], "release/2024.10");
1535 }
1536
1537 #[test]
1538 fn deserialize_toml_with_ignore_exports() {
1539 let toml_str = r#"
1540[[ignoreExports]]
1541file = "src/types/**/*.ts"
1542exports = ["*"]
1543"#;
1544 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1545 assert_eq!(config.ignore_exports.len(), 1);
1546 assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
1547 assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
1548 }
1549
1550 #[test]
1551 fn deserialize_toml_used_class_members_supports_scoped_rules() {
1552 let toml_str = r#"
1553usedClassMembers = [
1554 { implements = "ICellRendererAngularComp", members = ["refresh"] },
1555 { extends = "BaseCommand", members = ["execute"] },
1556]
1557"#;
1558 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1559 assert_eq!(
1560 config.used_class_members,
1561 vec![
1562 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1563 extends: None,
1564 implements: Some("ICellRendererAngularComp".to_string()),
1565 members: vec!["refresh".to_string()],
1566 }),
1567 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1568 extends: Some("BaseCommand".to_string()),
1569 implements: None,
1570 members: vec!["execute".to_string()],
1571 }),
1572 ]
1573 );
1574 }
1575
1576 #[test]
1577 fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
1578 let result = serde_json::from_str::<FallowConfig>(
1579 r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
1580 );
1581 assert!(
1582 result.is_err(),
1583 "unconstrained scoped rule should be rejected"
1584 );
1585 }
1586
1587 #[test]
1588 fn deserialize_ignore_exports_used_in_file_bool() {
1589 let config: FallowConfig =
1590 serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
1591
1592 assert!(config.ignore_exports_used_in_file.suppresses(false));
1593 assert!(config.ignore_exports_used_in_file.suppresses(true));
1594 }
1595
1596 #[test]
1597 fn deserialize_effect_schema_exports_as_types() {
1598 let default: FallowConfig = serde_json::from_str("{}").unwrap();
1599 assert!(!default.effect.schema_exports_as_types);
1600 assert!(
1601 !serde_json::to_string(&default)
1602 .unwrap()
1603 .contains("\"effect\""),
1604 "the default section is not serialized"
1605 );
1606
1607 let config: FallowConfig =
1608 serde_json::from_str(r#"{"effect":{"schemaExportsAsTypes":true}}"#).unwrap();
1609 assert!(config.effect.schema_exports_as_types);
1610
1611 let toml: FallowConfig = toml::from_str("[effect]\nschemaExportsAsTypes = true\n").unwrap();
1612 assert!(toml.effect.schema_exports_as_types);
1613
1614 let typo = serde_json::from_str::<FallowConfig>(r#"{"effect":{"schemaExports":true}}"#);
1615 assert!(typo.is_err(), "an unknown effect key fails the load");
1616 }
1617
1618 #[test]
1619 fn deserialize_ignore_exports_used_in_file_kind_form() {
1620 let config: FallowConfig =
1621 serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
1622
1623 assert!(!config.ignore_exports_used_in_file.suppresses(false));
1624 assert!(config.ignore_exports_used_in_file.suppresses(true));
1625 }
1626
1627 #[test]
1628 fn deserialize_toml_deny_unknown_fields() {
1629 let toml_str = r"bogus_field = true";
1630 let result: Result<FallowConfig, _> = toml::from_str(toml_str);
1631 assert!(result.is_err(), "unknown fields should be rejected");
1632 }
1633
1634 #[test]
1635 fn json_serialize_roundtrip() {
1636 let config = FallowConfig {
1637 entry: vec!["src/main.ts".to_string()],
1638 production: true.into(),
1639 ..FallowConfig::default()
1640 };
1641 let json = serde_json::to_string(&config).unwrap();
1642 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1643 assert_eq!(restored.entry, vec!["src/main.ts"]);
1644 assert!(restored.production);
1645 }
1646
1647 #[test]
1648 fn schema_field_not_serialized() {
1649 let config = FallowConfig {
1650 schema: Some("https://example.com/schema.json".to_string()),
1651 ..FallowConfig::default()
1652 };
1653 let json = serde_json::to_string(&config).unwrap();
1654 assert!(
1655 !json.contains("$schema"),
1656 "schema field should be skipped in serialization"
1657 );
1658 }
1659
1660 #[test]
1661 fn extends_field_not_serialized() {
1662 let config = FallowConfig {
1663 extends: vec!["base.json".to_string()],
1664 ..FallowConfig::default()
1665 };
1666 let json = serde_json::to_string(&config).unwrap();
1667 assert!(
1668 !json.contains("extends"),
1669 "extends field should be skipped in serialization"
1670 );
1671 }
1672
1673 #[test]
1674 fn regression_config_deserialize_json() {
1675 let json = r#"{
1676 "regression": {
1677 "baseline": {
1678 "totalIssues": 42,
1679 "unusedFiles": 10,
1680 "unusedExports": 5,
1681 "circularDependencies": 2
1682 }
1683 }
1684 }"#;
1685 let config: FallowConfig = serde_json::from_str(json).unwrap();
1686 let regression = config.regression.unwrap();
1687 let baseline = regression.baseline.unwrap();
1688 assert_eq!(baseline.total_issues, 42);
1689 assert_eq!(baseline.unused_files, 10);
1690 assert_eq!(baseline.unused_exports, 5);
1691 assert_eq!(baseline.circular_dependencies, 2);
1692 assert_eq!(baseline.unused_types, 0);
1693 assert_eq!(baseline.boundary_violations, 0);
1694 }
1695
1696 #[test]
1697 fn regression_config_defaults_to_none() {
1698 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1699 assert!(config.regression.is_none());
1700 }
1701
1702 #[test]
1703 fn regression_baseline_all_zeros_by_default() {
1704 let baseline = RegressionBaseline::default();
1705 assert_eq!(baseline.total_issues, 0);
1706 assert_eq!(baseline.unused_files, 0);
1707 assert_eq!(baseline.unused_exports, 0);
1708 assert_eq!(baseline.unused_types, 0);
1709 assert_eq!(baseline.unused_dependencies, 0);
1710 assert_eq!(baseline.unused_dev_dependencies, 0);
1711 assert_eq!(baseline.unused_optional_dependencies, 0);
1712 assert_eq!(baseline.unused_enum_members, 0);
1713 assert_eq!(baseline.unused_class_members, 0);
1714 assert_eq!(baseline.unresolved_imports, 0);
1715 assert_eq!(baseline.unlisted_dependencies, 0);
1716 assert_eq!(baseline.duplicate_exports, 0);
1717 assert_eq!(baseline.circular_dependencies, 0);
1718 assert_eq!(baseline.type_only_dependencies, 0);
1719 assert_eq!(baseline.test_only_dependencies, 0);
1720 assert_eq!(baseline.boundary_violations, 0);
1721 }
1722
1723 #[test]
1724 fn regression_config_serialize_roundtrip() {
1725 let baseline = RegressionBaseline {
1726 total_issues: 100,
1727 unused_files: 20,
1728 unused_exports: 30,
1729 ..RegressionBaseline::default()
1730 };
1731 let regression = RegressionConfig {
1732 baseline: Some(baseline),
1733 };
1734 let config = FallowConfig {
1735 regression: Some(regression),
1736 ..FallowConfig::default()
1737 };
1738 let json = serde_json::to_string(&config).unwrap();
1739 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1740 let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1741 assert_eq!(restored_baseline.total_issues, 100);
1742 assert_eq!(restored_baseline.unused_files, 20);
1743 assert_eq!(restored_baseline.unused_exports, 30);
1744 assert_eq!(restored_baseline.unused_types, 0);
1745 }
1746
1747 #[test]
1748 fn regression_config_empty_baseline_deserialize() {
1749 let json = r#"{"regression": {}}"#;
1750 let config: FallowConfig = serde_json::from_str(json).unwrap();
1751 let regression = config.regression.unwrap();
1752 assert!(regression.baseline.is_none());
1753 }
1754
1755 #[test]
1756 fn regression_baseline_not_serialized_when_none() {
1757 let config = FallowConfig {
1758 regression: None,
1759 ..FallowConfig::default()
1760 };
1761 let json = serde_json::to_string(&config).unwrap();
1762 assert!(
1763 !json.contains("regression"),
1764 "regression should be skipped when None"
1765 );
1766 }
1767
1768 #[test]
1769 fn deserialize_json_with_overrides() {
1770 let json = r#"{
1771 "overrides": [
1772 {
1773 "files": ["*.test.ts", "*.spec.ts"],
1774 "rules": {
1775 "unused-exports": "off",
1776 "unused-files": "warn"
1777 }
1778 }
1779 ]
1780 }"#;
1781 let config: FallowConfig = serde_json::from_str(json).unwrap();
1782 assert_eq!(config.overrides.len(), 1);
1783 assert_eq!(config.overrides[0].files.len(), 2);
1784 assert_eq!(
1785 config.overrides[0].rules.unused_exports,
1786 Some(Severity::Off)
1787 );
1788 assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1789 }
1790
1791 #[test]
1792 fn deserialize_json_with_boundaries() {
1793 let json = r#"{
1794 "boundaries": {
1795 "preset": "layered"
1796 }
1797 }"#;
1798 let config: FallowConfig = serde_json::from_str(json).unwrap();
1799 assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1800 }
1801
1802 #[test]
1803 fn deserialize_toml_with_regression_baseline() {
1804 let toml_str = r"
1805[regression.baseline]
1806totalIssues = 50
1807unusedFiles = 10
1808unusedExports = 15
1809";
1810 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1811 let baseline = config.regression.unwrap().baseline.unwrap();
1812 assert_eq!(baseline.total_issues, 50);
1813 assert_eq!(baseline.unused_files, 10);
1814 assert_eq!(baseline.unused_exports, 15);
1815 }
1816
1817 #[test]
1818 fn deserialize_toml_with_overrides() {
1819 let toml_str = r#"
1820[[overrides]]
1821files = ["*.test.ts"]
1822
1823[overrides.rules]
1824unused-exports = "off"
1825
1826[[overrides]]
1827files = ["*.stories.tsx"]
1828
1829[overrides.rules]
1830unused-files = "off"
1831"#;
1832 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1833 assert_eq!(config.overrides.len(), 2);
1834 assert_eq!(
1835 config.overrides[0].rules.unused_exports,
1836 Some(Severity::Off)
1837 );
1838 assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1839 }
1840
1841 #[test]
1842 fn regression_config_default_is_none_baseline() {
1843 let config = RegressionConfig::default();
1844 assert!(config.baseline.is_none());
1845 }
1846
1847 #[test]
1848 fn deserialize_json_multiple_ignore_export_rules() {
1849 let json = r#"{
1850 "ignoreExports": [
1851 {"file": "src/types/**/*.ts", "exports": ["*"]},
1852 {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1853 {"file": "src/index.ts", "exports": ["default"]}
1854 ]
1855 }"#;
1856 let config: FallowConfig = serde_json::from_str(json).unwrap();
1857 assert_eq!(config.ignore_exports.len(), 3);
1858 assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1859 }
1860
1861 #[test]
1862 fn deserialize_json_public_packages_camel_case() {
1863 let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1864 let config: FallowConfig = serde_json::from_str(json).unwrap();
1865 assert_eq!(
1866 config.public_packages,
1867 vec!["@myorg/shared-lib", "@myorg/utils"]
1868 );
1869 }
1870
1871 #[test]
1872 fn deserialize_json_public_packages_rejects_snake_case() {
1873 let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1874 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1875 assert!(
1876 result.is_err(),
1877 "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1878 );
1879 }
1880
1881 #[test]
1882 fn deserialize_json_public_packages_empty() {
1883 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1884 assert!(config.public_packages.is_empty());
1885 }
1886
1887 #[test]
1888 fn deserialize_toml_public_packages() {
1889 let toml_str = r#"
1890publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1891"#;
1892 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1893 assert_eq!(
1894 config.public_packages,
1895 vec!["@myorg/shared-lib", "@myorg/ui"]
1896 );
1897 }
1898
1899 #[test]
1900 fn public_packages_serialize_roundtrip() {
1901 let config = FallowConfig {
1902 public_packages: vec!["@myorg/shared-lib".to_string()],
1903 ..FallowConfig::default()
1904 };
1905 let json = serde_json::to_string(&config).unwrap();
1906 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1907 assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1908 }
1909}