1mod boundaries;
2mod duplicates_config;
3mod flags;
4mod format;
5pub mod glob_validation;
6mod health;
7mod parsing;
8mod resolution;
9mod resolve;
10mod rules;
11mod used_class_members;
12
13#[expect(
14 clippy::redundant_pub_crate,
15 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"
16)]
17pub(crate) use boundaries::wildcard_placement_error;
18pub use boundaries::{
19 AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
20 BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
21 LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
22 ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
23 ZoneReferenceKind, ZoneValidationError,
24};
25pub use duplicates_config::{
26 DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
27};
28pub use flags::{FlagsConfig, SdkPattern};
29pub use format::OutputFormat;
30pub use health::{EmailMode, HealthConfig, HealthThresholdOverride, OwnershipConfig};
31pub use resolution::{
32 CompiledIgnoreCatalogReferenceRule, CompiledIgnoreDependencyOverrideRule,
33 CompiledIgnoreExportRule, ConfigOverride, DEFAULT_MAX_FILE_SIZE_BYTES,
34 DEFAULT_MAX_FILE_SIZE_MB, IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule,
35 IgnoreExportRule, ResolvedConfig, ResolvedOverride, resolve_max_file_size_bytes,
36};
37pub use resolve::ResolveConfig;
38pub use rules::{PartialRulesConfig, RulesConfig, Severity};
39pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
40
41use schemars::JsonSchema;
42use serde::{Deserialize, Deserializer, Serialize};
43use std::ops::Not;
44use std::path::PathBuf;
45
46use crate::external_plugin::ExternalPluginDef;
47use crate::workspace::WorkspaceConfig;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
50#[serde(untagged, rename_all = "camelCase")]
51pub enum IgnoreExportsUsedInFileConfig {
52 Bool(bool),
53 ByKind(IgnoreExportsUsedInFileByKind),
54}
55
56impl Default for IgnoreExportsUsedInFileConfig {
57 fn default() -> Self {
58 Self::Bool(false)
59 }
60}
61
62impl From<bool> for IgnoreExportsUsedInFileConfig {
63 fn from(value: bool) -> Self {
64 Self::Bool(value)
65 }
66}
67
68impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
69 fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
70 Self::ByKind(value)
71 }
72}
73
74impl IgnoreExportsUsedInFileConfig {
75 #[must_use]
76 pub const fn is_enabled(self) -> bool {
77 match self {
78 Self::Bool(value) => value,
79 Self::ByKind(kind) => kind.type_ || kind.interface,
80 }
81 }
82
83 #[must_use]
84 pub const fn suppresses(self, is_type_only: bool) -> bool {
85 match self {
86 Self::Bool(value) => value,
87 Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
88 }
89 }
90}
91
92#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
93#[serde(rename_all = "camelCase")]
94pub struct IgnoreExportsUsedInFileByKind {
95 #[serde(default, rename = "type")]
96 pub type_: bool,
97 #[serde(default)]
98 pub interface: bool,
99}
100
101#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
111#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
112pub struct UnusedComponentPropsConfig {
113 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub ignore_pattern: Option<String>,
123}
124
125impl UnusedComponentPropsConfig {
126 #[must_use]
127 pub fn is_default(&self) -> bool {
128 self.ignore_pattern.is_none()
129 }
130}
131
132#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
133#[serde(rename_all = "camelCase")]
134pub struct FixConfig {
135 #[serde(default)]
136 pub catalog: CatalogFixConfig,
137}
138
139#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
140#[serde(rename_all = "camelCase")]
141pub struct CatalogFixConfig {
142 #[serde(default)]
143 pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
144}
145
146#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
147#[serde(rename_all = "lowercase")]
148pub enum CatalogPrecedingCommentPolicy {
149 #[default]
150 Auto,
151 Always,
152 Never,
153}
154
155#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
156#[serde(deny_unknown_fields, rename_all = "camelCase")]
157pub struct FallowConfig {
158 #[serde(rename = "$schema", default, skip_serializing)]
159 pub schema: Option<String>,
160
161 #[serde(default, skip_serializing)]
162 pub extends: Vec<String>,
163
164 #[serde(default)]
165 pub entry: Vec<String>,
166
167 #[serde(default)]
168 pub ignore_patterns: Vec<String>,
169
170 #[serde(default)]
171 pub framework: Vec<ExternalPluginDef>,
172
173 #[serde(default)]
174 pub workspaces: Option<WorkspaceConfig>,
175
176 #[serde(default)]
177 pub ignore_dependencies: Vec<String>,
178
179 #[serde(default)]
180 pub ignore_unresolved_imports: Vec<String>,
181
182 #[serde(default)]
183 pub ignore_exports: Vec<IgnoreExportRule>,
184
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
186 pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
187
188 #[serde(default, skip_serializing_if = "Vec::is_empty")]
189 pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
190
191 #[serde(default)]
192 pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
193
194 #[serde(default, skip_serializing_if = "Vec::is_empty")]
195 pub ignore_decorators: Vec<String>,
196
197 #[serde(default)]
198 pub used_class_members: Vec<UsedClassMemberRule>,
199
200 #[serde(default)]
201 pub duplicates: DuplicatesConfig,
202
203 #[serde(default)]
204 pub health: HealthConfig,
205
206 #[serde(default)]
207 pub rules: RulesConfig,
208
209 #[serde(
210 default,
211 skip_serializing_if = "UnusedComponentPropsConfig::is_default"
212 )]
213 pub unused_component_props: UnusedComponentPropsConfig,
214
215 #[serde(default)]
216 pub boundaries: BoundaryConfig,
217
218 #[serde(default)]
219 pub flags: FlagsConfig,
220
221 #[serde(default)]
222 pub security: SecurityConfig,
223
224 #[serde(default)]
225 pub fix: FixConfig,
226
227 #[serde(default)]
228 pub resolve: ResolveConfig,
229
230 #[serde(default)]
231 pub production: ProductionConfig,
232
233 #[serde(default)]
234 pub plugins: Vec<String>,
235
236 #[serde(default, skip_serializing_if = "Vec::is_empty")]
242 pub rule_packs: Vec<String>,
243
244 #[serde(default)]
245 pub dynamically_loaded: Vec<String>,
246
247 #[serde(default)]
248 pub overrides: Vec<ConfigOverride>,
249
250 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub codeowners: Option<String>,
252
253 #[serde(default)]
254 pub public_packages: Vec<String>,
255
256 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub regression: Option<RegressionConfig>,
258
259 #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
260 pub audit: AuditConfig,
261
262 #[serde(default)]
263 pub sealed: bool,
264
265 #[serde(default)]
266 pub include_entry_exports: bool,
267
268 #[serde(default)]
269 pub auto_imports: bool,
270
271 #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
272 pub cache: CacheConfig,
273}
274
275#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
279#[serde(deny_unknown_fields, rename_all = "camelCase")]
280pub struct SecurityConfig {
281 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub categories: Option<SecurityCategories>,
284 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 pub request_receivers: Vec<String>,
290}
291
292impl SecurityConfig {
293 #[must_use]
294 pub fn normalized_request_receivers(&self) -> Vec<String> {
295 let mut receivers = Vec::new();
296 for receiver in &self.request_receivers {
297 let normalized = receiver.trim().to_ascii_lowercase();
298 if !normalized.is_empty() && !receivers.contains(&normalized) {
299 receivers.push(normalized);
300 }
301 }
302 receivers
303 }
304
305 #[must_use]
306 pub fn request_receivers_are_valid(&self) -> bool {
307 self.request_receivers
308 .iter()
309 .all(|receiver| !receiver.trim().is_empty())
310 }
311}
312
313#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
318#[serde(deny_unknown_fields, rename_all = "camelCase")]
319pub struct SecurityCategories {
320 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub include: Option<Vec<String>>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub exclude: Option<Vec<String>>,
326}
327
328#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
329#[serde(deny_unknown_fields, rename_all = "camelCase")]
330pub struct CacheConfig {
331 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub dir: Option<PathBuf>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub max_size_mb: Option<u32>,
338}
339
340impl CacheConfig {
341 #[must_use]
342 pub fn is_default(&self) -> bool {
343 self.dir.is_none() && self.max_size_mb.is_none()
344 }
345}
346
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub enum ProductionAnalysis {
349 DeadCode,
350 Health,
351 Dupes,
352}
353
354#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
355#[serde(untagged)]
356pub enum ProductionConfig {
357 Global(bool),
358 PerAnalysis(PerAnalysisProductionConfig),
359}
360
361impl<'de> Deserialize<'de> for ProductionConfig {
362 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
363 where
364 D: Deserializer<'de>,
365 {
366 struct ProductionConfigVisitor;
367
368 impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
369 type Value = ProductionConfig;
370
371 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 formatter.write_str("a boolean or per-analysis production config object")
373 }
374
375 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
376 where
377 E: serde::de::Error,
378 {
379 Ok(ProductionConfig::Global(value))
380 }
381
382 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
383 where
384 A: serde::de::MapAccess<'de>,
385 {
386 PerAnalysisProductionConfig::deserialize(
387 serde::de::value::MapAccessDeserializer::new(map),
388 )
389 .map(ProductionConfig::PerAnalysis)
390 }
391 }
392
393 deserializer.deserialize_any(ProductionConfigVisitor)
394 }
395}
396
397impl Default for ProductionConfig {
398 fn default() -> Self {
399 Self::Global(false)
400 }
401}
402
403impl From<bool> for ProductionConfig {
404 fn from(value: bool) -> Self {
405 Self::Global(value)
406 }
407}
408
409impl Not for ProductionConfig {
410 type Output = bool;
411
412 fn not(self) -> Self::Output {
413 !self.any_enabled()
414 }
415}
416
417impl ProductionConfig {
418 #[must_use]
419 pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
420 match self {
421 Self::Global(value) => value,
422 Self::PerAnalysis(config) => match analysis {
423 ProductionAnalysis::DeadCode => config.dead_code,
424 ProductionAnalysis::Health => config.health,
425 ProductionAnalysis::Dupes => config.dupes,
426 },
427 }
428 }
429
430 #[must_use]
431 pub const fn global(self) -> bool {
432 match self {
433 Self::Global(value) => value,
434 Self::PerAnalysis(_) => false,
435 }
436 }
437
438 #[must_use]
439 pub const fn any_enabled(self) -> bool {
440 match self {
441 Self::Global(value) => value,
442 Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
443 }
444 }
445}
446
447#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
448#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
449pub struct PerAnalysisProductionConfig {
450 pub dead_code: bool,
451 pub health: bool,
452 pub dupes: bool,
453}
454
455#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
456#[serde(rename_all = "camelCase")]
457pub struct AuditConfig {
458 #[serde(default, skip_serializing_if = "AuditGate::is_default")]
459 pub gate: AuditGate,
460
461 #[serde(default, skip_serializing_if = "Option::is_none")]
462 pub dead_code_baseline: Option<String>,
463
464 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub health_baseline: Option<String>,
466
467 #[serde(default, skip_serializing_if = "Option::is_none")]
468 pub dupes_baseline: Option<String>,
469
470 #[serde(default, skip_serializing_if = "Option::is_none")]
471 pub cache_max_age_days: Option<u32>,
472}
473
474impl AuditConfig {
475 #[must_use]
476 pub fn is_empty(&self) -> bool {
477 self.gate.is_default()
478 && self.dead_code_baseline.is_none()
479 && self.health_baseline.is_none()
480 && self.dupes_baseline.is_none()
481 && self.cache_max_age_days.is_none()
482 }
483}
484
485#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
486#[serde(rename_all = "kebab-case")]
487pub enum AuditGate {
488 #[default]
489 NewOnly,
490 All,
491}
492
493impl AuditGate {
494 #[must_use]
495 pub const fn is_default(&self) -> bool {
496 matches!(self, Self::NewOnly)
497 }
498}
499
500#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
501#[serde(rename_all = "camelCase")]
502pub struct RegressionConfig {
503 #[serde(default, skip_serializing_if = "Option::is_none")]
504 pub baseline: Option<RegressionBaseline>,
505}
506
507#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
508#[serde(rename_all = "camelCase")]
509pub struct RegressionBaseline {
510 #[serde(default)]
511 pub total_issues: usize,
512 #[serde(default)]
513 pub unused_files: usize,
514 #[serde(default)]
515 pub unused_exports: usize,
516 #[serde(default)]
517 pub unused_types: usize,
518 #[serde(default)]
519 pub unused_dependencies: usize,
520 #[serde(default)]
521 pub unused_dev_dependencies: usize,
522 #[serde(default)]
523 pub unused_optional_dependencies: usize,
524 #[serde(default)]
525 pub unused_enum_members: usize,
526 #[serde(default)]
527 pub unused_class_members: usize,
528 #[serde(default)]
529 pub unresolved_imports: usize,
530 #[serde(default)]
531 pub unlisted_dependencies: usize,
532 #[serde(default)]
533 pub duplicate_exports: usize,
534 #[serde(default)]
535 pub circular_dependencies: usize,
536 #[serde(default)]
537 pub re_export_cycles: usize,
538 #[serde(default)]
539 pub type_only_dependencies: usize,
540 #[serde(default)]
541 pub test_only_dependencies: usize,
542 #[serde(default)]
543 pub boundary_violations: usize,
544 #[serde(default)]
545 pub boundary_coverage_violations: usize,
546 #[serde(default)]
547 pub boundary_call_violations: usize,
548 #[serde(default)]
549 pub policy_violations: usize,
550}
551
552#[cfg(test)]
553mod tests {
554 use super::*;
555
556 #[test]
557 fn default_config_has_empty_collections() {
558 let config = FallowConfig::default();
559 assert!(config.schema.is_none());
560 assert!(config.extends.is_empty());
561 assert!(config.entry.is_empty());
562 assert!(config.ignore_patterns.is_empty());
563 assert!(config.framework.is_empty());
564 assert!(config.workspaces.is_none());
565 assert!(config.ignore_dependencies.is_empty());
566 assert!(config.ignore_exports.is_empty());
567 assert!(config.used_class_members.is_empty());
568 assert!(config.plugins.is_empty());
569 assert!(config.dynamically_loaded.is_empty());
570 assert!(config.overrides.is_empty());
571 assert!(config.public_packages.is_empty());
572 assert_eq!(
573 config.fix.catalog.delete_preceding_comments,
574 CatalogPrecedingCommentPolicy::Auto
575 );
576 assert!(!config.production);
577 }
578
579 #[test]
580 fn default_config_rules_are_error() {
581 let config = FallowConfig::default();
582 assert_eq!(config.rules.unused_files, Severity::Error);
583 assert_eq!(config.rules.unused_exports, Severity::Error);
584 assert_eq!(config.rules.unused_dependencies, Severity::Error);
585 }
586
587 #[test]
588 fn default_config_duplicates_enabled() {
589 let config = FallowConfig::default();
590 assert!(config.duplicates.enabled);
591 assert_eq!(config.duplicates.min_tokens, 50);
592 assert_eq!(config.duplicates.min_lines, 5);
593 }
594
595 #[test]
596 fn default_config_health_thresholds() {
597 let config = FallowConfig::default();
598 assert_eq!(config.health.max_cyclomatic, 20);
599 assert_eq!(config.health.max_cognitive, 15);
600 }
601
602 #[test]
603 fn deserialize_empty_json_object() {
604 let config: FallowConfig = serde_json::from_str("{}").unwrap();
605 assert!(config.entry.is_empty());
606 assert!(!config.production);
607 }
608
609 #[test]
610 fn deserialize_json_with_all_top_level_fields() {
611 let json = r#"{
612 "$schema": "https://fallow.dev/schema.json",
613 "entry": ["src/main.ts"],
614 "ignorePatterns": ["generated/**"],
615 "ignoreDependencies": ["postcss"],
616 "production": true,
617 "plugins": ["custom-plugin.toml"],
618 "rules": {"unused-files": "warn"},
619 "duplicates": {"enabled": false},
620 "health": {"maxCyclomatic": 30}
621 }"#;
622 let config: FallowConfig = serde_json::from_str(json).unwrap();
623 assert_eq!(
624 config.schema.as_deref(),
625 Some("https://fallow.dev/schema.json")
626 );
627 assert_eq!(config.entry, vec!["src/main.ts"]);
628 assert_eq!(config.ignore_patterns, vec!["generated/**"]);
629 assert_eq!(config.ignore_dependencies, vec!["postcss"]);
630 assert!(config.production);
631 assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
632 assert_eq!(config.rules.unused_files, Severity::Warn);
633 assert!(!config.duplicates.enabled);
634 assert_eq!(config.health.max_cyclomatic, 30);
635 }
636
637 #[test]
638 fn deserialize_json_deny_unknown_fields() {
639 let json = r#"{"unknownField": true}"#;
640 let result: Result<FallowConfig, _> = serde_json::from_str(json);
641 assert!(result.is_err(), "unknown fields should be rejected");
642 }
643
644 #[test]
645 fn deserialize_json_production_mode_default_false() {
646 let config: FallowConfig = serde_json::from_str("{}").unwrap();
647 assert!(!config.production);
648 }
649
650 #[test]
651 fn deserialize_json_production_mode_true() {
652 let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
653 assert!(config.production);
654 }
655
656 #[test]
657 fn deserialize_json_per_analysis_production_mode() {
658 let config: FallowConfig = serde_json::from_str(
659 r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
660 )
661 .unwrap();
662 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
663 assert!(config.production.for_analysis(ProductionAnalysis::Health));
664 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
665 }
666
667 #[test]
668 fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
669 let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
670 .unwrap_err();
671 assert!(
672 err.to_string().contains("healthTypo"),
673 "error should name the unknown field: {err}"
674 );
675 }
676
677 #[test]
678 fn deserialize_json_dynamically_loaded() {
679 let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
680 let config: FallowConfig = serde_json::from_str(json).unwrap();
681 assert_eq!(
682 config.dynamically_loaded,
683 vec!["plugins/**/*.ts", "locales/**/*.json"]
684 );
685 }
686
687 #[test]
688 fn deserialize_json_dynamically_loaded_defaults_empty() {
689 let config: FallowConfig = serde_json::from_str("{}").unwrap();
690 assert!(config.dynamically_loaded.is_empty());
691 }
692
693 #[test]
694 fn deserialize_json_fix_catalog_delete_preceding_comments() {
695 let config: FallowConfig =
696 serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
697 .unwrap();
698 assert_eq!(
699 config.fix.catalog.delete_preceding_comments,
700 CatalogPrecedingCommentPolicy::Always
701 );
702 }
703
704 #[test]
705 fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
706 let err = serde_json::from_str::<FallowConfig>(
707 r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
708 )
709 .unwrap_err();
710 assert!(
711 err.to_string().contains("sometimes"),
712 "error should name the bad policy: {err}"
713 );
714 }
715
716 #[test]
717 fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
718 let json = r#"{
719 "usedClassMembers": [
720 "agInit",
721 { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
722 { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
723 ]
724 }"#;
725 let config: FallowConfig = serde_json::from_str(json).unwrap();
726 assert_eq!(
727 config.used_class_members,
728 vec![
729 UsedClassMemberRule::from("agInit"),
730 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
731 extends: None,
732 implements: Some("ICellRendererAngularComp".to_string()),
733 members: vec!["refresh".to_string()],
734 }),
735 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
736 extends: Some("BaseCommand".to_string()),
737 implements: Some("CanActivate".to_string()),
738 members: vec!["execute".to_string()],
739 }),
740 ]
741 );
742 }
743
744 #[test]
745 fn deserialize_toml_minimal() {
746 let toml_str = r#"
747entry = ["src/index.ts"]
748production = true
749"#;
750 let config: FallowConfig = toml::from_str(toml_str).unwrap();
751 assert_eq!(config.entry, vec!["src/index.ts"]);
752 assert!(config.production);
753 }
754
755 #[test]
756 fn deserialize_toml_per_analysis_production_mode() {
757 let toml_str = r"
758[production]
759deadCode = false
760health = true
761dupes = false
762";
763 let config: FallowConfig = toml::from_str(toml_str).unwrap();
764 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
765 assert!(config.production.for_analysis(ProductionAnalysis::Health));
766 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
767 }
768
769 #[test]
770 fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
771 let err = toml::from_str::<FallowConfig>(
772 r"
773[production]
774healthTypo = true
775",
776 )
777 .unwrap_err();
778 assert!(
779 err.to_string().contains("healthTypo"),
780 "error should name the unknown field: {err}"
781 );
782 }
783
784 #[test]
785 fn deserialize_toml_with_inline_framework() {
786 let toml_str = r#"
787[[framework]]
788name = "my-framework"
789enablers = ["my-framework-pkg"]
790entryPoints = ["src/routes/**/*.tsx"]
791"#;
792 let config: FallowConfig = toml::from_str(toml_str).unwrap();
793 assert_eq!(config.framework.len(), 1);
794 assert_eq!(config.framework[0].name, "my-framework");
795 assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
796 assert_eq!(
797 config.framework[0].entry_points,
798 vec!["src/routes/**/*.tsx"]
799 );
800 }
801
802 #[test]
803 fn deserialize_toml_fix_catalog_delete_preceding_comments() {
804 let toml_str = r#"
805[fix.catalog]
806deletePrecedingComments = "never"
807"#;
808 let config: FallowConfig = toml::from_str(toml_str).unwrap();
809 assert_eq!(
810 config.fix.catalog.delete_preceding_comments,
811 CatalogPrecedingCommentPolicy::Never
812 );
813 }
814
815 #[test]
816 fn deserialize_toml_with_workspace_config() {
817 let toml_str = r#"
818[workspaces]
819patterns = ["packages/*", "apps/*"]
820"#;
821 let config: FallowConfig = toml::from_str(toml_str).unwrap();
822 assert!(config.workspaces.is_some());
823 let ws = config.workspaces.unwrap();
824 assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
825 }
826
827 #[test]
828 fn deserialize_toml_with_ignore_exports() {
829 let toml_str = r#"
830[[ignoreExports]]
831file = "src/types/**/*.ts"
832exports = ["*"]
833"#;
834 let config: FallowConfig = toml::from_str(toml_str).unwrap();
835 assert_eq!(config.ignore_exports.len(), 1);
836 assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
837 assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
838 }
839
840 #[test]
841 fn deserialize_toml_used_class_members_supports_scoped_rules() {
842 let toml_str = r#"
843usedClassMembers = [
844 { implements = "ICellRendererAngularComp", members = ["refresh"] },
845 { extends = "BaseCommand", members = ["execute"] },
846]
847"#;
848 let config: FallowConfig = toml::from_str(toml_str).unwrap();
849 assert_eq!(
850 config.used_class_members,
851 vec![
852 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
853 extends: None,
854 implements: Some("ICellRendererAngularComp".to_string()),
855 members: vec!["refresh".to_string()],
856 }),
857 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
858 extends: Some("BaseCommand".to_string()),
859 implements: None,
860 members: vec!["execute".to_string()],
861 }),
862 ]
863 );
864 }
865
866 #[test]
867 fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
868 let result = serde_json::from_str::<FallowConfig>(
869 r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
870 );
871 assert!(
872 result.is_err(),
873 "unconstrained scoped rule should be rejected"
874 );
875 }
876
877 #[test]
878 fn deserialize_ignore_exports_used_in_file_bool() {
879 let config: FallowConfig =
880 serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
881
882 assert!(config.ignore_exports_used_in_file.suppresses(false));
883 assert!(config.ignore_exports_used_in_file.suppresses(true));
884 }
885
886 #[test]
887 fn deserialize_ignore_exports_used_in_file_kind_form() {
888 let config: FallowConfig =
889 serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
890
891 assert!(!config.ignore_exports_used_in_file.suppresses(false));
892 assert!(config.ignore_exports_used_in_file.suppresses(true));
893 }
894
895 #[test]
896 fn deserialize_toml_deny_unknown_fields() {
897 let toml_str = r"bogus_field = true";
898 let result: Result<FallowConfig, _> = toml::from_str(toml_str);
899 assert!(result.is_err(), "unknown fields should be rejected");
900 }
901
902 #[test]
903 fn json_serialize_roundtrip() {
904 let config = FallowConfig {
905 entry: vec!["src/main.ts".to_string()],
906 production: true.into(),
907 ..FallowConfig::default()
908 };
909 let json = serde_json::to_string(&config).unwrap();
910 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
911 assert_eq!(restored.entry, vec!["src/main.ts"]);
912 assert!(restored.production);
913 }
914
915 #[test]
916 fn schema_field_not_serialized() {
917 let config = FallowConfig {
918 schema: Some("https://example.com/schema.json".to_string()),
919 ..FallowConfig::default()
920 };
921 let json = serde_json::to_string(&config).unwrap();
922 assert!(
923 !json.contains("$schema"),
924 "schema field should be skipped in serialization"
925 );
926 }
927
928 #[test]
929 fn extends_field_not_serialized() {
930 let config = FallowConfig {
931 extends: vec!["base.json".to_string()],
932 ..FallowConfig::default()
933 };
934 let json = serde_json::to_string(&config).unwrap();
935 assert!(
936 !json.contains("extends"),
937 "extends field should be skipped in serialization"
938 );
939 }
940
941 #[test]
942 fn regression_config_deserialize_json() {
943 let json = r#"{
944 "regression": {
945 "baseline": {
946 "totalIssues": 42,
947 "unusedFiles": 10,
948 "unusedExports": 5,
949 "circularDependencies": 2
950 }
951 }
952 }"#;
953 let config: FallowConfig = serde_json::from_str(json).unwrap();
954 let regression = config.regression.unwrap();
955 let baseline = regression.baseline.unwrap();
956 assert_eq!(baseline.total_issues, 42);
957 assert_eq!(baseline.unused_files, 10);
958 assert_eq!(baseline.unused_exports, 5);
959 assert_eq!(baseline.circular_dependencies, 2);
960 assert_eq!(baseline.unused_types, 0);
961 assert_eq!(baseline.boundary_violations, 0);
962 }
963
964 #[test]
965 fn regression_config_defaults_to_none() {
966 let config: FallowConfig = serde_json::from_str("{}").unwrap();
967 assert!(config.regression.is_none());
968 }
969
970 #[test]
971 fn regression_baseline_all_zeros_by_default() {
972 let baseline = RegressionBaseline::default();
973 assert_eq!(baseline.total_issues, 0);
974 assert_eq!(baseline.unused_files, 0);
975 assert_eq!(baseline.unused_exports, 0);
976 assert_eq!(baseline.unused_types, 0);
977 assert_eq!(baseline.unused_dependencies, 0);
978 assert_eq!(baseline.unused_dev_dependencies, 0);
979 assert_eq!(baseline.unused_optional_dependencies, 0);
980 assert_eq!(baseline.unused_enum_members, 0);
981 assert_eq!(baseline.unused_class_members, 0);
982 assert_eq!(baseline.unresolved_imports, 0);
983 assert_eq!(baseline.unlisted_dependencies, 0);
984 assert_eq!(baseline.duplicate_exports, 0);
985 assert_eq!(baseline.circular_dependencies, 0);
986 assert_eq!(baseline.type_only_dependencies, 0);
987 assert_eq!(baseline.test_only_dependencies, 0);
988 assert_eq!(baseline.boundary_violations, 0);
989 }
990
991 #[test]
992 fn regression_config_serialize_roundtrip() {
993 let baseline = RegressionBaseline {
994 total_issues: 100,
995 unused_files: 20,
996 unused_exports: 30,
997 ..RegressionBaseline::default()
998 };
999 let regression = RegressionConfig {
1000 baseline: Some(baseline),
1001 };
1002 let config = FallowConfig {
1003 regression: Some(regression),
1004 ..FallowConfig::default()
1005 };
1006 let json = serde_json::to_string(&config).unwrap();
1007 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1008 let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1009 assert_eq!(restored_baseline.total_issues, 100);
1010 assert_eq!(restored_baseline.unused_files, 20);
1011 assert_eq!(restored_baseline.unused_exports, 30);
1012 assert_eq!(restored_baseline.unused_types, 0);
1013 }
1014
1015 #[test]
1016 fn regression_config_empty_baseline_deserialize() {
1017 let json = r#"{"regression": {}}"#;
1018 let config: FallowConfig = serde_json::from_str(json).unwrap();
1019 let regression = config.regression.unwrap();
1020 assert!(regression.baseline.is_none());
1021 }
1022
1023 #[test]
1024 fn regression_baseline_not_serialized_when_none() {
1025 let config = FallowConfig {
1026 regression: None,
1027 ..FallowConfig::default()
1028 };
1029 let json = serde_json::to_string(&config).unwrap();
1030 assert!(
1031 !json.contains("regression"),
1032 "regression should be skipped when None"
1033 );
1034 }
1035
1036 #[test]
1037 fn deserialize_json_with_overrides() {
1038 let json = r#"{
1039 "overrides": [
1040 {
1041 "files": ["*.test.ts", "*.spec.ts"],
1042 "rules": {
1043 "unused-exports": "off",
1044 "unused-files": "warn"
1045 }
1046 }
1047 ]
1048 }"#;
1049 let config: FallowConfig = serde_json::from_str(json).unwrap();
1050 assert_eq!(config.overrides.len(), 1);
1051 assert_eq!(config.overrides[0].files.len(), 2);
1052 assert_eq!(
1053 config.overrides[0].rules.unused_exports,
1054 Some(Severity::Off)
1055 );
1056 assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1057 }
1058
1059 #[test]
1060 fn deserialize_json_with_boundaries() {
1061 let json = r#"{
1062 "boundaries": {
1063 "preset": "layered"
1064 }
1065 }"#;
1066 let config: FallowConfig = serde_json::from_str(json).unwrap();
1067 assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1068 }
1069
1070 #[test]
1071 fn deserialize_toml_with_regression_baseline() {
1072 let toml_str = r"
1073[regression.baseline]
1074totalIssues = 50
1075unusedFiles = 10
1076unusedExports = 15
1077";
1078 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1079 let baseline = config.regression.unwrap().baseline.unwrap();
1080 assert_eq!(baseline.total_issues, 50);
1081 assert_eq!(baseline.unused_files, 10);
1082 assert_eq!(baseline.unused_exports, 15);
1083 }
1084
1085 #[test]
1086 fn deserialize_toml_with_overrides() {
1087 let toml_str = r#"
1088[[overrides]]
1089files = ["*.test.ts"]
1090
1091[overrides.rules]
1092unused-exports = "off"
1093
1094[[overrides]]
1095files = ["*.stories.tsx"]
1096
1097[overrides.rules]
1098unused-files = "off"
1099"#;
1100 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1101 assert_eq!(config.overrides.len(), 2);
1102 assert_eq!(
1103 config.overrides[0].rules.unused_exports,
1104 Some(Severity::Off)
1105 );
1106 assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1107 }
1108
1109 #[test]
1110 fn regression_config_default_is_none_baseline() {
1111 let config = RegressionConfig::default();
1112 assert!(config.baseline.is_none());
1113 }
1114
1115 #[test]
1116 fn deserialize_json_multiple_ignore_export_rules() {
1117 let json = r#"{
1118 "ignoreExports": [
1119 {"file": "src/types/**/*.ts", "exports": ["*"]},
1120 {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1121 {"file": "src/index.ts", "exports": ["default"]}
1122 ]
1123 }"#;
1124 let config: FallowConfig = serde_json::from_str(json).unwrap();
1125 assert_eq!(config.ignore_exports.len(), 3);
1126 assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1127 }
1128
1129 #[test]
1130 fn deserialize_json_public_packages_camel_case() {
1131 let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1132 let config: FallowConfig = serde_json::from_str(json).unwrap();
1133 assert_eq!(
1134 config.public_packages,
1135 vec!["@myorg/shared-lib", "@myorg/utils"]
1136 );
1137 }
1138
1139 #[test]
1140 fn deserialize_json_public_packages_rejects_snake_case() {
1141 let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1142 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1143 assert!(
1144 result.is_err(),
1145 "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1146 );
1147 }
1148
1149 #[test]
1150 fn deserialize_json_public_packages_empty() {
1151 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1152 assert!(config.public_packages.is_empty());
1153 }
1154
1155 #[test]
1156 fn deserialize_toml_public_packages() {
1157 let toml_str = r#"
1158publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1159"#;
1160 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1161 assert_eq!(
1162 config.public_packages,
1163 vec!["@myorg/shared-lib", "@myorg/ui"]
1164 );
1165 }
1166
1167 #[test]
1168 fn public_packages_serialize_roundtrip() {
1169 let config = FallowConfig {
1170 public_packages: vec!["@myorg/shared-lib".to_string()],
1171 ..FallowConfig::default()
1172 };
1173 let json = serde_json::to_string(&config).unwrap();
1174 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1175 assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1176 }
1177}