/** Copy text, with a fallback for admin screens served over plain HTTP. */ export async function copyText(text: string): Promise { try { if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); return true; } } catch { // Fall through to the legacy method. } const area = document.createElement('textarea'); area.value = text; area.setAttribute('readonly', ''); area.style.position = 'fixed'; area.style.top = '-1000px'; document.body.appendChild(area); area.select(); let ok = false; try { ok = document.execCommand('copy'); } catch { ok = false; } document.body.removeChild(area); return ok; } /** Save text as a file in the browser. */ export function downloadText(content: string, filename: string, type = 'text/plain') { const blob = new Blob([content], { type: `${type};charset=utf-8` }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.setTimeout(() => URL.revokeObjectURL(url), 1000); } /** * One CSV cell. Plugin names and advisory titles are written by third parties, * and a spreadsheet runs a cell that starts with =, +, - or @ as a formula, so * those get a leading apostrophe. Cells with a comma, quote or line break are * quoted. */ export function csvCell(value: unknown): string { let text = value === null || value === undefined ? '' : String(value); if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`; return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; } export function slugify(value: string, fallback = 'document'): string { const slug = value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); return slug || fallback; } export function uuid(): string { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' && window.isSecureContext) { return crypto.randomUUID(); } const bytes = new Uint8Array(16); crypto.getRandomValues(bytes); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; }