auditmysite 1.7.3

Resource-efficient WCAG 2.2 AA Accessibility Checker in Rust
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use super::super::helpers::localized_module_name;
use crate::audit::normalized::NormalizedReport;
use crate::output::report_model::{
    AffectedElement, AppendixBlock, AppendixViolation, CapabilitySignal, MethodologyBlock,
};

pub(super) fn build_appendix_block_from_normalized(
    locale: &str,
    normalized: &NormalizedReport,
) -> AppendixBlock {
    let violations: Vec<AppendixViolation> = normalized
        .findings
        .iter()
        .map(|f| {
            let affected_elements: Vec<AffectedElement> = f
                .occurrences
                .iter()
                .map(|occ| AffectedElement {
                    selector: occ.selector.clone().unwrap_or_else(|| occ.node_id.clone()),
                    node_id: occ.node_id.clone(),
                })
                .collect();

            // Stored title is canonical English (#406); re-derive the localized
            // title (taxonomy + SEO headings) for non-English reports.
            let rule_name = crate::output::builder::actions::localized_finding_text(locale, f).0;

            AppendixViolation {
                rule: f.wcag_criterion.clone(),
                rule_name,
                severity: f.severity,
                message: f.description.clone(),
                fix_suggestion: f.occurrences.first().and_then(|o| o.fix_suggestion.clone()),
                affected_elements,
            }
        })
        .collect();

    let has_violations = !violations.is_empty();

    let score_methodology = if locale == "en" {
        "Score calculation: each accessibility viewport starts at 100 points; taxonomy-defined, rule-specific penalties with logarithmic scaling account for repeated violations. With desktop and mobile data, the canonical accessibility score is 70% mobile plus 30% desktop. The consolidated finding list supports evidence and remediation and does not create a third score. Conflicting signals are flagged but do not alter the score retrospectively."
    } else {
        "Score-Berechnung: Jeder Barrierefreiheits-Viewport startet bei 100 Punkten; taxonomiebasierte, regelspezifische Abzüge mit logarithmischer Skalierung berücksichtigen wiederholte Verstöße. Bei Desktop- und Mobile-Daten ist der kanonische Barrierefreiheits-Score 70 % Mobile plus 30 % Desktop. Die zusammengeführte Befundliste dient Evidenz und Maßnahmenplanung und erzeugt keinen dritten Score. Widersprüchliche Signale werden markiert, verändern den Score aber nicht nachträglich."
    };

    AppendixBlock {
        violations,
        score_methodology: score_methodology.to_string(),
        has_violations,
    }
}

