/** * HTML escaping utilities for safe DOM manipulation. * * Import rule: may only import from src/contracts/. * Constructors are side-effect free. * * @module utils/html */ /** * Escapes HTML special characters to prevent XSS injection. * * @param {string} str - String to escape. * @returns {string} HTML-escaped string safe for innerHTML. */ export function escapeHtml(str) { if (str === null || str === undefined) return ''; return String(str).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[c])); } /** * Safely sets innerHTML with escaped content. * * @param {HTMLElement} element - Target DOM element. * @param {string} html - HTML content to set (will be escaped). * @returns {void} */ export function safeInnerHTML(element, html) { if (!element) return; element.innerHTML = escapeHtml(html); } /** * Creates a text node with escaped content. * * @param {string} text - Text content. * @returns {Text} Text node. */ export function safeText(text) { return document.createTextNode(escapeHtml(text)); }