|
| 1 | +/** |
| 2 | + * Client-side error + performance logger. |
| 3 | + * |
| 4 | + * Captures runtime errors, unhandled promise rejections, failed resource |
| 5 | + * loads, slow long-tasks, and a few page-load timings. Persists the most |
| 6 | + * recent events to localStorage (capped) so you can pull them back after a |
| 7 | + * page crash or slowdown. |
| 8 | + * |
| 9 | + * Logs are NOT shipped anywhere — they live only in the browser. To inspect |
| 10 | + * them: |
| 11 | + * |
| 12 | + * 1. Open DevTools console (errors print there in real time, prefixed |
| 13 | + * `[client-error]` / `[client-perf]`). |
| 14 | + * 2. Run `window.__getClientLog()` — returns the current buffer as an |
| 15 | + * array. |
| 16 | + * 3. Run `window.__downloadClientLog()` — downloads the buffer as a |
| 17 | + * JSON file you can attach to a bug report. Or visit any URL on the |
| 18 | + * site with `?downloadClientLog` to trigger the download |
| 19 | + * automatically. |
| 20 | + * 4. Run `window.__clearClientLog()` to reset the buffer. |
| 21 | + * |
| 22 | + * Nothing here is committed to git: logs only live in localStorage / Blob |
| 23 | + * downloads, and the *.log gitignore at repo root blocks any local files |
| 24 | + * you save from the download dialog. |
| 25 | + */ |
| 26 | + |
| 27 | +interface LogEntry { |
| 28 | + ts: string; |
| 29 | + kind: |
| 30 | + | "error" |
| 31 | + | "unhandledrejection" |
| 32 | + | "resource-error" |
| 33 | + | "long-task" |
| 34 | + | "navigation" |
| 35 | + | "console-error" |
| 36 | + | "console-warn"; |
| 37 | + href: string; |
| 38 | + details: Record<string, unknown>; |
| 39 | +} |
| 40 | + |
| 41 | +const LOG_KEY = "__cosmosconf_client_log__"; |
| 42 | +const MAX_ENTRIES = 200; |
| 43 | +const LONG_TASK_THRESHOLD_MS = 200; |
| 44 | + |
| 45 | +function safeStringify(value: unknown): string { |
| 46 | + if (value instanceof Error) { |
| 47 | + return `${value.name}: ${value.message}\n${value.stack ?? ""}`; |
| 48 | + } |
| 49 | + if (typeof value === "string") return value; |
| 50 | + try { |
| 51 | + return JSON.stringify(value); |
| 52 | + } catch { |
| 53 | + return String(value); |
| 54 | + } |
| 55 | +} |
| 56 | + |
1 | 57 | function runWhenBrowser(fn: () => void): void { |
2 | 58 | if (typeof window === "undefined" || typeof document === "undefined") return; |
3 | 59 | fn(); |
4 | 60 | } |
5 | 61 |
|
6 | 62 | runWhenBrowser(() => { |
7 | | - const logPrefix = "[client-error]"; |
| 63 | + const w = window as unknown as { |
| 64 | + __getClientLog?: () => LogEntry[]; |
| 65 | + __clearClientLog?: () => void; |
| 66 | + __downloadClientLog?: () => void; |
| 67 | + }; |
8 | 68 |
|
9 | | - window.addEventListener("error", (event) => { |
10 | | - const errorEvent = event as ErrorEvent; |
11 | | - const details = { |
12 | | - message: errorEvent.message, |
13 | | - filename: errorEvent.filename, |
14 | | - lineno: errorEvent.lineno, |
15 | | - colno: errorEvent.colno, |
16 | | - stack: errorEvent.error?.stack, |
| 69 | + const readBuffer = (): LogEntry[] => { |
| 70 | + try { |
| 71 | + const raw = window.localStorage.getItem(LOG_KEY); |
| 72 | + if (!raw) return []; |
| 73 | + const parsed = JSON.parse(raw); |
| 74 | + return Array.isArray(parsed) ? (parsed as LogEntry[]) : []; |
| 75 | + } catch { |
| 76 | + return []; |
| 77 | + } |
| 78 | + }; |
| 79 | + |
| 80 | + const writeBuffer = (entries: LogEntry[]): void => { |
| 81 | + try { |
| 82 | + window.localStorage.setItem(LOG_KEY, JSON.stringify(entries)); |
| 83 | + } catch { |
| 84 | + // Quota or privacy mode — ignore. |
| 85 | + } |
| 86 | + }; |
| 87 | + |
| 88 | + const push = (entry: Omit<LogEntry, "ts" | "href">): void => { |
| 89 | + const full: LogEntry = { |
| 90 | + ts: new Date().toISOString(), |
17 | 91 | href: window.location.href, |
18 | | - userAgent: navigator.userAgent, |
| 92 | + ...entry, |
19 | 93 | }; |
20 | | - console.error(logPrefix, "window.error", details); |
21 | | - }); |
| 94 | + const buffer = readBuffer(); |
| 95 | + buffer.push(full); |
| 96 | + if (buffer.length > MAX_ENTRIES) buffer.splice(0, buffer.length - MAX_ENTRIES); |
| 97 | + writeBuffer(buffer); |
| 98 | + }; |
22 | 99 |
|
| 100 | + // Uncaught runtime errors + failed resource loads (capture phase needed |
| 101 | + // for resource errors since they don't bubble). |
| 102 | + window.addEventListener( |
| 103 | + "error", |
| 104 | + (event) => { |
| 105 | + const target = event.target as |
| 106 | + | (HTMLElement & { src?: string; href?: string }) |
| 107 | + | null; |
| 108 | + const isResourceError = |
| 109 | + !!target && |
| 110 | + target !== (window as unknown as EventTarget) && |
| 111 | + (target.tagName === "IMG" || |
| 112 | + target.tagName === "SCRIPT" || |
| 113 | + target.tagName === "LINK" || |
| 114 | + target.tagName === "VIDEO" || |
| 115 | + target.tagName === "AUDIO" || |
| 116 | + target.tagName === "SOURCE"); |
| 117 | + |
| 118 | + if (isResourceError) { |
| 119 | + const details = { |
| 120 | + tag: target!.tagName, |
| 121 | + url: target!.src || target!.href, |
| 122 | + userAgent: navigator.userAgent, |
| 123 | + }; |
| 124 | + // eslint-disable-next-line no-console |
| 125 | + console.error("[client-error]", "resource-error", details); |
| 126 | + push({ kind: "resource-error", details }); |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + const errorEvent = event as ErrorEvent; |
| 131 | + const details = { |
| 132 | + message: errorEvent.message, |
| 133 | + filename: errorEvent.filename, |
| 134 | + lineno: errorEvent.lineno, |
| 135 | + colno: errorEvent.colno, |
| 136 | + stack: errorEvent.error?.stack, |
| 137 | + userAgent: navigator.userAgent, |
| 138 | + }; |
| 139 | + // eslint-disable-next-line no-console |
| 140 | + console.error("[client-error]", "window.error", details); |
| 141 | + push({ kind: "error", details }); |
| 142 | + }, |
| 143 | + true |
| 144 | + ); |
| 145 | + |
| 146 | + // Unhandled promise rejections. |
23 | 147 | window.addEventListener("unhandledrejection", (event) => { |
24 | 148 | const reason = event.reason as Error | string | undefined; |
25 | 149 | const details = { |
26 | 150 | reason: typeof reason === "string" ? reason : reason?.message, |
27 | 151 | stack: typeof reason === "string" ? undefined : reason?.stack, |
28 | | - href: window.location.href, |
29 | 152 | userAgent: navigator.userAgent, |
30 | 153 | }; |
31 | | - console.error(logPrefix, "unhandledrejection", details); |
| 154 | + // eslint-disable-next-line no-console |
| 155 | + console.error("[client-error]", "unhandledrejection", details); |
| 156 | + push({ kind: "unhandledrejection", details }); |
32 | 157 | }); |
| 158 | + |
| 159 | + // Wrap console.error / console.warn so React hydration mismatches and |
| 160 | + // Docusaurus runtime warnings get persisted, not just printed. |
| 161 | + const origError = console.error.bind(console); |
| 162 | + console.error = (...args: unknown[]) => { |
| 163 | + try { |
| 164 | + const first = args[0]; |
| 165 | + // Avoid recursion on our own logs. |
| 166 | + if (!(typeof first === "string" && first.startsWith("[client-"))) { |
| 167 | + push({ |
| 168 | + kind: "console-error", |
| 169 | + details: { args: args.map(safeStringify) }, |
| 170 | + }); |
| 171 | + } |
| 172 | + } catch { |
| 173 | + // ignore |
| 174 | + } |
| 175 | + origError(...args); |
| 176 | + }; |
| 177 | + |
| 178 | + const origWarn = console.warn.bind(console); |
| 179 | + console.warn = (...args: unknown[]) => { |
| 180 | + try { |
| 181 | + const first = args[0]; |
| 182 | + if (!(typeof first === "string" && first.startsWith("[client-"))) { |
| 183 | + push({ |
| 184 | + kind: "console-warn", |
| 185 | + details: { args: args.map(safeStringify) }, |
| 186 | + }); |
| 187 | + } |
| 188 | + } catch { |
| 189 | + // ignore |
| 190 | + } |
| 191 | + origWarn(...args); |
| 192 | + }; |
| 193 | + |
| 194 | + // Long-task observer — anything that blocks the main thread above the |
| 195 | + // threshold is a likely cause of perceived slowness. |
| 196 | + if (typeof PerformanceObserver !== "undefined") { |
| 197 | + try { |
| 198 | + const longTaskObserver = new PerformanceObserver((list) => { |
| 199 | + for (const entry of list.getEntries()) { |
| 200 | + if (entry.duration < LONG_TASK_THRESHOLD_MS) continue; |
| 201 | + const details = { |
| 202 | + duration: Math.round(entry.duration), |
| 203 | + startTime: Math.round(entry.startTime), |
| 204 | + name: entry.name, |
| 205 | + entryType: entry.entryType, |
| 206 | + }; |
| 207 | + // eslint-disable-next-line no-console |
| 208 | + console.warn("[client-perf]", "long-task", details); |
| 209 | + push({ kind: "long-task", details }); |
| 210 | + } |
| 211 | + }); |
| 212 | + longTaskObserver.observe({ type: "longtask", buffered: true }); |
| 213 | + } catch { |
| 214 | + // longtask not supported in this browser — non-fatal. |
| 215 | + } |
| 216 | + |
| 217 | + try { |
| 218 | + const navObserver = new PerformanceObserver((list) => { |
| 219 | + for (const entry of list.getEntries() as PerformanceNavigationTiming[]) { |
| 220 | + const details = { |
| 221 | + type: entry.type, |
| 222 | + duration: Math.round(entry.duration), |
| 223 | + domContentLoaded: Math.round( |
| 224 | + entry.domContentLoadedEventEnd - entry.startTime |
| 225 | + ), |
| 226 | + loadEvent: Math.round(entry.loadEventEnd - entry.startTime), |
| 227 | + transferSize: entry.transferSize, |
| 228 | + }; |
| 229 | + push({ kind: "navigation", details }); |
| 230 | + } |
| 231 | + }); |
| 232 | + navObserver.observe({ type: "navigation", buffered: true }); |
| 233 | + } catch { |
| 234 | + // ignore |
| 235 | + } |
| 236 | + } |
| 237 | + |
| 238 | + // Helpers exposed on window. |
| 239 | + w.__getClientLog = () => readBuffer(); |
| 240 | + w.__clearClientLog = () => writeBuffer([]); |
| 241 | + w.__downloadClientLog = () => { |
| 242 | + const data = readBuffer(); |
| 243 | + const blob = new Blob([JSON.stringify(data, null, 2)], { |
| 244 | + type: "application/json", |
| 245 | + }); |
| 246 | + const url = URL.createObjectURL(blob); |
| 247 | + const a = document.createElement("a"); |
| 248 | + a.href = url; |
| 249 | + a.download = `cosmosconf-client-log-${new Date() |
| 250 | + .toISOString() |
| 251 | + .replace(/[:.]/g, "-")}.json`; |
| 252 | + document.body.appendChild(a); |
| 253 | + a.click(); |
| 254 | + document.body.removeChild(a); |
| 255 | + URL.revokeObjectURL(url); |
| 256 | + }; |
| 257 | + |
| 258 | + // `?downloadClientLog` query param triggers an automatic download. |
| 259 | + try { |
| 260 | + const params = new URLSearchParams(window.location.search); |
| 261 | + if (params.has("downloadClientLog")) { |
| 262 | + window.setTimeout(() => w.__downloadClientLog?.(), 1000); |
| 263 | + } |
| 264 | + } catch { |
| 265 | + // ignore |
| 266 | + } |
| 267 | + |
| 268 | + // One-line breadcrumb so you know the logger is alive. |
| 269 | + // eslint-disable-next-line no-console |
| 270 | + console.info( |
| 271 | + "[client-perf]", |
| 272 | + "logger ready — window.__getClientLog() / __downloadClientLog() / __clearClientLog()" |
| 273 | + ); |
33 | 274 | }); |
0 commit comments