All files / scripts html-utils.ts

100% Statements 6/6
75% Branches 3/4
100% Functions 2/2
100% Lines 5/5

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                  20x               20x                   16346x 16328x   23171x      
/**
 * @module Infrastructure/HTMLSanitization
 * @description XSS-safe HTML entity escaping utility.
 * Bounded context: Infrastructure / Security
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
const HTML_ENTITY_MAP: Readonly<Record<string, string>> = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#039;',
} as const;
 
const HTML_ESCAPE_PATTERN = /[&<>"']/g;
 
/**
 * Escape HTML special characters for safe inclusion in HTML/JSON-LD.
 * Prevents XSS by converting &, <, >, ", ' to their HTML entity equivalents.
 *
 * @param text - Raw text to escape
 * @returns Escaped text safe for HTML insertion; empty string for falsy input
 */
export function escapeHtml(text: string | null | undefined | number): string {
  if (!text) return '';
  return String(text).replace(
    HTML_ESCAPE_PATTERN,
    (m: string): string => HTML_ENTITY_MAP[m] ?? m,
  );
}