pub(super) fn build_methodology(
    i18n: &crate::i18n::I18n,
    normalized: &NormalizedReport,
) -> MethodologyBlock {
    let locale = i18n.locale();
    let en = locale == "en";
    let active_modules = normalized
        .execution
        .module_runs
        .iter()
        .filter(|run| {
            matches!(
                run.status,
                crate::audit::ExecutionStatus::Completed | crate::audit::ExecutionStatus::Partial
            )
        })
        .map(|run| run.module.clone())
        .collect::<Vec<_>>()
        .join(", ");
    let requested_modules = normalized.execution.scope.requested_modules.join(", ");
    let failed_modules = normalized
        .execution
        .module_runs
        .iter()
        .filter(|run| run.status == crate::audit::ExecutionStatus::Failed)
        .map(|run| run.module.as_str())
        .collect::<Vec<_>>()
        .join(", ");

    let scope = if en {
        format!(
            "Automated audit of {} for accessibility per WCAG 2.2 (level {}). Requested modules: {}.",
            normalized.url, normalized.wcag_level, requested_modules
        )
    } else {
        format!(
            "Automatisierte Prüfung der Seite {} auf Barrierefreiheit nach WCAG 2.2 (Level {}). Angeforderte Module: {}.",
            normalized.url, normalized.wcag_level, requested_modules
        )
    };
    let executed_rules = normalized
        .rule_outcomes
        .iter()
        .filter(|outcome| !crate::wcag::rule_run_skipped(outcome))
        .count();
    let method = if en {
        format!("The audit was performed via the Chrome DevTools Protocol (CDP) and the browser's native accessibility tree. {executed_rules} automated rule executions were recorded across the configured viewports.")
    } else {
        format!("Die Prüfung erfolgte über das Chrome DevTools Protocol (CDP) und den nativen Accessibility Tree des Browsers. Über die konfigurierten Viewports wurden {executed_rules} automatisierte Regelausführungen erfasst.")
    };
    let mut limitations = if en {
        "Automated tests can detect about 30–40% of all accessibility issues. Complex aspects \
         such as correct tab order, meaningful alt texts, or understandable language additionally \
         require manual review."
            .to_string()
    } else {
        "Automatisierte Tests können ca. 30–40% aller Barrierefreiheitsprobleme erkennen. \
         Komplexe Aspekte wie korrekte Tab-Reihenfolge, sinnvolle Alt-Texte oder \
         verständliche Sprache erfordern zusätzlich manuelle Prüfung."
            .to_string()
    };
    if normalized.execution.quality.qualified_results {
        limitations.push_str(if en {
            " This run is incomplete: scores describe only the successfully measured scope."
        } else {
            " Dieser Lauf ist unvollständig: Die Scores beschreiben nur den erfolgreich gemessenen Umfang."
        });
    }
    let disclaimer = if en {
        "This report represents an automated technical analysis. It does not replace a complete \
         WCAG 2.2 conformance assessment. A legally defensible accessibility statement requires a \
         comprehensive manual audit by experts. Accessibility is not a one-time achievable state: \
         it is an ongoing process, and every new component or piece of content needs to be \
         re-audited when it is added."
            .to_string()
    } else {
        "Dieser Report stellt eine automatisierte technische Analyse dar. \
         Er ersetzt keine vollständige Konformitätsbewertung nach WCAG 2.2. \
         Für eine rechtsverbindliche Aussage zur Barrierefreiheit ist eine \
         umfassende manuelle Prüfung durch Experten erforderlich. Barrierefreiheit ist kein \
         einmalig erreichbarer Zustand, sondern ein fortlaufender Prozess: Jede neue Komponente \
         und jeder neue Inhalt muss bei Einführung erneut geprüft werden."
            .to_string()
    };

    let key = |de: &str, en_label: &str| -> String {
        if en {
            en_label.to_string()
        } else {
            de.to_string()
        }
    };

    let preview_value = if normalized.has_screenshots {
        if en {
            "Desktop and mobile captured".to_string()
        } else {
            "Desktop und Mobile erfasst".to_string()
        }
    } else if en {
        "Not captured".to_string()
    } else {
        "Nicht erfasst".to_string()
    };

    let total_score_value = {
        let contributing: Vec<_> = normalized
            .module_scores
            .iter()
            .filter(|m| m.contributes_to_overall)
            .collect();
        let total_raw: u32 = contributing.iter().map(|m| m.weight_pct).sum();
        let weights: Vec<String> = contributing
            .iter()
            .map(|m| {
                let pct = (m.weight_pct * 100 + total_raw / 2)
                    .checked_div(total_raw)
                    .unwrap_or(0);
                let name = localized_module_name(&m.name, i18n);
                if en {
                    format!("{name} {pct}%")
                } else {
                    format!("{name} {pct} %")
                }
            })
            .collect();
        let weights_label = if weights.is_empty() {
            if en {
                "Accessibility 100%".to_string()
            } else {
                "Barrierefreiheit 100 %".to_string()
            }
        } else {
            weights.join(", ")
        };
        let indicator_names: Vec<String> = normalized
            .module_scores
            .iter()
            .filter(|m| !m.contributes_to_overall || m.measurement_type == "heuristic")
            .map(|m| localized_module_name(&m.name, i18n))
            .collect();
        let indicator_note = if indicator_names.is_empty() {
            String::new()
        } else if en {
            format!(
                " Indicator modules shown separately: {}.",
                indicator_names.join(", ")
            )
        } else {
            format!(
                " Separat ausgewiesene Indikator-Module: {}.",
                indicator_names.join(", ")
            )
        };
        if en {
            format!(
                "{} / 100 — contributing weights: {}{}",
                normalized.overall_score, weights_label, indicator_note
            )
        } else {
            format!(
                "{} / 100 — beitragende Gewichtung: {}{}",
                normalized.overall_score, weights_label, indicator_note
            )
        }
    };

    let runtime_unit = "s";

    let accessibility_score_value = normalized
        .viewport_scores
        .as_ref()
        .map(|scores| {
            if en {
                format!(
                    "{} / 100 — 70% mobile ({}) + 30% desktop ({})",
                    normalized.score, scores.mobile.accessibility, scores.desktop.accessibility
                )
            } else {
                format!(
                    "{} / 100 — 70 % Mobile ({}) + 30 % Desktop ({})",
                    normalized.score, scores.mobile.accessibility, scores.desktop.accessibility
                )
            }
        })
        .unwrap_or_else(|| format!("{} / 100", normalized.score));
    let all_occurrences: usize = normalized
        .findings
        .iter()
        .map(|finding| finding.occurrence_count)
        .sum();
    let counting_value = if en {
        format!(
            "{} distinct WCAG finding groups, {} WCAG occurrences; {} finding rows and {} occurrences across all categories",
            normalized.severity_counts.total,
            normalized.occurrence_counts.total,
            normalized.findings.len(),
            all_occurrences
        )
    } else {
        format!(
            "{} unterschiedliche WCAG-Befundgruppen, {} WCAG-Vorkommen; {} Befundzeilen und {} Vorkommen über alle Kategorien",
            normalized.severity_counts.total,
            normalized.occurrence_counts.total,
            normalized.findings.len(),
            all_occurrences
        )
    };

    let mut audit_facts = vec![
        (
            key("Barrierefreiheits-Score", "Accessibility score"),
            accessibility_score_value,
        ),
        (
            key("Kombinierter technischer Wert", "Combined technical score"),
            total_score_value,
        ),
        (key("Zählweise", "Counting method"), counting_value),
        (
            key("WCAG-Level", "WCAG level"),
            normalized.wcag_level.to_string(),
        ),
        // #653: the mode the scores belong to, and what the page offers.
        (
            key("Darstellungsmodus", "Display mode"),
            crate::display::audited_mode_text(normalized.execution.scope.display_mode, en),
        ),
        (
            key("Darstellungsmodi der Seite", "Page display modes"),
            crate::display::offered_modes_text(normalized.execution.display_modes.as_ref(), en),
        ),
        (
            key("Geprüfte Knoten", "Checked nodes"),
            normalized.nodes_analyzed.to_string(),
        ),
        (
            key("Laufzeit", "Runtime"),
            format!(
                "{:.1} {}",
                normalized.duration_ms as f64 / 1000.0,
                runtime_unit
            ),
        ),
        (key("Aktive Module", "Active modules"), active_modules),
        (
            key("Fehlgeschlagene Module", "Failed modules"),
            if failed_modules.is_empty() {
                key("Keine", "None")
            } else {
                failed_modules
            },
        ),
        (
            key("Audit-Qualität", "Audit quality"),
            // Regression: `{:?}` leaked the raw English enum variant name
            // ("Complete"/"Partial"/"Insufficient") unlocalized into
            // German reports.
            match normalized.execution.quality.status {
                crate::audit::AuditQualityStatus::Complete => key("Vollständig", "Complete"),
                crate::audit::AuditQualityStatus::Partial => key("Teilweise", "Partial"),
                crate::audit::AuditQualityStatus::Insufficient => {
                    key("Unzureichend", "Insufficient")
                }
            },
        ),
        (
            key("Audit-Hinweise", "Audit notes"),
            normalized.audit_flags.len().to_string(),
        ),
        (key("Vorschau", "Preview"), preview_value),
    ];
    // Audit exclusions (#645): never silent — selectors, matches (also
    // zero) and what was dropped.
    if let Some(note) = normalized
        .execution
        .exclusions
        .as_ref()
        .and_then(|report| crate::audit::exclusion::exclusion_note(report, i18n))
    {
        audit_facts.push((i18n.t("exclusion-fact-label"), note));
    }

    MethodologyBlock {
        scope,
        method,
        limitations,
        disclaimer,
        audit_facts,
        confidence_summary: build_confidence_summary(locale, normalized),
        capabilities: build_capability_matrix(locale, normalized),
    }
}

