@sazabi/browser 0.2.0-dev.ga327325

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.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @sazabi/browser
2
+
3
+ Capture what actually happens in your users' browsers: a session-scoped event stream of navigation, clicks, frustration signals, JavaScript errors, console output, and network calls — correlated to your backend logs by `trace_id`, and streamed to [Sazabi](https://sazabi.com) as structured telemetry your agents can reason over.
4
+
5
+ Zero runtime dependencies, ~8 KB gzipped, and designed to never break your app: every hook is wrapped, patches are reversible, and input values are never captured.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ bun add @sazabi/browser
11
+ # or: npm install @sazabi/browser
12
+ ```
13
+
14
+ ## Quick start
15
+
16
+ ```ts
17
+ // First import in your app entry: installs instrumentation before any other
18
+ // module can capture native fetch/XHR/history references.
19
+ import "@sazabi/browser/register";
20
+
21
+ import { init } from "@sazabi/browser";
22
+
23
+ init({
24
+ publicKey: "sazabi_public_...",
25
+ intakeHost: "https://web.us-west-2.intake.sazabi.com",
26
+ serviceName: "my-web-app",
27
+ });
28
+ ```
29
+
30
+ `publicKey` is a Sazabi public key — it can only write telemetry, so it is safe to ship in your bundle. Replace the intake host region with your project's region.
31
+
32
+ The register import is optional but recommended. `init()` alone also instruments, but only at call time — HTTP clients constructed at module scope may capture the native functions first. Requests that bypass instrumentation are still observed through a resource-timing fallback, and the SDK logs a once-per-origin `instrumentation_gap` diagnostic naming the escaped origin so the gap is visible instead of silent.
33
+
34
+ ## What gets captured
35
+
36
+ | Event type | Contents |
37
+ |------------|----------|
38
+ | `navigation` | Page loads and SPA route changes — History API, hash, back/forward, and Navigation API (`navigation.navigate()`) |
39
+ | `click` | Capture-phase clicks with a privacy-safe selector and the element's label ("Save changes") — never input values |
40
+ | `rage_click` / `dead_click` | Frustration signals: rapid repeat clicks, clicks with no visible response |
41
+ | `input` | One event per field engagement — which field (by its label), for how long, how many edits, whether pasted. Never keystrokes, values, or value lengths |
42
+ | `error` | Uncaught exceptions and unhandled promise rejections with stack traces |
43
+ | `network` | fetch/XHR calls with method, status, duration — and a trace id when propagated |
44
+ | `log` | Mirrored `console.error`/`console.warn` output, plus anything you send with `log()` |
45
+ | `custom` | Marks you add with `addEvent()` |
46
+
47
+ Every event carries a cross-tab `session.id`, a per-tab `session.window_id`, and the page URL, so a user's activity reads as one ordered timeline.
48
+
49
+ ## Correlate with your backend
50
+
51
+ The SDK injects a W3C `traceparent` header into same-origin requests by default. To propagate to an API on another origin, allowlist it — and make sure the API's CORS `Access-Control-Allow-Headers` includes `traceparent`:
52
+
53
+ ```ts
54
+ init({
55
+ // ...
56
+ network: {
57
+ allowlist: ["https://api.example.com"],
58
+ },
59
+ });
60
+ ```
61
+
62
+ Backend log lines that run inside the extracted trace context then share a `trace_id` with the originating browser request. If your backend runs OpenTelemetry, extraction already happens by default; set `network: { sampledFlag: true }` if you also want your backend tracer to record those traces (the logs-side join works either way).
63
+
64
+ The SDK also records platform request ids echoed on responses (`x-request-id`, `cf-ray`, `x-vercel-id`, and similar) as `web.network.request_id`, giving you an exact join key against CDN and platform logs with no backend changes.
65
+
66
+ ## Identify users
67
+
68
+ ```ts
69
+ import { identify, reset } from "@sazabi/browser";
70
+
71
+ identify("user_123", { plan: "pro" }); // on login or app boot — use your internal id, not an email
72
+ reset(); // on logout — clears identity and starts a fresh session
73
+ ```
74
+
75
+ `identify()` stamps `session.distinct_id` on subsequent events and records the traits on the identify event. `reset()` clears the identity and rotates the session so activity on a shared device never threads into the previous user's timeline; switching identities without a `reset()` rotates automatically. Identity is client-asserted — treat it as a claim, not authentication.
76
+
77
+ ## Logs, custom events, and console output
78
+
79
+ ```ts
80
+ import { addEvent, log } from "@sazabi/browser";
81
+
82
+ addEvent("checkout_started", { cartValue: 42 });
83
+ log("WARN", "cache lookup failed", { requestId: "req_9" });
84
+ ```
85
+
86
+ `console.error` and `console.warn` are mirrored into the event stream by default (the original console behavior is untouched). Configure with `console: { levels: [...] }` or disable with `console: { capture: false }`.
87
+
88
+ ## Consent
89
+
90
+ If your users must opt in before capture, pass a consent gate — nothing is installed and nothing is sent until it resolves true:
91
+
92
+ ```ts
93
+ init({
94
+ // ...
95
+ consent: () => cookieBanner.accepted(),
96
+ });
97
+ ```
98
+
99
+ ## Configuration
100
+
101
+ | Option | Default | Purpose |
102
+ |--------|---------|---------|
103
+ | `network.capture` | `true` | Emit network events for fetch/XHR |
104
+ | `network.propagateTraceContext` | `true` | Inject `traceparent` into eligible requests |
105
+ | `network.allowlist` | same-origin only | Origins eligible for header injection |
106
+ | `network.sampledFlag` | `false` | Mark minted traces sampled (`-01`) for backend tracers |
107
+ | `network.resourceFallback` | `true` | Observe requests that bypass instrumentation |
108
+ | `network.requestIdHeaders` | common platform headers | Response headers probed for a request id |
109
+ | `console.capture` / `console.levels` | `true`, `["error", "warn"]` | Console mirroring |
110
+ | `input.capture` | `true` | Field-interaction episodes |
111
+ | `consent` | off | Hold all capture until it resolves true |
112
+ | `flushIntervalMs` | `5000` | Batch flush cadence |
113
+
114
+ ## Privacy and safety
115
+
116
+ - Input values, keystrokes, request bodies, and response bodies are never captured — not even value lengths.
117
+ - Element names come from developer-authored sources only (`aria-label`, `<label>`, `placeholder`, button captions), and only for interactive elements — clicks on plain containers, where user content lives, record selectors only. Add `data-sazabi-mask` to any element to suppress text capture for its whole subtree, or `data-sazabi-name` to set the reported name explicitly.
118
+ - Every patch is transparent, idempotent, and reversible; SDK failures are invisible to your app, and `shutdown()` restores the original functions.
119
+ - Events are delivered as OTLP/HTTP log records with batching, and flushed with `keepalive` when the tab closes.
@@ -0,0 +1,8 @@
1
+ import type { EventAttributes } from "./types";
2
+ export declare const truncateValue: (value: string, max?: number) => string;
3
+ /**
4
+ * Flatten nested metadata into dot-keyed scalar attributes. Non-scalar leaves
5
+ * are JSON-stringified; strings are length-capped so a hostile or buggy page
6
+ * cannot inflate rows.
7
+ */
8
+ export declare const flattenAttributes: (input: Record<string, unknown>, prefix?: string, depth?: number) => EventAttributes;
@@ -0,0 +1,5 @@
1
+ var l=(t)=>{try{Object.defineProperty(t,"__sazabiBrowserWrapped",{value:!0})}catch{}},R=(t)=>typeof t==="function"&&t.__sazabiBrowserWrapped===!0;var W={push:"pushState",replace:"replaceState",traverse:"popstate",reload:"reload"},I,y=(t)=>{let e=I;if(!e)return;try{let r=window.location.href,n=e.previousUrl;if(e.previousUrl=r,t!=="load"&&n===r)return;e.options.onNavigate(),e.options.emit({type:"navigation",body:`navigation ${window.location.pathname}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.navigation.type":t,"url.full":r,"web.navigation.from":n||void 0}})}catch{}},f,j=(t)=>{let{pushState:e,replaceState:r}=t;return{originalPushState:e,originalReplaceState:r,wrappedPushState:function(...s){e.apply(this,s),y("pushState")},wrappedReplaceState:function(...s){r.apply(this,s),y("replaceState")}}},_=()=>{let t=History.prototype;if(!R(t.pushState)){let e=j(t);l(e.wrappedPushState),l(e.wrappedReplaceState),t.pushState=e.wrappedPushState,t.replaceState=e.wrappedReplaceState,f=e}},Y=()=>{let t=History.prototype;if(f){if(t.pushState===f.wrappedPushState)t.pushState=f.originalPushState;if(t.replaceState===f.wrappedReplaceState)t.replaceState=f.originalReplaceState}f=void 0},J=(t)=>{_(),I={options:t,previousUrl:document.referrer||""};let e=()=>{y("popstate")},r=()=>{y("hashchange")};window.addEventListener("popstate",e),window.addEventListener("hashchange",r);let n=window.navigation,o=(s)=>{let g=s.navigationType,i=W[g??""];if(i)y(i)};return n?.addEventListener("currententrychange",o),y("load"),{teardown(){I=void 0,window.removeEventListener("popstate",e),window.removeEventListener("hashchange",r),n?.removeEventListener("currententrychange",o)}}};var N=(t)=>{try{let e=new URL(t);return e.origin===window.location.origin?e.pathname:`${e.host}${e.pathname}`}catch{return t}},U=(t)=>{if(t===0||t>=500)return"ERROR";if(t>=400)return"WARN";return"INFO"};var L=(t)=>{try{let e=new URL(t,window.location.href);return e.username="",e.password="",e.href}catch{return}},h,M=(t,e)=>{if(t.allowlist.length===0)try{return new URL(e).origin===window.location.origin}catch{return!1}return t.allowlist.some((r)=>typeof r==="string"?e.includes(r):r.test(e))},re=(t)=>{let e=h;if(!e?.propagateTraceContext)return!1;if(e.isInternalUrl(t))return!1;return M(e,t)},A=5000,E=300,w=[],T=(t)=>{if(w.push({url:t,startTime:performance.now()}),w.length>E)w=w.slice(-E)},ne=(t,e)=>{let r=w.findIndex((n)=>n.url===t&&Math.abs(n.startTime-e)<=A);if(r===-1)return!1;return w.splice(r,1),!0},C=(t,e)=>{try{let r=N(e.resolvedUrl),n=e.status>0?String(e.status):"failed",o={type:"network",body:`${e.method} ${r} → ${n}`,severity:U(e.status),timeUnixMs:Date.now(),attributes:{"http.request.method":e.method,"http.response.status_code":e.status>0?e.status:void 0,"url.full":e.resolvedUrl,"web.network.kind":e.kind,"web.network.duration_ms":Math.round(e.durationMs),"web.network.error":e.failureMessage,"web.network.request_id":e.requestId,"web.network.request_id_header":e.requestIdHeader}};if(e.injected)o.traceId=e.injected.traceId,o.spanId=e.injected.spanId;t.emit(o)}catch{}},D=(t,e)=>{try{for(let r of t.requestIdHeaders){let n=e.headers.get(r);if(n)return{requestId:n,requestIdHeader:r}}}catch{}return{}},F=(t,e)=>{try{for(let r of t.requestIdHeaders){let n=e.getResponseHeader(r);if(n)return{requestId:n,requestIdHeader:r}}}catch{}return{}},S,k=0,B=(t)=>{let e=(r,n,o)=>{k++;try{return t.call(r,n,o)}finally{k--}};return function(r,n){let o=h;if(!o||k>0||R(t))return t.call(this,r,n);let s,g="GET",i,p=n;try{let c=typeof r==="string"?r:r instanceof URL?r.href:r.url;if(s=L(c),typeof r==="object"&&"method"in r&&r.method)g=r.method.toUpperCase();if(n?.method)g=n.method.toUpperCase();let x=s===void 0||o.isInternalUrl(s);if(!x&&s&&o.propagateTraceContext&&M(o,s)){let H=o.traceContext.forRequest();if(r instanceof Request&&n===void 0)try{for(let[m,P]of Object.entries(H.headers))if(!r.headers.has(m))r.headers.set(m,P);i=H}catch{i=void 0}else{let m=r instanceof Request&&n?.headers===void 0?new Headers(r.headers):new Headers(n?.headers),P=m.has("traceparent");if(r instanceof Request&&r.headers.has("traceparent"))P=!0;if(!P){for(let[O,X]of Object.entries(H.headers))m.set(O,X);p={...n,headers:m},i=H}}}if(!x&&s!==void 0)T(s);if(x||!o.capture||s===void 0)return e(this,r,p)}catch{return e(this,r,n)}let a=performance.now(),v=s,u=g,q=i;return e(this,r,p).then((c)=>(C(o,{kind:"fetch",method:u,resolvedUrl:v,status:c.status,durationMs:performance.now()-a,injected:q,...D(o,c)}),c),(c)=>{throw C(o,{kind:"fetch",method:u,resolvedUrl:v,status:0,durationMs:performance.now()-a,failureMessage:c instanceof Error?c.message:String(c),injected:q}),c})}},b=new WeakMap,d,K=(t)=>{let{open:e,send:r,setRequestHeader:n}=t;return{originalOpen:e,originalSend:r,originalSetRequestHeader:n,wrappedOpen:function(...i){if(h)try{let[p,a]=i;b.set(this,{method:String(p).toUpperCase(),resolvedUrl:L(String(a)),customTraceparent:!1,start:0,processed:!1})}catch{}e.apply(this,i)},wrappedSend:function(i){let p=h;if(p)try{let a=b.get(this);if(a?.resolvedUrl&&!a.processed){a.processed=!0;let v=p.isInternalUrl(a.resolvedUrl);if(!v&&p.propagateTraceContext&&!a.customTraceparent&&M(p,a.resolvedUrl))try{let u=p.traceContext.forRequest();for(let[q,c]of Object.entries(u.headers))n.call(this,q,c);a.injected=u}catch{a.injected=void 0}if(!v)T(a.resolvedUrl);if(!v&&p.capture)a.start=performance.now(),this.addEventListener("loadend",()=>{let u=h??p;C(u,{kind:"xhr",method:a.method,resolvedUrl:a.resolvedUrl,status:this.status,durationMs:performance.now()-a.start,injected:a.injected,...F(u,this)})})}}catch{}r.call(this,i)},wrappedSetRequestHeader:function(i,p){if(h)try{if(i.toLowerCase()==="traceparent"){let a=b.get(this);if(a)a.customTraceparent=!0}}catch{}n.call(this,i,p)}}},G=()=>{if(!R(window.fetch)){let e=window.fetch,r=B(e);l(r),window.fetch=r,S={original:e,wrapped:r}}let t=XMLHttpRequest.prototype;if(!R(t.open)){let e=K(t);l(e.wrappedOpen),l(e.wrappedSetRequestHeader),l(e.wrappedSend),t.open=e.wrappedOpen,t.setRequestHeader=e.wrappedSetRequestHeader,t.send=e.wrappedSend,d=e}},ae=()=>{if(S&&window.fetch===S.wrapped)window.fetch=S.original;S=void 0;let t=XMLHttpRequest.prototype;if(d){if(t.open===d.wrappedOpen)t.open=d.originalOpen;if(t.setRequestHeader===d.wrappedSetRequestHeader)t.setRequestHeader=d.originalSetRequestHeader;if(t.send===d.wrappedSend)t.send=d.originalSend}d=void 0,w=[]},oe=(t)=>(G(),h=t,{teardown(){h=void 0}});
2
+ export{l as a,R as b,_ as c,Y as d,J as e,N as f,U as g,re as h,ne as i,G as j,ae as k,oe as l};
3
+
4
+ //# debugId=0E88B5801F6610F064756E2164756E21
5
+ //# sourceMappingURL=chunk-rfm4nnme.js.map
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/patch-marker.ts", "../src/navigation.ts", "../src/network-event-format.ts", "../src/network.ts"],
4
+ "sourcesContent": [
5
+ "export const WRAPPED_MARKER = \"__sazabiBrowserWrapped\";\n\n/** Best-effort idempotency marker on wrapper functions. */\nexport const markWrapped = (fn: object): void => {\n try {\n Object.defineProperty(fn, WRAPPED_MARKER, { value: true });\n } catch {\n // Non-extensible function object — idempotency guard degrades gracefully.\n }\n};\n\nexport const isWrapped = (fn: unknown): boolean =>\n typeof fn === \"function\" &&\n (fn as unknown as Record<string, unknown>)[WRAPPED_MARKER] === true;\n",
6
+ "import { isWrapped, markWrapped } from \"./patch-marker\";\nimport type { WebEvent } from \"./types\";\n\nexport interface NavigationCaptureOptions {\n emit(event: WebEvent): void;\n /** Fired on every captured navigation (dead-click signal). */\n onNavigate(): void;\n}\n\nexport interface NavigationCaptureHandle {\n teardown(): void;\n}\n\ntype NavigationType =\n | \"load\"\n | \"pushState\"\n | \"replaceState\"\n | \"popstate\"\n | \"hashchange\"\n | \"reload\";\n\n/**\n * Navigation API `currententrychange` types → our History-API-flavored\n * vocabulary, so queries see one taxonomy regardless of which API navigated.\n */\nconst NAVIGATION_API_TYPE_MAP: Record<string, NavigationType> = {\n push: \"pushState\",\n replace: \"replaceState\",\n traverse: \"popstate\",\n reload: \"reload\",\n};\n\n// ------------------------------------------------------------- activation --\n// History patches install dormant (routers commonly capture\n// History.prototype methods at module scope) and consult this slot per call.\n\ninterface ActiveNavigation {\n options: NavigationCaptureOptions;\n previousUrl: string;\n}\n\nlet active: ActiveNavigation | undefined;\n\nconst emitNavigation = (navigationType: NavigationType): void => {\n const current = active;\n if (!current) return;\n try {\n const currentUrl = window.location.href;\n const from = current.previousUrl;\n current.previousUrl = currentUrl;\n if (navigationType !== \"load\" && from === currentUrl) {\n return; // replaceState to the same URL etc. — not a navigation.\n }\n current.options.onNavigate();\n current.options.emit({\n type: \"navigation\",\n body: `navigation ${window.location.pathname}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.navigation.type\": navigationType,\n \"url.full\": currentUrl,\n \"web.navigation.from\": from || undefined,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n};\n\ninterface HistoryPatch {\n originalPushState: History[\"pushState\"];\n originalReplaceState: History[\"replaceState\"];\n wrappedPushState: History[\"pushState\"];\n wrappedReplaceState: History[\"replaceState\"];\n}\n\nlet historyPatch: HistoryPatch | undefined;\n\nconst makeHistoryPatch = (proto: History): HistoryPatch => {\n const originalPushState = proto.pushState;\n const originalReplaceState = proto.replaceState;\n\n const wrappedPushState = function (\n this: History,\n ...args: Parameters<History[\"pushState\"]>\n ): void {\n originalPushState.apply(this, args);\n emitNavigation(\"pushState\");\n };\n\n const wrappedReplaceState = function (\n this: History,\n ...args: Parameters<History[\"replaceState\"]>\n ): void {\n originalReplaceState.apply(this, args);\n emitNavigation(\"replaceState\");\n };\n\n return {\n originalPushState,\n originalReplaceState,\n wrappedPushState,\n wrappedReplaceState,\n };\n};\n\n/**\n * Install dormant history patches around whatever implementations are\n * currently live. Idempotent; re-wraps if a later actor replaced the methods\n * after an earlier install (the displaced wrappers are inert passthroughs).\n */\nexport const ensureNavigationPatches = (): void => {\n const proto = History.prototype;\n if (!isWrapped(proto.pushState)) {\n const patch = makeHistoryPatch(proto);\n markWrapped(patch.wrappedPushState);\n markWrapped(patch.wrappedReplaceState);\n proto.pushState = patch.wrappedPushState;\n proto.replaceState = patch.wrappedReplaceState;\n historyPatch = patch;\n }\n};\n\n/** Restore the natives if the current implementations are still ours. */\nexport const uninstallNavigationPatches = (): void => {\n const proto = History.prototype;\n if (historyPatch) {\n if (proto.pushState === historyPatch.wrappedPushState) {\n proto.pushState = historyPatch.originalPushState;\n }\n if (proto.replaceState === historyPatch.wrappedReplaceState) {\n proto.replaceState = historyPatch.originalReplaceState;\n }\n }\n historyPatch = undefined;\n};\n\n/**\n * SPA navigation capture. Listeners alone miss programmatic navigation —\n * which is most navigation in React apps — so `history.pushState` /\n * `replaceState` are wrapped under the same isolation rules as the network\n * patch.\n */\nexport const installNavigationCapture = (\n options: NavigationCaptureOptions,\n): NavigationCaptureHandle => {\n ensureNavigationPatches();\n active = { options, previousUrl: document.referrer || \"\" };\n\n const onPopState = (): void => {\n emitNavigation(\"popstate\");\n };\n const onHashChange = (): void => {\n emitNavigation(\"hashchange\");\n };\n window.addEventListener(\"popstate\", onPopState);\n window.addEventListener(\"hashchange\", onHashChange);\n\n // Navigation API (Chromium): `navigation.navigate()` same-document\n // navigations call neither pushState nor popstate, but every same-document\n // navigation — whichever API initiated it — fires `currententrychange`.\n // The same-URL dedupe in emitNavigation collapses the overlap with the\n // history patch and legacy listeners; first signal wins.\n const navigationApi = (window as { navigation?: EventTarget }).navigation;\n const onCurrentEntryChange = (event: Event): void => {\n const navigationType = (event as { navigationType?: string | null })\n .navigationType;\n const mapped = NAVIGATION_API_TYPE_MAP[navigationType ?? \"\"];\n if (mapped) {\n // Unmapped/null types (e.g. updateCurrentEntry metadata edits) are\n // not navigations.\n emitNavigation(mapped);\n }\n };\n navigationApi?.addEventListener(\"currententrychange\", onCurrentEntryChange);\n\n // The page we landed on is the first navigation of the window.\n emitNavigation(\"load\");\n\n return {\n teardown() {\n active = undefined;\n window.removeEventListener(\"popstate\", onPopState);\n window.removeEventListener(\"hashchange\", onHashChange);\n navigationApi?.removeEventListener(\n \"currententrychange\",\n onCurrentEntryChange,\n );\n },\n };\n};\n",
7
+ "import type { EventSeverity } from \"./types\";\n\n/** Compact display path: pathname when same-origin, host+path cross-origin. */\nexport const urlPath = (resolved: string): string => {\n try {\n const url = new URL(resolved);\n return url.origin === window.location.origin\n ? url.pathname\n : `${url.host}${url.pathname}`;\n } catch {\n return resolved;\n }\n};\n\n/** Status 0 means transport failure. */\nexport const severityForStatus = (status: number): EventSeverity => {\n if (status === 0 || status >= 500) return \"ERROR\";\n if (status >= 400) return \"WARN\";\n return \"INFO\";\n};\n",
8
+ "import { severityForStatus, urlPath } from \"./network-event-format\";\nimport { isWrapped, markWrapped } from \"./patch-marker\";\nimport type { RequestTraceContext, TraceContextManager } from \"./trace-context\";\nimport type { WebEvent } from \"./types\";\n\nexport interface NetworkCaptureOptions {\n emit(event: WebEvent): void;\n traceContext: TraceContextManager;\n /** Emit network events. */\n capture: boolean;\n /** Inject `traceparent` into allowlisted requests. */\n propagateTraceContext: boolean;\n /** Injection allowlist; empty means same-origin only. */\n allowlist: (string | RegExp)[];\n /** Response headers probed for a platform request id, in priority order. */\n requestIdHeaders: string[];\n /** SDK-internal endpoints: never captured, never injected. */\n isInternalUrl(url: string): boolean;\n}\n\nexport interface NetworkCaptureHandle {\n teardown(): void;\n}\n\nconst resolveUrl = (raw: string): string | undefined => {\n try {\n const url = new URL(raw, window.location.href);\n url.username = \"\";\n url.password = \"\";\n return url.href;\n } catch {\n return undefined;\n }\n};\n\n// ------------------------------------------------------------- activation --\n// Patches install dormant (possibly via `@sazabi/browser/register` before\n// any app module can capture the natives) and consult this slot per call.\n// Undefined slot = transparent passthrough.\n\nlet active: NetworkCaptureOptions | undefined;\n\nconst isAllowedForInjection = (\n options: NetworkCaptureOptions,\n resolved: string,\n): boolean => {\n if (options.allowlist.length === 0) {\n try {\n return new URL(resolved).origin === window.location.origin;\n } catch {\n return false;\n }\n }\n return options.allowlist.some((pattern) =>\n typeof pattern === \"string\"\n ? resolved.includes(pattern)\n : pattern.test(resolved),\n );\n};\n\n/** Injection eligibility for the active config; used by the resource observer\n * to decide whether a bypassed request is a diagnosable instrumentation gap. */\nexport const isActiveInjectionTarget = (resolved: string): boolean => {\n const options = active;\n if (!options?.propagateTraceContext) return false;\n if (options.isInternalUrl(resolved)) return false;\n return isAllowedForInjection(options, resolved);\n};\n\n// ----------------------------------------------------- wrapper-seen ledger --\n// Every request processed by an active wrapper is recorded so the resource-\n// timing observer can tell wrapper-captured traffic (skip: a richer event was\n// already emitted) from traffic that bypassed the patches entirely.\n\ninterface SeenRequest {\n url: string;\n /** performance.now() timebase, comparable to PerformanceEntry.startTime. */\n startTime: number;\n}\n\nconst SEEN_MATCH_WINDOW_MS = 5_000;\nconst SEEN_MAX_ENTRIES = 300;\nlet seenByWrapper: SeenRequest[] = [];\n\nconst recordWrapperRequest = (url: string): void => {\n seenByWrapper.push({ url, startTime: performance.now() });\n if (seenByWrapper.length > SEEN_MAX_ENTRIES) {\n seenByWrapper = seenByWrapper.slice(-SEEN_MAX_ENTRIES);\n }\n};\n\n/** Consume a wrapper-seen record matching this resource entry, if any. */\nexport const consumeWrapperSeen = (url: string, startTime: number): boolean => {\n const index = seenByWrapper.findIndex(\n (seen) =>\n seen.url === url &&\n Math.abs(seen.startTime - startTime) <= SEEN_MATCH_WINDOW_MS,\n );\n if (index === -1) return false;\n seenByWrapper.splice(index, 1);\n return true;\n};\n\nconst emitNetworkEvent = (\n options: NetworkCaptureOptions,\n details: {\n kind: \"fetch\" | \"xhr\";\n method: string;\n resolvedUrl: string;\n status: number;\n durationMs: number;\n failureMessage?: string;\n injected?: RequestTraceContext;\n requestId?: string;\n requestIdHeader?: string;\n },\n): void => {\n try {\n const path = urlPath(details.resolvedUrl);\n const outcome = details.status > 0 ? String(details.status) : \"failed\";\n const event: WebEvent = {\n type: \"network\",\n body: `${details.method} ${path} → ${outcome}`,\n severity: severityForStatus(details.status),\n timeUnixMs: Date.now(),\n attributes: {\n \"http.request.method\": details.method,\n \"http.response.status_code\":\n details.status > 0 ? details.status : undefined,\n \"url.full\": details.resolvedUrl,\n \"web.network.kind\": details.kind,\n \"web.network.duration_ms\": Math.round(details.durationMs),\n \"web.network.error\": details.failureMessage,\n \"web.network.request_id\": details.requestId,\n \"web.network.request_id_header\": details.requestIdHeader,\n },\n };\n if (details.injected) {\n event.traceId = details.injected.traceId;\n event.spanId = details.injected.spanId;\n }\n options.emit(event);\n } catch {\n // Capture failures must never surface to the host.\n }\n};\n\nconst readFetchRequestId = (\n options: NetworkCaptureOptions,\n response: Response,\n): { requestId?: string; requestIdHeader?: string } => {\n try {\n for (const name of options.requestIdHeaders) {\n const value = response.headers.get(name);\n if (value) return { requestId: value, requestIdHeader: name };\n }\n } catch {\n // Header access failures are ignorable detail loss.\n }\n return {};\n};\n\nconst readXhrRequestId = (\n options: NetworkCaptureOptions,\n xhr: XMLHttpRequest,\n): { requestId?: string; requestIdHeader?: string } => {\n try {\n for (const name of options.requestIdHeaders) {\n const value = xhr.getResponseHeader(name);\n if (value) return { requestId: value, requestIdHeader: name };\n }\n } catch {\n // Cross-origin/invalid-state header access — ignorable detail loss.\n }\n return {};\n};\n\n// ------------------------------------------------------------------ fetch --\n\ninterface FetchPatch {\n original: typeof fetch;\n wrapped: typeof fetch;\n}\n\nlet fetchPatch: FetchPatch | undefined;\n\n/**\n * Outermost-wins sandwich guard. When a third party patches fetch between our\n * register-time install and init (Sentry, analytics), init's re-wrap makes\n * the chain ourWrapper2(thirdParty(ourWrapper1(native))) — two ACTIVE copies\n * of our wrapper in one call path, which would double-emit every event. The\n * outermost wrapper raises this depth for the synchronous span of its\n * call-through; inner copies see it and become pure passthroughs.\n */\nlet fetchProcessingDepth = 0;\n\nconst makeWrappedFetch = (originalFetch: typeof fetch): typeof fetch => {\n const callThrough = (\n thisArg: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n fetchProcessingDepth++;\n try {\n return originalFetch.call(thisArg, input, init);\n } finally {\n fetchProcessingDepth--;\n }\n };\n\n return function (\n this: unknown,\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n const options = active;\n if (!options || fetchProcessingDepth > 0 || isWrapped(originalFetch)) {\n return originalFetch.call(this, input, init);\n }\n\n let resolvedUrl: string | undefined;\n let method = \"GET\";\n let injected: RequestTraceContext | undefined;\n let finalInit = init;\n\n try {\n const rawUrl =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n resolvedUrl = resolveUrl(rawUrl);\n\n if (typeof input === \"object\" && \"method\" in input && input.method) {\n method = input.method.toUpperCase();\n }\n if (init?.method) {\n method = init.method.toUpperCase();\n }\n\n const internal =\n resolvedUrl === undefined || options.isInternalUrl(resolvedUrl);\n\n if (\n !internal &&\n resolvedUrl &&\n options.propagateTraceContext &&\n isAllowedForInjection(options, resolvedUrl)\n ) {\n const requestContext = options.traceContext.forRequest();\n\n if (input instanceof Request && init === undefined) {\n // Headers on a constructed Request are mutable for non-forbidden\n // names; if the guard rejects them, skip injection rather than\n // clone (cloning can consume one-shot bodies).\n try {\n for (const [name, value] of Object.entries(\n requestContext.headers,\n )) {\n if (!input.headers.has(name)) {\n input.headers.set(name, value);\n }\n }\n injected = requestContext;\n } catch {\n injected = undefined;\n }\n } else {\n // Per fetch semantics, init.headers replaces the Request's own\n // headers entirely. When the caller passed a Request plus an init\n // WITHOUT headers, seed the merge from the Request so injection\n // does not silently strip Authorization/Content-Type/etc.\n const merged =\n input instanceof Request && init?.headers === undefined\n ? new Headers(input.headers)\n : new Headers(init?.headers);\n let alreadyTraced = merged.has(\"traceparent\");\n if (input instanceof Request && input.headers.has(\"traceparent\")) {\n alreadyTraced = true;\n }\n if (!alreadyTraced) {\n for (const [name, value] of Object.entries(\n requestContext.headers,\n )) {\n merged.set(name, value);\n }\n finalInit = { ...init, headers: merged };\n injected = requestContext;\n }\n }\n }\n\n if (!internal && resolvedUrl !== undefined) {\n recordWrapperRequest(resolvedUrl);\n }\n\n if (internal || !options.capture || resolvedUrl === undefined) {\n return callThrough(this, input, finalInit);\n }\n } catch {\n // Any preparation failure: fall through to a plain passthrough call.\n return callThrough(this, input, init);\n }\n\n const start = performance.now();\n const capturedUrl = resolvedUrl;\n const capturedMethod = method;\n const capturedInjection = injected;\n\n return callThrough(this, input, finalInit).then(\n (response) => {\n emitNetworkEvent(options, {\n kind: \"fetch\",\n method: capturedMethod,\n resolvedUrl: capturedUrl,\n status: response.status,\n durationMs: performance.now() - start,\n injected: capturedInjection,\n ...readFetchRequestId(options, response),\n });\n return response;\n },\n (error: unknown) => {\n emitNetworkEvent(options, {\n kind: \"fetch\",\n method: capturedMethod,\n resolvedUrl: capturedUrl,\n status: 0,\n durationMs: performance.now() - start,\n failureMessage:\n error instanceof Error ? error.message : String(error),\n injected: capturedInjection,\n });\n throw error;\n },\n );\n };\n};\n\n// ------------------------------------------------------------------ XHR --\n\ninterface XhrRequestState {\n method: string;\n resolvedUrl?: string;\n customTraceparent: boolean;\n injected?: RequestTraceContext;\n start: number;\n /** Set by the outermost of our send wrappers in a third-party sandwich. */\n processed: boolean;\n}\n\nconst xhrState = new WeakMap<XMLHttpRequest, XhrRequestState>();\n\ninterface XhrPatch {\n originalOpen: XMLHttpRequest[\"open\"];\n originalSend: XMLHttpRequest[\"send\"];\n originalSetRequestHeader: XMLHttpRequest[\"setRequestHeader\"];\n wrappedOpen: XMLHttpRequest[\"open\"];\n wrappedSend: XMLHttpRequest[\"send\"];\n wrappedSetRequestHeader: XMLHttpRequest[\"setRequestHeader\"];\n}\n\nlet xhrPatch: XhrPatch | undefined;\n\nconst makeXhrPatch = (proto: XMLHttpRequest): XhrPatch => {\n const originalOpen = proto.open;\n const originalSend = proto.send;\n const originalSetRequestHeader = proto.setRequestHeader;\n\n // Forward `open` arguments with exact arity: `open(m, u, undefined)` would\n // coerce async to false (sync XHR) — not equivalent to the 2-arg call.\n const wrappedOpen = function (\n this: XMLHttpRequest,\n ...args: [string, string | URL, ...unknown[]]\n ): void {\n if (active) {\n try {\n const [method, url] = args;\n xhrState.set(this, {\n method: String(method).toUpperCase(),\n resolvedUrl: resolveUrl(String(url)),\n customTraceparent: false,\n start: 0,\n processed: false,\n });\n } catch {\n // Tracking failure must not affect the request.\n }\n }\n originalOpen.apply(this, args as Parameters<XMLHttpRequest[\"open\"]>);\n };\n\n const wrappedSetRequestHeader = function (\n this: XMLHttpRequest,\n name: string,\n value: string,\n ): void {\n if (active) {\n try {\n if (name.toLowerCase() === \"traceparent\") {\n const tracked = xhrState.get(this);\n if (tracked) {\n tracked.customTraceparent = true;\n }\n }\n } catch {\n // Ignore.\n }\n }\n originalSetRequestHeader.call(this, name, value);\n };\n\n const wrappedSend = function (\n this: XMLHttpRequest,\n body?: Document | XMLHttpRequestBodyInit | null,\n ): void {\n const options = active;\n if (options) {\n try {\n const tracked = xhrState.get(this);\n // `processed` = an outer copy of our wrapper already handled this\n // send (third-party sandwich); inner copies must not re-inject or\n // attach a second loadend emitter.\n if (tracked?.resolvedUrl && !tracked.processed) {\n tracked.processed = true;\n const internal = options.isInternalUrl(tracked.resolvedUrl);\n\n if (\n !internal &&\n options.propagateTraceContext &&\n !tracked.customTraceparent &&\n isAllowedForInjection(options, tracked.resolvedUrl)\n ) {\n try {\n const requestContext = options.traceContext.forRequest();\n for (const [name, value] of Object.entries(\n requestContext.headers,\n )) {\n originalSetRequestHeader.call(this, name, value);\n }\n tracked.injected = requestContext;\n } catch {\n tracked.injected = undefined;\n }\n }\n\n if (!internal) {\n recordWrapperRequest(tracked.resolvedUrl);\n }\n\n if (!internal && options.capture) {\n tracked.start = performance.now();\n this.addEventListener(\"loadend\", () => {\n const current = active ?? options;\n emitNetworkEvent(current, {\n kind: \"xhr\",\n method: tracked.method,\n resolvedUrl: tracked.resolvedUrl as string,\n status: this.status,\n durationMs: performance.now() - tracked.start,\n injected: tracked.injected,\n ...readXhrRequestId(current, this),\n });\n });\n }\n }\n } catch {\n // Fall through to the untouched send.\n }\n }\n originalSend.call(this, body);\n };\n\n return {\n originalOpen,\n originalSend,\n originalSetRequestHeader,\n wrappedOpen,\n wrappedSend,\n wrappedSetRequestHeader,\n };\n};\n\n// ----------------------------------------------------------------- install --\n\n/**\n * Install dormant fetch/XHR patches around whatever implementations are\n * currently live. Idempotent, and re-wraps when a later actor (test stubs,\n * mocking layers) replaced the primitives after an earlier install — the\n * displaced wrapper is an inert passthrough, so single-processing holds.\n */\nexport const ensureNetworkPatches = (): void => {\n if (!isWrapped(window.fetch)) {\n const original = window.fetch;\n const wrapped = makeWrappedFetch(original);\n markWrapped(wrapped);\n window.fetch = wrapped;\n fetchPatch = { original, wrapped };\n }\n\n const proto = XMLHttpRequest.prototype;\n if (!isWrapped(proto.open)) {\n const patch = makeXhrPatch(proto);\n markWrapped(patch.wrappedOpen);\n markWrapped(patch.wrappedSetRequestHeader);\n markWrapped(patch.wrappedSend);\n proto.open = patch.wrappedOpen;\n proto.setRequestHeader = patch.wrappedSetRequestHeader;\n proto.send = patch.wrappedSend;\n xhrPatch = patch;\n }\n};\n\n/**\n * Restore the natives if the current implementations are still ours; if\n * someone patched on top of us, restoring would clobber them — the inactive\n * wrappers pass through.\n */\nexport const uninstallNetworkPatches = (): void => {\n if (fetchPatch && window.fetch === fetchPatch.wrapped) {\n window.fetch = fetchPatch.original;\n }\n fetchPatch = undefined;\n\n const proto = XMLHttpRequest.prototype;\n if (xhrPatch) {\n if (proto.open === xhrPatch.wrappedOpen) {\n proto.open = xhrPatch.originalOpen;\n }\n if (proto.setRequestHeader === xhrPatch.wrappedSetRequestHeader) {\n proto.setRequestHeader = xhrPatch.originalSetRequestHeader;\n }\n if (proto.send === xhrPatch.wrappedSend) {\n proto.send = xhrPatch.originalSend;\n }\n }\n xhrPatch = undefined;\n seenByWrapper = [];\n};\n\nexport const installNetworkCapture = (\n options: NetworkCaptureOptions,\n): NetworkCaptureHandle => {\n ensureNetworkPatches();\n active = options;\n\n return {\n teardown() {\n active = undefined;\n },\n };\n};\n"
9
+ ],
10
+ "mappings": "AAGO,IAAM,EAAc,CAAC,IAAqB,CAC/C,GAAI,CACF,OAAO,eAAe,EALI,yBAKgB,CAAE,MAAO,EAAK,CAAC,EACzD,KAAM,IAKG,EAAY,CAAC,IACxB,OAAO,IAAO,YACb,EAb2B,yBAamC,GCYjE,IAAM,EAA0D,CAC9D,KAAM,YACN,QAAS,eACT,SAAU,WACV,OAAQ,QACV,EAWI,EAEE,EAAiB,CAAC,IAAyC,CAC/D,IAAM,EAAU,EAChB,GAAI,CAAC,EAAS,OACd,GAAI,CACF,IAAM,EAAa,OAAO,SAAS,KAC7B,EAAO,EAAQ,YAErB,GADA,EAAQ,YAAc,EAClB,IAAmB,QAAU,IAAS,EACxC,OAEF,EAAQ,QAAQ,WAAW,EAC3B,EAAQ,QAAQ,KAAK,CACnB,KAAM,aACN,KAAM,cAAc,OAAO,SAAS,WACpC,SAAU,OACV,WAAY,KAAK,IAAI,EACrB,WAAY,CACV,sBAAuB,EACvB,WAAY,EACZ,sBAAuB,GAAQ,MACjC,CACF,CAAC,EACD,KAAM,IAYN,EAEE,EAAmB,CAAC,IAAiC,CACzD,IAAgC,UAA1B,EAC6B,aAA7B,GAAuB,EAkB7B,MAAO,CACL,oBACA,uBACA,iBAnBuB,QAAS,IAE7B,EACG,CACN,EAAkB,MAAM,KAAM,CAAI,EAClC,EAAe,WAAW,GAe1B,oBAZ0B,QAAS,IAEhC,EACG,CACN,EAAqB,MAAM,KAAM,CAAI,EACrC,EAAe,cAAc,EAQ/B,GAQW,EAA0B,IAAY,CACjD,IAAM,EAAQ,QAAQ,UACtB,GAAI,CAAC,EAAU,EAAM,SAAS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EAAM,iBAAmB,EAAS,yBAEpC,GAAI,EAAM,OAAS,EAAS,YAC1B,EAAM,KAAO,EAAS,aAG1B,EAAW,OACX,EAAgB,CAAC,GAGN,GAAwB,CACnC,KAEA,EAAqB,EACrB,EAAS,EAEF,CACL,QAAQ,EAAG,CACT,EAAS,OAEb",
11
+ "debugId": "0E88B5801F6610F064756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1,17 @@
1
+ import type { ConsoleCaptureLevel, WebEvent } from "./types";
2
+ export interface ConsoleCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ levels: ConsoleCaptureLevel[];
5
+ }
6
+ export interface ConsoleCaptureHandle {
7
+ teardown(): void;
8
+ }
9
+ /** SDK-emitted console lines carry this prefix and are never re-captured. */
10
+ export declare const SDK_CONSOLE_PREFIX = "[@sazabi/browser]";
11
+ /**
12
+ * Mirror selected console levels into the event stream as `log` events.
13
+ * The original console method always runs first — devtools behavior is never
14
+ * altered — and capture failures are swallowed. Lines the SDK itself prints
15
+ * (prefixed with SDK_CONSOLE_PREFIX) are skipped to avoid self-capture.
16
+ */
17
+ export declare const installConsoleCapture: (options: ConsoleCaptureOptions) => ConsoleCaptureHandle;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Human-readable element names for timeline events — a pragmatic subset of
3
+ * the ARIA accessible-name computation, biased hard toward developer-authored
4
+ * sources. The bright line: app-authored static text (labels, aria-label,
5
+ * placeholder, button captions) is capturable; user-reflected text (values,
6
+ * selected options, data rendered into the DOM) is not. `data-sazabi-name`
7
+ * overrides any element's reported name; `data-sazabi-mask` on an ancestor
8
+ * suppresses name capture for the whole subtree.
9
+ */
10
+ /**
11
+ * Name for an input/textarea/select/contenteditable — developer-authored
12
+ * sources only; the field's value and (for selects) the chosen option text
13
+ * are never read.
14
+ */
15
+ export declare const computeInputName: (element: Element) => string | undefined;
16
+ /**
17
+ * Name for a click target: nearest interactive ancestor's accessible-ish
18
+ * name. Residual risk is labels that interpolate user data ("Delete 'My
19
+ * Project'") — that is app-authored markup, capped at 64 chars, and
20
+ * suppressible via `data-sazabi-mask` / overridable via `data-sazabi-name`.
21
+ */
22
+ export declare const computeClickName: (target: Element) => string | undefined;
@@ -0,0 +1,8 @@
1
+ import type { WebEvent } from "./types";
2
+ export interface ErrorCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ }
5
+ export interface ErrorCaptureHandle {
6
+ teardown(): void;
7
+ }
8
+ export declare const installErrorCapture: (options: ErrorCaptureOptions) => ErrorCaptureHandle;
@@ -0,0 +1,30 @@
1
+ import type { BrowserSdkConfig, EventSeverity } from "./types";
2
+ export type { AttributeValue, BrowserSdkConfig, ConsoleCaptureConfig, ConsoleCaptureLevel, EventAttributes, EventSeverity, InputCaptureConfig, NetworkCaptureConfig, WebEvent, WebEventType, } from "./types";
3
+ export { SDK_VERSION } from "./version";
4
+ /**
5
+ * Initialize the SDK. Idempotent: repeat calls are ignored. When `consent`
6
+ * is provided, nothing new is installed — no listeners, no patches, no
7
+ * network — until it resolves true; on false (or a throw) the SDK stays
8
+ * dormant. (Patches pre-installed by `@sazabi/browser/register` exist
9
+ * but remain inert passthroughs until activation.)
10
+ */
11
+ export declare const init: (config: BrowserSdkConfig) => void;
12
+ /** Set the client-asserted user identity (`session.distinct_id`). */
13
+ export declare const identify: (distinctId: string, traits?: Record<string, unknown>) => void;
14
+ /**
15
+ * Logout: clear the client-asserted identity and rotate both session and
16
+ * window ids, so later activity on this device never threads into the
17
+ * previous user's timeline.
18
+ */
19
+ export declare const reset: () => void;
20
+ /** Emit a custom mark into the session event stream. */
21
+ export declare const addEvent: (name: string, attributes?: Record<string, unknown>) => void;
22
+ /**
23
+ * Emit an application log line (`web.event_type: "log"`) with session context
24
+ * attached. Drops silently before init/consent, like all capture.
25
+ */
26
+ export declare const log: (severity: EventSeverity, message: string, metadata?: Record<string, unknown>) => void;
27
+ /** Force-flush queued events. */
28
+ export declare const flush: () => Promise<void>;
29
+ /** Tear down all patches/listeners (restoring originals) and flush. */
30
+ export declare const shutdown: () => Promise<void>;
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import{a as P,b as H,d as ae,e as ce,f as q,g as z,h as ue,i as J,k as de,l as le}from"./chunk-rfm4nnme.js";var v=(e,t=4096)=>e.length>t?e.slice(0,t):e,h=(e,t="",n=0)=>{let r={};for(let[s,o]of Object.entries(e)){let i=t?`${t}.${s}`:s;if(o===null||o===void 0)continue;if(typeof o==="object"&&!Array.isArray(o)&&n<4){Object.assign(r,h(o,i,n+1));continue}if(typeof o==="number"||typeof o==="boolean")r[i]=o;else if(typeof o==="string")r[i]=v(o);else try{r[i]=v(JSON.stringify(o)??"")}catch{}}return r};var x="[@sazabi/browser]",pe={error:"ERROR",warn:"WARN",info:"INFO",debug:"DEBUG"},D=1000,fe=4000,me=(e)=>{let t;if(typeof e==="string")t=e;else if(e instanceof Error)t=`${e.name}: ${e.message}`;else try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>D?`${t.slice(0,D)}…`:t},V=(e)=>{let t=[],n=!1;for(let r of e.levels){let s=console[r];if(typeof s!=="function"||H(s))continue;let o=function(...i){if(s.apply(this??console,i),n)return;try{if(typeof i[0]==="string"&&i[0].startsWith(x))return;n=!0;let c=i.map(me).join(" ").slice(0,fe);e.emit({type:"log",body:c||`console.${r}`,severity:pe[r],timeUnixMs:Date.now(),attributes:{"web.console.level":r}})}catch{}finally{n=!1}};P(o),console[r]=o,t.push(()=>{if(console[r]===o)console[r]=s})}return{teardown(){for(let r of t)try{r()}catch{}}}};var U=(e)=>{let t=(r)=>{try{let s=r.error,o=s instanceof Error?s.name:"Error",i=r.message||"Unknown error";e.emit({type:"error",body:v(`${o}: ${i}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":o,"exception.message":i,"exception.stacktrace":s instanceof Error?s.stack??"":"","web.error.kind":"uncaught","web.error.filename":r.filename||void 0,"web.error.lineno":r.lineno||void 0,"web.error.colno":r.colno||void 0}})}catch{}},n=(r)=>{try{let s=r.reason,o=s instanceof Error,i=o?s.name:"UnhandledRejection",c=o?s.message:String(s);e.emit({type:"error",body:v(`${i}: ${c}`,512),severity:"ERROR",timeUnixMs:Date.now(),attributes:{"exception.type":i,"exception.message":c,"exception.stacktrace":o?s.stack??"":"","web.error.kind":"unhandledrejection"}})}catch{}};return window.addEventListener("error",t),window.addEventListener("unhandledrejection",n),{teardown(){window.removeEventListener("error",t),window.removeEventListener("unhandledrejection",n)}}};var ge=["button","a[href]","summary",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="option"]','[role="checkbox"]','[role="switch"]','input[type="submit"]','input[type="button"]','input[type="reset"]'].join(","),w=(e)=>{if(!e)return;let t=e.replace(/\s+/g," ").trim();if(!t)return;return t.length>64?`${t.slice(0,64)}…`:t},K=(e)=>{try{return e.closest("[data-sazabi-mask]")!==null}catch{return!0}},W=(e)=>{let t=w(e.getAttribute("data-sazabi-name"));if(t)return t;let n=w(e.getAttribute("aria-label"));if(n)return n;let r=e.getAttribute("aria-labelledby");if(!r)return;return w(r.split(/\s+/).map((s)=>document.getElementById(s)?.textContent??"").join(" "))},F=(e)=>{try{if(K(e))return;let t=W(e);if(t)return t;if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)for(let r of Array.from(e.labels??[])){let s=w(r.textContent);if(s)return s}let n=w(e.getAttribute("placeholder"));if(n)return n;return w(e.getAttribute("name"))}catch{return}},B=(e)=>{try{let t=e.closest(ge);if(!t||K(t))return;let n=W(t);if(n)return n;if(t instanceof HTMLInputElement)return w(t.getAttribute("value"));return w(t.textContent)}catch{return}};var G=1000,Y=30,ye=4,Ee=800,be=200,ve="a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]",R=(e)=>{let t=e.getAttribute("data-testid");if(t)return`[data-testid="${t}"]`;if(e.id)return`#${e.id}`;let n=[],r=e;while(r&&n.length<3){let s=r.tagName.toLowerCase();if(r.id){n.unshift(`#${r.id}`);break}let o=Array.from(r.classList).slice(0,2);if(o.length>0)s+=`.${o.join(".")}`;n.unshift(s),r=r.parentElement}return n.join(" > ").slice(0,be)},j=(e)=>{let t=0,n=0,r=[],s=Number.NEGATIVE_INFINITY,o=new Set,i=new MutationObserver(()=>{t=performance.now()});try{i.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}catch{}let c=(m)=>{try{let y=m.target;if(!(y instanceof Element))return;let a=performance.now(),u=R(y),d=y.tagName.toLowerCase(),l=B(y);e.emit({type:"click",body:l?`click "${l}"`:`click ${u}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}}),r.push({time:a,x:m.clientX,y:m.clientY});while(r.length>0&&a-r[0].time>G)r.shift();let f=r.filter((g)=>Math.abs(g.x-m.clientX)<=Y&&Math.abs(g.y-m.clientY)<=Y);if(f.length>=ye&&a-s>G)s=a,e.emit({type:"rage_click",body:l?`rage click "${l}"`:`rage click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l,"web.click_count":f.length}});if(y.closest(ve)){let g=a,S=window.setTimeout(()=>{o.delete(S);try{if(t<=g&&n<=g)e.emit({type:"dead_click",body:l?`dead click "${l}"`:`dead click ${u}`,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.element.selector":u,"web.element.tag":d,"web.element.name":l}})}catch{}},Ee);o.add(S)}}catch{}};return document.addEventListener("click",c,{capture:!0,passive:!0}),{notifyNavigation(){n=performance.now()},teardown(){document.removeEventListener("click",c,{capture:!0}),i.disconnect();for(let m of o)window.clearTimeout(m);o.clear()}}};var we=1e4,Se=20,he=new Set(["button","submit","reset","image","checkbox","radio","range","file","color"]),Ie=(e)=>{if(e instanceof HTMLInputElement){let t=(e.type||"text").toLowerCase();return he.has(t)?void 0:t}if(e instanceof HTMLTextAreaElement)return"textarea";if(e instanceof HTMLSelectElement)return"select";if(e instanceof HTMLElement&&e.isContentEditable)return"contenteditable";return},X=(e)=>{let t=new Map,n=(a,u)=>{t.delete(a.element);try{e.emit({type:"input",body:a.name?`input "${a.name}"`:`input ${a.selector}`,severity:"INFO",timeUnixMs:a.startUnixMs,attributes:{"web.element.selector":a.selector,"web.element.name":a.name,"web.input.field_type":a.fieldType,"web.input.edit_count":a.editCount,"web.input.duration_ms":Math.max(0,Math.round(a.lastInputPerf-a.startPerf)),...a.pasted?{"web.input.pasted":!0}:{},"web.input.ended_by":u}})}catch{}},r=(a)=>{for(let u of Array.from(t.values()))n(u,a)},s=(a)=>{for(let u of Array.from(t.values()))if(a-u.lastInputPerf>we)n(u,"idle")},o=(a)=>{try{let u=performance.now();s(u);let d=a.target,l=Ie(d);if(l===void 0||!(d instanceof Element))return;if(a.type==="change"&&l!=="select")return;let f=t.get(d);if(!f){if(t.size>=Se)return;f={element:d,selector:R(d),name:F(d),fieldType:l,startUnixMs:Date.now(),startPerf:u,lastInputPerf:u,editCount:0,pasted:!1},t.set(d,f)}f.editCount+=1,f.lastInputPerf=u;let g=a.inputType;if(typeof g==="string"&&g.startsWith("insertFromPaste"))f.pasted=!0;if(a.type==="change"&&l==="select")n(f,"change")}catch{}},i=(a)=>{try{let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"blur")}}catch{}},c=(a)=>{try{if(a.key!=="Enter")return;let u=a.target;if(u instanceof Element){let d=t.get(u);if(d)n(d,"enter")}}catch{}},m=()=>{if(document.visibilityState==="hidden")r("hidden")},y=()=>{r("unload")};return document.addEventListener("input",o,{capture:!0,passive:!0}),document.addEventListener("change",o,{capture:!0,passive:!0}),document.addEventListener("focusout",i,{capture:!0,passive:!0}),document.addEventListener("keydown",c,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",m),window.addEventListener("pagehide",y),{notifyNavigation(){r("navigation")},teardown(){document.removeEventListener("input",o,{capture:!0}),document.removeEventListener("change",o,{capture:!0}),document.removeEventListener("focusout",i,{capture:!0}),document.removeEventListener("keydown",c,{capture:!0}),document.removeEventListener("visibilitychange",m),window.removeEventListener("pagehide",y),r("unload")}}};var Q=(e)=>{if(typeof PerformanceObserver>"u")return{teardown(){}};let t=new Set,n=(o)=>{let i;try{i=new URL(o).origin}catch{return}if(t.has(i))return;t.add(i);let c=`requests to ${i} bypass SDK instrumentation (fetch/XHR captured pre-init). Fix: import "@sazabi/browser/register" first.`;e.emit({type:"log",body:c,severity:"WARN",timeUnixMs:Date.now(),attributes:{"web.sdk.diagnostic":"instrumentation_gap","web.sdk.bypassed_origin":i}});try{console.warn(`${x} ${c}`)}catch{}},r=(o)=>{try{if(o.initiatorType!=="fetch"&&o.initiatorType!=="xmlhttprequest")return;let i=o.name;if(e.isInternalUrl(i))return;if(J(i,o.startTime))return;let c=o.responseStatus??0,m=Math.round(performance.timeOrigin+o.startTime+o.duration);if(e.emit({type:"network",body:`request ${q(i)} → ${c>0?c:"observed"}`,severity:c>0?z(c):"INFO",timeUnixMs:m,attributes:{"http.response.status_code":c>0?c:void 0,"url.full":i,"web.network.kind":o.initiatorType==="fetch"?"fetch":"xhr","web.network.duration_ms":Math.round(o.duration),"web.network.source":"resource-timing"}}),e.isInjectionTarget(i))n(i)}catch{}},s;try{s=new PerformanceObserver((o)=>{for(let i of o.getEntries())r(i)}),s.observe({type:"resource",buffered:!0})}catch{return{teardown(){}}}return{teardown(){try{s.disconnect()}catch{}}}};var Ae=()=>{let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("")},_=(e)=>`${e}_${Date.now().toString(36)}${Ae()}`,Z=(e)=>{let t=new Map;return{get(n){try{return e().getItem(n)}catch{return t.get(n)??null}},set(n,r){try{e().setItem(n,r)}catch{t.set(n,r)}},remove(n){t.delete(n);try{e().removeItem(n)}catch{}}}},_e=(e)=>{if(!e)return;try{let t=JSON.parse(e);if(typeof t==="object"&&t!==null&&typeof t.id==="string"&&typeof t.startedAt==="number"&&typeof t.lastActivityAt==="number")return t}catch{}return},ee=()=>{let e=Z(()=>window.localStorage),t=Z(()=>window.sessionStorage),n=0,r=()=>{let i=Date.now(),c=_e(e.get("sazabi.session"));if(c&&i-c.lastActivityAt<=1800000&&i-c.startedAt<=86400000)return c;let m={id:_("sess"),startedAt:i,lastActivityAt:i};return e.set("sazabi.session",JSON.stringify(m)),n=i,m},s=t.get("sazabi.windowId");if(!s)s=_("win"),t.set("sazabi.windowId",s);let o=()=>{let i=Date.now();e.set("sazabi.session",JSON.stringify({id:_("sess"),startedAt:i,lastActivityAt:i})),n=i,s=_("win"),t.set("sazabi.windowId",s)};return{getSessionId(){return r().id},getWindowId(){return s},getDistinctId(){return e.get("sazabi.distinctId")??void 0},setDistinctId(i){let c=e.get("sazabi.distinctId")??void 0;if(c!==void 0&&c!==i)o();e.set("sazabi.distinctId",i)},reset(){e.remove("sazabi.distinctId"),o()},touch(){let i=Date.now(),c=r();if(i-n>=5000)e.set("sazabi.session",JSON.stringify({...c,lastActivityAt:i})),n=i}}};var Te=/^[0-9a-f]{32}$/,Ce=/^[0-9a-f]{16}$/,xe="0".repeat(32),Re="0".repeat(16),te=(e)=>{let t=new Uint8Array(e);do crypto.getRandomValues(t);while(t.every((n)=>n===0));return Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")},Oe=(e)=>{if(typeof e!=="object"||e===null)return!1;let{traceId:t,spanId:n,traceFlags:r}=e;return typeof t==="string"&&Te.test(t)&&t!==xe&&typeof n==="string"&&Ce.test(n)&&n!==Re&&typeof r==="number"},Ne=Symbol.for("opentelemetry.js.api.1"),ke=Symbol.for("OpenTelemetry Context Key SPAN"),Le=()=>{try{let r=globalThis[Ne]?.context?.active?.()?.getValue?.(ke)?.spanContext?.();return Oe(r)?r:void 0}catch{return}},Me=(e)=>{let t=(e.traceFlags&255).toString(16).padStart(2,"0");return`00-${e.traceId}-${e.spanId}-${t}`},De=(e)=>{try{return e.traceState?.serialize()||void 0}catch{return}},ne=(e)=>{let t=()=>({traceId:te(16),spanId:te(8),traceFlags:e.sampledFlag?1:0});return{forRequest(){let n=Le()??t(),r={traceparent:Me(n)},s=De(n);if(s)r.tracestate=s;return{headers:r,traceId:n.traceId,spanId:n.spanId}}}};var T="@sazabi/browser",I="0.2.0";var Pe={DEBUG:5,INFO:9,WARN:13,ERROR:17},He=1024,Ve=(e)=>{if(typeof e==="boolean")return{boolValue:e};if(typeof e==="number")return Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e};return{stringValue:v(e)}},re=(e)=>{let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;t.push({key:n,value:Ve(r)})}return t},oe=(e,t)=>{let n={timeUnixNano:`${e.timeUnixMs}000000`,severityNumber:Pe[e.severity],severityText:e.severity,body:{stringValue:v(e.body,He)},attributes:re({...t,...e.attributes})};if(e.traceId)n.traceId=e.traceId;if(e.spanId)n.spanId=e.spanId;return n},ie=(e)=>{let t=[],n=0,r,s=!1,o=(d)=>JSON.stringify({resourceLogs:[{resource:{attributes:re(e.resourceAttributes)},scopeLogs:[{scope:{name:T,version:I},logRecords:d}]}]}),i=o([]).length+64,c=Math.max(4096,e.maxBatchBytes-i),m=()=>{if(r!==void 0)window.clearTimeout(r),r=void 0},y=()=>{if(r!==void 0||s)return;r=window.setTimeout(()=>{r=void 0,u()},e.flushIntervalMs)},a=()=>{let d=[],l=[],f=0;for(let g of t){if(l.length>0&&f+g.bytes>c)d.push(l),l=[],f=0;l.push(g.record),f+=g.bytes}if(l.length>0)d.push(l);return t.length=0,n=0,d},u=async(d)=>{if(m(),t.length===0)return;let l=a().map((f)=>e.fetchImpl(e.url,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.publicKey}`},body:o(f),keepalive:d?.keepalive===!0}).catch(()=>{}));await Promise.all(l)};return{enqueue(d){if(s)return;let l=JSON.stringify(d).length+1;t.push({record:d,bytes:l}),n+=l;while(t.length>e.maxQueuedEvents){let f=t.shift();if(f)n-=f.bytes}if(n>=c)u();else y()},flush:u,async shutdown(){s=!0,await u()}}};var Ue=5000,Ke=57344,$e=500,We=["x-request-id","cf-ray","x-vercel-id","x-amz-cf-id","fly-request-id"],E,O=!1,A,C=!1,se=(e)=>{let t=window.fetch.bind(window),n=e.intakeHost.replace(/\/+$/,""),r=`${n}/v1/logs`,s=ee();if(C)s.reset(),C=!1;let o=A;if(A=void 0,o)s.setDistinctId(o.distinctId);let i=ie({url:r,publicKey:e.publicKey,resourceAttributes:{"service.name":e.serviceName,"service.version":e.serviceVersion,"deployment.environment":e.environment,"telemetry.sdk.name":T,"telemetry.sdk.version":I,"telemetry.sdk.language":"webjs","browser.user_agent":navigator.userAgent,"browser.language":navigator.language},fetchImpl:t,flushIntervalMs:e.flushIntervalMs??Ue,maxBatchBytes:e.maxBatchBytes??Ke,maxQueuedEvents:e.maxQueuedEvents??$e}),c=(p)=>{try{s.touch();let b={"web.event_type":p.type,"session.id":s.getSessionId(),"session.window_id":s.getWindowId(),"session.distinct_id":s.getDistinctId(),"web.page.url":window.location.href,"derived.source":"sdk"};i.enqueue(oe(p,b))}catch{}},m=(p)=>p.startsWith(n),y=(p)=>{try{c(p())}catch{}},a=[],u=U({emit:c});a.push(()=>u.teardown());let d=j({emit:c});a.push(()=>d.teardown());let l;if(e.input?.capture!==!1)l=X({emit:c}),a.push(()=>l?.teardown());let f=ce({emit:c,onNavigate:()=>{d.notifyNavigation(),l?.notifyNavigation()}});if(a.push(()=>f.teardown()),e.console?.capture!==!1){let p=V({emit:c,levels:e.console?.levels??["error","warn"]});a.push(()=>p.teardown())}let g=e.network??{},S=g.capture??!0,N=g.propagateTraceContext??!0;if(S||N){let p=le({emit:c,traceContext:ne({sampledFlag:g.sampledFlag??!1}),capture:S,propagateTraceContext:N,allowlist:g.allowlist??[],requestIdHeaders:g.requestIdHeaders??We,isInternalUrl:m});a.push(()=>p.teardown())}if(S&&g.resourceFallback!==!1){let p=Q({emit:c,isInternalUrl:m,isInjectionTarget:ue});a.push(()=>p.teardown())}let k=()=>{if(document.visibilityState==="hidden")i.flush({keepalive:!0})},L=()=>{i.flush({keepalive:!0})};if(document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",L),a.push(()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",L)}),E={identify(p,b){y(()=>(s.setDistinctId(p),{type:"custom",body:`identify ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":"identify",...b?h(b,"custom"):{}}}))},reset(){try{s.reset()}catch{}},addEvent(p,b){y(()=>({type:"custom",body:`custom ${p}`,severity:"INFO",timeUnixMs:Date.now(),attributes:{"web.custom.name":p,...b?h(b,"custom"):{}}}))},log(p,b,M){y(()=>({type:"log",body:b,severity:p,timeUnixMs:Date.now(),attributes:M?h(M):{}}))},flush(){return i.flush()},async shutdown(){for(let p of a.reverse())try{p()}catch{}de(),ae(),await i.shutdown()}},o)E.identify(o.distinctId,o.traits)},ht=(e)=>{if(typeof window>"u")return;if(O)return;if(O=!0,!e.publicKey||!e.intakeHost||!e.serviceName){console.warn("[@sazabi/browser] init() requires publicKey, intakeHost, and serviceName; SDK disabled.");return}if(e.consent===void 0){se(e);return}try{Promise.resolve(e.consent()).then((t)=>{if(t===!0)se(e)}).catch(()=>{})}catch{}},It=(e,t)=>{if(E)E.identify(e,t);else A={distinctId:e,traits:t}},At=()=>{if(E)E.reset();else C=!0,A=void 0},_t=(e,t)=>{E?.addEvent(e,t)},Tt=(e,t,n)=>{E?.log(e,t,n)},Ct=async()=>{await E?.flush()},xt=async()=>{let e=E;E=void 0,O=!1,A=void 0,C=!1,await e?.shutdown()};export{I as SDK_VERSION,_t as addEvent,Ct as flush,It as identify,ht as init,Tt as log,At as reset,xt as shutdown};
2
+
3
+ //# debugId=DC6876C1DCB5F18464756E2164756E21
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,21 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/attributes.ts", "../src/console.ts", "../src/errors.ts", "../src/element-name.ts", "../src/interactions.ts", "../src/input-capture.ts", "../src/resource-observer.ts", "../src/session.ts", "../src/trace-context.ts", "../src/version.ts", "../src/transport.ts", "../src/index.ts"],
4
+ "sourcesContent": [
5
+ "import type { EventAttributes } from \"./types\";\n\nconst MAX_VALUE_LENGTH = 4096;\nconst MAX_FLATTEN_DEPTH = 4;\n\nexport const truncateValue = (value: string, max = MAX_VALUE_LENGTH): string =>\n value.length > max ? value.slice(0, max) : value;\n\n/**\n * Flatten nested metadata into dot-keyed scalar attributes. Non-scalar leaves\n * are JSON-stringified; strings are length-capped so a hostile or buggy page\n * cannot inflate rows.\n */\nexport const flattenAttributes = (\n input: Record<string, unknown>,\n prefix = \"\",\n depth = 0,\n): EventAttributes => {\n const result: EventAttributes = {};\n\n for (const [key, rawValue] of Object.entries(input)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (rawValue === null || rawValue === undefined) {\n continue;\n }\n\n if (\n typeof rawValue === \"object\" &&\n !Array.isArray(rawValue) &&\n depth < MAX_FLATTEN_DEPTH\n ) {\n Object.assign(\n result,\n flattenAttributes(\n rawValue as Record<string, unknown>,\n fullKey,\n depth + 1,\n ),\n );\n continue;\n }\n\n if (typeof rawValue === \"number\" || typeof rawValue === \"boolean\") {\n result[fullKey] = rawValue;\n } else if (typeof rawValue === \"string\") {\n result[fullKey] = truncateValue(rawValue);\n } else {\n try {\n result[fullKey] = truncateValue(JSON.stringify(rawValue) ?? \"\");\n } catch {\n // Circular or unserializable — drop rather than throw into the host.\n }\n }\n }\n\n return result;\n};\n",
6
+ "import { isWrapped, markWrapped } from \"./patch-marker\";\nimport type { ConsoleCaptureLevel, EventSeverity, WebEvent } from \"./types\";\n\nexport interface ConsoleCaptureOptions {\n emit(event: WebEvent): void;\n levels: ConsoleCaptureLevel[];\n}\n\nexport interface ConsoleCaptureHandle {\n teardown(): void;\n}\n\n/** SDK-emitted console lines carry this prefix and are never re-captured. */\nexport const SDK_CONSOLE_PREFIX = \"[@sazabi/browser]\";\n\nconst SEVERITY_BY_LEVEL: Record<ConsoleCaptureLevel, EventSeverity> = {\n error: \"ERROR\",\n warn: \"WARN\",\n info: \"INFO\",\n debug: \"DEBUG\",\n};\n\nconst MAX_ARG_CHARS = 1_000;\nconst MAX_BODY_CHARS = 4_000;\n\nconst stringifyArg = (value: unknown): string => {\n let text: string;\n if (typeof value === \"string\") {\n text = value;\n } else if (value instanceof Error) {\n text = `${value.name}: ${value.message}`;\n } else {\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = String(value);\n }\n }\n return text.length > MAX_ARG_CHARS\n ? `${text.slice(0, MAX_ARG_CHARS)}…`\n : text;\n};\n\n/**\n * Mirror selected console levels into the event stream as `log` events.\n * The original console method always runs first — devtools behavior is never\n * altered — and capture failures are swallowed. Lines the SDK itself prints\n * (prefixed with SDK_CONSOLE_PREFIX) are skipped to avoid self-capture.\n */\nexport const installConsoleCapture = (\n options: ConsoleCaptureOptions,\n): ConsoleCaptureHandle => {\n const restores: Array<() => void> = [];\n let emitting = false;\n\n for (const level of options.levels) {\n const original = console[level];\n if (typeof original !== \"function\" || isWrapped(original)) {\n continue;\n }\n\n const wrapped = function (this: unknown, ...args: unknown[]): void {\n original.apply(this ?? console, args);\n if (emitting) return;\n try {\n if (\n typeof args[0] === \"string\" &&\n args[0].startsWith(SDK_CONSOLE_PREFIX)\n ) {\n return;\n }\n emitting = true;\n const body = args.map(stringifyArg).join(\" \").slice(0, MAX_BODY_CHARS);\n options.emit({\n type: \"log\",\n body: body || `console.${level}`,\n severity: SEVERITY_BY_LEVEL[level],\n timeUnixMs: Date.now(),\n attributes: {\n \"web.console.level\": level,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n } finally {\n emitting = false;\n }\n };\n\n markWrapped(wrapped);\n console[level] = wrapped as typeof original;\n restores.push(() => {\n if (console[level] === wrapped) {\n console[level] = original;\n }\n });\n }\n\n return {\n teardown() {\n for (const restore of restores) {\n try {\n restore();\n } catch {\n // Best-effort restore.\n }\n }\n },\n };\n};\n",
7
+ "import { truncateValue } from \"./attributes\";\nimport type { WebEvent } from \"./types\";\n\nexport interface ErrorCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface ErrorCaptureHandle {\n teardown(): void;\n}\n\nexport const installErrorCapture = (\n options: ErrorCaptureOptions,\n): ErrorCaptureHandle => {\n const onError = (event: ErrorEvent): void => {\n try {\n const error: unknown = event.error;\n const exceptionType = error instanceof Error ? error.name : \"Error\";\n const message = event.message || \"Unknown error\";\n\n options.emit({\n type: \"error\",\n body: truncateValue(`${exceptionType}: ${message}`, 512),\n severity: \"ERROR\",\n timeUnixMs: Date.now(),\n attributes: {\n \"exception.type\": exceptionType,\n \"exception.message\": message,\n \"exception.stacktrace\":\n error instanceof Error ? (error.stack ?? \"\") : \"\",\n \"web.error.kind\": \"uncaught\",\n \"web.error.filename\": event.filename || undefined,\n \"web.error.lineno\": event.lineno || undefined,\n \"web.error.colno\": event.colno || undefined,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n const onUnhandledRejection = (event: PromiseRejectionEvent): void => {\n try {\n const reason: unknown = event.reason;\n const isError = reason instanceof Error;\n const exceptionType = isError ? reason.name : \"UnhandledRejection\";\n const message = isError ? reason.message : String(reason);\n\n options.emit({\n type: \"error\",\n body: truncateValue(`${exceptionType}: ${message}`, 512),\n severity: \"ERROR\",\n timeUnixMs: Date.now(),\n attributes: {\n \"exception.type\": exceptionType,\n \"exception.message\": message,\n \"exception.stacktrace\": isError ? (reason.stack ?? \"\") : \"\",\n \"web.error.kind\": \"unhandledrejection\",\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n window.addEventListener(\"error\", onError);\n window.addEventListener(\"unhandledrejection\", onUnhandledRejection);\n\n return {\n teardown() {\n window.removeEventListener(\"error\", onError);\n window.removeEventListener(\"unhandledrejection\", onUnhandledRejection);\n },\n };\n};\n",
8
+ "/**\n * Human-readable element names for timeline events — a pragmatic subset of\n * the ARIA accessible-name computation, biased hard toward developer-authored\n * sources. The bright line: app-authored static text (labels, aria-label,\n * placeholder, button captions) is capturable; user-reflected text (values,\n * selected options, data rendered into the DOM) is not. `data-sazabi-name`\n * overrides any element's reported name; `data-sazabi-mask` on an ancestor\n * suppresses name capture for the whole subtree.\n */\n\nconst MAX_NAME_CHARS = 64;\nconst NAME_ATTRIBUTE = \"data-sazabi-name\";\nconst MASK_ATTRIBUTE = \"data-sazabi-mask\";\n\n/**\n * Click-name eligibility: genuinely interactive elements only. Clicks on\n * plain containers (divs, table cells — where user content lives) get a\n * selector but never text.\n */\nconst INTERACTIVE_NAME_SELECTOR = [\n \"button\",\n \"a[href]\",\n \"summary\",\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"tab\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"checkbox\"]',\n '[role=\"switch\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"button\"]',\n 'input[type=\"reset\"]',\n].join(\",\");\n\nconst normalizeName = (raw: string | null | undefined): string | undefined => {\n if (!raw) return undefined;\n const collapsed = raw.replace(/\\s+/g, \" \").trim();\n if (!collapsed) return undefined;\n return collapsed.length > MAX_NAME_CHARS\n ? `${collapsed.slice(0, MAX_NAME_CHARS)}…`\n : collapsed;\n};\n\nconst isMasked = (element: Element): boolean => {\n try {\n return element.closest(`[${MASK_ATTRIBUTE}]`) !== null;\n } catch {\n return true; // Fail closed: no name beats a leaked name.\n }\n};\n\n/** Shared dev-authored sources: override attr → aria-label → aria-labelledby. */\nconst authoredName = (element: Element): string | undefined => {\n const explicit = normalizeName(element.getAttribute(NAME_ATTRIBUTE));\n if (explicit) return explicit;\n const ariaLabel = normalizeName(element.getAttribute(\"aria-label\"));\n if (ariaLabel) return ariaLabel;\n\n const ids = element.getAttribute(\"aria-labelledby\");\n if (!ids) return undefined;\n return normalizeName(\n ids\n .split(/\\s+/)\n .map((id) => document.getElementById(id)?.textContent ?? \"\")\n .join(\" \"),\n );\n};\n\n/**\n * Name for an input/textarea/select/contenteditable — developer-authored\n * sources only; the field's value and (for selects) the chosen option text\n * are never read.\n */\nexport const computeInputName = (element: Element): string | undefined => {\n try {\n if (isMasked(element)) return undefined;\n\n const named = authoredName(element);\n if (named) return named;\n\n if (\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLSelectElement\n ) {\n for (const label of Array.from(element.labels ?? [])) {\n const labelText = normalizeName(label.textContent);\n if (labelText) return labelText;\n }\n }\n\n const placeholder = normalizeName(element.getAttribute(\"placeholder\"));\n if (placeholder) return placeholder;\n return normalizeName(element.getAttribute(\"name\"));\n } catch {\n return undefined;\n }\n};\n\n/**\n * Name for a click target: nearest interactive ancestor's accessible-ish\n * name. Residual risk is labels that interpolate user data (\"Delete 'My\n * Project'\") — that is app-authored markup, capped at 64 chars, and\n * suppressible via `data-sazabi-mask` / overridable via `data-sazabi-name`.\n */\nexport const computeClickName = (target: Element): string | undefined => {\n try {\n const interactive = target.closest(INTERACTIVE_NAME_SELECTOR);\n if (!interactive || isMasked(interactive)) return undefined;\n\n const named = authoredName(interactive);\n if (named) return named;\n\n if (interactive instanceof HTMLInputElement) {\n // submit/button/reset inputs: the value attribute IS the caption.\n return normalizeName(interactive.getAttribute(\"value\"));\n }\n return normalizeName(interactive.textContent);\n } catch {\n return undefined;\n }\n};\n",
9
+ "import { computeClickName } from \"./element-name\";\nimport type { WebEvent } from \"./types\";\n\nexport interface InteractionCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface InteractionCaptureHandle {\n /** Navigation counts as a click response for dead-click detection. */\n notifyNavigation(): void;\n teardown(): void;\n}\n\nconst RAGE_WINDOW_MS = 1000;\nconst RAGE_RADIUS_PX = 30;\nconst RAGE_CLICK_COUNT = 4;\nconst DEAD_CLICK_TIMEOUT_MS = 800;\nconst MAX_SELECTOR_LENGTH = 200;\n\nconst INTERACTIVE_SELECTOR =\n \"a,button,[role=button],input,select,textarea,label,summary,[tabindex],[onclick]\";\n\n/** Short, stable-ish selector for an element; never includes text content. */\nexport const computeSelector = (element: Element): string => {\n const testId = element.getAttribute(\"data-testid\");\n if (testId) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id) {\n return `#${element.id}`;\n }\n\n const segments: string[] = [];\n let current: Element | null = element;\n while (current && segments.length < 3) {\n let segment = current.tagName.toLowerCase();\n if (current.id) {\n segments.unshift(`#${current.id}`);\n break;\n }\n const classes = Array.from(current.classList).slice(0, 2);\n if (classes.length > 0) {\n segment += `.${classes.join(\".\")}`;\n }\n segments.unshift(segment);\n current = current.parentElement;\n }\n return segments.join(\" > \").slice(0, MAX_SELECTOR_LENGTH);\n};\n\ninterface RecentClick {\n time: number;\n x: number;\n y: number;\n}\n\nexport const installInteractionCapture = (\n options: InteractionCaptureOptions,\n): InteractionCaptureHandle => {\n let lastDomActivityAt = 0;\n let lastNavigationAt = 0;\n const recentClicks: RecentClick[] = [];\n // Not 0: performance.now() < 1s during early page life would read as\n // \"just reported\" and suppress a genuine first-second rage burst.\n let rageReportedAt = Number.NEGATIVE_INFINITY;\n const pendingDeadClickTimers = new Set<number>();\n\n const observer = new MutationObserver(() => {\n lastDomActivityAt = performance.now();\n });\n try {\n observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n } catch {\n // Without mutation signal, dead clicks are simply never reported.\n }\n\n const onClick = (event: MouseEvent): void => {\n try {\n const target = event.target;\n if (!(target instanceof Element)) {\n return;\n }\n\n const now = performance.now();\n const selector = computeSelector(target);\n const tag = target.tagName.toLowerCase();\n const name = computeClickName(target);\n\n options.emit({\n type: \"click\",\n body: name ? `click \"${name}\"` : `click ${selector}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.element.selector\": selector,\n \"web.element.tag\": tag,\n \"web.element.name\": name,\n },\n });\n\n // Rage click: repeated clicks in a tight radius within the window.\n recentClicks.push({ time: now, x: event.clientX, y: event.clientY });\n while (\n recentClicks.length > 0 &&\n now - (recentClicks[0] as RecentClick).time > RAGE_WINDOW_MS\n ) {\n recentClicks.shift();\n }\n const clustered = recentClicks.filter(\n (click) =>\n Math.abs(click.x - event.clientX) <= RAGE_RADIUS_PX &&\n Math.abs(click.y - event.clientY) <= RAGE_RADIUS_PX,\n );\n if (\n clustered.length >= RAGE_CLICK_COUNT &&\n now - rageReportedAt > RAGE_WINDOW_MS\n ) {\n rageReportedAt = now;\n options.emit({\n type: \"rage_click\",\n body: name ? `rage click \"${name}\"` : `rage click ${selector}`,\n severity: \"WARN\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.element.selector\": selector,\n \"web.element.tag\": tag,\n \"web.element.name\": name,\n \"web.click_count\": clustered.length,\n },\n });\n }\n\n // Dead click: an interactive target where nothing observable follows.\n if (target.closest(INTERACTIVE_SELECTOR)) {\n const clickedAt = now;\n const timer = window.setTimeout(() => {\n pendingDeadClickTimers.delete(timer);\n try {\n if (\n lastDomActivityAt <= clickedAt &&\n lastNavigationAt <= clickedAt\n ) {\n options.emit({\n type: \"dead_click\",\n body: name ? `dead click \"${name}\"` : `dead click ${selector}`,\n severity: \"WARN\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.element.selector\": selector,\n \"web.element.tag\": tag,\n \"web.element.name\": name,\n },\n });\n }\n } catch {\n // Never throw from a timer into the host.\n }\n }, DEAD_CLICK_TIMEOUT_MS);\n pendingDeadClickTimers.add(timer);\n }\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n document.addEventListener(\"click\", onClick, { capture: true, passive: true });\n\n return {\n notifyNavigation() {\n lastNavigationAt = performance.now();\n },\n teardown() {\n document.removeEventListener(\"click\", onClick, { capture: true });\n observer.disconnect();\n for (const timer of pendingDeadClickTimers) {\n window.clearTimeout(timer);\n }\n pendingDeadClickTimers.clear();\n },\n };\n};\n",
10
+ "import { computeInputName } from \"./element-name\";\nimport { computeSelector } from \"./interactions\";\nimport type { WebEvent } from \"./types\";\n\nexport interface InputCaptureOptions {\n emit(event: WebEvent): void;\n}\n\nexport interface InputCaptureHandle {\n /** SPA navigation ends any open episodes. */\n notifyNavigation(): void;\n teardown(): void;\n}\n\nconst IDLE_END_MS = 10_000;\nconst MAX_TRACKED_EPISODES = 20;\n\n/** Input types that are click-like toggles, not typing surfaces. */\nconst NON_TEXT_INPUT_TYPES = new Set([\n \"button\",\n \"submit\",\n \"reset\",\n \"image\",\n \"checkbox\",\n \"radio\",\n \"range\",\n \"file\",\n \"color\",\n]);\n\ntype EpisodeEndReason =\n | \"blur\"\n | \"enter\"\n | \"change\"\n | \"idle\"\n | \"navigation\"\n | \"hidden\"\n | \"unload\";\n\ninterface InputEpisode {\n element: Element;\n selector: string;\n name?: string;\n fieldType: string;\n startUnixMs: number;\n startPerf: number;\n lastInputPerf: number;\n editCount: number;\n pasted: boolean;\n}\n\nconst editableFieldType = (target: EventTarget | null): string | undefined => {\n if (target instanceof HTMLInputElement) {\n const type = (target.type || \"text\").toLowerCase();\n return NON_TEXT_INPUT_TYPES.has(type) ? undefined : type;\n }\n if (target instanceof HTMLTextAreaElement) return \"textarea\";\n if (target instanceof HTMLSelectElement) return \"select\";\n if (target instanceof HTMLElement && target.isContentEditable) {\n return \"contenteditable\";\n }\n return undefined;\n};\n\n/**\n * Field-interaction episodes: one `input` event per engagement with an\n * editable element, not per keystroke. The event is timestamped at episode\n * START (so the timeline reads causally: typed → the request that followed)\n * and emitted when the episode ends — blur, Enter, ~10s idle, SPA\n * navigation, tab hidden, or teardown.\n *\n * Privacy invariants: `event.data`, field values, selected option text, and\n * key identities are never read (Enter is inspected solely as a boundary and\n * never recorded); no value derivatives, including length. Names come from\n * developer-authored sources only (see element-name.ts).\n */\nexport const installInputCapture = (\n options: InputCaptureOptions,\n): InputCaptureHandle => {\n const episodes = new Map<Element, InputEpisode>();\n\n const endEpisode = (\n episode: InputEpisode,\n endedBy: EpisodeEndReason,\n ): void => {\n episodes.delete(episode.element);\n try {\n options.emit({\n type: \"input\",\n body: episode.name\n ? `input \"${episode.name}\"`\n : `input ${episode.selector}`,\n severity: \"INFO\",\n timeUnixMs: episode.startUnixMs,\n attributes: {\n \"web.element.selector\": episode.selector,\n \"web.element.name\": episode.name,\n \"web.input.field_type\": episode.fieldType,\n \"web.input.edit_count\": episode.editCount,\n \"web.input.duration_ms\": Math.max(\n 0,\n Math.round(episode.lastInputPerf - episode.startPerf),\n ),\n ...(episode.pasted ? { \"web.input.pasted\": true } : {}),\n \"web.input.ended_by\": endedBy,\n },\n });\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n const endAll = (endedBy: EpisodeEndReason): void => {\n for (const episode of Array.from(episodes.values())) {\n endEpisode(episode, endedBy);\n }\n };\n\n const sweepIdle = (now: number): void => {\n for (const episode of Array.from(episodes.values())) {\n if (now - episode.lastInputPerf > IDLE_END_MS) {\n endEpisode(episode, \"idle\");\n }\n }\n };\n\n const onInput = (event: Event): void => {\n try {\n const now = performance.now();\n sweepIdle(now);\n\n const target = event.target;\n const fieldType = editableFieldType(target);\n if (fieldType === undefined || !(target instanceof Element)) {\n return;\n }\n // `change` matters only for selects (option committed): for text\n // fields it fires at commit time and would double-count the episode.\n if (event.type === \"change\" && fieldType !== \"select\") {\n return;\n }\n\n let episode = episodes.get(target);\n if (!episode) {\n if (episodes.size >= MAX_TRACKED_EPISODES) {\n return; // Safety valve; the idle sweep keeps this map tiny.\n }\n episode = {\n element: target,\n selector: computeSelector(target),\n name: computeInputName(target),\n fieldType,\n startUnixMs: Date.now(),\n startPerf: now,\n lastInputPerf: now,\n editCount: 0,\n pasted: false,\n };\n episodes.set(target, episode);\n }\n\n episode.editCount += 1;\n episode.lastInputPerf = now;\n // Only the paste marker is read off the event — never `data`/values.\n const inputType = (event as InputEvent).inputType;\n if (\n typeof inputType === \"string\" &&\n inputType.startsWith(\"insertFromPaste\")\n ) {\n episode.pasted = true;\n }\n\n // A select commits atomically on change; there is no blur to wait for\n // (programmatic/JS-driven selects never focus the element).\n if (event.type === \"change\" && fieldType === \"select\") {\n endEpisode(episode, \"change\");\n }\n } catch {\n // Capture failures must never surface to the host.\n }\n };\n\n const onFocusOut = (event: Event): void => {\n try {\n const target = event.target;\n if (target instanceof Element) {\n const episode = episodes.get(target);\n if (episode) endEpisode(episode, \"blur\");\n }\n } catch {\n // Ignore.\n }\n };\n\n const onKeyDown = (event: KeyboardEvent): void => {\n try {\n // Enter is the only key ever inspected, solely as an episode\n // boundary; key identities are never recorded.\n if (event.key !== \"Enter\") return;\n const target = event.target;\n if (target instanceof Element) {\n const episode = episodes.get(target);\n if (episode) endEpisode(episode, \"enter\");\n }\n } catch {\n // Ignore.\n }\n };\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === \"hidden\") {\n endAll(\"hidden\");\n }\n };\n const onPageHide = (): void => {\n endAll(\"unload\");\n };\n\n document.addEventListener(\"input\", onInput, { capture: true, passive: true });\n // Selects commit through `change`; some drivers/frameworks emit it without\n // a preceding `input`.\n document.addEventListener(\"change\", onInput, {\n capture: true,\n passive: true,\n });\n document.addEventListener(\"focusout\", onFocusOut, {\n capture: true,\n passive: true,\n });\n document.addEventListener(\"keydown\", onKeyDown, {\n capture: true,\n passive: true,\n });\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", onPageHide);\n\n return {\n notifyNavigation() {\n endAll(\"navigation\");\n },\n teardown() {\n document.removeEventListener(\"input\", onInput, { capture: true });\n document.removeEventListener(\"change\", onInput, { capture: true });\n document.removeEventListener(\"focusout\", onFocusOut, { capture: true });\n document.removeEventListener(\"keydown\", onKeyDown, { capture: true });\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", onPageHide);\n endAll(\"unload\");\n },\n };\n};\n",
11
+ "import { SDK_CONSOLE_PREFIX } from \"./console\";\nimport { consumeWrapperSeen } from \"./network\";\nimport { severityForStatus, urlPath } from \"./network-event-format\";\nimport type { WebEvent } from \"./types\";\n\nexport interface ResourceObserverOptions {\n emit(event: WebEvent): void;\n /** SDK-internal endpoints: never reported. */\n isInternalUrl(url: string): boolean;\n /** Would the active config have injected trace context into this URL? */\n isInjectionTarget(url: string): boolean;\n}\n\nexport interface ResourceObserverHandle {\n teardown(): void;\n}\n\n/**\n * Patch-independent network visibility: PerformanceObserver resource timing\n * sees every fetch/XHR the page performs — including ones issued by clients\n * that captured the native functions before the SDK patched (`buffered: true`\n * also replays requests from before init). Wrapper-captured requests are\n * deduped out via the wrapper-seen ledger; the leftovers get a degraded\n * network event (no method, no trace id — observation cannot inject), plus a\n * once-per-origin instrumentation-gap diagnostic when the URL was an\n * injection target, so bypass is a visible signal instead of silent loss.\n */\nexport const installResourceObserver = (\n options: ResourceObserverOptions,\n): ResourceObserverHandle => {\n if (typeof PerformanceObserver === \"undefined\") {\n return { teardown() {} };\n }\n\n const diagnosedOrigins = new Set<string>();\n\n const diagnoseBypass = (url: string): void => {\n let origin: string;\n try {\n origin = new URL(url).origin;\n } catch {\n return;\n }\n if (diagnosedOrigins.has(origin)) return;\n diagnosedOrigins.add(origin);\n\n const message = `requests to ${origin} bypass SDK instrumentation (fetch/XHR captured pre-init). Fix: import \"@sazabi/browser/register\" first.`;\n options.emit({\n type: \"log\",\n body: message,\n severity: \"WARN\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.sdk.diagnostic\": \"instrumentation_gap\",\n \"web.sdk.bypassed_origin\": origin,\n },\n });\n try {\n console.warn(`${SDK_CONSOLE_PREFIX} ${message}`);\n } catch {\n // Console unavailability is not our problem.\n }\n };\n\n const handleEntry = (entry: PerformanceResourceTiming): void => {\n try {\n if (\n entry.initiatorType !== \"fetch\" &&\n entry.initiatorType !== \"xmlhttprequest\"\n ) {\n return;\n }\n const url = entry.name;\n if (options.isInternalUrl(url)) return;\n if (consumeWrapperSeen(url, entry.startTime)) return;\n\n // Typed required in current lib.dom, but absent in older engines.\n const status = (entry.responseStatus as number | undefined) ?? 0;\n const completedAtMs = Math.round(\n performance.timeOrigin + entry.startTime + entry.duration,\n );\n\n options.emit({\n type: \"network\",\n body: `request ${urlPath(url)} → ${status > 0 ? status : \"observed\"}`,\n severity: status > 0 ? severityForStatus(status) : \"INFO\",\n timeUnixMs: completedAtMs,\n attributes: {\n \"http.response.status_code\": status > 0 ? status : undefined,\n \"url.full\": url,\n \"web.network.kind\": entry.initiatorType === \"fetch\" ? \"fetch\" : \"xhr\",\n \"web.network.duration_ms\": Math.round(entry.duration),\n \"web.network.source\": \"resource-timing\",\n },\n });\n\n if (options.isInjectionTarget(url)) {\n diagnoseBypass(url);\n }\n } catch {\n // Observation failures must never surface to the host.\n }\n };\n\n let observer: PerformanceObserver;\n try {\n observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n handleEntry(entry as PerformanceResourceTiming);\n }\n });\n observer.observe({ type: \"resource\", buffered: true });\n } catch {\n return { teardown() {} };\n }\n\n return {\n teardown() {\n try {\n observer.disconnect();\n } catch {\n // Best-effort.\n }\n },\n };\n};\n",
12
+ "const SESSION_STORAGE_KEY = \"sazabi.session\";\nconst WINDOW_STORAGE_KEY = \"sazabi.windowId\";\nconst DISTINCT_STORAGE_KEY = \"sazabi.distinctId\";\n\nconst SESSION_IDLE_MS = 30 * 60 * 1000;\nconst SESSION_MAX_MS = 24 * 60 * 60 * 1000;\n/** Throttle localStorage activity writes; click bursts must not spam storage. */\nconst ACTIVITY_PERSIST_INTERVAL_MS = 5_000;\n\ninterface StoredSession {\n id: string;\n startedAt: number;\n lastActivityAt: number;\n}\n\nexport interface SessionManager {\n getSessionId(): string;\n getWindowId(): string;\n getDistinctId(): string | undefined;\n /**\n * Set the client-asserted identity. Switching from one identity directly\n * to a different one rotates the session and window ids so two users on a\n * shared device never thread into one timeline.\n */\n setDistinctId(distinctId: string): void;\n /** Logout: clear identity and rotate both session and window ids. */\n reset(): void;\n /** Record user activity; may rotate the session on idle/max-age expiry. */\n touch(): void;\n}\n\nconst randomSuffix = (): string => {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n};\n\nconst newId = (prefix: string): string =>\n `${prefix}_${Date.now().toString(36)}${randomSuffix()}`;\n\n/**\n * Storage access that degrades to in-memory when storage is unavailable\n * (Safari private mode, disabled cookies, sandboxed iframes). A degraded\n * session is per-page rather than cross-tab — acceptable fallback.\n */\nconst createSafeStorage = (\n getStore: () => Storage,\n): {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n} => {\n const memory = new Map<string, string>();\n return {\n get(key) {\n try {\n return getStore().getItem(key);\n } catch {\n return memory.get(key) ?? null;\n }\n },\n set(key, value) {\n try {\n getStore().setItem(key, value);\n } catch {\n memory.set(key, value);\n }\n },\n remove(key) {\n memory.delete(key);\n try {\n getStore().removeItem(key);\n } catch {\n // Fallback map already cleared.\n }\n },\n };\n};\n\nconst parseStoredSession = (raw: string | null): StoredSession | undefined => {\n if (!raw) return undefined;\n try {\n const parsed: unknown = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof (parsed as StoredSession).id === \"string\" &&\n typeof (parsed as StoredSession).startedAt === \"number\" &&\n typeof (parsed as StoredSession).lastActivityAt === \"number\"\n ) {\n return parsed as StoredSession;\n }\n } catch {\n // Corrupt value — treat as absent and rotate.\n }\n return undefined;\n};\n\n/**\n * Cross-tab session identity. `session.id` is the visit (localStorage, shared\n * across tabs, last-writer-wins on rotation races — a split session is\n * cosmetic, not data loss). `session.window_id` is this tab (sessionStorage).\n * `session.distinct_id` is read through storage so identify/reset in one tab\n * is visible to sibling tabs on their next event.\n */\nexport const createSessionManager = (): SessionManager => {\n const local = createSafeStorage(() => window.localStorage);\n const session = createSafeStorage(() => window.sessionStorage);\n\n let lastPersistedActivity = 0;\n\n const readOrRotate = (): StoredSession => {\n const now = Date.now();\n const stored = parseStoredSession(local.get(SESSION_STORAGE_KEY));\n\n if (\n stored &&\n now - stored.lastActivityAt <= SESSION_IDLE_MS &&\n now - stored.startedAt <= SESSION_MAX_MS\n ) {\n return stored;\n }\n\n const fresh: StoredSession = {\n id: newId(\"sess\"),\n startedAt: now,\n lastActivityAt: now,\n };\n local.set(SESSION_STORAGE_KEY, JSON.stringify(fresh));\n lastPersistedActivity = now;\n return fresh;\n };\n\n let windowId = session.get(WINDOW_STORAGE_KEY);\n if (!windowId) {\n windowId = newId(\"win\");\n session.set(WINDOW_STORAGE_KEY, windowId);\n }\n\n const rotate = (): void => {\n const now = Date.now();\n local.set(\n SESSION_STORAGE_KEY,\n JSON.stringify({\n id: newId(\"sess\"),\n startedAt: now,\n lastActivityAt: now,\n }),\n );\n lastPersistedActivity = now;\n windowId = newId(\"win\");\n session.set(WINDOW_STORAGE_KEY, windowId);\n };\n\n return {\n getSessionId() {\n return readOrRotate().id;\n },\n getWindowId() {\n return windowId as string;\n },\n getDistinctId() {\n return local.get(DISTINCT_STORAGE_KEY) ?? undefined;\n },\n setDistinctId(id: string) {\n const current = local.get(DISTINCT_STORAGE_KEY) ?? undefined;\n if (current !== undefined && current !== id) {\n // Identity switch without reset(): defensive rotation so the new\n // user's events never join the previous user's session.\n rotate();\n }\n local.set(DISTINCT_STORAGE_KEY, id);\n },\n reset() {\n local.remove(DISTINCT_STORAGE_KEY);\n rotate();\n },\n touch() {\n const now = Date.now();\n const current = readOrRotate();\n if (now - lastPersistedActivity >= ACTIVITY_PERSIST_INTERVAL_MS) {\n local.set(\n SESSION_STORAGE_KEY,\n JSON.stringify({ ...current, lastActivityAt: now }),\n );\n lastPersistedActivity = now;\n }\n },\n };\n};\n",
13
+ "export interface RequestTraceContext {\n /** Headers to inject (`traceparent`, and `tracestate` when present). */\n headers: Record<string, string>;\n traceId: string;\n spanId: string;\n}\n\nexport interface TraceContextManager {\n /** Trace context for one outgoing request, minted at request time. */\n forRequest(): RequestTraceContext;\n}\n\n/** The subset of an OTel SpanContext this module consumes. */\nexport interface HostSpanContext {\n traceId: string;\n spanId: string;\n traceFlags: number;\n traceState?: { serialize(): string };\n}\n\nconst SAMPLED_FLAG = 0x1;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\nconst ALL_ZERO_TRACE_ID = \"0\".repeat(32);\nconst ALL_ZERO_SPAN_ID = \"0\".repeat(16);\n\nconst randomHexId = (byteLength: number): string => {\n const bytes = new Uint8Array(byteLength);\n do {\n crypto.getRandomValues(bytes);\n } while (bytes.every((b) => b === 0)); // all-zero ids are invalid per W3C spec\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n};\n\nconst isValidHostSpanContext = (\n candidate: unknown,\n): candidate is HostSpanContext => {\n if (typeof candidate !== \"object\" || candidate === null) return false;\n const { traceId, spanId, traceFlags } = candidate as HostSpanContext;\n return (\n typeof traceId === \"string\" &&\n TRACE_ID_PATTERN.test(traceId) &&\n traceId !== ALL_ZERO_TRACE_ID &&\n typeof spanId === \"string\" &&\n SPAN_ID_PATTERN.test(spanId) &&\n spanId !== ALL_ZERO_SPAN_ID &&\n typeof traceFlags === \"number\"\n );\n};\n\n// ------------------------------------------------- host OTel interop --------\n// Dependency-free read of the host app's active span, through the\n// @opentelemetry/api package's own cross-copy compatibility contract: every\n// api copy interoperates via the global delegate registered at\n// Symbol.for(\"opentelemetry.js.api.1\"), and context keys are Symbol.for(...)\n// strings — that registry IS the mechanism by which independent api copies\n// find each other, which is what makes it load-bearing rather than private.\n// An integration test against the real api package (devDependency) pins the\n// contract; any shape drift degrades here to \"no active span\" and we mint\n// our own roots instead.\n\nconst OTEL_GLOBAL_KEY = Symbol.for(\"opentelemetry.js.api.1\");\nconst OTEL_SPAN_CONTEXT_KEY = Symbol.for(\"OpenTelemetry Context Key SPAN\");\n\ninterface OtelGlobalShape {\n context?: {\n active?: () => { getValue?: (key: symbol) => unknown } | undefined;\n };\n}\n\nexport const readHostSpanContext = (): HostSpanContext | undefined => {\n try {\n const otelApi = (globalThis as Record<symbol, unknown>)[OTEL_GLOBAL_KEY] as\n | OtelGlobalShape\n | undefined;\n const activeContext = otelApi?.context?.active?.();\n const span = activeContext?.getValue?.(OTEL_SPAN_CONTEXT_KEY) as\n | { spanContext?: () => unknown }\n | undefined;\n const candidate = span?.spanContext?.();\n return isValidHostSpanContext(candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst formatTraceparent = (spanContext: HostSpanContext): string => {\n const flags = (spanContext.traceFlags & 0xff).toString(16).padStart(2, \"0\");\n return `00-${spanContext.traceId}-${spanContext.spanId}-${flags}`;\n};\n\nconst readTraceState = (spanContext: HostSpanContext): string | undefined => {\n try {\n const serialized = spanContext.traceState?.serialize();\n return serialized || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * W3C trace context for outgoing requests — hand-rolled header formatting\n * (equivalence-tested against OTel's W3CTraceContextPropagator), zero\n * runtime dependencies. If the host app runs its own OTel and has an active\n * span, that span's context (including its flags and tracestate) is reused\n * so we join the customer's trace instead of forking a new one; otherwise a\n * fresh root is minted with the sampled flag defaulting to off (`-00`).\n */\nexport const createTraceContextManager = (options: {\n sampledFlag: boolean;\n}): TraceContextManager => {\n const mintRootSpanContext = (): HostSpanContext => ({\n traceId: randomHexId(16),\n spanId: randomHexId(8),\n traceFlags: options.sampledFlag ? SAMPLED_FLAG : 0,\n });\n\n return {\n forRequest() {\n const spanContext = readHostSpanContext() ?? mintRootSpanContext();\n const headers: Record<string, string> = {\n traceparent: formatTraceparent(spanContext),\n };\n const traceState = readTraceState(spanContext);\n if (traceState) {\n headers.tracestate = traceState;\n }\n return {\n headers,\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n };\n },\n };\n};\n",
14
+ "export const SDK_NAME = \"@sazabi/browser\";\nexport const SDK_VERSION = \"0.2.0\";\n",
15
+ "import { truncateValue } from \"./attributes\";\nimport type {\n AttributeValue,\n EventAttributes,\n EventSeverity,\n WebEvent,\n} from \"./types\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\ntype OtlpAnyValue =\n | { stringValue: string }\n | { intValue: string }\n | { doubleValue: number }\n | { boolValue: boolean };\n\ninterface OtlpKeyValue {\n key: string;\n value: OtlpAnyValue;\n}\n\nexport interface OtlpLogRecord {\n timeUnixNano: string;\n severityNumber: number;\n severityText: EventSeverity;\n body: { stringValue: string };\n attributes: OtlpKeyValue[];\n /** OTLP/JSON encodes trace/span ids as hex (unlike proto3 JSON's base64). */\n traceId?: string;\n spanId?: string;\n}\n\nconst SEVERITY_NUMBERS: Record<EventSeverity, number> = {\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n};\n\nconst MAX_BODY_LENGTH = 1024;\n\nconst encodeValue = (value: AttributeValue): OtlpAnyValue => {\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n if (typeof value === \"number\") {\n // proto3 JSON maps int64 to string; doubles stay numeric.\n return Number.isInteger(value)\n ? { intValue: String(value) }\n : { doubleValue: value };\n }\n return { stringValue: truncateValue(value) };\n};\n\nconst encodeAttributes = (attributes: EventAttributes): OtlpKeyValue[] => {\n const encoded: OtlpKeyValue[] = [];\n for (const [key, value] of Object.entries(attributes)) {\n if (value === undefined) {\n continue;\n }\n encoded.push({ key, value: encodeValue(value) });\n }\n return encoded;\n};\n\nexport const encodeLogRecord = (\n event: WebEvent,\n baseAttributes: EventAttributes,\n): OtlpLogRecord => {\n const record: OtlpLogRecord = {\n timeUnixNano: `${event.timeUnixMs}000000`,\n severityNumber: SEVERITY_NUMBERS[event.severity],\n severityText: event.severity,\n body: { stringValue: truncateValue(event.body, MAX_BODY_LENGTH) },\n attributes: encodeAttributes({ ...baseAttributes, ...event.attributes }),\n };\n if (event.traceId) {\n record.traceId = event.traceId;\n }\n if (event.spanId) {\n record.spanId = event.spanId;\n }\n return record;\n};\n\nexport interface TransportOptions {\n /** Full OTLP logs endpoint, e.g. `https://web.<region>.intake.<domain>/v1/logs`. */\n url: string;\n publicKey: string;\n resourceAttributes: EventAttributes;\n /**\n * The fetch to deliver with — captured before the SDK's network patch\n * installs, so exporter traffic can never recurse through our own wrapper\n * or appear in the captured event stream.\n */\n fetchImpl: typeof fetch;\n flushIntervalMs: number;\n maxBatchBytes: number;\n maxQueuedEvents: number;\n}\n\nexport interface Transport {\n enqueue(record: OtlpLogRecord): void;\n /**\n * Deliver everything queued. `keepalive: true` is for unload paths — each\n * request body must stay inside the browser's ~64 KiB keepalive budget,\n * which enqueue-side chunking guarantees via `maxBatchBytes`.\n */\n flush(options?: { keepalive?: boolean }): Promise<void>;\n shutdown(): Promise<void>;\n}\n\ninterface QueuedRecord {\n record: OtlpLogRecord;\n bytes: number;\n}\n\nexport const createTransport = (options: TransportOptions): Transport => {\n const queue: QueuedRecord[] = [];\n let queuedBytes = 0;\n let timer: number | undefined;\n let shutDown = false;\n\n const buildEnvelope = (records: OtlpLogRecord[]): string =>\n JSON.stringify({\n resourceLogs: [\n {\n resource: {\n attributes: encodeAttributes(options.resourceAttributes),\n },\n scopeLogs: [\n {\n scope: { name: SDK_NAME, version: SDK_VERSION },\n logRecords: records,\n },\n ],\n },\n ],\n });\n\n const envelopeOverhead = buildEnvelope([]).length + 64;\n const chunkBudget = Math.max(4096, options.maxBatchBytes - envelopeOverhead);\n\n const clearTimer = (): void => {\n if (timer !== undefined) {\n window.clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const scheduleFlush = (): void => {\n if (timer !== undefined || shutDown) {\n return;\n }\n timer = window.setTimeout(() => {\n timer = undefined;\n void flush();\n }, options.flushIntervalMs);\n };\n\n const takeChunks = (): OtlpLogRecord[][] => {\n const chunks: OtlpLogRecord[][] = [];\n let current: OtlpLogRecord[] = [];\n let currentBytes = 0;\n\n for (const queued of queue) {\n if (current.length > 0 && currentBytes + queued.bytes > chunkBudget) {\n chunks.push(current);\n current = [];\n currentBytes = 0;\n }\n current.push(queued.record);\n currentBytes += queued.bytes;\n }\n if (current.length > 0) {\n chunks.push(current);\n }\n\n queue.length = 0;\n queuedBytes = 0;\n return chunks;\n };\n\n const flush = async (flushOptions?: {\n keepalive?: boolean;\n }): Promise<void> => {\n clearTimer();\n if (queue.length === 0) {\n return;\n }\n\n const requests = takeChunks().map((chunk) =>\n options\n .fetchImpl(options.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${options.publicKey}`,\n },\n body: buildEnvelope(chunk),\n keepalive: flushOptions?.keepalive === true,\n })\n .catch(() => {\n // Delivery is best-effort; the SDK must stay silent on failure.\n }),\n );\n\n await Promise.all(requests);\n };\n\n return {\n enqueue(record) {\n if (shutDown) {\n return;\n }\n const bytes = JSON.stringify(record).length + 1;\n queue.push({ record, bytes });\n queuedBytes += bytes;\n\n while (queue.length > options.maxQueuedEvents) {\n const dropped = queue.shift();\n if (dropped) {\n queuedBytes -= dropped.bytes;\n }\n }\n\n if (queuedBytes >= chunkBudget) {\n void flush();\n } else {\n scheduleFlush();\n }\n },\n flush,\n async shutdown() {\n shutDown = true;\n await flush();\n },\n };\n};\n",
16
+ "import { flattenAttributes } from \"./attributes\";\nimport { installConsoleCapture } from \"./console\";\nimport { installErrorCapture } from \"./errors\";\nimport { type InputCaptureHandle, installInputCapture } from \"./input-capture\";\nimport { installInteractionCapture } from \"./interactions\";\nimport {\n installNavigationCapture,\n uninstallNavigationPatches,\n} from \"./navigation\";\nimport {\n installNetworkCapture,\n isActiveInjectionTarget,\n uninstallNetworkPatches,\n} from \"./network\";\nimport { installResourceObserver } from \"./resource-observer\";\nimport { createSessionManager } from \"./session\";\nimport { createTraceContextManager } from \"./trace-context\";\nimport { createTransport, encodeLogRecord } from \"./transport\";\nimport type {\n BrowserSdkConfig,\n EventAttributes,\n EventSeverity,\n NetworkCaptureConfig,\n WebEvent,\n} from \"./types\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\nexport type {\n AttributeValue,\n BrowserSdkConfig,\n ConsoleCaptureConfig,\n ConsoleCaptureLevel,\n EventAttributes,\n EventSeverity,\n InputCaptureConfig,\n NetworkCaptureConfig,\n WebEvent,\n WebEventType,\n} from \"./types\";\nexport { SDK_VERSION } from \"./version\";\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 5_000;\nconst DEFAULT_MAX_BATCH_BYTES = 57_344;\nconst DEFAULT_MAX_QUEUED_EVENTS = 500;\n/**\n * Platform request-id response headers probed for `web.network.request_id`,\n * in priority order: generic first, then common CDN/PaaS edges.\n */\nconst DEFAULT_REQUEST_ID_HEADERS = [\n \"x-request-id\",\n \"cf-ray\",\n \"x-vercel-id\",\n \"x-amz-cf-id\",\n \"fly-request-id\",\n];\n\ninterface SdkInstance {\n identify(distinctId: string, traits?: Record<string, unknown>): void;\n reset(): void;\n addEvent(name: string, attributes?: Record<string, unknown>): void;\n log(\n severity: EventSeverity,\n message: string,\n metadata?: Record<string, unknown>,\n ): void;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\ninterface PendingIdentity {\n distinctId: string;\n traits?: Record<string, unknown>;\n}\n\nlet instance: SdkInstance | undefined;\nlet initialized = false;\nlet pendingIdentity: PendingIdentity | undefined;\nlet pendingReset = false;\n\nconst start = (config: BrowserSdkConfig): void => {\n // Bound before capture activates. Under `register` this may already be the\n // dormant wrapper; intake URLs take its internal passthrough branch, so\n // transport traffic never recurses into capture either way.\n const prePatchFetch = window.fetch.bind(window);\n\n const intakeBase = config.intakeHost.replace(/\\/+$/, \"\");\n const intakeUrl = `${intakeBase}/v1/logs`;\n\n const session = createSessionManager();\n // Apply buffered identity before any capture emits, so even the initial\n // navigation event carries the identity claimed while consent was pending.\n if (pendingReset) {\n session.reset();\n pendingReset = false;\n }\n const appliedPendingIdentity = pendingIdentity;\n pendingIdentity = undefined;\n if (appliedPendingIdentity) {\n session.setDistinctId(appliedPendingIdentity.distinctId);\n }\n\n const transport = createTransport({\n url: intakeUrl,\n publicKey: config.publicKey,\n resourceAttributes: {\n \"service.name\": config.serviceName,\n \"service.version\": config.serviceVersion,\n \"deployment.environment\": config.environment,\n \"telemetry.sdk.name\": SDK_NAME,\n \"telemetry.sdk.version\": SDK_VERSION,\n \"telemetry.sdk.language\": \"webjs\",\n \"browser.user_agent\": navigator.userAgent,\n \"browser.language\": navigator.language,\n },\n fetchImpl: prePatchFetch,\n flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxBatchBytes: config.maxBatchBytes ?? DEFAULT_MAX_BATCH_BYTES,\n maxQueuedEvents: config.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_EVENTS,\n });\n\n const emit = (event: WebEvent): void => {\n try {\n session.touch();\n const base: EventAttributes = {\n \"web.event_type\": event.type,\n \"session.id\": session.getSessionId(),\n \"session.window_id\": session.getWindowId(),\n \"session.distinct_id\": session.getDistinctId(),\n \"web.page.url\": window.location.href,\n \"derived.source\": \"sdk\",\n };\n transport.enqueue(encodeLogRecord(event, base));\n } catch {\n // Emitting must never throw into the host.\n }\n };\n\n const isInternalUrl = (url: string): boolean => url.startsWith(intakeBase);\n\n // Guards event construction (attribute flattening can throw on exotic\n // input); emit() itself already guards delivery.\n const safeEmitEvent = (build: () => WebEvent): void => {\n try {\n emit(build());\n } catch {\n // Never throw into the host.\n }\n };\n\n const teardowns: Array<() => void> = [];\n\n const errorCapture = installErrorCapture({ emit });\n teardowns.push(() => errorCapture.teardown());\n\n const interactions = installInteractionCapture({ emit });\n teardowns.push(() => interactions.teardown());\n\n let inputCapture: InputCaptureHandle | undefined;\n if (config.input?.capture !== false) {\n inputCapture = installInputCapture({ emit });\n teardowns.push(() => inputCapture?.teardown());\n }\n\n const navigation = installNavigationCapture({\n emit,\n onNavigate: () => {\n interactions.notifyNavigation();\n inputCapture?.notifyNavigation();\n },\n });\n teardowns.push(() => navigation.teardown());\n\n if (config.console?.capture !== false) {\n const consoleCapture = installConsoleCapture({\n emit,\n levels: config.console?.levels ?? [\"error\", \"warn\"],\n });\n teardowns.push(() => consoleCapture.teardown());\n }\n\n const networkConfig: NetworkCaptureConfig = config.network ?? {};\n const networkCapture = networkConfig.capture ?? true;\n const propagateTraceContext = networkConfig.propagateTraceContext ?? true;\n if (networkCapture || propagateTraceContext) {\n const network = installNetworkCapture({\n emit,\n traceContext: createTraceContextManager({\n sampledFlag: networkConfig.sampledFlag ?? false,\n }),\n capture: networkCapture,\n propagateTraceContext,\n allowlist: networkConfig.allowlist ?? [],\n requestIdHeaders:\n networkConfig.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS,\n isInternalUrl,\n });\n teardowns.push(() => network.teardown());\n }\n\n if (networkCapture && networkConfig.resourceFallback !== false) {\n const resourceObserver = installResourceObserver({\n emit,\n isInternalUrl,\n isInjectionTarget: isActiveInjectionTarget,\n });\n teardowns.push(() => resourceObserver.teardown());\n }\n\n // Unload flush: visibilitychange→hidden is the reliable signal; pagehide\n // covers bfcache navigations. keepalive lets the batch outlive the page.\n const onVisibilityChange = (): void => {\n if (document.visibilityState === \"hidden\") {\n void transport.flush({ keepalive: true });\n }\n };\n const onPageHide = (): void => {\n void transport.flush({ keepalive: true });\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", onPageHide);\n teardowns.push(() => {\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", onPageHide);\n });\n\n instance = {\n identify(distinctId, traits) {\n safeEmitEvent(() => {\n session.setDistinctId(distinctId);\n return {\n type: \"custom\",\n body: `identify ${distinctId}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.custom.name\": \"identify\",\n ...(traits ? flattenAttributes(traits, \"custom\") : {}),\n },\n };\n });\n },\n reset() {\n try {\n session.reset();\n } catch {\n // Never throw into the host.\n }\n },\n addEvent(name, attributes) {\n safeEmitEvent(() => ({\n type: \"custom\",\n body: `custom ${name}`,\n severity: \"INFO\",\n timeUnixMs: Date.now(),\n attributes: {\n \"web.custom.name\": name,\n ...(attributes ? flattenAttributes(attributes, \"custom\") : {}),\n },\n }));\n },\n log(severity, message, metadata) {\n safeEmitEvent(() => ({\n type: \"log\",\n body: message,\n severity,\n timeUnixMs: Date.now(),\n // Raw-key flattening (no prefix) for parity with app loggers,\n // so existing log queries keep their attribute names.\n attributes: metadata ? flattenAttributes(metadata) : {},\n }));\n },\n flush() {\n return transport.flush();\n },\n async shutdown() {\n for (const teardown of teardowns.reverse()) {\n try {\n teardown();\n } catch {\n // Teardown must be best-effort.\n }\n }\n // Deactivation above leaves dormant patches; full shutdown restores\n // the natives (when still ours).\n uninstallNetworkPatches();\n uninstallNavigationPatches();\n await transport.shutdown();\n },\n };\n\n // The identify event for a pre-consent identify() is emitted only now that\n // capture exists; the id itself was applied to the session earlier.\n if (appliedPendingIdentity) {\n instance.identify(\n appliedPendingIdentity.distinctId,\n appliedPendingIdentity.traits,\n );\n }\n};\n\n/**\n * Initialize the SDK. Idempotent: repeat calls are ignored. When `consent`\n * is provided, nothing new is installed — no listeners, no patches, no\n * network — until it resolves true; on false (or a throw) the SDK stays\n * dormant. (Patches pre-installed by `@sazabi/browser/register` exist\n * but remain inert passthroughs until activation.)\n */\nexport const init = (config: BrowserSdkConfig): void => {\n if (typeof window === \"undefined\") {\n return; // SSR — nothing to capture.\n }\n if (initialized) {\n return;\n }\n initialized = true;\n\n if (!config.publicKey || !config.intakeHost || !config.serviceName) {\n // Developer-facing misconfiguration: warn once, never throw.\n console.warn(\n \"[@sazabi/browser] init() requires publicKey, intakeHost, and serviceName; SDK disabled.\",\n );\n return;\n }\n\n if (config.consent === undefined) {\n start(config);\n return;\n }\n\n try {\n void Promise.resolve(config.consent())\n .then((granted) => {\n if (granted === true) {\n start(config);\n }\n })\n .catch(() => {\n // Consent evaluation failed — stay dormant.\n });\n } catch {\n // Synchronous throw from consent() — stay dormant.\n }\n};\n\n/** Set the client-asserted user identity (`session.distinct_id`). */\nexport const identify = (\n distinctId: string,\n traits?: Record<string, unknown>,\n): void => {\n if (instance) {\n instance.identify(distinctId, traits);\n } else {\n // Buffer identity across a pending consent gate; the identify event is\n // emitted when capture starts.\n pendingIdentity = { distinctId, traits };\n }\n};\n\n/**\n * Logout: clear the client-asserted identity and rotate both session and\n * window ids, so later activity on this device never threads into the\n * previous user's timeline.\n */\nexport const reset = (): void => {\n if (instance) {\n instance.reset();\n } else {\n pendingReset = true;\n pendingIdentity = undefined;\n }\n};\n\n/** Emit a custom mark into the session event stream. */\nexport const addEvent = (\n name: string,\n attributes?: Record<string, unknown>,\n): void => {\n instance?.addEvent(name, attributes);\n};\n\n/**\n * Emit an application log line (`web.event_type: \"log\"`) with session context\n * attached. Drops silently before init/consent, like all capture.\n */\nexport const log = (\n severity: EventSeverity,\n message: string,\n metadata?: Record<string, unknown>,\n): void => {\n instance?.log(severity, message, metadata);\n};\n\n/** Force-flush queued events. */\nexport const flush = async (): Promise<void> => {\n await instance?.flush();\n};\n\n/** Tear down all patches/listeners (restoring originals) and flush. */\nexport const shutdown = async (): Promise<void> => {\n const active = instance;\n instance = undefined;\n initialized = false;\n pendingIdentity = undefined;\n pendingReset = false;\n await active?.shutdown();\n};\n"
17
+ ],
18
+ "mappings": "4GAKO,IAAM,EAAgB,CAAC,EAAe,EAHpB,OAIvB,EAAM,OAAS,EAAM,EAAM,MAAM,EAAG,CAAG,EAAI,EAOhC,EAAoB,CAC/B,EACA,EAAS,GACT,EAAQ,IACY,CACpB,IAAM,EAA0B,CAAC,EAEjC,QAAY,EAAK,KAAa,OAAO,QAAQ,CAAK,EAAG,CACnD,IAAM,EAAU,EAAS,GAAG,KAAU,IAAQ,EAE9C,GAAI,IAAa,MAAQ,IAAa,OACpC,SAGF,GACE,OAAO,IAAa,UACpB,CAAC,MAAM,QAAQ,CAAQ,GACvB,EA3BoB,EA4BpB,CACA,OAAO,OACL,EACA,EACE,EACA,EACA,EAAQ,CACV,CACF,EACA,SAGF,GAAI,OAAO,IAAa,UAAY,OAAO,IAAa,UACtD,EAAO,GAAW,EACb,QAAI,OAAO,IAAa,SAC7B,EAAO,GAAW,EAAc,CAAQ,EAExC,QAAI,CACF,EAAO,GAAW,EAAc,KAAK,UAAU,CAAQ,GAAK,EAAE,EAC9D,KAAM,G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AS,EAAY,CAAM,EAIpC,OAAkB,CAAE,aAAY,QAAO,GAS9B,GAAQ,IAAY,CAC/B,GAAI,EACF,EAAS,MAAM,EAEf,OAAe,GACf,EAAkB,QAKT,GAAW,CACtB,EACA,IACS,CACT,GAAU,SAAS,EAAM,CAAU,GAOxB,GAAM,CACjB,EACA,EACA,IACS,CACT,GAAU,IAAI,EAAU,EAAS,CAAQ,GAI9B,GAAQ,SAA2B,CAC9C,MAAM,GAAU,MAAM,GAIX,GAAW,SAA2B,CACjD,IAAM,EAAS,EACf,EAAW,OACX,EAAc,GACd,EAAkB,OAClB,EAAe,GACf,MAAM,GAAQ,SAAS",
19
+ "debugId": "DC6876C1DCB5F18464756E2164756E21",
20
+ "names": []
21
+ }
@@ -0,0 +1,22 @@
1
+ import type { WebEvent } from "./types";
2
+ export interface InputCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ }
5
+ export interface InputCaptureHandle {
6
+ /** SPA navigation ends any open episodes. */
7
+ notifyNavigation(): void;
8
+ teardown(): void;
9
+ }
10
+ /**
11
+ * Field-interaction episodes: one `input` event per engagement with an
12
+ * editable element, not per keystroke. The event is timestamped at episode
13
+ * START (so the timeline reads causally: typed → the request that followed)
14
+ * and emitted when the episode ends — blur, Enter, ~10s idle, SPA
15
+ * navigation, tab hidden, or teardown.
16
+ *
17
+ * Privacy invariants: `event.data`, field values, selected option text, and
18
+ * key identities are never read (Enter is inspected solely as a boundary and
19
+ * never recorded); no value derivatives, including length. Names come from
20
+ * developer-authored sources only (see element-name.ts).
21
+ */
22
+ export declare const installInputCapture: (options: InputCaptureOptions) => InputCaptureHandle;
@@ -0,0 +1,12 @@
1
+ import type { WebEvent } from "./types";
2
+ export interface InteractionCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ }
5
+ export interface InteractionCaptureHandle {
6
+ /** Navigation counts as a click response for dead-click detection. */
7
+ notifyNavigation(): void;
8
+ teardown(): void;
9
+ }
10
+ /** Short, stable-ish selector for an element; never includes text content. */
11
+ export declare const computeSelector: (element: Element) => string;
12
+ export declare const installInteractionCapture: (options: InteractionCaptureOptions) => InteractionCaptureHandle;
@@ -0,0 +1,24 @@
1
+ import type { WebEvent } from "./types";
2
+ export interface NavigationCaptureOptions {
3
+ emit(event: WebEvent): void;
4
+ /** Fired on every captured navigation (dead-click signal). */
5
+ onNavigate(): void;
6
+ }
7
+ export interface NavigationCaptureHandle {
8
+ teardown(): void;
9
+ }
10
+ /**
11
+ * Install dormant history patches around whatever implementations are
12
+ * currently live. Idempotent; re-wraps if a later actor replaced the methods
13
+ * after an earlier install (the displaced wrappers are inert passthroughs).
14
+ */
15
+ export declare const ensureNavigationPatches: () => void;
16
+ /** Restore the natives if the current implementations are still ours. */
17
+ export declare const uninstallNavigationPatches: () => void;
18
+ /**
19
+ * SPA navigation capture. Listeners alone miss programmatic navigation —
20
+ * which is most navigation in React apps — so `history.pushState` /
21
+ * `replaceState` are wrapped under the same isolation rules as the network
22
+ * patch.
23
+ */
24
+ export declare const installNavigationCapture: (options: NavigationCaptureOptions) => NavigationCaptureHandle;
@@ -0,0 +1,5 @@
1
+ import type { EventSeverity } from "./types";
2
+ /** Compact display path: pathname when same-origin, host+path cross-origin. */
3
+ export declare const urlPath: (resolved: string) => string;
4
+ /** Status 0 means transport failure. */
5
+ export declare const severityForStatus: (status: number) => EventSeverity;
@@ -0,0 +1,38 @@
1
+ import type { TraceContextManager } from "./trace-context";
2
+ import type { WebEvent } from "./types";
3
+ export interface NetworkCaptureOptions {
4
+ emit(event: WebEvent): void;
5
+ traceContext: TraceContextManager;
6
+ /** Emit network events. */
7
+ capture: boolean;
8
+ /** Inject `traceparent` into allowlisted requests. */
9
+ propagateTraceContext: boolean;
10
+ /** Injection allowlist; empty means same-origin only. */
11
+ allowlist: (string | RegExp)[];
12
+ /** Response headers probed for a platform request id, in priority order. */
13
+ requestIdHeaders: string[];
14
+ /** SDK-internal endpoints: never captured, never injected. */
15
+ isInternalUrl(url: string): boolean;
16
+ }
17
+ export interface NetworkCaptureHandle {
18
+ teardown(): void;
19
+ }
20
+ /** Injection eligibility for the active config; used by the resource observer
21
+ * to decide whether a bypassed request is a diagnosable instrumentation gap. */
22
+ export declare const isActiveInjectionTarget: (resolved: string) => boolean;
23
+ /** Consume a wrapper-seen record matching this resource entry, if any. */
24
+ export declare const consumeWrapperSeen: (url: string, startTime: number) => boolean;
25
+ /**
26
+ * Install dormant fetch/XHR patches around whatever implementations are
27
+ * currently live. Idempotent, and re-wraps when a later actor (test stubs,
28
+ * mocking layers) replaced the primitives after an earlier install — the
29
+ * displaced wrapper is an inert passthrough, so single-processing holds.
30
+ */
31
+ export declare const ensureNetworkPatches: () => void;
32
+ /**
33
+ * Restore the natives if the current implementations are still ours; if
34
+ * someone patched on top of us, restoring would clobber them — the inactive
35
+ * wrappers pass through.
36
+ */
37
+ export declare const uninstallNetworkPatches: () => void;
38
+ export declare const installNetworkCapture: (options: NetworkCaptureOptions) => NetworkCaptureHandle;
@@ -0,0 +1,4 @@
1
+ export declare const WRAPPED_MARKER = "__sazabiBrowserWrapped";
2
+ /** Best-effort idempotency marker on wrapper functions. */
3
+ export declare const markWrapped: (fn: object) => void;
4
+ export declare const isWrapped: (fn: unknown) => boolean;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import{c as e,j as t}from"./chunk-rfm4nnme.js";if(typeof window<"u")try{t(),e()}catch{}
2
+
3
+ //# debugId=711997A6CB99FCE864756E2164756E21
4
+ //# sourceMappingURL=register.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/register.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Early-instrumentation entrypoint: `import \"@sazabi/browser/register\"`.\n *\n * Importing this module installs the SDK's fetch/XHR/history patches as\n * dormant, transparent passthroughs at module-evaluation time — before any\n * other library's module-scope code can capture the native functions (the\n * race `init()` alone cannot win, since every static import in an app's\n * entry file evaluates before its first statement). `init()` later activates\n * them with configuration; until then they observe nothing, store nothing,\n * and send nothing.\n *\n * Put this import above all other imports in your application entry module.\n */\nimport { ensureNavigationPatches } from \"./navigation\";\nimport { ensureNetworkPatches } from \"./network\";\n\nif (typeof window !== \"undefined\") {\n try {\n ensureNetworkPatches();\n ensureNavigationPatches();\n } catch {\n // Registration must never break the host app; init() re-ensures.\n }\n}\n"
6
+ ],
7
+ "mappings": "+CAgBA,GAAI,OAAO,OAAW,IACpB,GAAI,CACF,EAAqB,EACrB,EAAwB,EACxB,KAAM",
8
+ "debugId": "711997A6CB99FCE864756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,22 @@
1
+ import type { WebEvent } from "./types";
2
+ export interface ResourceObserverOptions {
3
+ emit(event: WebEvent): void;
4
+ /** SDK-internal endpoints: never reported. */
5
+ isInternalUrl(url: string): boolean;
6
+ /** Would the active config have injected trace context into this URL? */
7
+ isInjectionTarget(url: string): boolean;
8
+ }
9
+ export interface ResourceObserverHandle {
10
+ teardown(): void;
11
+ }
12
+ /**
13
+ * Patch-independent network visibility: PerformanceObserver resource timing
14
+ * sees every fetch/XHR the page performs — including ones issued by clients
15
+ * that captured the native functions before the SDK patched (`buffered: true`
16
+ * also replays requests from before init). Wrapper-captured requests are
17
+ * deduped out via the wrapper-seen ledger; the leftovers get a degraded
18
+ * network event (no method, no trace id — observation cannot inject), plus a
19
+ * once-per-origin instrumentation-gap diagnostic when the URL was an
20
+ * injection target, so bypass is a visible signal instead of silent loss.
21
+ */
22
+ export declare const installResourceObserver: (options: ResourceObserverOptions) => ResourceObserverHandle;
@@ -0,0 +1,23 @@
1
+ export interface SessionManager {
2
+ getSessionId(): string;
3
+ getWindowId(): string;
4
+ getDistinctId(): string | undefined;
5
+ /**
6
+ * Set the client-asserted identity. Switching from one identity directly
7
+ * to a different one rotates the session and window ids so two users on a
8
+ * shared device never thread into one timeline.
9
+ */
10
+ setDistinctId(distinctId: string): void;
11
+ /** Logout: clear identity and rotate both session and window ids. */
12
+ reset(): void;
13
+ /** Record user activity; may rotate the session on idle/max-age expiry. */
14
+ touch(): void;
15
+ }
16
+ /**
17
+ * Cross-tab session identity. `session.id` is the visit (localStorage, shared
18
+ * across tabs, last-writer-wins on rotation races — a split session is
19
+ * cosmetic, not data loss). `session.window_id` is this tab (sessionStorage).
20
+ * `session.distinct_id` is read through storage so identify/reset in one tab
21
+ * is visible to sibling tabs on their next event.
22
+ */
23
+ export declare const createSessionManager: () => SessionManager;
@@ -0,0 +1,31 @@
1
+ export interface RequestTraceContext {
2
+ /** Headers to inject (`traceparent`, and `tracestate` when present). */
3
+ headers: Record<string, string>;
4
+ traceId: string;
5
+ spanId: string;
6
+ }
7
+ export interface TraceContextManager {
8
+ /** Trace context for one outgoing request, minted at request time. */
9
+ forRequest(): RequestTraceContext;
10
+ }
11
+ /** The subset of an OTel SpanContext this module consumes. */
12
+ export interface HostSpanContext {
13
+ traceId: string;
14
+ spanId: string;
15
+ traceFlags: number;
16
+ traceState?: {
17
+ serialize(): string;
18
+ };
19
+ }
20
+ export declare const readHostSpanContext: () => HostSpanContext | undefined;
21
+ /**
22
+ * W3C trace context for outgoing requests — hand-rolled header formatting
23
+ * (equivalence-tested against OTel's W3CTraceContextPropagator), zero
24
+ * runtime dependencies. If the host app runs its own OTel and has an active
25
+ * span, that span's context (including its flags and tracestate) is reused
26
+ * so we join the customer's trace instead of forking a new one; otherwise a
27
+ * fresh root is minted with the sampled flag defaulting to off (`-00`).
28
+ */
29
+ export declare const createTraceContextManager: (options: {
30
+ sampledFlag: boolean;
31
+ }) => TraceContextManager;
@@ -0,0 +1,56 @@
1
+ import type { EventAttributes, EventSeverity, WebEvent } from "./types";
2
+ type OtlpAnyValue = {
3
+ stringValue: string;
4
+ } | {
5
+ intValue: string;
6
+ } | {
7
+ doubleValue: number;
8
+ } | {
9
+ boolValue: boolean;
10
+ };
11
+ interface OtlpKeyValue {
12
+ key: string;
13
+ value: OtlpAnyValue;
14
+ }
15
+ export interface OtlpLogRecord {
16
+ timeUnixNano: string;
17
+ severityNumber: number;
18
+ severityText: EventSeverity;
19
+ body: {
20
+ stringValue: string;
21
+ };
22
+ attributes: OtlpKeyValue[];
23
+ /** OTLP/JSON encodes trace/span ids as hex (unlike proto3 JSON's base64). */
24
+ traceId?: string;
25
+ spanId?: string;
26
+ }
27
+ export declare const encodeLogRecord: (event: WebEvent, baseAttributes: EventAttributes) => OtlpLogRecord;
28
+ export interface TransportOptions {
29
+ /** Full OTLP logs endpoint, e.g. `https://web.<region>.intake.<domain>/v1/logs`. */
30
+ url: string;
31
+ publicKey: string;
32
+ resourceAttributes: EventAttributes;
33
+ /**
34
+ * The fetch to deliver with — captured before the SDK's network patch
35
+ * installs, so exporter traffic can never recurse through our own wrapper
36
+ * or appear in the captured event stream.
37
+ */
38
+ fetchImpl: typeof fetch;
39
+ flushIntervalMs: number;
40
+ maxBatchBytes: number;
41
+ maxQueuedEvents: number;
42
+ }
43
+ export interface Transport {
44
+ enqueue(record: OtlpLogRecord): void;
45
+ /**
46
+ * Deliver everything queued. `keepalive: true` is for unload paths — each
47
+ * request body must stay inside the browser's ~64 KiB keepalive budget,
48
+ * which enqueue-side chunking guarantees via `maxBatchBytes`.
49
+ */
50
+ flush(options?: {
51
+ keepalive?: boolean;
52
+ }): Promise<void>;
53
+ shutdown(): Promise<void>;
54
+ }
55
+ export declare const createTransport: (options: TransportOptions) => Transport;
56
+ export {};
@@ -0,0 +1,96 @@
1
+ export type AttributeValue = string | number | boolean;
2
+ export type EventAttributes = Record<string, AttributeValue | undefined>;
3
+ export type EventSeverity = "DEBUG" | "INFO" | "WARN" | "ERROR";
4
+ export type WebEventType = "navigation" | "click" | "rage_click" | "dead_click" | "input" | "network" | "error" | "custom" | "log";
5
+ /** An SDK-internal semantic event, before OTLP encoding. */
6
+ export interface WebEvent {
7
+ type: WebEventType;
8
+ body: string;
9
+ severity: EventSeverity;
10
+ timeUnixMs: number;
11
+ /** Set on network events when trace context was injected into the request. */
12
+ traceId?: string;
13
+ spanId?: string;
14
+ attributes: EventAttributes;
15
+ }
16
+ export interface InputCaptureConfig {
17
+ /**
18
+ * Emit one `input` event per field-interaction episode (never keystrokes,
19
+ * never values — see the privacy invariants in input-capture.ts).
20
+ * Default true.
21
+ */
22
+ capture?: boolean;
23
+ }
24
+ export type ConsoleCaptureLevel = "error" | "warn" | "info" | "debug";
25
+ export interface ConsoleCaptureConfig {
26
+ /** Mirror console output into the event stream. Default true. */
27
+ capture?: boolean;
28
+ /** Console levels to mirror. Default ["error", "warn"]. */
29
+ levels?: ConsoleCaptureLevel[];
30
+ }
31
+ export interface NetworkCaptureConfig {
32
+ /** Emit network events for fetch/XHR. Default true. */
33
+ capture?: boolean;
34
+ /** Inject W3C `traceparent` into allowlisted requests. Default true. */
35
+ propagateTraceContext?: boolean;
36
+ /**
37
+ * Patch-independent fallback capture via PerformanceObserver resource
38
+ * timing: requests that bypass the fetch/XHR patches (clients that
39
+ * captured the natives before the SDK) still produce degraded network
40
+ * events plus a once-per-origin instrumentation-gap diagnostic.
41
+ * Default true.
42
+ */
43
+ resourceFallback?: boolean;
44
+ /**
45
+ * Response headers probed (in order) for a platform request id to attach
46
+ * as `web.network.request_id` — an exact join key against platform logs
47
+ * (CDN/edge/PaaS) without any backend change. Cross-origin reads require
48
+ * the header in `Access-Control-Expose-Headers`.
49
+ */
50
+ requestIdHeaders?: string[];
51
+ /**
52
+ * URL patterns eligible for `traceparent` injection. Strings match by
53
+ * substring, RegExps by test. Default: same-origin requests only —
54
+ * cross-origin injection requires the target to allowlist the header in
55
+ * CORS, so it is opt-in.
56
+ */
57
+ allowlist?: (string | RegExp)[];
58
+ /**
59
+ * Set the sampled flag (`-01`) on SDK-minted trace roots. Default false
60
+ * (`-00`): the sampled bit steers customers' ParentBased backend samplers,
61
+ * and forcing 100% backend trace sampling is not this SDK's call to make.
62
+ * The logs-side trace_id join works regardless of this flag.
63
+ */
64
+ sampledFlag?: boolean;
65
+ }
66
+ export interface BrowserSdkConfig {
67
+ /** Sazabi public ingest key (`sazabi_public_...`). */
68
+ publicKey: string;
69
+ /** Adapter intake host, e.g. `https://web.us-west-2.intake.sazabi.com`. */
70
+ intakeHost: string;
71
+ /** Logical service name for the frontend app. */
72
+ serviceName: string;
73
+ /** Service version (e.g. git SHA). */
74
+ serviceVersion?: string;
75
+ /** Deployment environment (e.g. "production"). */
76
+ environment?: string;
77
+ network?: NetworkCaptureConfig;
78
+ console?: ConsoleCaptureConfig;
79
+ input?: InputCaptureConfig;
80
+ /**
81
+ * Consent gate: capture holds until this resolves true. When it resolves
82
+ * false the SDK stays dormant. Richer semantics (revocation, per-plane
83
+ * grants) are deliberately deferred; only the API shape is stable.
84
+ */
85
+ consent?: () => boolean | Promise<boolean>;
86
+ /** Batch flush cadence in ms. Default 5000. */
87
+ flushIntervalMs?: number;
88
+ /**
89
+ * Soft cap per OTLP request body in bytes. Default 57344 (56 KiB), leaving
90
+ * headroom under the ~64 KiB fetch-keepalive budget that unload flushes
91
+ * must fit inside.
92
+ */
93
+ maxBatchBytes?: number;
94
+ /** Max buffered events before the oldest are dropped. Default 500. */
95
+ maxQueuedEvents?: number;
96
+ }
@@ -0,0 +1,2 @@
1
+ export declare const SDK_NAME = "@sazabi/browser";
2
+ export declare const SDK_VERSION = "0.2.0";
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@sazabi/browser",
3
+ "description": "Sazabi browser observability SDK \u2014 semantic event stream capture with W3C trace context propagation",
4
+ "version": "0.2.0-dev.ga327325",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./register": {
14
+ "types": "./dist/register.d.ts",
15
+ "default": "./dist/register.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "sideEffects": [
23
+ "./dist/register.js"
24
+ ],
25
+ "license": "UNLICENSED",
26
+ "homepage": "https://github.com/sazabi/browser",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/sazabi/browser.git"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org"
34
+ }
35
+ }