interface JsonViewerProps { data: unknown; collapsed?: boolean; } // Escape characters that have special meaning inside HTML so that user-supplied // JSON content (metadata, retrieval payloads, etc.) cannot inject markup when // rendered via dangerouslySetInnerHTML below. function escapeHtml(input: string): string { return input .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } function syntaxHighlight(jsonString: string): string { // Escape first, then run the syntax-highlight regex against the escaped // text. The regex only matches ASCII punctuation (quotes, digits, the // literal words true/false/null) which survive HTML escaping unchanged, // so token boundaries are preserved. return escapeHtml(jsonString).replace( /("(\\u[\da-fA-F]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, (match) => { let cls = "text-orange-600 dark:text-orange-400"; // number if (match.startsWith('"')) { if (match.endsWith(":")) { cls = "text-blue-600 dark:text-blue-400"; // key } else { cls = "text-green-600 dark:text-green-400"; // string } } else if (/true|false/.test(match)) { cls = "text-violet-600 dark:text-violet-400"; // boolean } else if (match === "null") { cls = "text-muted-foreground"; // null } return `${match}`; }, ); } export function JsonViewer({ data, collapsed = false }: JsonViewerProps) { const jsonString = JSON.stringify(data, null, 2); if (collapsed) { const preview = typeof data === "object" && data !== null ? Array.isArray(data) ? `[…] (${data.length} items)` : `{…} (${Object.keys(data).length} keys)` : jsonString; return (
        {preview}
      
); } return (
      
    
); }