// Copyright 2026 OpenObserve Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see .
/**
* HTML Utility Functions
* ======================
*
* Provides utilities for safe HTML rendering and manipulation.
*/
/**
* Escapes HTML characters in text for safe rendering
*
* Prevents XSS attacks by converting dangerous HTML characters into safe HTML entities.
* This ensures user content displays as literal text instead of executing as HTML markup.
*
* @param str - String to escape
* @returns HTML-safe string with entities escaped
*
* @example
* // Input containing malicious HTML
* const userInput = '';
* const safeOutput = escapeHtml(userInput);
* // Output: '<script>alert("hack")</script>'
* // Displays as: (visible text, not executed)
*
* @example
* // Log data with HTML tags
* const logMessage = '
Error: Database connection failed
';
* const escapedLog = escapeHtml(logMessage);
* // Output: '<h1>Error: Database connection failed</h1>'
* // Displays as: Error: Database connection failed
(visible text)
*
* @example
* // JSON data with quotes and ampersands
* const jsonData = '{"message": "Success & complete", "html": "content
"}';
* const safeJson = escapeHtml(jsonData);
* // Output: '{"message": "Success & complete", "html": "<div>content</div>"}'
*/
export function escapeHtml(str: string): string {
if (str == null) return "";
const s = typeof str === "string" ? str : String(str);
return s
.replace(/&/g, "&") // Must be first: & → &
.replace(//g, ">")
.replace(/"/g, """);
}