fallow-api 2.103.0

Programmatic API contract types for fallow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Shared JSON output assembly for CLI and programmatic consumers.

use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;

use fallow_engine::duplicates::DuplicationReport;
use fallow_output::{
    CHECK_SCHEMA_VERSION, CheckGroupedEntry, CheckGroupedOutput, CheckOutput, CheckOutputInput,
    DupesOutput, DupesOutputInput, GroupByMode, RootEnvelopeMode,
    apply_config_fixable_to_duplicate_exports, build_check_output, build_dupes_output,
    strip_root_prefix,
};
use fallow_types::envelope::{
    BaselineDeltas, BaselineMatch, ElapsedMs, Meta, RegressionResult, SchemaVersion, ToolVersion,
};
use fallow_types::output::NextStep;
use fallow_types::results::AnalysisResults;
use fallow_types::workspace::WorkspaceDiagnostic;

use crate::{DupesReportPayload, DuplicationGroup, DuplicationGrouping, ResultGroup};

type SuppressAnchor = (String, u64);

/// Inputs for `fallow dead-code --format json` output assembly.
pub struct CheckJsonOutputInput<'a> {
    pub results: &'a AnalysisResults,
    pub root: &'a Path,
    pub elapsed: Duration,
    pub config_fixable: bool,
    pub meta: Option<Meta>,
    pub extras: CheckJsonExtraOutputs,
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    pub next_steps: Vec<NextStep>,
    pub envelope_mode: RootEnvelopeMode,
    pub telemetry_analysis_run_id: Option<&'a str>,
}

/// Inputs for the dead-code JSON payload without a root envelope.
pub struct CheckJsonPayloadInput<'a> {
    pub results: &'a AnalysisResults,
    pub root: &'a Path,
    pub elapsed: Duration,
    pub config_fixable: bool,
    pub extras: CheckJsonExtraOutputs,
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
}

/// Optional root sections for dead-code JSON envelopes.
///
/// These fields are part of the output contract, but they are computed by
/// caller-specific workflows such as baseline and regression gates.
#[derive(Debug, Clone, Default)]
pub struct CheckJsonExtraOutputs {
    pub baseline_deltas: Option<BaselineDeltas>,
    pub baseline: Option<BaselineMatch>,
    pub regression: Option<RegressionResult>,
}

struct CheckJsonEnvelopeInput<'a> {
    results: &'a AnalysisResults,
    elapsed: Duration,
    config_fixable: bool,
    meta: Option<Meta>,
    extras: CheckJsonExtraOutputs,
    workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    next_steps: Vec<NextStep>,
}

/// Inputs for grouped dead-code JSON output assembly.
pub struct GroupedCheckJsonOutputInput<'a> {
    pub groups: &'a [ResultGroup],
    pub original: &'a AnalysisResults,
    pub root: &'a Path,
    pub elapsed: Duration,
    pub grouped_by: GroupByMode,
    pub config_fixable: bool,
    pub meta: Option<Meta>,
    pub next_steps: Vec<NextStep>,
    pub envelope_mode: RootEnvelopeMode,
    pub telemetry_analysis_run_id: Option<&'a str>,
}

/// Inputs for `fallow dupes --format json` output assembly.
pub struct DuplicationJsonOutputInput<'a> {
    pub report: &'a DuplicationReport,
    pub root: &'a Path,
    pub elapsed: Duration,
    pub meta: Option<Meta>,
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    pub next_steps: Vec<NextStep>,
    pub envelope_mode: RootEnvelopeMode,
    pub telemetry_analysis_run_id: Option<&'a str>,
}

/// Inputs for grouped duplication JSON output assembly.
pub struct GroupedDuplicationJsonOutputInput<'a> {
    pub report: &'a DuplicationReport,
    pub grouping: &'a DuplicationGrouping,
    pub root: &'a Path,
    pub elapsed: Duration,
    pub meta: Option<Meta>,
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    pub next_steps: Vec<NextStep>,
    pub envelope_mode: RootEnvelopeMode,
    pub telemetry_analysis_run_id: Option<&'a str>,
}