fn build_confidence_summary(locale: &str, normalized: &NormalizedReport) -> Vec<(String, String)> {
    let en = locale == "en";
    let base_confidence = if normalized.nodes_analyzed >= 2_000 {
        if en {
            "High"
        } else {
            "Hoch"
        }
    } else if normalized.nodes_analyzed >= 500 {
        if en {
            "Solid"
        } else {
            "Solide"
        }
    } else if en {
        "Limited"
    } else {
        "Begrenzt"
    };
    let caveat_level = if normalized.audit_flags.is_empty() {
        if en {
            "No automatically detected conflict signals"
        } else {
            "Keine automatisiert erkannten Konfliktsignale"
        }
    } else if normalized.audit_flags.len() == 1 {
        if en {
            "1 caveat signal"
        } else {
            "1 Hinweissignal"
        }
    } else if en {
        "Multiple caveat signals"
    } else {
        "Mehrere Hinweissignale"
    };
    let module_coverage = if normalized.module_scores.len() >= 5 {
        if en {
            "Broad"
        } else {
            "Breit"
        }
    } else if normalized.module_scores.len() >= 3 {
        if en {
            "Extended"
        } else {
            "Erweitert"
        }
    } else if en {
        "Core checks"
    } else {
        "Kern-Checks"
    };

    let (label_trust, label_coverage, label_signals, label_manual, val_manual) = if en {
        (
            "Audit confidence",
            "Module coverage",
            "Conflict signals",
            "Manual review needed",
            "Yes, for semantic quality and usage context",
        )
    } else {
        (
            "Audit-Vertrauen",
            "Modul-Abdeckung",
            "Konfliktsignale",
            "Manuelle Prüfung nötig",
            "Ja, für semantische Qualität und Nutzungskontext",
        )
    };

    vec![
        (label_trust.to_string(), base_confidence.to_string()),
        (label_coverage.to_string(), module_coverage.to_string()),
        (label_signals.to_string(), caveat_level.to_string()),
        (label_manual.to_string(), val_manual.to_string()),
    ]
}

