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 | 8x 1x 1x 7x 11x 17x 17x 3x 14x 2x 2x 4x 2x 6x 6x 6x 2x 5x 2x 8x 11x 1x 1x 11x 9x 9x 17x 2x 3x 3x 3x 15x 15x 15x 15x 15x 15x 15x 7x 14x 14x 8x 15x 17246x 146x 146x 146x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Utils/FileUtils
* @description Shared file system utilities for news article operations
*/
import fs from 'fs';
import path from 'path';
import { NEWS_DIR, ARTICLE_FILENAME_PATTERN } from '../constants/config.js';
import type { ParsedArticle } from '../types/index.js';
/**
* Get all news article HTML files from the news directory
*
* @param newsDir - News directory path (defaults to NEWS_DIR)
* @returns List of article filenames
*/
export function getNewsArticles(newsDir: string = NEWS_DIR): string[] {
if (!fs.existsSync(newsDir)) {
console.log('📁 News directory does not exist yet');
return [];
}
const files = fs.readdirSync(newsDir);
return files.filter((f) => f.endsWith('.html') && !f.startsWith('index-'));
}
/**
* Parse article filename to extract metadata
*
* @param filename - Article filename (e.g., "2025-01-15-week-ahead-en.html")
* @returns Parsed metadata or null if filename doesn't match pattern
*/
export function parseArticleFilename(filename: string): ParsedArticle | null {
const match = filename.match(ARTICLE_FILENAME_PATTERN);
if (!match) {
return null;
}
return {
date: match[1] as string,
slug: match[2] as string,
lang: match[3] as string,
filename,
};
}
/**
* Group articles by language code
*
* @param articles - List of article filenames
* @param languages - Supported language codes
* @returns Articles grouped by language, sorted newest first
*/
export function groupArticlesByLanguage(
articles: string[],
languages: readonly string[]
): Record<string, ParsedArticle[]> {
const grouped: Record<string, ParsedArticle[]> = {};
for (const lang of languages) {
grouped[lang] = [];
}
for (const article of articles) {
const parsed = parseArticleFilename(article);
Eif (parsed && grouped[parsed.lang] !== undefined) {
grouped[parsed.lang]!.push(parsed);
}
}
// Sort by date (newest first)
for (const lang in grouped) {
grouped[lang]!.sort((a, b) => b.date.localeCompare(a.date));
}
return grouped;
}
/**
* Format slug for display (hyphen-separated to Title Case)
*
* @param slug - Hyphen-separated slug string
* @returns Formatted title string
*/
export function formatSlug(slug: string): string {
return slug
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
/**
* Get file modification time as YYYY-MM-DD string
*
* @param filepath - Path to file
* @returns Last modified date in YYYY-MM-DD format
*/
export function getModifiedDate(filepath: string): string {
const stats = fs.statSync(filepath);
// split('T') on an ISO string always produces at least one element
return stats.mtime.toISOString().split('T')[0]!;
}
/**
* Format date for article slug
*
* @param date - Date to format (defaults to now)
* @returns Formatted date string (YYYY-MM-DD)
*/
export function formatDateForSlug(date: Date = new Date()): string {
// split('T') on an ISO string always produces at least one element
return date.toISOString().split('T')[0]!;
}
/**
* Calculate read time estimate from content
*
* @param content - Article content text
* @param wordsPerMinute - Reading speed (default 250)
* @returns Estimated read time in minutes
*/
export function calculateReadTime(content: string, wordsPerMinute: number = 250): number {
const words = content.split(/\s+/).length;
return Math.ceil(words / wordsPerMinute);
}
/**
* Ensure a directory exists, creating it recursively if needed
*
* @param dirPath - Directory path to ensure
*/
export function ensureDirectoryExists(dirPath: string): void {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
/**
* Write content to a file with UTF-8 encoding
*
* @param filepath - Output file path
* @param content - File content
*/
export function writeFileContent(filepath: string, content: string): void {
const dir = path.dirname(filepath);
ensureDirectoryExists(dir);
fs.writeFileSync(filepath, content, 'utf-8');
}
/**
* Decode the 5 HTML entities produced by escapeHTML() back to plain text.
* Used when extracting text from our own generated HTML to obtain unescaped values.
*
* IMPORTANT: `&` MUST be decoded last. Decoding it first would convert
* `&lt;` to `<` before the `<` → `<` replacement runs, causing
* double-decoding. The correct order is: decode all specific entities first,
* then decode `&` as the final step.
*
* @param str - HTML string with entities
* @returns Plain text with entities decoded
*/
function decodeHtmlEntities(str: string): string {
return str
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
/**
* Extract title and description from a generated article HTML file.
* Reads the predictable template structure produced by article-template.ts.
* Falls back to empty strings when the file cannot be read.
* HTML entities from the template are decoded to produce plain text.
*
* NOTE: The meta description regex relies on the template's use of escapeHTML(),
* which converts `"` to `"`. Because descriptions are always stored with
* double-quote delimiters and inner quotes are HTML-encoded, the `[^"]+` pattern
* safely captures the full value. If the template ever changes its quoting
* convention this regex must be updated accordingly.
*
* @param filepath - Path to the article HTML file
* @returns Object with title (from first h1) and description (from meta description)
*/
export function extractArticleMeta(filepath: string): { title: string; description: string } {
let title = '';
let description = '';
try {
const content = fs.readFileSync(filepath, 'utf-8');
// Matches h1 with any attributes but only plain-text content (no nested tags).
// The template always writes plain escaped text in h1, so this is correct.
const titleMatch = content.match(/<h1[^>]*>([^<]+)<\/h1>/u);
if (titleMatch?.[1]) {
title = decodeHtmlEntities(titleMatch[1].trim());
}
const descMatch = content.match(/<meta name="description" content="([^"]+)"/u);
if (descMatch?.[1]) {
description = decodeHtmlEntities(descMatch[1]);
}
} catch {
// File not readable – return empty strings
}
return { title, description };
}
/**
* Escape special HTML characters to prevent XSS
*
* @param str - Raw string to escape
* @returns HTML-safe string
*/
export function escapeHTML(str: string): string {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Validate that a URL uses a safe scheme (http or https)
*
* @param url - URL string to validate
* @returns true if URL has a safe scheme
*/
export function isSafeURL(url: string): boolean {
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}
|