/// Build and serialize dead-code JSON through the API-owned output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_check_json(
    input: CheckJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
    let envelope = build_check_json_envelope(CheckJsonEnvelopeInput {
        results: input.results,
        elapsed: input.elapsed,
        config_fixable: input.config_fixable,
        meta: input.meta,
        extras: input.extras,
        workspace_diagnostics: input.workspace_diagnostics,
        next_steps: input.next_steps,
    });
    let mut output = fallow_output::serialize_check_json_output(
        envelope,
        input.envelope_mode,
        input.telemetry_analysis_run_id,
    )?;
    postprocess_check_json(&mut output, input.root);
    Ok(output)
}

/// Build a dead-code JSON payload without adding a root envelope.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_check_json_payload(
    input: CheckJsonPayloadInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
    let envelope = build_check_json_envelope(CheckJsonEnvelopeInput {
        results: input.results,
        elapsed: input.elapsed,
        config_fixable: input.config_fixable,
        meta: None,
        extras: input.extras,
        workspace_diagnostics: input.workspace_diagnostics,
        next_steps: Vec::new(),
    });
    let mut output = serde_json::to_value(envelope)?;
    postprocess_check_json(&mut output, input.root);
    Ok(output)
}

/// Build and serialize grouped dead-code JSON through the API output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_grouped_check_json(
    input: GroupedCheckJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
    let entries = input
        .groups
        .iter()
        .map(|group| {
            let mut results = group.results.clone();
            apply_config_fixable_to_duplicate_exports(&mut results, input.config_fixable);
            CheckGroupedEntry {
                key: group.key.clone(),
                owners: group.owners.clone(),
                total_issues: results.total_issues(),
                results,
            }
        })
        .collect();

    let envelope = CheckGroupedOutput {
        schema_version: SchemaVersion(CHECK_SCHEMA_VERSION),
        version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
        elapsed_ms: ElapsedMs(input.elapsed.as_millis() as u64),
        grouped_by: input.grouped_by,
        total_issues: input.original.total_issues(),
        groups: entries,
        meta: input.meta,
        next_steps: input.next_steps,
    };

    let mut output = fallow_output::serialize_check_grouped_json_output(
        envelope,
        input.envelope_mode,
        input.telemetry_analysis_run_id,
    )?;
    let root_prefix = format!("{}/", input.root.display());
    if let Some(arr) = output
        .get_mut("groups")
        .and_then(serde_json::Value::as_array_mut)
    {
        for entry in arr {
            strip_root_prefix(entry, &root_prefix);
            harmonize_multi_kind_suppress_line_actions(entry);
        }
    }
    Ok(output)
}

/// Build and serialize duplication JSON through the API-owned output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_duplication_json(
    input: DuplicationJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
    let payload = DupesReportPayload::from_report(input.report);
    let envelope: DupesOutput<DupesReportPayload, DuplicationGroup> =
        build_dupes_output(DupesOutputInput {
            schema_version: CHECK_SCHEMA_VERSION,
            version: env!("CARGO_PKG_VERSION").to_string(),
            elapsed: input.elapsed,
            report: payload,
            grouped_by: None,
            total_issues: None,
            groups: None,
            meta: input.meta,
            workspace_diagnostics: input.workspace_diagnostics,
            next_steps: input.next_steps,
        });
    let mut output = fallow_output::serialize_dupes_json_output(
        envelope,
        input.envelope_mode,
        input.telemetry_analysis_run_id,
    )?;
    let root_prefix = format!("{}/", input.root.display());
    strip_root_prefix(&mut output, &root_prefix);
    Ok(output)
}

