@xovris/browser 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ import { type Client } from '@xovris/core';
2
+ export interface BrowserOptions {
3
+ url: string | undefined;
4
+ key: string | undefined;
5
+ release?: string | undefined;
6
+ environment?: string | undefined;
7
+ tunnel?: string | undefined;
8
+ }
9
+ export declare function init(o: BrowserOptions, w?: Window | undefined): Client;
10
+ export declare function captureException(err: unknown): string | null;
11
+ /** Tests only: forget the page-wide client. */
12
+ export declare function resetForTests(): void;
package/dist/index.js ADDED
@@ -0,0 +1,29 @@
1
+ // @xovris/browser (ADR 0011): browser errors and unhandled rejections sent to Xovris with the page address. Nothing is
2
+ // sent until init() has both values the wizard wrote; the key is ingestion-only (it can send, never read). The client is
3
+ // page-wide, shared by every bundle that loaded Xovris, so two copies on one page never send twice.
4
+ import { createClient } from '@xovris/core';
5
+ const SHARED = Symbol.for('xovris.browser.v1');
6
+ const shared = () => {
7
+ const g = globalThis;
8
+ return (g[SHARED] ??= { client: null, windows: new WeakSet() });
9
+ };
10
+ export function init(o, w = typeof window === 'undefined' ? undefined : window) {
11
+ const s = shared();
12
+ if (s.client)
13
+ return s.client;
14
+ const c = createClient({ url: o.url, key: o.key, release: o.release, environment: o.environment, platform: 'javascript', tunnel: o.tunnel, isOnline: () => (typeof navigator === 'undefined' ? true : navigator.onLine !== false) });
15
+ s.client = c;
16
+ // One pair of listeners per window, always reporting through the page's current client - never a stale one.
17
+ if (c.enabled && w && !s.windows.has(w)) {
18
+ s.windows.add(w);
19
+ const where = () => ({ url: w.location.href });
20
+ w.addEventListener('error', (e) => { shared().client?.captureException(e.error ?? e.message, { handled: false, mechanism: 'onerror', request: where() }); });
21
+ w.addEventListener('unhandledrejection', (e) => { shared().client?.captureException(e.reason, { handled: false, mechanism: 'onunhandledrejection', request: where() }); });
22
+ }
23
+ return c;
24
+ }
25
+ export function captureException(err) {
26
+ return shared().client?.captureException(err, { handled: true, mechanism: 'manual' }) ?? null;
27
+ }
28
+ /** Tests only: forget the page-wide client. */
29
+ export function resetForTests() { shared().client = null; }
package/dist/mask.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** Free text with every personal value replaced by its kind. Bounded: at most 2,000 characters are read. */
2
+ export declare function maskText(input: unknown, max?: number): string;
3
+ /** A URL as the person's browser held it, kept to what identifies the page: origin and path, identifiers replaced, query values and fragment gone. */
4
+ export declare function maskUrl(input: string, base?: string): string;
5
+ /** An element named for a person debugging the page - tag, id and up to two classes, or its data-xovris-name - never its text or its values. */
6
+ export declare function safeTarget(el: Element | Node | null | undefined): string | undefined;
7
+ /** Every string inside a value masked, keys kept - the last guard before anything is queued to leave. */
8
+ export declare function maskDeep<T>(v: T, depth?: number): T;
package/dist/mask.js ADDED
@@ -0,0 +1,102 @@
1
+ // D06.01.01, D06.03.01: masking on by default, in the browser, before anything leaves it - the same mask for every signal
2
+ // (RUM events, replay, feedback, the element a vital names) so no path carries what another path hides. Text is never read
3
+ // for sending: an element is named by its tag, id and classes; a URL keeps its path with every identifier replaced and loses
4
+ // its query values and fragment; any free text that must travel (an error message, a feedback note) has emails, card numbers
5
+ // (Luhn-checked), phone numbers, national identifiers, IBANs, IP addresses, tokens and long digit runs replaced by their kind.
6
+ const EMAIL = /\b[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
7
+ const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g;
8
+ const BEARER = /\b(bearer|basic|token)\s+[A-Za-z0-9._~+/=-]{12,}/gi;
9
+ const KEYISH = /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{8,}\b|\bgh[pousr]_[A-Za-z0-9]{20,}\b|\bxox[abposr]-[A-Za-z0-9-]{10,}\b|\bAKIA[A-Z0-9]{16}\b|\bAIza[0-9A-Za-z_-]{35}\b/g;
10
+ const SECRET_KV = /\b(password|passwd|pwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|token|session[_-]?id)(\s*[:=]\s*)["']?[^\s"'&,;]{3,}/gi;
11
+ const IBAN = /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,7}(?:\s?[A-Z0-9]{1,4})?\b/g;
12
+ const CARD = /\b(?:\d[ -]?){12,18}\d\b/g;
13
+ const SSN = /\b\d{3}-\d{2}-\d{4}\b/g;
14
+ const NINO = /\b[A-Z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-D]\b/gi;
15
+ const PHONE = /(?:\+|\b00)\d[\d ()-]{7,16}\d\b|\b0\d{2,4}[ -]?\d{3,4}[ -]?\d{3,4}\b|\(\d{3}\)\s?\d{3}[ -]?\d{4}\b/g;
16
+ const IPV4 = /\b(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}\b/g;
17
+ const IPV6 = /\b(?:[0-9a-f]{1,4}:){3,7}[0-9a-f]{1,4}\b/gi;
18
+ const DIGITS = /\b\d{6,}\b/g;
19
+ function luhn(digits) {
20
+ let sum = 0;
21
+ let double = false;
22
+ for (let i = digits.length - 1; i >= 0; i -= 1) {
23
+ let d = digits.charCodeAt(i) - 48;
24
+ if (d < 0 || d > 9)
25
+ return false;
26
+ if (double) {
27
+ d *= 2;
28
+ if (d > 9)
29
+ d -= 9;
30
+ }
31
+ sum += d;
32
+ double = !double;
33
+ }
34
+ return digits.length >= 13 && digits.length <= 19 && sum % 10 === 0;
35
+ }
36
+ /** Free text with every personal value replaced by its kind. Bounded: at most 2,000 characters are read. */
37
+ export function maskText(input, max = 500) {
38
+ let s = String(input ?? '').slice(0, 2000);
39
+ s = s.replace(JWT, '[token]').replace(BEARER, (_m, w) => `${w} [token]`).replace(KEYISH, '[token]').replace(SECRET_KV, (_m, k, sep) => `${k}${sep}[secret]`);
40
+ s = s.replace(EMAIL, '[email]').replace(IBAN, '[iban]');
41
+ s = s.replace(CARD, (m) => (luhn(m.replace(/[ -]/g, '')) ? '[card]' : m));
42
+ s = s.replace(SSN, '[id]').replace(NINO, '[id]').replace(PHONE, '[phone]').replace(IPV4, '[ip]').replace(IPV6, '[ip]').replace(DIGITS, '[number]');
43
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
44
+ }
45
+ const ID_SEGMENT = /^(?:\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|[A-Za-z0-9_-]{24,})$/i;
46
+ /** A URL as the person's browser held it, kept to what identifies the page: origin and path, identifiers replaced, query values and fragment gone. */
47
+ export function maskUrl(input, base = 'https://x.invalid') {
48
+ let u;
49
+ try {
50
+ u = new URL(input, base);
51
+ }
52
+ catch {
53
+ return maskText(input, 200);
54
+ }
55
+ const path = u.pathname.split('/').map((seg) => {
56
+ if (!seg)
57
+ return seg;
58
+ let d = seg;
59
+ try {
60
+ d = decodeURIComponent(seg);
61
+ }
62
+ catch { /* keep the raw segment */ }
63
+ if (ID_SEGMENT.test(d))
64
+ return ':id';
65
+ const m = maskText(d, 120);
66
+ return m === d ? seg : ':masked';
67
+ }).join('/');
68
+ const keys = [...new Set([...u.searchParams.keys()])].slice(0, 12).map((k) => `${encodeURIComponent(maskText(k, 40))}=`);
69
+ const origin = u.origin === 'null' || base.startsWith(u.origin) ? '' : u.origin;
70
+ return `${origin}${path}${keys.length ? `?${keys.join('&')}` : ''}`;
71
+ }
72
+ const SAFE_TOKEN = /^[A-Za-z][A-Za-z0-9_-]{0,40}$/;
73
+ /** An element named for a person debugging the page - tag, id and up to two classes, or its data-xovris-name - never its text or its values. */
74
+ export function safeTarget(el) {
75
+ if (!el || el.nodeType !== 1)
76
+ return undefined;
77
+ const e = el;
78
+ const named = e.getAttribute('data-xovris-name');
79
+ if (named && SAFE_TOKEN.test(named))
80
+ return `[data-xovris-name=${named}]`;
81
+ const tag = e.tagName.toLowerCase();
82
+ const id = e.id && SAFE_TOKEN.test(e.id) && maskText(e.id) === e.id ? `#${e.id}` : '';
83
+ const cls = Array.from(e.classList ?? []).filter((c) => SAFE_TOKEN.test(c) && maskText(c) === c).slice(0, 2).map((c) => `.${c}`).join('');
84
+ const role = e.getAttribute('role');
85
+ return `${tag}${id}${cls}${role && SAFE_TOKEN.test(role) ? `[role=${role}]` : ''}`;
86
+ }
87
+ /** Every string inside a value masked, keys kept - the last guard before anything is queued to leave. */
88
+ export function maskDeep(v, depth = 0) {
89
+ if (depth > 8)
90
+ return undefined;
91
+ if (typeof v === 'string')
92
+ return maskText(v, 2000);
93
+ if (Array.isArray(v))
94
+ return v.slice(0, 500).map((x) => maskDeep(x, depth + 1));
95
+ if (v && typeof v === 'object') {
96
+ const out = {};
97
+ for (const [k, x] of Object.entries(v).slice(0, 200))
98
+ out[k] = maskDeep(x, depth + 1);
99
+ return out;
100
+ }
101
+ return v;
102
+ }
@@ -0,0 +1,31 @@
1
+ export interface ReplayOptions {
2
+ endpoint: string;
3
+ key: string;
4
+ session: string;
5
+ transport?: (url: string, body: string, beacon: boolean) => unknown;
6
+ chunkMs?: number;
7
+ /** Why recording is allowed: the visitor's consent, or the site's own setting where it asks for none - the door checks it again. */
8
+ basis: 'consent' | 'site_setting';
9
+ consent: () => 'granted' | 'denied' | 'unknown';
10
+ }
11
+ /** The recorder's own options - the masking contract, exported so the class proof reads exactly what runs. */
12
+ export declare const REPLAY_RECORD_OPTIONS: {
13
+ readonly maskAllInputs: true;
14
+ readonly maskTextSelector: '*';
15
+ readonly blockSelector: 'img,picture,video,audio,canvas,iframe,object,embed,[data-xovris-block]';
16
+ readonly inlineImages: false;
17
+ readonly inlineStylesheet: true;
18
+ readonly recordCanvas: false;
19
+ readonly collectFonts: false;
20
+ readonly recordCrossOriginIframes: false;
21
+ readonly slimDOMOptions: 'all';
22
+ readonly sampling: {
23
+ readonly mousemove: 50;
24
+ readonly scroll: 150;
25
+ readonly input: 'last';
26
+ readonly media: 800;
27
+ };
28
+ };
29
+ /** One rrweb event with every attribute value masked, walked to any depth (snapshots nest, mutations list attributes). */
30
+ export declare function maskReplayEvent<T>(ev: T, origin?: string, depth?: number): T;
31
+ export declare function startReplay(o: ReplayOptions, w: Window): () => void;
package/dist/replay.js ADDED
@@ -0,0 +1,80 @@
1
+ // D06.01.01, D06.08: privacy-masked session replay - rrweb's recorder (MIT; the recorder Sentry, PostHog and Highlight build
2
+ // theirs on), adopted rather than rebuilt, with every masking switch on and none of them exposed: all text masked, every input
3
+ // masked, images, video, canvas and frames blocked, no inlined images, fonts or canvas pixels, and every attribute that can carry
4
+ // a value (href, src, title, alt, value, aria-label, data-*) run through the same mask as every other signal before a chunk
5
+ // leaves. Loaded only when the site turned replay on and the visitor consented (rum.ts decides); chunks every five seconds.
6
+ import { record } from '@rrweb/record';
7
+ import { maskText, maskUrl } from './mask.js';
8
+ /** The recorder's own options - the masking contract, exported so the class proof reads exactly what runs. */
9
+ export const REPLAY_RECORD_OPTIONS = {
10
+ maskAllInputs: true,
11
+ maskTextSelector: '*',
12
+ blockSelector: 'img,picture,video,audio,canvas,iframe,object,embed,[data-xovris-block]',
13
+ inlineImages: false,
14
+ inlineStylesheet: true,
15
+ recordCanvas: false,
16
+ collectFonts: false,
17
+ recordCrossOriginIframes: false,
18
+ slimDOMOptions: 'all',
19
+ sampling: { mousemove: 50, scroll: 150, input: 'last', media: 800 },
20
+ };
21
+ const URL_ATTRS = new Set(['href', 'src', 'srcset', 'action', 'poster', 'cite', 'data']);
22
+ const TEXT_ATTRS = /^(title|alt|value|placeholder|aria-[a-z-]+|data-[a-z0-9_-]+|content|label|name)$/i;
23
+ /** One rrweb event with every attribute value masked, walked to any depth (snapshots nest, mutations list attributes). */
24
+ export function maskReplayEvent(ev, origin = 'https://x.invalid', depth = 0) {
25
+ // G96's bank (19 Oct): an array for depth became a growing string at every level and 100,000 items never returned - read as numbers
26
+ if (typeof depth !== 'number' || !Number.isFinite(depth))
27
+ depth = 0;
28
+ if (typeof origin !== 'string')
29
+ origin = 'https://x.invalid';
30
+ if (depth > 400 || ev === null || typeof ev !== 'object')
31
+ return ev;
32
+ if (Array.isArray(ev))
33
+ return ev.map((x) => maskReplayEvent(x, origin, depth + 1));
34
+ const out = {};
35
+ for (const [k, v] of Object.entries(ev)) {
36
+ if (k === 'attributes' && v && typeof v === 'object' && !Array.isArray(v)) {
37
+ const a = {};
38
+ for (const [n, x] of Object.entries(v)) {
39
+ if (typeof x !== 'string') {
40
+ a[n] = x;
41
+ continue;
42
+ }
43
+ a[n] = URL_ATTRS.has(n.toLowerCase()) ? maskUrl(x, origin) : TEXT_ATTRS.test(n) ? (x ? '*'.repeat(Math.min(x.length, 24)) : x) : maskText(x, 400);
44
+ }
45
+ out[k] = a;
46
+ }
47
+ else if (k === 'textContent' && typeof v === 'string')
48
+ out[k] = v.replace(/\S/g, '*');
49
+ else if ((k === 'text' || k === 'href') && typeof v === 'string')
50
+ out[k] = k === 'href' ? maskUrl(v, origin) : v.replace(/\S/g, '*');
51
+ else
52
+ out[k] = maskReplayEvent(v, origin, depth + 1);
53
+ }
54
+ return out;
55
+ }
56
+ export function startReplay(o, w) {
57
+ let buffer = [];
58
+ let seq = 0;
59
+ const flush = (beacon) => {
60
+ if (!buffer.length)
61
+ return;
62
+ const events = buffer.splice(0, buffer.length).map((e) => maskReplayEvent(e, w.location.origin));
63
+ if (o.consent() === 'denied')
64
+ return;
65
+ const body = JSON.stringify({ v: 1, key: o.key, session: o.session, seq: seq++, basis: o.basis, consent: o.consent(), events });
66
+ try {
67
+ if (o.transport)
68
+ o.transport(o.endpoint, body, beacon);
69
+ else if (!(beacon && w.navigator.sendBeacon?.(o.endpoint, new Blob([body], { type: 'text/plain' }))))
70
+ void w.fetch(o.endpoint, { method: 'POST', body, keepalive: true, credentials: 'omit', headers: { 'content-type': 'text/plain' } }).catch(() => undefined);
71
+ }
72
+ catch { /* never reports itself */ }
73
+ };
74
+ const stopRec = record({ ...REPLAY_RECORD_OPTIONS, emit: (e) => { buffer.push(e); if (buffer.length >= 200)
75
+ flush(false); } });
76
+ const timer = setInterval(() => flush(false), o.chunkMs ?? 5000);
77
+ const onHide = () => flush(true);
78
+ w.addEventListener('pagehide', onHide);
79
+ return () => { clearInterval(timer); w.removeEventListener('pagehide', onHide); flush(true); stopRec?.(); buffer = []; };
80
+ }
package/dist/rum.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ export type Consent = 'granted' | 'denied' | 'unknown';
2
+ export type RumKind = 'view' | 'vital' | 'resource' | 'interaction' | 'freeze' | 'error' | 'connectivity' | 'broken_screen' | 'startup' | 'feedback' | 'flag' | 'repair';
3
+ export interface RumEvent {
4
+ kind: RumKind;
5
+ at: number;
6
+ route: string;
7
+ data: Record<string, unknown>;
8
+ }
9
+ export interface Cohort {
10
+ device: 'mobile' | 'tablet' | 'desktop';
11
+ browser: string;
12
+ os: string;
13
+ connection?: string;
14
+ lang?: string;
15
+ }
16
+ export interface RumOptions {
17
+ /** The ingest origin the wizard wrote (https://ingest.xovris.ai); nothing is sent without it and the key. */
18
+ url: string | undefined;
19
+ key: string | undefined;
20
+ release?: string | undefined;
21
+ environment?: string | undefined;
22
+ /** Share of sessions recorded (0-1, default 1), decided once per session. */
23
+ sampleRate?: number;
24
+ flushMs?: number;
25
+ /** At most this many events a page view (default 300); the server's caps stand behind it. */
26
+ maxEventsPerView?: number;
27
+ /** The visitor's choice where the site asks; 'denied' stops everything, and replay waits for 'granted'. */
28
+ consent?: Consent;
29
+ replay?: false | {
30
+ sampleRate?: number;
31
+ consentRequired?: boolean;
32
+ };
33
+ /** Xovris may correct a fault in this visitor's browser when the server names one (today: a stale service worker unregistered and the page loaded once). Default on; false keeps it to reporting. */
34
+ repairs?: boolean;
35
+ /** Tests and custom transports: where a batch goes instead of the network; a transport that answers with the door's JSON gets its directives applied. */
36
+ transport?: (url: string, body: string, beacon: boolean) => unknown;
37
+ }
38
+ export interface Rum {
39
+ readonly session: string;
40
+ readonly cohort: Cohort;
41
+ readonly sampled: boolean;
42
+ /** A feature flag's value in this session - read when a fault concentrates on one (D06.02.01). */
43
+ setFlag(name: string, value: string | boolean | number): void;
44
+ setConsent(c: Consent): void;
45
+ /** The visitor's own words about what went wrong, linked to this session only; the visitor is shown nothing back. */
46
+ feedback(message: string, o?: {
47
+ contact?: string;
48
+ }): void;
49
+ /** A route change a router reports itself (history changes are seen without it). */
50
+ view(route?: string): void;
51
+ flush(): void;
52
+ stop(): void;
53
+ readonly queued: number;
54
+ /** Tests: record a vital as web-vitals reports it. */
55
+ readonly vital: (m: {
56
+ name: string;
57
+ value: number;
58
+ rating?: string;
59
+ navigationType?: string;
60
+ attribution?: Record<string, unknown>;
61
+ }) => void;
62
+ }
63
+ /** The cohort a person is in, from what the browser says of itself - never an identifier. */
64
+ export declare function cohortOf(w: Window): Cohort;
65
+ /** D06.03: did the screen break after the page answered 200? Read in the visitor's browser; no text leaves it. */
66
+ export declare function brokenScreen(d: Document, o: {
67
+ status: number | null;
68
+ errorSinceView: boolean;
69
+ }): string[];
70
+ export declare function startRum(o: RumOptions, w?: Window | undefined): Rum;
package/dist/rum.js ADDED
@@ -0,0 +1,369 @@
1
+ // D06.01, D06.01.02.01, D06.01.03, D06.03: real-user monitoring in @xovris/browser. Before this the browser SDK sent errors only
2
+ // (D06.07's note). One session per tab (30 minutes idle ends it), sampled once at its start; every signal a person feels:
3
+ // navigation and route changes with their timings, the Core Web Vitals through Google's own web-vitals library (attribution
4
+ // build) naming the element or interaction responsible, failed and slow API calls, rage, dead and error clicks, freezes (long
5
+ // animation frames and a stalled main thread), crashes, startup time, connectivity changes - each with the session's cohort
6
+ // (device, browser, OS, connection). A screen that broke after an HTTP 200 (blank, an empty root, an error message, an error
7
+ // straight after load) is detected here, in the session that saw it. Masking is on by default and cannot be turned off for
8
+ // inputs (mask.ts); replay is a separate, consent-gated recorder (replay.ts) loaded only when allowed.
9
+ import { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals/attribution';
10
+ import { maskDeep, maskText, maskUrl, safeTarget } from './mask.js';
11
+ const SESSION_KEY = 'xovris.rum.session';
12
+ const REPAIRED_KEY = 'xovris.rum.repaired';
13
+ const IDLE_MS = 30 * 60_000;
14
+ const ERROR_TEXT = /\b(something went wrong|application error|unexpected error|an error occurred|chunkloaderror|failed to fetch dynamically imported module|this page isn['’]t working|oops)\b/i;
15
+ function randomId(w) {
16
+ const b = new Uint8Array(16);
17
+ (w.crypto ?? globalThis.crypto).getRandomValues(b);
18
+ return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
19
+ }
20
+ /** The session this tab is in: kept 30 idle minutes in the tab's own storage, sampled once when it begins. */
21
+ function sessionOf(w, rate) {
22
+ const now = Date.now();
23
+ try {
24
+ const raw = w.sessionStorage.getItem(SESSION_KEY);
25
+ const s = raw ? JSON.parse(raw) : null;
26
+ if (s && /^[0-9a-f]{32}$/.test(s.id) && now - s.last < IDLE_MS) {
27
+ w.sessionStorage.setItem(SESSION_KEY, JSON.stringify({ ...s, last: now }));
28
+ return s;
29
+ }
30
+ const fresh = { id: randomId(w), last: now, sampled: Math.random() < rate };
31
+ w.sessionStorage.setItem(SESSION_KEY, JSON.stringify(fresh));
32
+ return fresh;
33
+ }
34
+ catch {
35
+ return { id: randomId(w), sampled: Math.random() < rate };
36
+ }
37
+ }
38
+ /** The cohort a person is in, from what the browser says of itself - never an identifier. */
39
+ export function cohortOf(w) {
40
+ const n = w.navigator;
41
+ const ua = n.userAgent ?? '';
42
+ const width = w.innerWidth || 1024;
43
+ const mobile = n.userAgentData?.mobile ?? /Mobi|Android|iPhone/i.test(ua);
44
+ const device = /iPad|Tablet/i.test(ua) || (!mobile && /Android/i.test(ua)) ? 'tablet' : mobile || width < 600 ? 'mobile' : 'desktop';
45
+ const brand = n.userAgentData?.brands?.find((b) => !/Not.?A.?Brand|Chromium/i.test(b.brand));
46
+ const m = /(Edg|OPR|Firefox|Chrome|Version)\/(\d+)/.exec(ua);
47
+ const browser = brand ? `${brand.brand} ${brand.version.split('.')[0]}` : m ? `${m[1] === 'Version' ? 'Safari' : m[1] === 'Edg' ? 'Edge' : m[1] === 'OPR' ? 'Opera' : m[1]} ${m[2]}` : 'unknown';
48
+ const os = n.userAgentData?.platform || (/Windows/.test(ua) ? 'Windows' : /Mac OS X|Macintosh/.test(ua) ? 'macOS' : /Android/.test(ua) ? 'Android' : /iPhone|iPad|iOS/.test(ua) ? 'iOS' : /Linux/.test(ua) ? 'Linux' : 'unknown');
49
+ const lang = (n.language ?? '').split('-')[0] || undefined;
50
+ return { device, browser, os, ...(n.connection?.effectiveType ? { connection: n.connection.effectiveType } : {}), ...(lang ? { lang } : {}) };
51
+ }
52
+ /** D06.03: did the screen break after the page answered 200? Read in the visitor's browser; no text leaves it. */
53
+ export function brokenScreen(d, o) {
54
+ if (o.status !== null && o.status !== 200)
55
+ return [];
56
+ const why = [];
57
+ const body = d.body;
58
+ const text = (body?.innerText ?? body?.textContent ?? '').replace(/\s+/g, ' ').trim();
59
+ const media = body ? body.querySelectorAll('img,svg,canvas,video,iframe').length : 0;
60
+ if (text.length < 3 && media === 0)
61
+ why.push('blank');
62
+ const root = d.querySelector('#root, #app, #__next, [data-reactroot], main');
63
+ if (root && root.children.length === 0 && (root.textContent ?? '').trim().length === 0)
64
+ why.push('empty_root');
65
+ if (text && ERROR_TEXT.test(text.slice(0, 4000)))
66
+ why.push('error_text');
67
+ if (o.errorSinceView)
68
+ why.push('error_after_load');
69
+ return why;
70
+ }
71
+ export function startRum(o, w = typeof window === 'undefined' ? undefined : window) {
72
+ const cohort = w ? cohortOf(w) : { device: 'desktop', browser: 'unknown', os: 'unknown' };
73
+ const gpc = w?.navigator?.globalPrivacyControl === true;
74
+ const s = w ? sessionOf(w, Math.min(1, Math.max(0, o.sampleRate ?? 1))) : { id: '', sampled: false };
75
+ let consent = o.consent ?? 'unknown';
76
+ const off = { session: s.id, cohort, sampled: false, setFlag: () => undefined, setConsent: () => undefined, feedback: () => undefined, view: () => undefined, flush: () => undefined, stop: () => undefined, queued: 0, vital: () => undefined };
77
+ if (!w || !o.url || !o.key || !/^[a-f0-9]{32}$/.test(o.key) || !s.sampled || consent === 'denied')
78
+ return { ...off, sampled: false };
79
+ const endpoint = `${new URL(o.url).origin}/v1/rum`;
80
+ const flags = {};
81
+ const maxPerView = o.maxEventsPerView ?? 300;
82
+ let queue = [];
83
+ // a visitor's notes ride in the next batch itself, so a note can never reach the door before the session it belongs to
84
+ const notes = [];
85
+ let inView = 0;
86
+ let route = maskUrl(w.location.pathname, w.location.origin);
87
+ let viewAt = Date.now();
88
+ let lastErrorAt = 0;
89
+ let lastNetworkAt = 0;
90
+ let lastMutationAt = 0;
91
+ let timer = null;
92
+ let brokenTimer = null;
93
+ const stops = [];
94
+ const send = (beacon) => {
95
+ if (timer) {
96
+ clearTimeout(timer);
97
+ timer = null;
98
+ }
99
+ if ((!queue.length && !notes.length) || consent === 'denied')
100
+ return;
101
+ const events = queue.splice(0, 100);
102
+ const feedback = notes.splice(0, 5);
103
+ const body = JSON.stringify({ v: 1, key: o.key, session: s.id, release: o.release ?? null, environment: o.environment ?? null, cohort, consent, flags, repairs: o.repairs !== false, events, ...(feedback.length ? { feedback } : {}) });
104
+ try {
105
+ if (o.transport)
106
+ void Promise.resolve(o.transport(endpoint, body, beacon)).then(applyAnswer).catch(() => undefined);
107
+ else if (!(beacon && w.navigator.sendBeacon?.(endpoint, new Blob([body], { type: 'text/plain' })))) {
108
+ void (of ?? w.fetch.bind(w))(endpoint, { method: 'POST', body, keepalive: true, credentials: 'omit', headers: { 'content-type': 'text/plain' } }).then((r) => r.text()).then(applyAnswer).catch(() => undefined);
109
+ }
110
+ }
111
+ catch { /* the monitor never reports itself */ }
112
+ if (queue.length || notes.length)
113
+ send(beacon);
114
+ };
115
+ const push = (kind, data) => {
116
+ if (consent === 'denied' || inView >= maxPerView)
117
+ return;
118
+ inView += 1;
119
+ queue.push({ kind, at: Date.now(), route, data: maskDeep(data) });
120
+ if (!timer)
121
+ timer = setTimeout(() => send(false), o.flushMs ?? 5000);
122
+ };
123
+ // D06.03 repair: the door names a correction this page earned on its own evidence; a stale service worker is unregistered and the
124
+ // page loaded once from the newest release - once per tab, so a correction can never loop, and recorded as a 'repair' signal.
125
+ function applyAnswer(raw) {
126
+ if (o.repairs === false || typeof raw !== 'string' || !raw)
127
+ return;
128
+ let a;
129
+ try {
130
+ a = JSON.parse(raw);
131
+ }
132
+ catch {
133
+ return;
134
+ }
135
+ const d = (a.directives ?? []).find((x) => x.kind === 'unregister_service_worker');
136
+ const sw = w.navigator.serviceWorker;
137
+ if (!d || !sw?.getRegistrations)
138
+ return;
139
+ try {
140
+ if (w.sessionStorage.getItem(REPAIRED_KEY))
141
+ return;
142
+ w.sessionStorage.setItem(REPAIRED_KEY, String(Date.now()));
143
+ }
144
+ catch {
145
+ return;
146
+ }
147
+ void sw.getRegistrations().then((rs) => Promise.all(rs.map((r) => r.unregister()))).then((done) => {
148
+ push('repair', { kind: 'unregister_service_worker', from: d.release ?? null, to: d.newest ?? null, unregistered: done.filter(Boolean).length });
149
+ send(true);
150
+ w.location.reload();
151
+ }).catch(() => undefined);
152
+ }
153
+ // the view, its timings and its status - and the broken-screen check a few seconds after it settles
154
+ const navStatus = () => {
155
+ try {
156
+ const nav = w.performance?.getEntriesByType?.('navigation')?.[0];
157
+ return typeof nav?.responseStatus === 'number' && nav.responseStatus > 0 ? nav.responseStatus : null;
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ };
163
+ const checkScreen = (status) => {
164
+ if (brokenTimer)
165
+ clearTimeout(brokenTimer);
166
+ brokenTimer = setTimeout(() => {
167
+ const why = brokenScreen(w.document, { status, errorSinceView: lastErrorAt >= viewAt });
168
+ if (why.length)
169
+ push('broken_screen', { why, status: status ?? 200, afterMs: Date.now() - viewAt });
170
+ }, 3000);
171
+ };
172
+ const view = (next, soft = true) => {
173
+ route = maskUrl(next ?? w.location.pathname, w.location.origin);
174
+ viewAt = Date.now();
175
+ inView = 0;
176
+ if (soft) {
177
+ push('view', { navigationType: 'soft' });
178
+ checkScreen(null);
179
+ return;
180
+ }
181
+ const nav = w.performance?.getEntriesByType?.('navigation')?.[0];
182
+ const status = navStatus();
183
+ push('view', { navigationType: nav?.type ?? 'navigate', status, ttfbMs: nav ? Math.round(nav.responseStart) : null, domContentLoadedMs: nav ? Math.round(nav.domContentLoadedEventEnd) : null, loadMs: nav ? Math.round(nav.loadEventEnd) : null, sw: !!w.navigator.serviceWorker?.controller });
184
+ if (nav && nav.domInteractive > 0)
185
+ push('startup', { interactiveMs: Math.round(nav.domInteractive), domContentLoadedMs: Math.round(nav.domContentLoadedEventEnd), loadMs: Math.round(nav.loadEventEnd) });
186
+ checkScreen(status);
187
+ };
188
+ // route changes made by the page itself
189
+ const H = w.history;
190
+ const orig = { push: H.pushState, replace: H.replaceState };
191
+ H.pushState = function (...a) { const r = orig.push.apply(this, a); view(); return r; };
192
+ H.replaceState = function (...a) { const before = w.location.pathname; const r = orig.replace.apply(this, a); if (w.location.pathname !== before)
193
+ view(); return r; };
194
+ const onPop = () => view();
195
+ w.addEventListener('popstate', onPop);
196
+ stops.push(() => { H.pushState = orig.push; H.replaceState = orig.replace; w.removeEventListener('popstate', onPop); });
197
+ // the Core Web Vitals, each naming what was responsible - through Google's own library, never a hand-made copy
198
+ const vital = (m) => {
199
+ const a = m.attribution ?? {};
200
+ const target = (a['target'] ?? a['interactionTarget'] ?? a['largestShiftTarget']);
201
+ push('vital', { name: m.name, value: Math.round(m.value * (m.name === 'CLS' ? 1000 : 1)) / (m.name === 'CLS' ? 1000 : 1), rating: m.rating ?? null, navigationType: m.navigationType ?? null, ...(target ? { target: maskText(target, 160) } : {}), ...(a['interactionType'] ? { interaction: a['interactionType'] } : {}), ...(typeof a['inputDelay'] === 'number' ? { inputDelayMs: Math.round(a['inputDelay']), processingMs: Math.round(a['processingDuration'] ?? 0), presentationMs: Math.round(a['presentationDelay'] ?? 0) } : {}) });
202
+ };
203
+ const opts = { generateTarget: (el) => safeTarget(el) };
204
+ try {
205
+ onLCP(vital, opts);
206
+ onINP(vital, opts);
207
+ onCLS(vital, opts);
208
+ onFCP(vital, opts);
209
+ onTTFB(vital, opts);
210
+ }
211
+ catch { /* a browser without the APIs reports none */ }
212
+ // API calls the page depends on: failed or slow, never their bodies
213
+ const self = (u) => u.startsWith(endpoint);
214
+ const of = w.fetch?.bind(w);
215
+ if (of) {
216
+ w.fetch = async (input, init) => {
217
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
218
+ const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET')).toUpperCase();
219
+ const t0 = Date.now();
220
+ try {
221
+ const r = await of(input, init);
222
+ if (!self(url)) {
223
+ lastNetworkAt = Date.now();
224
+ if (r.status >= 400 || Date.now() - t0 > 3000)
225
+ push('resource', { api: true, method, url: maskUrl(url, w.location.origin), status: r.status, durationMs: Date.now() - t0 });
226
+ }
227
+ return r;
228
+ }
229
+ catch (e) {
230
+ if (!self(url)) {
231
+ lastNetworkAt = Date.now();
232
+ push('resource', { api: true, method, url: maskUrl(url, w.location.origin), status: 0, failed: String(e?.name ?? 'Error'), durationMs: Date.now() - t0 });
233
+ }
234
+ throw e;
235
+ }
236
+ };
237
+ stops.push(() => { w.fetch = of; });
238
+ }
239
+ // failed scripts, styles and images (capture phase), and the page's own errors
240
+ const onError = (e) => {
241
+ const t = e.target;
242
+ if (t && t !== w && typeof t.tagName === 'string') {
243
+ push('resource', { api: false, type: t.tagName.toLowerCase(), url: maskUrl(t.src || t.href || '', w.location.origin), failed: 'load' });
244
+ return;
245
+ }
246
+ lastErrorAt = Date.now();
247
+ const ev = e;
248
+ const err = ev.error;
249
+ push('error', { type: err?.name ?? 'Error', message: maskText(err?.message ?? ev.message ?? '', 300), handled: false });
250
+ };
251
+ const onRejection = (e) => { lastErrorAt = Date.now(); const r = e.reason; push('error', { type: r?.name ?? 'UnhandledRejection', message: maskText(r?.message ?? String(e.reason ?? ''), 300), handled: false }); };
252
+ w.addEventListener('error', onError, true);
253
+ w.addEventListener('unhandledrejection', onRejection);
254
+ stops.push(() => { w.removeEventListener('error', onError, true); w.removeEventListener('unhandledrejection', onRejection); });
255
+ // rage, dead and error clicks
256
+ const MO = w.MutationObserver;
257
+ const mo = typeof MO === 'function' ? new MO(() => { lastMutationAt = Date.now(); }) : null;
258
+ mo?.observe(w.document, { subtree: true, childList: true, attributes: true, characterData: true });
259
+ stops.push(() => mo?.disconnect());
260
+ const recent = [];
261
+ const onClick = (e) => {
262
+ const at = Date.now();
263
+ const target = safeTarget(e.target) ?? 'unknown';
264
+ recent.push({ at, x: e.clientX, y: e.clientY, target });
265
+ while (recent.length && at - recent[0].at > 1000)
266
+ recent.shift();
267
+ const near = recent.filter((c) => Math.abs(c.x - e.clientX) < 30 && Math.abs(c.y - e.clientY) < 30);
268
+ if (near.length === 3)
269
+ push('interaction', { type: 'rage', target, clicks: near.length });
270
+ const el = e.target?.closest?.('a,button,[role=button],input[type=submit],input[type=button],summary,label');
271
+ if (el) {
272
+ const href = w.location.href;
273
+ setTimeout(() => {
274
+ const answered = lastMutationAt >= at || lastNetworkAt >= at || w.location.href !== href;
275
+ if (lastErrorAt >= at)
276
+ push('interaction', { type: 'error', target });
277
+ else if (!answered)
278
+ push('interaction', { type: 'dead', target });
279
+ }, 1000);
280
+ }
281
+ };
282
+ w.document.addEventListener('click', onClick, true);
283
+ stops.push(() => w.document.removeEventListener('click', onClick, true));
284
+ // freezes: long animation frames (long tasks where that is all the browser offers), and a main thread that stalled outright
285
+ const PO = w.PerformanceObserver;
286
+ const types = PO?.supportedEntryTypes ?? [];
287
+ if (PO && (types.includes('long-animation-frame') || types.includes('longtask'))) {
288
+ try {
289
+ const po = new PO((list) => {
290
+ for (const en of list.getEntries()) {
291
+ if (en.duration < 1000)
292
+ continue;
293
+ const scripts = (en.scripts ?? []).slice(0, 3).map((x) => ({ source: maskUrl(x.sourceURL ?? '', w.location.origin), invoker: maskText(x.invoker ?? '', 80) }));
294
+ push('freeze', { durationMs: Math.round(en.duration), via: en.entryType, scripts });
295
+ }
296
+ });
297
+ po.observe({ type: types.includes('long-animation-frame') ? 'long-animation-frame' : 'longtask', buffered: true });
298
+ stops.push(() => po.disconnect());
299
+ }
300
+ catch { /* observed nothing */ }
301
+ }
302
+ let beat = Date.now();
303
+ const hb = setInterval(() => {
304
+ const now = Date.now();
305
+ if (now - beat > 5000 && w.document.visibilityState === 'visible')
306
+ push('freeze', { durationMs: now - beat - 1000, via: 'stalled' });
307
+ beat = now;
308
+ }, 1000);
309
+ stops.push(() => clearInterval(hb));
310
+ // connectivity
311
+ const conn = w.navigator.connection;
312
+ const onOnline = () => push('connectivity', { online: true, effectiveType: conn?.effectiveType ?? null });
313
+ const onOffline = () => push('connectivity', { online: false });
314
+ const onConn = () => push('connectivity', { online: w.navigator.onLine, effectiveType: conn?.effectiveType ?? null });
315
+ w.addEventListener('online', onOnline);
316
+ w.addEventListener('offline', onOffline);
317
+ conn?.addEventListener?.('change', onConn);
318
+ stops.push(() => { w.removeEventListener('online', onOnline); w.removeEventListener('offline', onOffline); conn?.removeEventListener?.('change', onConn); });
319
+ const onHide = () => send(true);
320
+ const onVis = () => { if (w.document.visibilityState === 'hidden')
321
+ send(true); };
322
+ w.addEventListener('pagehide', onHide);
323
+ w.document.addEventListener('visibilitychange', onVis);
324
+ stops.push(() => { w.removeEventListener('pagehide', onHide); w.document.removeEventListener('visibilitychange', onVis); });
325
+ view(undefined, false);
326
+ // replay: its own recorder, loaded only when the site turned it on, the visitor consented where asked, and the browser sends no GPC
327
+ const replayAllowed = () => !!o.replay && !gpc && (consent === 'granted' || o.replay.consentRequired === false) && consent !== 'denied';
328
+ let replayStop = null;
329
+ const maybeReplay = () => {
330
+ if (replayStop || !replayAllowed() || Math.random() >= ((o.replay || {}).sampleRate ?? 1))
331
+ return;
332
+ replayStop = () => undefined;
333
+ void import('./replay.js').then((m) => {
334
+ replayStop = m.startReplay({ endpoint: `${new URL(o.url).origin}/v1/rum/replay`, key: o.key, session: s.id, basis: consent === 'granted' ? 'consent' : 'site_setting', consent: () => consent, ...(o.transport ? { transport: o.transport } : {}) }, w);
335
+ }).catch(() => { replayStop = null; });
336
+ };
337
+ maybeReplay();
338
+ return {
339
+ session: s.id, cohort, sampled: true,
340
+ setFlag(name, value) { const k = maskText(name, 60); flags[k] = maskText(String(value), 60); push('flag', { name: k, value: flags[k] }); },
341
+ setConsent(c) { consent = c; if (c === 'denied') {
342
+ queue = [];
343
+ replayStop?.();
344
+ replayStop = null;
345
+ }
346
+ else
347
+ maybeReplay(); },
348
+ // the note travels with the session's own batch and is linked to this session alone; the signal stream only records that one was sent
349
+ feedback(message, f = {}) {
350
+ if (consent === 'denied')
351
+ return;
352
+ notes.push({ message: maskText(message, 2000), ...(f.contact ? { contact: String(f.contact).slice(0, 200) } : {}) });
353
+ push('feedback', { sent: true, contact: !!f.contact });
354
+ send(false);
355
+ },
356
+ view: (r) => view(r),
357
+ flush: () => send(false),
358
+ stop() { for (const f of stops.splice(0)) {
359
+ try {
360
+ f();
361
+ }
362
+ catch { /* ignore */ }
363
+ } if (timer)
364
+ clearTimeout(timer); if (brokenTimer)
365
+ clearTimeout(brokenTimer); replayStop?.(); },
366
+ get queued() { return queue.length; },
367
+ vital,
368
+ };
369
+ }
@@ -0,0 +1,36 @@
1
+ export type SiteErrorKind = 'error' | 'unhandledrejection' | 'react' | 'boundary' | 'resource' | 'console' | 'csp' | 'deprecation' | 'intervention' | 'other';
2
+ export interface SiteReporterOptions {
3
+ /** POST target, e.g. https://api.xovris.ai/v1/public/site-errors. */
4
+ endpoint: string;
5
+ /** The served build's commit (7-40 hex). Without it nothing is sent. */
6
+ release: string;
7
+ /** Errors sent per page load at most (default 20); the server's own limits stand behind it. */
8
+ maxPerPage?: number;
9
+ /** Milliseconds a batch waits for company before it leaves (default 1000). */
10
+ batchMs?: number;
11
+ }
12
+ export interface SiteReport {
13
+ kind: SiteErrorKind;
14
+ type: string;
15
+ message: string;
16
+ stack?: string;
17
+ component?: string;
18
+ componentStack?: string;
19
+ handled?: boolean;
20
+ at: string;
21
+ }
22
+ export interface SiteReporter {
23
+ /** For an error boundary or a caught failure: report it with the part of the page it broke. */
24
+ report(err: unknown, extra?: {
25
+ component?: string;
26
+ componentStack?: string;
27
+ kind?: SiteErrorKind;
28
+ handled?: boolean;
29
+ }): void;
30
+ /** Send what is queued now (also runs on pagehide and when the page is hidden). */
31
+ flush(): void;
32
+ /** Tests and teardown: stop listening. */
33
+ stop(): void;
34
+ readonly sent: number;
35
+ }
36
+ export declare function installSiteReporter(o: SiteReporterOptions, w?: Window | undefined): SiteReporter;
@@ -0,0 +1,136 @@
1
+ // MI-X19 P5, the site's half: xovris.ai's own errors - thrown, rejected, a React boundary's catch, a failed asset, and
2
+ // the browser's own reports (CSP, deprecation, intervention) - posted to Xovris's error pipeline. No cookie, no storage,
3
+ // no lasting id: one random id per page load. A visitor's extension noise and opaque "Script error." are not sent.
4
+ // The reporter never throws and never reports its own failure, so it can never become the loop it is watching for.
5
+ const NOISE = /(?:chrome|moz|safari(?:-web)?)-extension:|^Script error\.?$|ResizeObserver loop (?:limit exceeded|completed with undelivered notifications)/;
6
+ function sessionId(w) {
7
+ const b = new Uint8Array(16);
8
+ (w.crypto ?? globalThis.crypto).getRandomValues(b);
9
+ return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
10
+ }
11
+ function describe(err) {
12
+ if (err instanceof Error)
13
+ return { type: err.name || 'Error', message: err.message || String(err), stack: err.stack ?? '' };
14
+ if (typeof err === 'string')
15
+ return { type: 'Error', message: err, stack: '' };
16
+ try {
17
+ return { type: 'NonError', message: JSON.stringify(err)?.slice(0, 300) ?? String(err), stack: '' };
18
+ }
19
+ catch {
20
+ return { type: 'NonError', message: String(err), stack: '' };
21
+ }
22
+ }
23
+ export function installSiteReporter(o, w = typeof window === 'undefined' ? undefined : window) {
24
+ const off = { report: () => undefined, flush: () => undefined, stop: () => undefined, sent: 0 };
25
+ if (!w || !/^[0-9a-f]{7,40}$/i.test(o.release) || !o.endpoint)
26
+ return off;
27
+ const max = o.maxPerPage ?? 20;
28
+ const session = sessionId(w);
29
+ const seen = new Set();
30
+ let queue = [];
31
+ let sent = 0;
32
+ let pausedUntil = 0;
33
+ let timer = null;
34
+ const send = (beacon) => {
35
+ if (timer) {
36
+ clearTimeout(timer);
37
+ timer = null;
38
+ }
39
+ if (queue.length === 0 || Date.now() < pausedUntil)
40
+ return;
41
+ const errors = queue.splice(0, 10);
42
+ const body = JSON.stringify({ v: 1, release: o.release.toLowerCase(), page: w.location.pathname, session, errors });
43
+ try {
44
+ // A beacon survives the page closing and, as text/plain, needs no preflight.
45
+ if (beacon && w.navigator?.sendBeacon?.(o.endpoint, new Blob([body], { type: 'text/plain' })))
46
+ return;
47
+ void w.fetch(o.endpoint, { method: 'POST', body, keepalive: true, headers: { 'content-type': 'text/plain' }, credentials: 'omit' })
48
+ .then((r) => { if (r.status === 429 || r.status === 503)
49
+ pausedUntil = Date.now() + 60_000; })
50
+ .catch(() => undefined);
51
+ }
52
+ catch { /* the reporter never reports itself */ }
53
+ if (queue.length)
54
+ send(beacon);
55
+ };
56
+ const schedule = () => { if (!timer)
57
+ timer = setTimeout(() => send(false), o.batchMs ?? 1000); };
58
+ const push = (r) => {
59
+ if (sent >= max || NOISE.test(r.message) || NOISE.test(r.stack ?? ''))
60
+ return;
61
+ const key = `${r.kind}|${r.type}|${r.message}|${(r.stack ?? '').split('\n')[1] ?? ''}`;
62
+ if (seen.has(key))
63
+ return;
64
+ seen.add(key);
65
+ sent += 1;
66
+ queue.push(r);
67
+ schedule();
68
+ };
69
+ const onError = (e) => {
70
+ try {
71
+ const t = e.target;
72
+ if (t && t !== w && typeof t.tagName === 'string') {
73
+ // A failed script, stylesheet or image (seen in the capture phase only).
74
+ const src = (t.src || t.href || '').split(/[?#]/)[0] ?? '';
75
+ push({ kind: 'resource', type: 'ResourceError', message: `${t.tagName.toLowerCase()} failed to load ${src}`.trim(), at: new Date().toISOString() });
76
+ return;
77
+ }
78
+ const ev = e;
79
+ const d = describe(ev.error ?? ev.message);
80
+ push({ kind: 'error', ...d, handled: false, at: new Date().toISOString() });
81
+ }
82
+ catch { /* never throw from a listener */ }
83
+ };
84
+ const onRejection = (e) => {
85
+ try {
86
+ push({ kind: 'unhandledrejection', ...describe(e.reason), handled: false, at: new Date().toISOString() });
87
+ }
88
+ catch { /* ignore */ }
89
+ };
90
+ const onHide = () => send(true);
91
+ const onVisibility = () => { if (w.document.visibilityState === 'hidden')
92
+ send(true); };
93
+ w.addEventListener('error', onError, true);
94
+ w.addEventListener('unhandledrejection', onRejection);
95
+ w.addEventListener('pagehide', onHide);
96
+ w.document.addEventListener('visibilitychange', onVisibility);
97
+ const RO = w.ReportingObserver;
98
+ let observer = null;
99
+ if (RO) {
100
+ try {
101
+ observer = new RO((reports) => {
102
+ for (const r of reports) {
103
+ const b = r.body ?? {};
104
+ const stack = b.sourceFile ? `Error\n at ${r.type} (${String(b.sourceFile).split(/[?#]/)[0]}:${b.lineNumber ?? 0}:${b.columnNumber ?? 0})` : '';
105
+ if (r.type === 'csp-violation')
106
+ push({ kind: 'csp', type: 'CSP violation', message: `${b.effectiveDirective ?? ''} blocked ${(b.blockedURL ?? '').split(/[?#]/)[0] || 'an inline resource'}`, stack, at: new Date().toISOString() });
107
+ else if (r.type === 'deprecation' || r.type === 'intervention')
108
+ push({ kind: r.type, type: r.type === 'deprecation' ? 'Deprecation' : 'Browser intervention', message: `${b.id ?? ''}: ${b.message ?? ''}`, stack, at: new Date().toISOString() });
109
+ }
110
+ }, { types: ['csp-violation', 'deprecation', 'intervention'], buffered: true });
111
+ observer.observe();
112
+ }
113
+ catch {
114
+ observer = null;
115
+ }
116
+ }
117
+ return {
118
+ report(err, extra = {}) {
119
+ try {
120
+ push({ kind: extra.kind ?? 'boundary', ...describe(err), ...(extra.component ? { component: extra.component } : {}), ...(extra.componentStack ? { componentStack: extra.componentStack } : {}), handled: extra.handled ?? true, at: new Date().toISOString() });
121
+ }
122
+ catch { /* ignore */ }
123
+ },
124
+ flush: () => send(false),
125
+ stop() {
126
+ w.removeEventListener('error', onError, true);
127
+ w.removeEventListener('unhandledrejection', onRejection);
128
+ w.removeEventListener('pagehide', onHide);
129
+ w.document.removeEventListener('visibilitychange', onVisibility);
130
+ observer?.disconnect();
131
+ if (timer)
132
+ clearTimeout(timer);
133
+ },
134
+ get sent() { return sent; },
135
+ };
136
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@xovris/browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Xovris in the browser: errors and unhandled rejections with the page address (ADR 0011).",
4
+ "version": "0.1.0",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ },
15
+ "./site": {
16
+ "types": "./dist/site-reporter.d.ts",
17
+ "import": "./dist/site-reporter.js"
18
+ },
19
+ "./rum": {
20
+ "types": "./dist/rum.d.ts",
21
+ "import": "./dist/rum.js"
22
+ },
23
+ "./mask": {
24
+ "types": "./dist/mask.d.ts",
25
+ "import": "./dist/mask.js"
26
+ },
27
+ "./replay": {
28
+ "types": "./dist/replay.d.ts",
29
+ "import": "./dist/replay.js"
30
+ }
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@rrweb/record": "2.1.7",
37
+ "web-vitals": "6.2.3",
38
+ "@xovris/core": "0.1.0"
39
+ },
40
+ "devDependencies": {
41
+ "happy-dom": "^20.14.6"
42
+ },
43
+ "homepage": "https://xovris.ai/developers/",
44
+ "engines": {
45
+ "node": ">=20"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.build.json",
49
+ "typecheck": "tsc --noEmit -p .",
50
+ "test": "vitest run"
51
+ }
6
52
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.