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 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 | 1x 1x 1x 1x 1x 11x 11x 7x 7x 7x 6x 6x 1x 10x 6x 1x 6x 6x 6x 2x 4x 3x 3x 1x 2x 2x 1x 1x 1x 1x 1x | #!/usr/bin/env -S npx tsx
/**
* Fix Analysis References: Inject missing "š Analysis & Sources" section
*
* This script ensures ALL news articles contain the analysis-references section
* linking to the analysis files that were created in the same workflow run.
* It scans the analysis/ directory to discover exactly which files exist,
* then injects properly localized links into any article missing the section.
*
* **Idempotent** ā safe to run multiple times. Skips articles that already
* have `class="analysis-references"`.
*
* Usage:
* npx tsx scripts/fix-analysis-references.ts
* npx tsx scripts/fix-analysis-references.ts --dry-run
* npx tsx scripts/fix-analysis-references.ts --date 2026-04-10
* npx tsx scripts/fix-analysis-references.ts --date 2026-04-10 --type committee-reports
*
* @author Hack23 AB
* @license Apache-2.0
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import type { Language } from './types/language.js';
import { ALL_LANG_CODES } from './article-template/constants.js';
import {
generateAnalysisReferencesHtml,
AGGREGATION_ARTICLE_TYPES,
} from './analysis-references.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const NEWS_DIR = path.join(ROOT, 'news');
// ---------------------------------------------------------------------------
// Filename slug ā article type mapping
// ---------------------------------------------------------------------------
/**
* Maps filename slugs (as they appear in article filenames) to the canonical
* article type keys used by ARTICLE_TYPE_TO_ANALYSIS_SUBFOLDER.
*
* Filenames like `2026-04-10-government-propositions-en.html` use
* `government-propositions` as the slug, but the analysis subfolder key is
* `propositions`.
*/
const FILENAME_SLUG_TO_ARTICLE_TYPE: Record<string, string> = {
'committee-reports': 'committee-reports',
'government-propositions': 'propositions',
'opposition-motions': 'motions',
'interpellation-debates': 'interpellations',
'evening-analysis': 'evening-analysis',
'week-ahead': 'week-ahead',
'month-ahead': 'month-ahead',
'weekly-review': 'weekly-review',
'monthly-review': 'monthly-review',
'deep-inspection': 'deep-inspection',
};
// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------
interface ArticleInfo {
date: string;
slug: string;
articleType: string;
lang: Language;
filepath: string;
}
/**
* Parse an article filename into its components.
* Returns null for files that don't match the expected pattern.
*/
function parseArticleFilename(filename: string): ArticleInfo | null {
// Pattern: YYYY-MM-DD-{slug}-{lang}.html
const match = filename.match(/^(\d{4}-\d{2}-\d{2})-(.+)-([a-z]{2})\.html$/);
if (!match) return null;
const [, date, slug, langStr] = match;
const lang = langStr as Language;
if (!ALL_LANG_CODES.includes(lang)) return null;
// Try direct slug match first
let articleType = FILENAME_SLUG_TO_ARTICLE_TYPE[slug];
// If no direct match, try prefix matching for breaking news and other dynamic slugs
if (!articleType) {
for (const [prefix, type] of Object.entries(FILENAME_SLUG_TO_ARTICLE_TYPE)) {
Iif (slug.startsWith(prefix)) {
articleType = type;
break;
}
}
}
// Breaking news: slug starts with "breaking-"
if (!articleType && slug.startsWith('breaking-')) {
articleType = 'breaking';
}
// Realtime monitor articles have timestamps
Iif (!articleType && slug.startsWith('realtime-')) {
articleType = 'realtime';
}
Iif (!articleType) return null;
return {
date,
slug,
articleType,
lang,
filepath: path.join(NEWS_DIR, filename),
};
}
// ---------------------------------------------------------------------------
// Injection logic
// ---------------------------------------------------------------------------
/**
* Check if an article already has an analysis-references section.
*/
function hasAnalysisReferences(html: string): boolean {
return html.includes('class="analysis-references"');
}
/**
* Check if an aggregation-type article has cross-reference links.
* Returns true if the article has the "Cross-Referenced Analysis" subsection.
*/
function hasCrossReferences(html: string): boolean {
return html.includes('Cross-Referenced Analysis') || html.includes('Korsrefererad analys');
}
/**
* Remove the existing analysis-references section from HTML.
* Returns the HTML without the section, or the original if not found.
*/
function removeAnalysisReferences(html: string): string {
const startTag = '<section class="analysis-references"';
const endTag = '</section>';
const startIdx = html.indexOf(startTag);
if (startIdx === -1) return html;
const endIdx = html.indexOf(endTag, startIdx);
if (endIdx === -1) return html;
// Remove from start of section to end of </section> plus trailing newline
const afterEnd = endIdx + endTag.length;
const trailing = html[afterEnd] === '\n' ? afterEnd + 1 : afterEnd;
return html.slice(0, startIdx) + html.slice(trailing);
}
/**
* Inject the analysis-references HTML section into an article.
* Inserts before </body>, or before <footer if </body> not found.
* Returns the modified HTML, or null if no injection point was found.
*/
function injectAnalysisReferences(html: string, referencesHtml: string): string | null {
if (!referencesHtml) return null;
// Try insertion points in priority order:
// 1. Before <footer class="article-footer"> (standard template pattern)
const footerMatch = html.match(/<footer\s+class="article-footer"/);
if (footerMatch && footerMatch.index !== undefined) {
return (
html.slice(0, footerMatch.index) +
referencesHtml +
'\n ' +
html.slice(footerMatch.index)
);
}
// 2. Before any <footer> tag
const anyFooterIdx = html.indexOf('<footer');
if (anyFooterIdx !== -1) {
return (
html.slice(0, anyFooterIdx) +
referencesHtml +
'\n ' +
html.slice(anyFooterIdx)
);
}
// 3. Before </body>
const bodyCloseIdx = html.indexOf('</body>');
Eif (bodyCloseIdx !== -1) {
return (
html.slice(0, bodyCloseIdx) +
referencesHtml +
'\n' +
html.slice(bodyCloseIdx)
);
}
// 4. Append before end of file as last resort
return html + '\n' + referencesHtml + '\n';
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
function main(): void {
const args = process.argv.slice(2);
const dryRun = args.includes('--dry-run');
const upgrade = args.includes('--upgrade');
const dateIdx = args.indexOf('--date');
const filterDate = dateIdx !== -1 ? args[dateIdx + 1] : undefined;
const typeIdx = args.indexOf('--type');
const filterType = typeIdx !== -1 ? args[typeIdx + 1] : undefined;
console.log('š Fix Analysis References ā Ensuring all articles link to their analysis files');
if (dryRun) console.log(' (dry run ā no files will be modified)\n');
if (upgrade) console.log(' (upgrade mode ā will replace existing sections for aggregation types missing cross-references)\n');
if (filterDate) console.log(` Filtering to date: ${filterDate}`);
if (filterType) console.log(` Filtering to type: ${filterType}`);
console.log('');
if (!fs.existsSync(NEWS_DIR)) {
console.log('No news/ directory found. Nothing to do.');
return;
}
const files = fs.readdirSync(NEWS_DIR).filter(f => f.endsWith('.html') && !f.startsWith('index'));
console.log(`Found ${files.length} article files in news/\n`);
let checked = 0;
let alreadyHas = 0;
let injected = 0;
let upgraded = 0;
let noAnalysis = 0;
let skipped = 0;
for (const filename of files.sort()) {
const info = parseArticleFilename(filename);
if (!info) {
skipped++;
continue;
}
// Apply filters
if (filterDate && info.date !== filterDate) continue;
if (filterType && info.articleType !== filterType && info.slug !== filterType) continue;
checked++;
let html = fs.readFileSync(info.filepath, 'utf-8');
const alreadyExists = hasAnalysisReferences(html);
// Check if this aggregation-type article needs cross-reference upgrade
if (alreadyExists && upgrade && AGGREGATION_ARTICLE_TYPES.has(info.articleType) && !hasCrossReferences(html)) {
// Remove old section and re-inject with cross-references
html = removeAnalysisReferences(html);
const referencesHtml = generateAnalysisReferencesHtml({
date: info.date,
articleType: info.articleType,
lang: info.lang,
});
if (referencesHtml) {
const modified = injectAnalysisReferences(html, referencesHtml);
if (modified) {
if (!dryRun) {
fs.writeFileSync(info.filepath, modified, 'utf-8');
}
upgraded++;
console.log(` š ${dryRun ? 'Would upgrade' : 'Upgraded'} with cross-references: ${filename}`);
continue;
}
}
}
if (alreadyExists) {
alreadyHas++;
continue;
}
// Generate analysis references for this article
const referencesHtml = generateAnalysisReferencesHtml({
date: info.date,
articleType: info.articleType,
lang: info.lang,
});
if (!referencesHtml) {
noAnalysis++;
console.log(` ā ļø No analysis files found for: ${filename} (type=${info.articleType}, date=${info.date})`);
continue;
}
const modified = injectAnalysisReferences(html, referencesHtml);
if (!modified) {
console.log(` ā Could not find injection point in: ${filename}`);
continue;
}
if (!dryRun) {
fs.writeFileSync(info.filepath, modified, 'utf-8');
}
injected++;
console.log(` ā
${dryRun ? 'Would inject' : 'Injected'} analysis references into: ${filename}`);
}
console.log('\n=== Summary ===');
console.log(`Articles checked: ${checked}`);
console.log(`Already have analysis references: ${alreadyHas}`);
console.log(`Injected analysis references: ${injected}`);
console.log(`Upgraded with cross-references: ${upgraded}`);
console.log(`No analysis files available: ${noAnalysis}`);
console.log(`Skipped (unrecognized pattern): ${skipped}`);
if (dryRun) console.log('\n(Dry run ā no files were modified)');
console.log('\nā Done!');
}
import { pathToFileURL } from 'url';
Iif (import.meta.url === pathToFileURL(process.argv[1]).href) {
main();
}
// ---------------------------------------------------------------------------
// Exports for testing
// ---------------------------------------------------------------------------
export {
parseArticleFilename,
hasAnalysisReferences,
hasCrossReferences,
removeAnalysisReferences,
injectAnalysisReferences,
FILENAME_SLUG_TO_ARTICLE_TYPE,
};
export type { ArticleInfo };
|