/// Build and serialize grouped duplication JSON through the API output boundary.
///
/// # Errors
///
/// Returns a serde error when the typed envelope cannot be converted to JSON.
pub fn serialize_grouped_duplication_json(
    input: GroupedDuplicationJsonOutputInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
    let root_prefix = format!("{}/", input.root.display());
    let payload = DupesReportPayload::from_report(input.report);
    let envelope: DupesOutput<DupesReportPayload, DuplicationGroup> =
        build_dupes_output(DupesOutputInput {
            schema_version: CHECK_SCHEMA_VERSION,
            version: env!("CARGO_PKG_VERSION").to_string(),
            elapsed: input.elapsed,
            report: payload,
            grouped_by: Some(group_by_mode_from_label(input.grouping.mode)),
            total_issues: Some(input.report.clone_groups.len()),
            groups: None,
            meta: input.meta,
            workspace_diagnostics: input.workspace_diagnostics,
            next_steps: input.next_steps,
        });
    let mut output = fallow_output::serialize_dupes_json_output(
        envelope,
        input.envelope_mode,
        input.telemetry_analysis_run_id,
    )?;
    strip_root_prefix(&mut output, &root_prefix);

    let group_values = input
        .grouping
        .groups
        .iter()
        .map(|group| {
            let mut value = serde_json::to_value(group)?;
            strip_root_prefix(&mut value, &root_prefix);
            Ok(value)
        })
        .collect::<Result<Vec<_>, serde_json::Error>>()?;

    if let serde_json::Value::Object(ref mut map) = output {
        map.insert("groups".to_string(), serde_json::Value::Array(group_values));
    }

    Ok(output)
}

fn build_check_json_envelope(input: CheckJsonEnvelopeInput<'_>) -> CheckOutput {
    let mut output = build_check_output(CheckOutputInput {
        schema_version: CHECK_SCHEMA_VERSION,
        version: env!("CARGO_PKG_VERSION").to_string(),
        elapsed: input.elapsed,
        results: input.results.clone(),
        config_fixable: input.config_fixable,
        meta: input.meta,
        workspace_diagnostics: input.workspace_diagnostics,
        next_steps: input.next_steps,
    });
    output.baseline_deltas = input.extras.baseline_deltas;
    output.baseline = input.extras.baseline;
    output.regression = input.extras.regression;
    output
}

fn postprocess_check_json(output: &mut serde_json::Value, root: &Path) {
    let root_prefix = format!("{}/", root.display());
    strip_root_prefix(output, &root_prefix);
    harmonize_multi_kind_suppress_line_actions(output);
}

/// Merge same-line suppress actions so multi-kind findings share one comment.
pub fn harmonize_multi_kind_suppress_line_actions(output: &mut serde_json::Value) {
    let mut anchors: BTreeMap<SuppressAnchor, Vec<String>> = BTreeMap::new();
    collect_suppress_line_anchors(output, &mut anchors);

    anchors.retain(|_, kinds| {
        sort_suppression_kinds(kinds);
        kinds.dedup();
        kinds.len() > 1
    });
    if anchors.is_empty() {
        return;
    }

    rewrite_suppress_line_actions(output, &anchors);
}

fn collect_suppress_line_anchors(
    value: &serde_json::Value,
    anchors: &mut BTreeMap<SuppressAnchor, Vec<String>>,
) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(anchor) = suppression_anchor(map)
                && let Some(actions) = map.get("actions").and_then(serde_json::Value::as_array)
            {
                for action in actions {
                    if let Some(comment) = suppress_line_comment(action) {
                        for kind in parse_suppress_line_comment(comment) {
                            let kinds = anchors.entry(anchor.clone()).or_default();
                            if !kinds.iter().any(|existing| existing == &kind) {
                                kinds.push(kind);
                            }
                        }
                    }
                }
            }

            for child in map.values() {
                collect_suppress_line_anchors(child, anchors);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                collect_suppress_line_anchors(item, anchors);
            }
        }
        _ => {}
    }
}

