Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Utils/ValidateArticles
* @description CI-ready article validation tool that checks all news articles
* for quality, structural correctness, language consistency, and meta tag alignment.
*
* Can be run standalone or integrated into CI pipelines as a quality gate.
* Exits with code 1 if any article has validation errors.
*
* Usage:
* - Validate all articles: `npx tsx src/utils/validate-articles.ts`
* - Validate specific date: `npx tsx src/utils/validate-articles.ts --date=2026-03-04`
* - Strict mode (warnings are errors): `npx tsx src/utils/validate-articles.ts --strict`
* - Dry run (no exit code): `npx tsx src/utils/validate-articles.ts --dry-run`
*/
import fs from 'node:fs';
import path from 'node:path';
import { NEWS_DIR, ARTICLE_FILENAME_PATTERN } from '../constants/config.js';
import { validateArticleContent } from './content-validator.js';
// ─── Types ────────────────────────────────────────────────────────────────────
/** Validation summary for a single article */
interface ArticleValidationSummary {
filename: string;
lang: string;
slug: string;
date: string;
valid: boolean;
errors: string[];
warnings: string[];
wordCount: number;
}
/** Overall validation report */
interface ValidationReport {
totalArticles: number;
passed: number;
failed: number;
warnings: number;
articles: ArticleValidationSummary[];
}
// ─── CLI argument parsing ─────────────────────────────────────────────────────
const args = process.argv.slice(2);
/**
* Extract a CLI flag value: --flag=value
*
* @param name - Flag name to extract
* @returns Flag value or undefined if not found
*/
function getArg(name: string): string | undefined {
const prefix = `--${name}=`;
const arg = args.find((a) => a.startsWith(prefix));
return arg?.slice(prefix.length);
}
const filterDate = getArg('date');
const strictMode = args.includes('--strict');
const dryRun = args.includes('--dry-run');
// ─── Slug-to-article-type mapping ─────────────────────────────────────────────
/**
* Map article slug to article type for validator word-count thresholds.
* The slug is the middle portion of the filename: {date}-{slug}-{lang}.html
*
* @param slug - Article slug (e.g. "week-ahead", "breaking", "committee-reports")
* @returns Article type string matching ArticleCategory values
*/
function slugToArticleType(slug: string): string {
const mapping: Record<string, string> = {
'week-ahead': 'week-ahead',
'month-ahead': 'month-ahead',
breaking: 'breaking',
'committee-reports': 'committee-reports',
propositions: 'propositions',
motions: 'motions',
'week-in-review': 'week-in-review',
'month-in-review': 'month-in-review',
'weekly-review': 'week-in-review',
'monthly-review': 'month-in-review',
};
return mapping[slug] ?? slug;
}
// ─── Main validation logic ────────────────────────────────────────────────────
/**
* Validate all news articles in the news directory.
*
* @returns Validation report with per-article summaries
*/
function validateAllArticles(): ValidationReport {
if (!fs.existsSync(NEWS_DIR)) {
console.error(`❌ News directory not found: ${NEWS_DIR}`);
return { totalArticles: 0, passed: 0, failed: 0, warnings: 0, articles: [] };
}
const files = fs
.readdirSync(NEWS_DIR)
.filter((f) => f.endsWith('.html'))
.filter((f) => ARTICLE_FILENAME_PATTERN.test(f))
.filter((f) => (filterDate ? f.startsWith(filterDate) : true))
.sort();
const articles: ArticleValidationSummary[] = [];
let passed = 0;
let failed = 0;
let warningCount = 0;
for (const filename of files) {
const match = ARTICLE_FILENAME_PATTERN.exec(filename);
if (!match) continue;
const date = match[1] ?? '';
const slug = match[2] ?? '';
const lang = match[3] ?? '';
const filePath = path.join(NEWS_DIR, filename);
const html = fs.readFileSync(filePath, 'utf-8');
const articleType = slugToArticleType(slug);
const result = validateArticleContent(html, lang, articleType);
const summary: ArticleValidationSummary = {
filename,
lang,
slug,
date,
valid: strictMode ? result.valid && result.warnings.length === 0 : result.valid,
errors: [...result.errors],
warnings: [...result.warnings],
wordCount: result.metrics.wordCount,
};
if (strictMode && result.warnings.length > 0) {
summary.errors.push(...result.warnings.map((w) => `[strict] ${w}`));
}
if (summary.valid) {
passed++;
} else {
failed++;
}
if (result.warnings.length > 0) {
warningCount++;
}
articles.push(summary);
}
return {
totalArticles: files.length,
passed,
failed,
warnings: warningCount,
articles,
};
}
/**
* Print a formatted validation report to the console.
*
* @param report - Validation report to print
*/
function printReport(report: ValidationReport): void {
console.log('\n════════════════════════════════════════════════════════════════');
console.log(' EU Parliament Monitor — Article Validation Report');
console.log('════════════════════════════════════════════════════════════════\n');
if (filterDate) {
console.log(` Filter: articles from ${filterDate}`);
}
if (strictMode) {
console.log(' Mode: STRICT (warnings treated as errors)');
}
console.log(` Total articles: ${report.totalArticles}`);
console.log(` ✅ Passed: ${report.passed}`);
console.log(` ❌ Failed: ${report.failed}`);
console.log(` ⚠️ With warnings: ${report.warnings}\n`);
printFailures(report);
printWarnings(report);
console.log('══════════════════════════════════════════════════════════════\n');
}
/**
* Print failure details from the validation report.
*
* @param report - Validation report
*/
function printFailures(report: ValidationReport): void {
const failures = report.articles.filter((a) => !a.valid);
if (failures.length === 0) return;
console.log('── FAILURES ──────────────────────────────────────────────────\n');
for (const article of failures) {
console.log(` ❌ ${article.filename} (${article.wordCount} words)`);
for (const error of article.errors) {
console.log(` ERROR: ${error}`);
}
for (const warning of article.warnings) {
console.log(` WARN: ${warning}`);
}
console.log('');
}
}
/**
* Print warning details from the validation report.
*
* @param report - Validation report
*/
function printWarnings(report: ValidationReport): void {
const withWarnings = report.articles.filter((a) => a.valid && a.warnings.length > 0);
if (withWarnings.length === 0) return;
console.log('── WARNINGS ──────────────────────────────────────────────────\n');
for (const article of withWarnings) {
console.log(` ⚠️ ${article.filename} (${article.wordCount} words)`);
for (const warning of article.warnings) {
console.log(` WARN: ${warning}`);
}
console.log('');
}
}
// ─── CLI execution ────────────────────────────────────────────────────────────
const report = validateAllArticles();
printReport(report);
if (!dryRun && report.failed > 0) {
console.error(`❌ Validation failed: ${report.failed} article(s) have errors`);
process.exit(1);
} else if (report.failed === 0) {
console.log('✅ All articles passed validation');
}
|