| 1 | // Opt-in error/feedback mailbox. Off by default — the promise that "nothing |
| 2 | // leaves your machine" stays true unless the user decides otherwise in |
| 3 | // Settings. When it is on: |
| 4 | // - uncaught errors (window.onerror / unhandledrejection) and the specific |
| 5 | // places in the code that call reportError() are sent to /proxy/report |
| 6 | // (same origin, through the shared Elffuss proxy) |
| 7 | // - sendFeedback() sends free text the user deliberately wrote |
| 8 | // Code and project content are NEVER sent — only the technical message, the |
| 9 | // stack, the URL and the user agent. No queue and no retries: if the send |
| 10 | // fails it is simply dropped (this keeps a network failure from turning into |
| 11 | // unbounded storage). |
| 12 | let appName = 'elffuss'; |
| 13 | let enabled = false; |
| 14 | let hooked = false; |
| 15 | |
| 16 | const storageKey = () => 'elffuss.telemetry.' + appName; |
| 17 | |
| 18 | export function isEnabled() { return enabled; } |
| 19 | |
| 20 | export function setEnabled(v) { |
| 21 | enabled = !!v; |
| 22 | try { localStorage.setItem(storageKey(), enabled ? '1' : '0'); } catch { /* localStorage full/blocked */ } |
| 23 | if (enabled) hookGlobalErrors(); |
| 24 | } |
| 25 | |
| 26 | async function post(kind, message, opts = {}) { |
| 27 | if (!enabled) return; |
| 28 | try { |
| 29 | await fetch('/proxy/report', { |
| 30 | method: 'POST', |
| 31 | headers: { 'Content-Type': 'application/json' }, |
| 32 | body: JSON.stringify({ |
| 33 | app: appName, kind, message: String(message ?? '').slice(0, 2000), |
| 34 | stack: String(opts.stack || '').slice(0, 4000), |
| 35 | url: location.href, userAgent: navigator.userAgent, |
| 36 | extra: String(opts.extra || '').slice(0, 2000), |
| 37 | }), |
| 38 | }); |
| 39 | } catch { /* offline or proxy down: dropped, no retry */ } |
| 40 | } |
| 41 | |
| 42 | export function reportError(message, opts = {}) { return post('error', message, opts); } |
| 43 | export function sendFeedback(text) { return post('feedback', text); } |
| 44 | |
| 45 | function hookGlobalErrors() { |
| 46 | if (hooked) return; |
| 47 | hooked = true; |
| 48 | window.addEventListener('error', e => { |
| 49 | reportError(e.message || String(e.error) || 'error', { stack: e.error?.stack || '' }); |
| 50 | }); |
| 51 | window.addEventListener('unhandledrejection', e => { |
| 52 | const r = e.reason; |
| 53 | reportError('unhandledrejection: ' + (r?.message || r), { stack: r?.stack || '' }); |
| 54 | }); |
| 55 | } |
| 56 | |
| 57 | // Call ONCE at startup with the name of the app (so elffuss-code and |
| 58 | // elffuss-claw can be told apart in the reports) — reads the stored preference. |
| 59 | export function init(name) { |
| 60 | appName = name || appName; |
| 61 | try { enabled = localStorage.getItem(storageKey()) === '1'; } catch { enabled = false; } |
| 62 | if (enabled) hookGlobalErrors(); |
| 63 | } |