fn rewrite_suppress_line_actions(
    value: &mut serde_json::Value,
    anchors: &BTreeMap<SuppressAnchor, Vec<String>>,
) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(anchor) = suppression_anchor(map)
                && let Some(kinds) = anchors.get(&anchor)
            {
                let comment = format!("// fallow-ignore-next-line {}", kinds.join(", "));
                if let Some(actions) = map
                    .get_mut("actions")
                    .and_then(serde_json::Value::as_array_mut)
                {
                    for action in actions {
                        if suppress_line_comment(action).is_some()
                            && let serde_json::Value::Object(action_map) = action
                        {
                            action_map.insert("comment".to_string(), serde_json::json!(comment));
                        }
                    }
                }
            }

            for child in map.values_mut() {
                rewrite_suppress_line_actions(child, anchors);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                rewrite_suppress_line_actions(item, anchors);
            }
        }
        _ => {}
    }
}

fn suppression_anchor(map: &serde_json::Map<String, serde_json::Value>) -> Option<SuppressAnchor> {
    let path = map
        .get("path")
        .or_else(|| map.get("from_path"))
        .and_then(serde_json::Value::as_str)?;
    let line = map.get("line").and_then(serde_json::Value::as_u64)?;
    Some((path.to_string(), line))
}

fn suppress_line_comment(action: &serde_json::Value) -> Option<&str> {
    (action.get("type").and_then(serde_json::Value::as_str) == Some("suppress-line"))
        .then_some(())
        .and_then(|()| action.get("comment").and_then(serde_json::Value::as_str))
}

fn parse_suppress_line_comment(comment: &str) -> Vec<String> {
    comment
        .strip_prefix("// fallow-ignore-next-line ")
        .map(|rest| {
            rest.split(|c: char| c == ',' || c.is_whitespace())
                .filter(|token| !token.is_empty())
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

fn sort_suppression_kinds(kinds: &mut [String]) {
    kinds.sort_by_key(|kind| suppression_kind_rank(kind));
}

fn suppression_kind_rank(kind: &str) -> usize {
    match kind {
        "unused-file" => 0,
        "unused-export" => 1,
        "unused-type" => 2,
        "private-type-leak" => 3,
        "unused-enum-member" => 4,
        "unused-class-member" => 5,
        "unused-store-member" => 6,
        "unresolved-import" => 7,
        "unlisted-dependency" => 8,
        "duplicate-export" => 9,
        "circular-dependency" => 10,
        "re-export-cycle" => 11,
        "boundary-violation" => 12,
        "code-duplication" => 13,
        "complexity" => 14,
        "unprovided-inject" => 15,
        "unrendered-component" => 16,
        "unused-server-action" => 17,
        _ => usize::MAX,
    }
}

fn group_by_mode_from_label(label: &str) -> GroupByMode {
    match label {
        "directory" => GroupByMode::Directory,
        "package" => GroupByMode::Package,
        "section" => GroupByMode::Section,
        _ => GroupByMode::Owner,
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn harmonize_suppress_actions_merges_same_line_issue_kinds() {
        let mut output = json!({
            "unused_exports": [{
                "path": "src/api.ts",
                "line": 4,
                "actions": [{
                    "type": "suppress-line",
                    "comment": "// fallow-ignore-next-line unused-export"
                }]
            }],
            "unused_types": [{
                "path": "src/api.ts",
                "line": 4,
                "actions": [{
                    "type": "suppress-line",
                    "comment": "// fallow-ignore-next-line unused-type"
                }]
            }]
        });

        harmonize_multi_kind_suppress_line_actions(&mut output);

        assert_eq!(
            output["unused_exports"][0]["actions"][0]["comment"],
            "// fallow-ignore-next-line unused-export, unused-type"
        );
        assert_eq!(
            output["unused_types"][0]["actions"][0]["comment"],
            "// fallow-ignore-next-line unused-export, unused-type"
        );
    }
}