All files / src/utils file-utils.ts

96.96% Statements 96/99
82.45% Branches 47/57
100% Functions 23/23
96.87% Lines 93/96

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 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                                            15x 1x 1x     14x 20x                   26x   26x 3x     23x 23x       23x                                     2x   2x 4x     2x 6x 6x 6x         2x 4x     2x                   9x   14x                     26x   26x                     18x                     12x 12x                 40x 3x                     3x 3x 3x                 4x 4x   3x 3x                                   2x 4x 4x 4x 4x   3x 3x 2x   1x                         23x 23x     22x 22x   1x 1x 1x                                           23x 23x 23x 23x 23x 23x 23x 23x   3x 3x 2x   1x       23x                                         5x 5x                               25x                                               24x 24x 24x 24x     24x 24x 13x   23x 23x 12x         24x                   74479x                             325x 325x 325x                                   26x                                             33x   33x 231x 231x 36x   231x 21x       33x    
// 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 { randomUUID } from 'crypto';
import fs from 'fs';
import path from 'path';
import { NEWS_DIR, ARTICLE_FILENAME_PATTERN } from '../constants/config.js';
import { ALL_LANGUAGES } from '../constants/language-core.js';
import type { LanguageCode, 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;
  }
 
  const langCandidate = match[3] as string;
  Iif (!ALL_LANGUAGES.includes(langCandidate as LanguageCode)) {
    return null;
  }
 
  return {
    date: match[1] as string,
    slug: match[2] as string,
    lang: langCandidate as LanguageCode,
    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');
}
 
/**
 * Remove a file, ignoring ENOENT (file already deleted by another writer).
 *
 * @param filepath - Path to the file to remove
 */
function unlinkIfExists(filepath: string): void {
  try {
    fs.unlinkSync(filepath);
  } catch (err: unknown) {
    const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : '';
    Iif (code !== 'ENOENT') {
      throw err;
    }
  }
}
 
/**
 * Attempt to rename `src` to `dest` with a bounded retry loop.
 *
 * On each attempt the existing destination is removed first, then
 * `renameSync` is retried.  `EEXIST`/`EPERM` failures from concurrent
 * writers are tolerated for up to `maxRetries` attempts.
 *
 * @param src - Source (temp) file path
 * @param dest - Final destination path
 * @param maxRetries - Maximum number of unlink-then-rename attempts
 */
function renameWithRetry(src: string, dest: string, maxRetries: number): void {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    unlinkIfExists(dest);
    try {
      fs.renameSync(src, dest);
      return;
    } catch (retryErr: unknown) {
      const retryCode = retryErr instanceof Error ? (retryErr as NodeJS.ErrnoException).code : '';
      if ((retryCode === 'EEXIST' || retryCode === 'EPERM') && attempt < maxRetries - 1) {
        continue;
      }
      throw retryErr;
    }
  }
}
 
/**
 * Best-effort removal of a temporary file.  Ignores ENOENT (the file was
 * already renamed or never created) but logs a warning for other errors
 * (e.g. EBUSY, EACCES) so operators can detect leaked temp files.
 *
 * @param tempPath - Path to the temp file to remove
 */
function cleanupTempFile(tempPath: string): void {
  try {
    fs.unlinkSync(tempPath);
  } catch (unlinkErr: unknown) {
    const errno =
      unlinkErr && typeof unlinkErr === 'object' ? (unlinkErr as NodeJS.ErrnoException) : undefined;
    if (errno?.code !== 'ENOENT') {
      const message =
        errno && typeof errno.message === 'string' ? errno.message : String(unlinkErr);
      const code = errno?.code ?? 'UNKNOWN';
      console.warn(
        `atomicWrite: failed to remove temporary file "${tempPath}" (code: ${code}): ${message}`
      );
    }
  }
}
 