fn build_capability_matrix(locale: &str, normalized: &NormalizedReport) -> Vec<CapabilitySignal> {
    let en = locale == "en";
    let confidence_high = if en { "High" } else { "Hoch" };
    let confidence_solid = if en { "Solid" } else { "Solide" };
    let confidence_off = if en { "Not active" } else { "Nicht aktiv" };

    let mut capabilities = vec![
        CapabilitySignal {
            signal: if en {
                "WCAG rules & occurrences".into()
            } else {
                "WCAG-Regeln & Vorkommen".into()
            },
            source: if en {
                "Accessibility tree + rule engine".into()
            } else {
                "Accessibility Tree + Regelengine".into()
            },
            confidence: if normalized.nodes_analyzed >= 500 {
                confidence_high.to_string()
            } else {
                confidence_solid.to_string()
            },
            surfaces: vec!["CLI".into(), "JSON".into(), "PDF".into(), "Studio".into()],
            note: if en {
                "Primary audit truth for automatically detectable violations.".to_string()
            } else {
                "Primäre Audit-Wahrheit für automatisiert erkennbare Verstöße.".to_string()
            },
        },
        CapabilitySignal {
            signal: if en {
                "Web vitals & loading indicators".into()
            } else {
                "Web Vitals & Ladeindikatoren".into()
            },
            source: if en {
                "Performance module".into()
            } else {
                "Performance-Modul".into()
            },
            confidence: if normalized
                .module_scores
                .iter()
                .any(|m| m.name == "Performance")
            {
                confidence_high.to_string()
            } else {
                confidence_off.to_string()
            },
            surfaces: vec!["CLI".into(), "JSON".into(), "PDF".into()],
            note: if en {
                "FCP, CLS and TTFB are reflected in facts and module sections.".to_string()
            } else {
                "FCP, CLS und TTFB werden in Facts und Modulkapiteln gespiegelt.".to_string()
            },
        },
        CapabilitySignal {
            signal: if en {
                "SEO structure & schema".into()
            } else {
                "SEO-Struktur & Schema".into()
            },
            source: if en {
                "SEO module".into()
            } else {
                "SEO-Modul".into()
            },
            confidence: if normalized.module_scores.iter().any(|m| m.name == "SEO") {
                confidence_solid.to_string()
            } else {
                confidence_off.to_string()
            },
            surfaces: vec!["CLI".into(), "JSON".into(), "PDF".into()],
            note: if en {
                "Meta, heading and schema signals are condensed into a report-ready form."
                    .to_string()
            } else {
                "Meta-, Heading- und Schema-Signale sind reportfähig verdichtet.".to_string()
            },
        },
        CapabilitySignal {
            signal: if en {
                "Security headers & HTTPS".into()
            } else {
                "Security Header & HTTPS".into()
            },
            source: if en {
                "Security module".into()
            } else {
                "Security-Modul".into()
            },
            confidence: if normalized
                .module_scores
                .iter()
                .any(|m| m.name == "Security")
            {
                confidence_high.to_string()
            } else {
                confidence_off.to_string()
            },
            surfaces: vec!["CLI".into(), "JSON".into(), "PDF".into()],
            note: if en {
                "Header presence and HTTPS status remain visible as raw signal.".to_string()
            } else {
                "Header-Präsenz und HTTPS-Status bleiben als Rohsignal sichtbar.".to_string()
            },
        },
        CapabilitySignal {
            signal: if en {
                "Mobile, UX, journey".into()
            } else {
                "Mobile, UX, Journey".into()
            },
            source: if en {
                "Heuristic modules".into()
            } else {
                "Heuristik-Module".into()
            },
            confidence: if en {
                "Indicator-based".into()
            } else {
                "Hinweisbasiert".into()
            },
            surfaces: vec!["CLI".into(), "JSON".into(), "PDF".into(), "Studio".into()],
            note: if en {
                "Useful for prioritization, not the sole UX truth.".to_string()
            } else {
                "Zur Priorisierung geeignet, nicht als alleinige UX-Gesamtwahrheit.".to_string()
            },
        },
    ];

    if !normalized.audit_flags.is_empty() {
        capabilities.push(CapabilitySignal {
            signal: if en {
                "Audit conflict signals".into()
            } else {
                "Audit-Konfliktsignale".into()
            },
            source: if en {
                "Normalization / cross-checks".into()
            } else {
                "Normalisierung / Cross-Checks".into()
            },
            confidence: if en {
                "Explicitly flagged".into()
            } else {
                "Explizit markiert".into()
            },
            surfaces: vec!["JSON".into(), "PDF".into()],
            note: if en {
                format!(
                    "{} conflict {} surfaced openly rather than hidden in the score.",
                    normalized.audit_flags.len(),
                    if normalized.audit_flags.len() == 1 {
                        "signal is"
                    } else {
                        "signals are"
                    }
                )
            } else {
                format!(
                    "{} {} offen ausgewiesen statt im Score versteckt.",
                    normalized.audit_flags.len(),
                    if normalized.audit_flags.len() == 1 {
                        "Konfliktsignal wird"
                    } else {
                        "Konfliktsignale werden"
                    }
                )
            },
        });
    }

    capabilities
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::normalized::normalize;
    use crate::audit::AuditQualityStatus;
    use crate::audit::AuditReport;
    use crate::cli::WcagLevel;
    use crate::i18n::I18n;
    use crate::wcag::WcagResults;

    fn report_with_quality_status(status: AuditQualityStatus) -> NormalizedReport {
        let raw = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            WcagResults::new(),
            500,
        );
        let mut normalized = normalize(&raw).normalized;
        normalized.execution.quality.status = status;
        normalized
    }

    #[test]
    fn audit_quality_status_is_localized_not_debug_formatted() {
        // Regression: `format!("{:?}", ...status)` leaked the raw English
        // enum variant name ("Partial") unlocalized into German reports.
        let normalized = report_with_quality_status(AuditQualityStatus::Partial);
        let i18n_de = I18n::new("de").expect("de locale loads");
        let block_de = build_methodology(&i18n_de, &normalized);
        let (_, value_de) = block_de
            .audit_facts
            .iter()
            .find(|(k, _)| k == "Audit-Qualität")
            .expect("Audit-Qualität fact present");
        assert_eq!(value_de, "Teilweise");

        let i18n_en = I18n::new("en").expect("en locale loads");
        let block_en = build_methodology(&i18n_en, &normalized);
        let (_, value_en) = block_en
            .audit_facts
            .iter()
            .find(|(k, _)| k == "Audit quality")
            .expect("Audit quality fact present");
        assert_eq!(value_en, "Partial");
    }
}