/**
 * Write content to a file atomically.
 *
 * Writes to a uniquely-named temporary file in the same directory first, then
 * renames it to the final path. The temp filename includes the PID and a random
 * UUID so that concurrent callers targeting the same destination never collide
 * on the intermediate file. If the rename fails the temp file is cleaned up in
 * a `finally` block. On platforms where `renameSync` does not overwrite an
 * existing destination (e.g. Windows), the error is caught and the target is
 * removed before retrying the rename.
 *
 * @param filepath - Final output file path
 * @param content - File content to write
 */
export function atomicWrite(filepath: string, content: string): void {
  const dir = path.dirname(filepath);
  ensureDirectoryExists(dir);
  const uniqueSuffix = `${process.pid}-${randomUUID()}`;
  const tempPath = `${filepath}.${uniqueSuffix}.tmp`;
  try {
    fs.writeFileSync(tempPath, content, 'utf-8');
    try {
      fs.renameSync(tempPath, filepath);
    } catch (err: unknown) {
      const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : '';
      if (code === 'EEXIST' || code === 'EPERM') {
        renameWithRetry(tempPath, filepath, 3);
      } else {
        throw err;
      }
    }
  } finally {
    cleanupTempFile(tempPath);
  }
}
 
/**
 * Check whether a news article file already exists on disk.
 *
 * This is used by generation pipelines to skip work when a prior workflow run
 * (or the same run) has already produced the article, avoiding unnecessary
 * regeneration and potential merge conflicts.
 *
 * @param slug - Article slug including date prefix (e.g. `"2025-01-15-week-ahead"`)
 * @param lang - Language code (e.g. `"en"`)
 * @param newsDir - Absolute path to the news output directory (defaults to NEWS_DIR)
 * @returns `true` when the article file exists
 */
export function checkArticleExists(
  slug: string,
  lang: string,
  newsDir: string = NEWS_DIR
): boolean {
  const filename = `${slug}-${lang}.html`;
  return fs.existsSync(path.join(newsDir, filename));
}
 
/**
 * 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: `&amp;` MUST be decoded last. Decoding it first would convert
 * `&amp;lt;` to `&lt;` before the `&lt;` → `<` replacement runs, causing
 * double-decoding. The correct order is: decode all specific entities first,
 * then decode `&amp;` as the final step.
 *
 * @param str - HTML string with entities
 * @returns Plain text with entities decoded
 */
function decodeHtmlEntities(str: string): string {
  return str
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&amp;/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 `&quot;`. 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, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
 
/**
 * 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;
  }
}
 
/** Result of article HTML validation */
export interface ArticleValidationResult {
  /** Whether the article passes all structural checks */
  valid: boolean;
  /** List of missing elements */
  errors: readonly string[];
}
 
/** Required structural elements that every article must contain */
const REQUIRED_ARTICLE_ELEMENTS: ReadonlyArray<{
  selector: string | readonly string[];
  label: string;
}> = [
  {
    selector: ['class="site-header__langs"', 'class="language-switcher"'],
    label: 'language switcher nav',
  },
  { selector: 'class="article-top-nav"', label: 'article-top-nav (back button)' },
  { selector: 'class="site-header"', label: 'site-header' },
  { selector: 'class="skip-link"', label: 'skip-link' },
  { selector: 'class="reading-progress"', label: 'reading-progress bar' },
  { selector: '<main id="main"', label: 'main content wrapper' },
  { selector: 'class="site-footer"', label: 'site-footer' },
] as const;
 
/**
 * Validate that generated article HTML includes all required structural elements.
 *
 * This is the primary validation gate — articles must be generated correctly
 * by the template. The fix-articles script is only a fallback for legacy articles.
 *
 * @param html - Complete HTML string of the article
 * @returns Validation result with errors list (empty if valid)
 */
export function validateArticleHTML(html: string): ArticleValidationResult {
  const errors: string[] = [];
 
  for (const element of REQUIRED_ARTICLE_ELEMENTS) {
    const sel = element.selector;
    const found = Array.isArray(sel)
      ? sel.some((s) => html.includes(s))
      : html.includes(sel as string);
    if (!found) {
      errors.push(`Missing required element: ${element.label}`);
    }
  }
 
  return { valid: errors.length === 0, errors };
}