@groundcover/browser 2.1.0-rc.1 → 2.1.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,37 +4,63 @@ All notable changes to `@groundcover/browser` are documented here. This project
4
4
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and the
5
5
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format.
6
6
 
7
- ## [2.1.0-rc.1] — 2026-10-07
7
+ ## [2.1.1-rc.0] — 2026-10-13
8
8
 
9
- Second release candidate of `2.1.0`. Tunes canvas capture's default from measurements; nothing
10
- changes unless `options.replay.canvas.enabled` is set.
9
+ First release candidate of `2.1.1`, on top of `2.1.0`. Session replay no longer serializes the whole
10
+ DOM inside a user interaction. No configuration or API changes.
11
11
 
12
- ### Changed
13
-
14
- - **`replay.canvas.fps` defaults to 1** (was 4). rrweb re-encodes every canvas on every tick whether
15
- or not it changed, so the rate drives CPU even on a static page, while bytes grow only when content
16
- changes. On a six-chart test dashboard, 1 fps used about 12% of a CPU core against about 35% at
17
- 4 fps, with the same bytes. Set `fps` explicitly for animated canvases.
18
- - **README: canvas capture recipes** for dashboards, animated canvases, constrained bandwidth and
19
- CPU-sensitive pages, with measured costs for scale.
20
-
21
- ## [2.1.0-rc.0] — 2026-10-06
12
+ ### Fixed
22
13
 
23
- First release candidate of `2.1.0`, on top of `2.0.0`. Adds opt-in canvas capture to session replay;
24
- nothing changes unless `options.replay.canvas.enabled` is set.
14
+ - **The periodic full snapshot no longer runs inside user interactions.** rrweb's
15
+ `checkoutEveryNms` took the 30-second checkout synchronously inside the first event recorded after
16
+ the interval — usually the user's click, input or scroll — so serializing the whole DOM delayed
17
+ that interaction's response on large pages. The SDK now takes the checkout itself at idle time
18
+ (`requestIdleCallback` with a 5s timeout; where it is unsupported, the task after the next frame,
19
+ or the 5s timeout in a hidden tab), on the same trigger: the first recorded event more than 30
20
+ seconds after the last full snapshot. The serialization itself is unchanged, so a checkout still
21
+ runs as one task, now between interactions instead of inside one.
22
+ - **Resuming a recording paused for inactivity no longer runs inside the user's input.** rrweb's
23
+ initial full snapshot ran inside the first click, keypress or scroll after the pause. The resume
24
+ now also waits for idle time, at most 1s.
25
+ - **A checkout's full snapshot is sent as its own replay batch**, instead of waiting in memory for
26
+ the next event. A batch is marked as a full snapshot only when it contains the `FullSnapshot`
27
+ event, not just the checkout's `Meta`.
28
+ - **Buffered replay frames are flushed when the page is hidden**, together with the rest of the
29
+ events pool.
30
+ - **A failing full snapshot retries at most once per 30-second interval**, instead of on every
31
+ recorded event.
32
+
33
+ ## [2.1.0] — 2026-10-12
34
+
35
+ Stable release of the `2.1.0-rc.0` and `2.1.0-rc.1` line. Adds opt-in canvas capture to session
36
+ replay; nothing changes unless `options.replay.canvas.enabled` is set. No breaking changes from
37
+ `2.0.0`.
38
+
39
+ The shipped JavaScript (`index.js`, `index.mjs` and the replay worker) is byte-for-byte rc.1's. The
40
+ type declarations differ from rc.1 only in the `replay.canvas.fps` doc comment. Against `2.0.0`, the
41
+ declarations add `ReplayCanvasOptions` and the optional `replay.canvas` field, and the exported types
42
+ are otherwise unchanged.
25
43
 
26
44
  ### Added
27
45
 
28
46
  - **Session replay can capture `<canvas>`-rendered content** (e.g. chart data series that replayed
29
47
  as empty frames) via `options.replay.canvas`. Off by default. `enabled` maps to rrweb
30
- `recordCanvas`, `fps` (default 4, clamped to 1–15 with a warning) to `sampling.canvas`, and
48
+ `recordCanvas`, `fps` (default 1, clamped to 1–15 with a warning) to `sampling.canvas`, and
31
49
  `imageType` / `imageQuality` (default `image/webp` at 0.6) to `dataURLOptions`. Canvas frames are
32
50
  pixel snapshots: they increase replay bandwidth and page CPU, and are **not** covered by `privacy`
33
51
  text/input masking. WebGL capture is best-effort only (the page's context must use
34
52
  `preserveDrawingBuffer: true`).
53
+ - **`fps` sets CPU cost and time resolution, not bytes.** rrweb re-encodes every canvas on every
54
+ tick whether or not it changed, so the rate drives CPU even on a static page; a frame identical to
55
+ the previous one is dropped, so bytes grow only when content changes. On a six-chart test
56
+ dashboard, 1 fps used about 12% of a CPU core against about 35% at 4 fps, with the same bytes. A
57
+ canvas state shorter than `1/fps` seconds may not appear in the replay, so raise `fps` for
58
+ animated canvases.
35
59
  - **Changing `replay.canvas` through `updateConfig` restarts the active recording**, like
36
60
  `replay.blockedSelectors` and `privacy`. A partial update merges into the current canvas options,
37
61
  so `{ canvas: { fps: 8 } }` keeps capture enabled.
62
+ - **README: canvas capture recipes** for dashboards, animated canvases, constrained bandwidth and
63
+ CPU-sensitive pages, with measured costs for scale.
38
64
 
39
65
  ### Fixed
40
66
 
package/README.md CHANGED
@@ -242,6 +242,11 @@ redraw. Start from the closest recipe and adjust:
242
242
  | Constrained bandwidth | `{ enabled: true, imageQuality: 0.3 }` plus `replay.blockedSelectors` | Lower quality shrinks each image; blocked canvases are skipped entirely. |
243
243
  | CPU-sensitive pages (low-end devices) | `{ enabled: true, imageType: "image/png" }` | PNG encodes much faster than webp but produces about twice the bytes. |
244
244
 
245
+ Capture samples each canvas every `1/fps` seconds and drops a frame that's identical to the
246
+ previous one, so an unchanged canvas sends nothing between full snapshots. The sampling also sets
247
+ the time resolution: a canvas state that lasts less than `1/fps` seconds, such as a brief transition
248
+ or a hover highlight, may not appear in the replay. Raise `fps` when those moments matter.
249
+
245
250
  For scale, on a test dashboard with six canvas charts on a 2× display, canvas capture added about
246
251
  280 KB/min while the charts were static and about 1 MB/min while they refreshed every 10 s. The
247
252
  recorder used about 12% of a CPU core at 1 fps and about 35% at 4 fps, with the same bytes. PNG at
package/dist/index.d.mts CHANGED
@@ -346,8 +346,11 @@ interface ReplayCanvasOptions {
346
346
  * Snapshot frame rate, in frames per second. Defaults to 1 and is clamped to
347
347
  * [1, 15]; out-of-range values are clamped with a `console.warn`. Maps to
348
348
  * rrweb's `sampling.canvas`. Every canvas is re-encoded on every tick, so a
349
- * higher rate costs CPU even when nothing changes; it adds bytes only for
350
- * canvases that change faster than the rate. Raise it for animated canvases.
349
+ * higher rate costs CPU even when nothing changes; frames identical to the
350
+ * previous one are dropped, so it adds bytes only for canvases that change
351
+ * faster than the rate. The rate is also the time resolution: a canvas state
352
+ * shorter than `1/fps` seconds (a brief transition or hover highlight) may not
353
+ * appear in the replay. Raise it for animated canvases.
351
354
  */
352
355
  fps?: number;
353
356
  /**
package/dist/index.d.ts CHANGED
@@ -346,8 +346,11 @@ interface ReplayCanvasOptions {
346
346
  * Snapshot frame rate, in frames per second. Defaults to 1 and is clamped to
347
347
  * [1, 15]; out-of-range values are clamped with a `console.warn`. Maps to
348
348
  * rrweb's `sampling.canvas`. Every canvas is re-encoded on every tick, so a
349
- * higher rate costs CPU even when nothing changes; it adds bytes only for
350
- * canvases that change faster than the rate. Raise it for animated canvases.
349
+ * higher rate costs CPU even when nothing changes; frames identical to the
350
+ * previous one are dropped, so it adds bytes only for canvases that change
351
+ * faster than the rate. The rate is also the time resolution: a canvas state
352
+ * shorter than `1/fps` seconds (a brief transition or hover highlight) may not
353
+ * appear in the replay. Raise it for animated canvases.
351
354
  */
352
355
  fps?: number;
353
356
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("error-stack-parser"),t=require("web-vitals"),n=require("rrweb"),r=require("@rrweb/packer"),s=require("fflate");function i(e){return e&&e.__esModule?e:{default:e}}var o=i(e),a=console.log.bind(console),l=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&a(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},c=l.getInstance();function h(e){c.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}function u(e){try{console.warn(`${e} (groundcoverIgnore)`)}catch{}}var d=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)g[e]=Math.floor(16*Math.random())+48,g[e]>=58&&(g[e]+=39);return p+String.fromCharCode.apply(null,g.slice(0,16))},this.generateSpanId=f(8),this.generateId=f(16)}},g=Array(32);function f(e){return function(){for(let t=0;t<2*e;t++)g[t]=Math.floor(16*Math.random())+48,g[t]>=58&&(g[t]+=39);return String.fromCharCode.apply(null,g.slice(0,2*e))}}var p="0000000000000000";function v({text:e,maxLength:t=1e4,ellipsis:n=""}){if(null==e)return"";const r="string"==typeof e?e:String(e);return r.length<=t?r:r.substring(0,t)+n}function m(e){return(e||"").replace(/\s+/g," ").trim()}var y="[REDACTED]",b=["authorization","cookie","set-cookie"],w=/(token|key|secret|passwd|password|auth|bearer|credential)/i,k=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,E=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),S=1e5;function I(e,t){if(!e)return!1;if(k.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function T(e,t){return E.has(e.toLowerCase())||I(e,t)}function L(e){return e.includes("-")&&w.test(e)}function R(e,t){return I(e,t)||L(e)}function x(e,t){const n=e.sensitive?y:e.value;if(!t)return n;try{const r=t(e);return void 0===r?n:r}catch(e){return h(e),n}}function A(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const r=e.slice(0,n),s=e.slice(n+1);let i=r;try{i=decodeURIComponent(r)}catch{}let o=s;try{o=decodeURIComponent(s)}catch{}const a=T(i,t.sensitiveKeys),l=x({key:i,value:o,path:[i],kind:t.kind??"query",sensitive:a},t.redact);return l===o?e:`${r}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function N(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${A(e.slice(n+1),t)}`}function M(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},r=e.indexOf("#"),s=-1===r?e:e.slice(0,r),i=-1===r?"":e.slice(r+1),o=N(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${y}@`))}(s),n);return-1===r?o:`${o}#${N(i,n)}`}function C(e,t,n,r,s,i){const o=!!e&&I(e,r.sensitiveKeys);if(null!==t&&"object"==typeof t){if(o||s>8)return y;if(function(e,t){if(!e.isOpaqueNode)return!1;try{return e.isOpaqueNode(t)}catch{return!0}}(r,t))return y;if(i.has(t))return y;i.add(t);try{if(Array.isArray(t))return t.map((t=>C(e,t,n,r,s+1,i)));const o={};for(const[e,a]of Object.entries(t))o[e]=C(e,a,[...n,e],r,s+1,i);return o}catch(e){return h(e),y}finally{i.delete(t)}}return x({key:e,value:t,path:n,kind:r.kind??"log",sensitive:o},r.redact)}function q(e,t={}){if(!e)return e;if(e.length>S)return`${q(e.slice(0,S),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>R(n,t.sensitiveKeys)?`"${n}":"${y}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return T(e,t)||L(e)}(n,t.sensitiveKeys)?`${n}=${y}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>R(n,t.sensitiveKeys)?`${n}: ${y}`:e))}catch(t){h(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){h(e)}return n}function O(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=S&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(C("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?A(e,t):q(e,t)}function z(e,t={}){try{const n=C("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return h(e),{}}}function _(e,t){return"allow"!==t.level&&e?z(e,{sensitiveKeys:t.sensitiveKeys,redact:t.redact,isOpaqueNode:t.isOpaqueNode}):e}function P(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const r={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log",isOpaqueNode:e.isOpaqueNode};return{message:q(t,r),attributes:n?z(n,r):n}}var D=class{constructor(e){this.logger=l.getInstance(),this.config=e.config,this.pool=e.pool,this.enricher=e.enricher}sendCustomEvent(e){this.logger.log("[manual-event-emitter.sendCustomEvent] called",e);try{const t=this.enricher.enrich({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.pool.addEvent(t)}catch(e){h(e)}}emitLog(e,t,n){this.logger.log("[manual-event-emitter.emitLog] called",{message:e,level:t,attributes:n});try{const r={...n||{}};delete r.message,delete r.level;for(const e of this.enricher.reservedAttributeKeys)delete r[e];const{message:s,attributes:i}=P(this.config.getPrivacy(),e,r),o=this.enricher.enrich({type:"log",attributes:{...i,message:v({text:s}),level:t}});this.pool.addEvent(o)}catch(e){h(e)}}},F=globalThis,j=class{constructor(e){this.logger=l.getInstance(),this.config=e.config,this.eventsPool=e.eventsPool,this.enricher=e.enricher}};function H(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function B(e){const t=e.getPrivacy(),n=e.getConfig()?.providedOptions?.privacy;return{...t,maskSelectors:H(n?.maskSelectors)}}var U="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function K(e,t){try{return e.getAttribute(t)||""}catch{return""}}function Y(e){try{const t=U?.call(e);return"string"==typeof t?t:""}catch{return""}}function $(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function W(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>K(e,t))).filter(Boolean)}(e).some((e=>I(e,t))))}function Q(e,t){return"allow"!==t.level&&(!!e&&(!!$(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>$(e,t))))||("mask-all"===t.level||function(e){const t=Y(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&W(e,t.sensitiveKeys)))))}var G={role:"",accessibleName:"",ariaLabel:"",title:"",alt:"",placeholder:"",name:"",inputType:"",href:""},X=["button","a","input","select","textarea","label","summary",'[role~="button"]','[role~="link"]','[role~="menuitem"]','[role~="menuitemcheckbox"]','[role~="menuitemradio"]','[role~="tab"]','[role~="checkbox"]','[role~="radio"]','[role~="switch"]','[role~="option"]','[role~="treeitem"]','[role~="slider"]','[role~="spinbutton"]','[role~="combobox"]','[role~="textbox"]','[role~="searchbox"]'].join(", "),J=[X,"li","option","tr","td","th",'[role~="listitem"]','[role~="row"]','[role~="gridcell"]','[role~="cell"]'].join(", ");function V(e){return!!e&&1===e.nodeType}function Z(e){const t=Y(e).toLowerCase();return"body"===t||"html"===t}function ee(e){return v({text:e,maxLength:255})}function te(e){return v({text:e,maxLength:99,ellipsis:"…"})}function ne(e){const t=m(K(e,"role"));return t?t.split(" ")[0]??t:function(e){switch(Y(e).toLowerCase()){case"a":return K(e,"href")?"link":"";case"button":return"button";case"input":switch(K(e,"type").toLowerCase()){case"checkbox":return"checkbox";case"radio":return"radio";case"submit":case"button":case"reset":return"button";case"range":return"slider";case"number":return"spinbutton";default:return"textbox"}case"textarea":return"textbox";case"select":return"combobox";case"img":return"img";case"nav":return"navigation";case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"heading";default:return""}}(e)}function re(e){if(!V(e))return"";try{if(Z(e))return"";if(function(e){try{return e.querySelectorAll(J).length>=2}catch{return!1}}(e))return"";const t=m(e.textContent||"");return t?t.length>1e3?"":v({text:t,maxLength:255}):""}catch{return""}}function se(e){return K(e,"aria-labelledby").split(/\s+/).filter(Boolean).slice(0,5)}function ie(e,t){if(Z(e))return"";const n=function(e){const t=[];for(const n of se(e))try{const e=re(document.getElementById(n));e&&t.push(e)}catch{}return m(t.join(" "))}(e);if(n)return te(n);const r=m(K(e,"aria-label"));if(r)return te(r);const s=m(K(e,"alt"));if(s)return te(s);if(function(e){const t=Y(e).toLowerCase();if("button"===t)return!0;if("input"!==t)return!1;const n=K(e,"type").toLowerCase();return"submit"===n||"button"===n||"reset"===n}(e)){const t=m(K(e,"value"));if(t)return te(t)}const i=t??re(e);if(i)return te(i);const o=m(K(e,"title"));if(o)return te(o);const a=m(K(e,"placeholder"));return a?te(a):""}function oe(e,t){if("allow"===t.level)return!1;try{return!!e.querySelector("[data-private]")||t.maskSelectors.some((t=>{try{return null!=e.querySelector(t)}catch{return!1}}))}catch{return!1}}var ae=class extends j{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>Q(e.target,B(this.config)),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){h(e)}};this.eventHandlers.push({type:e,handler:t}),F?.addEventListener(e,t)}))}catch(e){h(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}}buildEvent(e){const t=this.getCoordinates(e),n=e.target,r=function(e){if(!V(e))return null;try{return e.closest(X)}catch{return null}}(n)??n,s=B(this.config),i=this.getShouldMaskText({target:n||null})||!!r&&(oe(r,s)||function(e,t){if("allow"===t.level)return!1;try{for(const n of se(e)){const e=document.getElementById(n);if(e&&re(e)&&(Q(e,t)||oe(e,t)))return!0}}catch{}return!1}(r,s)),o=r?this.generateSelector(r,i?{priorityAttributes:["id","class","name","type"]}:{}):"",a=this.getKeyCode(e,i),l=re(r),c=function(e,t){if(!V(e))return{...G};try{return{role:ee(ne(e)),accessibleName:ie(e,t),ariaLabel:ee(m(K(e,"aria-label"))),title:ee(m(K(e,"title"))),alt:ee(m(K(e,"alt"))),placeholder:ee(m(K(e,"placeholder"))),name:ee(K(e,"name")),inputType:ee(K(e,"type")),href:ee(K(e,"href"))}}catch{return{...G}}}(r,l),h=s.shouldMaskNetworkQueryParams?M(c.href,{sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"}):c.href,u=e=>i&&e?"*":e;this.logger.log("[dom-events-listener.buildEvent] called");const d={dom_event_selector:o,dom_event_key_code:a,dom_event_type:e.type,dom_event_coordinates:t||{clientX:0,clientY:0},dom_event_target:{id:K(r,"id"),tagName:Y(r),className:K(r,"class"),text:i?"*":l,role:c.role,accessibleName:u(c.accessibleName),ariaLabel:u(c.ariaLabel),title:u(c.title),alt:u(c.alt),placeholder:u(c.placeholder),name:c.name,inputType:c.inputType,href:u(h)}};return this.enricher.enrich({type:"dom.event",attributes:d})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,r=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===Y(e).toLowerCase())return"html";let i="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<r;){let e=Y(a).toLowerCase();try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=Y(a).toLowerCase()||"*"}l.unshift(e||"*"),i=l.join(" > ");try{if(1===n.querySelectorAll(i).length)return i}catch(e){l.shift(),i=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return i||"*"}},le=["log","info","warn","error","debug","assert","trace"],ce=class extends j{constructor(){super(...arguments),this.originalConsole=null,this.patchedConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods();const e={};le.forEach((t=>{if(!(t in console))return;const n=(...e)=>{try{this.isInitialized&&this.handleEvent(e,t)}catch(e){h(e)}finally{this.originalConsole?.[t]&&this.originalConsole[t](...e)}};console[t]=n,e[t]=n})),this.patchedConsole=e,this.isInitialized=!0}catch(e){h(e)}}destroy(){try{if(!this.isInitialized)return;le.forEach((e=>{this.originalConsole?.[e]&&this.patchedConsole?.[e]&&console[e]===this.patchedConsole[e]&&(console[e]=this.originalConsole[e])})),this.patchedConsole=null,this.isInitialized=!1}catch(e){h(e)}}handleEvent(e,t){try{const n=Array.isArray(e)?e:[e];if("assert"===t&&n[0])return;const r=this.formatMessage(n,t);if(!r||r?.includes("groundcoverIgnore"))return;const s=this.extractAttributes(n),i=this.buildEvent({message:r,level:t,attributes:s});this.queueEvent(i)}catch(e){h(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:r,attributes:s}=P(this.config.getPrivacy(),e,n);return this.enricher.enrich({type:"log",attributes:{...s,message:v({text:r}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);delete t.message,delete t.level;for(const e of this.enricher.reservedAttributeKeys)delete t[e];return t}catch(e){return void h(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return h(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{le.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){h(e)}return e}},he=class{constructor(){this.installed=[]}install(e){const t=e,n=[],r=[];try{for(const e of t){const t=e.get();r.push({spec:e,original:t});const s=e.wrap(t);e.set(s),n.push({spec:e,original:t,wrapped:s})}return this.installed.push(...n),!0}catch(e){for(const{spec:e,original:t}of r.reverse())try{e.get()!==t&&e.set(t)}catch{}return h(e),!1}}restore(){const e=this.installed;this.installed=[];for(const{spec:t,original:n,wrapped:r}of e.reverse())try{t.get()===r&&t.set(n)}catch(e){h(e)}}get isEmpty(){return 0===this.installed.length}},ue="[request body too large]",de="[request body unavailable]",ge="[response body too large]",fe="[response body unavailable]",pe="[unreadable response body]",ve="[form data]",me="[binary data]";function ye(e){return(e.split(";")[0]||"").trim().toLowerCase()}function be(e){const t=(e||"").toLowerCase();return t.includes("multipart/form-data")?ve:function(e){const t=ye(e);return!!t&&(!!t.startsWith("text/")||"application/x-www-form-urlencoded"===t||"application/javascript"===t||"application/ecmascript"===t||"application/graphql"===t||/^application\/([\w.-]+\+)?(json|xml)$/.test(t))}(t)?null:function(e){const t=ye(e);return t.startsWith("image/")?"[image data]":t.startsWith("audio/")?"[audio data]":t.startsWith("video/")?"[video data]":t.startsWith("font/")||t.startsWith("application/font")||"application/vnd.ms-fontobject"===t?"[font data]":"application/pdf"===t?"[pdf data]":"application/zip"===t||"application/gzip"===t||"application/x-gzip"===t||"application/x-tar"===t||"application/x-7z-compressed"===t||"application/x-rar-compressed"===t?"[archive data]":"application/wasm"===t?"[wasm data]":t.includes("protobuf")||t.startsWith("application/grpc")?"[protobuf data]":me}(t)}function we(e,t,n){return e&&(e.length>=t||function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=2;else if(r>=55296&&r<=56319){const r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=4,n++):t+=3}else t+=3}return t}(e)>=t)?n:e}var ke=1e6;function Ee(e){return e*ke}function Se(e){return e/ke}function Ie(e){return"string"==typeof e&&/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}function Te(e,t){const n="allow"===t.level,r=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,r])=>{const s=n.toLowerCase(),i=x({key:n,value:r,path:[n],kind:"header",sensitive:b.includes(s)||w.test(s)||I(n,t.sensitiveKeys)},t.redact);return e[n]=null===i?"":String(i),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact}),s={};for(const[e,t]of Object.entries(r))s[e]=v({text:t});return s}function Le(e,t){const{privacy:n}=t,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"query"};let{path:s,fullUrl:i}=t.resolveUrl(e.url);n.shouldMaskNetworkQueryParams&&(s=M(s,r),i=M(i,r));const o=e.method?.toUpperCase()||"UNKNOWN",a=e.method||"UNKNOWN",l=e.status?.toString(),{traceId:c,spanId:h}=function(e,t){const n={};for(const t of Object.keys(e))n[t.toLowerCase()]=e[t];const r=e=>{if(!e)return"";const t=n[e.toLowerCase()];return"string"==typeof t?t:""};let s=r(t?.traceIdHeaderName),i=r(t?.spanIdHeaderName);if(!s||!i){let e="";for(const n of t?.propagationHeaders??[])if(e=r(n),e)break;e||(e=r("traceparent"));const n=e.split("-");4===n.length&&"00"===n[0]&&(s||32!==n[1]?.length||(s=n[1]),i||16!==n[2]?.length||(i=n[2]))}return{traceId:s,spanId:i}}(e.request.headers,t.tracing),u=(e,r)=>v({text:n.shouldMaskNetworkBodies?O(e,{sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:r}):e,maxLength:t.maxBodyLength}),d={type:"HTTP",operation:{name:o},resource_name:s,status:l,subType:o,url:{full:i},http:{route:s,path:s,method:a,status:l,request:{headers:Te(e.request.headers,n),method:a},response:{headers:Te(e.response.headers,n),status_code:l}},error:e.error?.type?{type:e.error.type}:void 0,gc:{request:{body:u(e.request.body,"request-body")},response:{body:u(e.response.body,"response-body")}}},g={type:"network",timestamp:Re(e.timestamp),end_timestamp:Re(e.end_time),span_name:`${o} ${s}`,attributes:d};return c&&(g.traceId=c),h&&(g.spanId=h),g}function Re(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Ee(e):void 0}function xe(e){return function(e){try{return 9===e?.nodeType}catch{return!1}}(e)?"[document data]":function(e){try{if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof FormData&&e instanceof FormData)return"[form data]";if("undefined"!=typeof Blob&&e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if(ArrayBuffer.isView(e))return"[arraybuffer data]";if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return"[stream data]";if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return h(`Failed to format body: ${e}`),"[unreadable body]"}}(e)}var Ae=[".tsx",".jsx",".css"],Ne=e=>Ae.some((t=>e.toLowerCase().endsWith(t))),Me=class extends j{constructor(){super(...arguments),this.maxBodyLength=5e3,this.requestBodyReadTimeoutMs=3e3,this.responseBodyReadTimeoutMs=3e3,this.idGenerator=new d,this.patches=new he,this.active=!1,this.handleEvent=e=>{try{if(!this.active)return;if(this.shouldIgnoreRequest(e.url))return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}},this.buildEvent=e=>(this.logger.log("[network-events-listener.buildEvent] called",{event:e}),this.enricher.enrich(Le(e,{privacy:this.config.getPrivacy(),maxBodyLength:this.maxBodyLength,tracing:this.config.getConfig()?.options?.tracing,resolveUrl:e=>{try{return{path:new URL(e).pathname,fullUrl:e}}catch{return{path:e,fullUrl:new URL(e,globalThis.location.href).href}}}})))}async readBodyStreamCapped(e,t={}){if(!e)return"";const{timeoutMs:n,overflowPlaceholder:r,timeoutPlaceholder:s}=t,i=e.getReader(),o=new TextDecoder;let a,l="",c=0,h=!1,u=!1;const d=null!=n?new Promise((e=>{a=setTimeout((()=>e({timedOut:!0})),n)})):void 0;try{for(;;){const e=d?await Promise.race([i.read(),d]):await i.read();if("timedOut"in e){u=!0;break}const{done:t,value:n}=e;if(t)break;if(c+n.byteLength>=this.maxBodyLength){const e=n.subarray(0,this.maxBodyLength-c);l+=o.decode(e,{stream:!0}),h=!0;break}c+=n.byteLength,l+=o.decode(n,{stream:!0})}return l+=o.decode(),u&&null!=s?s:h&&null!=r?r:l}finally{clearTimeout(a);try{i.cancel()?.catch((()=>{}))}catch{}}}async getRequestBody(e,t){try{if(!e.body)return"";const n=be(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.requestBodyReadTimeoutMs,overflowPlaceholder:ue,timeoutPlaceholder:de})}catch{return de}}async getResponseBody(e){if(!e.body)return"";const t=e.headers?.get?.("content-type")??"";if(function(e){return"text/event-stream"===ye(e||"")}(t))return pe;const n=be(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.responseBodyReadTimeoutMs,overflowPlaceholder:ge,timeoutPlaceholder:fe})}initialize(){this.logger.log("[network-events-listener.initialize] called");const e=this.patches.install(this.xhrPatches()),t=this.patches.install([this.fetchPatch()]);this.active=e||t}destroy(){this.active=!1,this.patches.restore()}shouldIgnoreRequest(e){try{const t=this.config.getConfig();return function(e,t){try{return!(!t.endpoint||!e.includes(t.endpoint))||!!t.extraIgnore?.(e)||(t.excludedUrls??[]).some((t=>t instanceof RegExp?t.test(e):"string"==typeof t&&(t.includes("*")||t.includes("?"))?new RegExp(t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")).test(e):e===t))}catch(e){return h(e),!1}}(e,{endpoint:t?.getEndpoint(),excludedUrls:t?.options?.excludedUrls,extraIgnore:Ne})}catch(e){return h(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}xhrPatches(){const e=this,t=globalThis.XMLHttpRequest.prototype;let n;return[{get:()=>t.open,set:e=>{t.open=e},wrap:t=>function(r,s,i=!0,o,a){if(!e.active)return t.apply(this,[r,s,i,o,a]);if(n=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[r,s,i,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=r,this._requestUrl=l,this._requestHeaders={},t.apply(this,[r,s,i,o,a])}},{get:()=>t.setRequestHeader,set:e=>{t.setRequestHeader=e},wrap:t=>function(n,r){return e.active?(this._requestHeaders&&(this._requestHeaders[n]=r),t.apply(this,[n,r])):t.apply(this,[n,r])}},{get:()=>t.send,set:e=>{t.send=e},wrap:t=>function(...r){if(!e.active)return t.apply(this,r);const s=this._requestUrl?.toString();if(!s||e.shouldIgnoreRequest(s))return t.apply(this,r);if(e.shouldAddTraceHeader(s))for(const[t,n]of Object.entries(e.buildTraceHeaders()))e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n});return this._requestBody=r[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),r={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,n]=e.split(": ");t&&n&&(r[t.trim()]=n.trim())}));const s=we(xe(this._requestBody),e.maxBodyLength,ue),i=""===this.responseType||"text"===this.responseType,o=i?this.responseText:this.response,a=(i?be(r["content-type"]||""):null)??we(xe(o),e.maxBodyLength,ge),l={timestamp:n,end_time:t,method:this._requestMethod,url:this._requestUrl,status:this.status,request:{headers:this._requestHeaders||{},body:s},response:{headers:r,body:a}};e.handleEvent(l)})),t.apply(this,r)}}]}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){for(const[t,n]of Object.entries(this.buildTraceHeaders()))this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n})}buildTraceHeaders(){return function(e,t){const n={},r=(e,t)=>{Ie(e)&&(n[e]=t)};e?.origin?.name&&r(e.origin.name,e.origin.value),e?.traceIdHeaderName&&r(e.traceIdHeaderName,t.decimalTraceId),e?.spanIdHeaderName&&r(e.spanIdHeaderName,t.decimalSpanId);const s=e?.propagationHeaders,i=s?.length?s:["traceparent"];for(const e of i)r(e,t.traceparent);return n}(this.config.getConfig()?.options?.tracing,function(e){const t=e.generateSpanId(),n=e.generateTraceId();let r,s;try{r=BigInt("0x"+n).toString(10),s=BigInt("0x"+t).toString(10)}catch{r=n,s=t}return{traceparent:`00-${n}-${t}-01`,traceId:n,spanId:t,decimalTraceId:r,decimalSpanId:s}}(this.idGenerator))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}fetchPatch(){return{get:()=>globalThis.fetch,set:e=>{globalThis.fetch=e},wrap:e=>(...t)=>{if(!this.active)return e.apply(globalThis,t);const n=Date.now();let[r,s]=t;s={...s||{}},t[1]=s;const i=r instanceof Request,o=s?.method||(i?r.method:"GET"),a=r instanceof Request?r.url:r.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);s.headers=this.normalizeHeaders(i?r.headers:void 0,s.headers),l&&this.addTraceHeaders(s);const c=this.extractHeadersRecord(s.headers),h=null!=s?.body?we(xe(s.body),this.maxBodyLength,ue):"",u=null!=s?.body?Promise.resolve(h):i?this.getRequestBody(r,"content-type"in c?c["content-type"]:r.headers.get("content-type")??""):Promise.resolve("");let d;return u.then((e=>{d=e})).catch((()=>{})),e.apply(globalThis,t).then((e=>{const t=Date.now(),r={};e.headers.forEach(((e,t)=>{r[t]=e}));const s={method:o,url:a,timestamp:n,status:e.status,end_time:t,request:{headers:c,body:""},response:{headers:r,body:""}},i=()=>{u.then((e=>{s.request.body=e,this.handleEvent(s)}))};return this.getResponseBody(e).then((e=>{s.response.body=e,i()})).catch((e=>{s.response.body=pe,i(),this.logger.log("[network-events-listener.fetch] response body error",{error:e})})),e})).catch((e=>{const t=Date.now();let r="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?r="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?r="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(r="ERR_CONNECTION_REFUSED");const i={method:o,url:a,timestamp:n,status:0,end_time:t,request:{headers:c,body:d??h},response:{headers:{},body:""},error:{type:r}};throw this.handleEvent(i),e}))}}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),Ie(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),Ie(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}shouldAddTraceHeader(e){const t=(n=this.propagationCandidates(e),r=this.config.getConfig()?.options?.tracing?.propagationUrls,!!r?.length&&r.some((e=>{try{if("string"!=typeof e)return!1;const t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),r=new RegExp(`^${t}$`);return n.some((e=>r.test(e)))}catch{return!1}})));var n,r;return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:t}),t}propagationCandidates(e){try{const t=globalThis.location.href,n=new URL(e,t),r=[n.href];return"/"!==n.pathname||n.search||n.hash||r.push(n.href.slice(0,-1)),n.origin===new URL(t).origin&&r.push(n.pathname),r}catch{return[e]}}};function Ce(e){try{return o.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch{return[]}}var qe=class extends j{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const r=this.buildEvent(n,t);this.queueEvent(r)}catch(e){h(e)}}}initialize(){F?.addEventListener("error",this.handleEvent),F?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){F?.removeEventListener("error",this.handleEvent),F?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return this.enricher.enrich(function(e,t,n){const r=n.shouldMaskErrors,s={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error",isOpaqueNode:n.isOpaqueNode},i=e.message||"Unknown error",o=r?q(i,s):i,a=r&&t?.metadata?z(t.metadata,s):t?.metadata;return{type:"exception",attributes:{error_type:e.name||"Error",error_message:o,error_stacktrace:Ce(e),error_fingerprint:`${e.name}:${v({text:o,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:a}}}(e,t,this.config.getPrivacy()))}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}enhanceError(e,t){const{filename:n,lineno:r,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),r&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:r}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}},Oe=class extends j{constructor(e,{isEnabled:t}){if(super(e),this.currentUrl="",this.patches=new he,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&t)try{this.isAutomaticNavigationEnabled=t,this.currentUrl=F.location.href}catch(e){h(e)}}isInBrowserEnvironment(){try{return void 0!==F&&void 0!==F.location&&void 0!==F.history&&"function"==typeof F.addEventListener}catch(e){return h(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||"function"!=typeof history.pushState||"function"!=typeof history.replaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");this.patches.install([this.historyPatch("pushState"),this.historyPatch("replaceState")]),F&&"function"==typeof F.addEventListener&&(F.addEventListener("popstate",this.popStateHandler),F.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){h(e)}}historyPatch(e){return{get:()=>history[e],set:t=>{history[e]=t},wrap:e=>(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n}}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.patches.restore(),F&&"function"==typeof F.removeEventListener&&(F.removeEventListener("popstate",this.popStateHandler),F.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){h(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",F.location.href);const e=this.config.getPrivacy(),t=F.location.href,n=this.activeNavigation?.metadata,r={page_url:e.shouldMaskNetworkQueryParams?M(t,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):t,metadata:_(n,e),duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0};return this.enricher.enrich({type:"navigation",attributes:r})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}startNavigation(e){try{this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:F?.location?.href||"",metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}catch(e){h(e)}}endNavigation(e){try{if(this.logger.log("[navigation-listener.endNavigation] called",e),!this.activeNavigation)return void this.logger.log("[navigation-listener.endNavigation] no active navigation found");this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()}catch(e){h(e)}}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===F.location.href)return;let e,t;try{e=new URL(F.location.href),t=new URL(this.currentUrl)}catch(e){return void h(e)}const n=e=>e.startsWith("#/"),r=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||r&&e.hash!==t.hash)&&(this.currentUrl=F.location.href,this.handleEvent())}catch(e){h(e)}}},ze=class extends j{constructor(e){super(e),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",F),"complete"===F?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):F?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),h(e)}}destroy(){F?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),r={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,i=t.initiatorType;r.totalSize+=n,r.totalDuration+=s,r.byType[i]||(r.byType[i]={count:0,size:0,duration:0}),r.byType[i].count++,r.byType[i].size+=n,r.byType[i].duration+=s}));const s=this.config.getPrivacy(),i=s.shouldMaskNetworkQueryParams,o={sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"},a=F?.location?.href||"",l=F?.document?.referrer||"",c={page_url:i?M(a,o):a,page_load_time:t,page_referrer:i?M(l,o):l,page_resources:r};return this.enricher.enrich({type:"pageload",attributes:c})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}},_e=class extends j{constructor(){super(...arguments),this.handleEvent=e=>{try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}}}initialize(){t.onCLS(this.handleEvent),t.onLCP(this.handleEvent),t.onFCP(this.handleEvent),t.onTTFB(this.handleEvent),t.onINP(this.handleEvent)}destroy(){}buildEvent(e){const t={performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""};return this.enricher.enrich({type:"performance",attributes:t})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}},Pe=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=l.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,r){const s=e.getInstance();if(!s.isAvailable)return n();try{return await t(s)}catch(e){return l.getInstance().log(`[${r}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,r=this.worker;return new Promise(((s,i)=>{const o=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),i(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:s,reject:i,timeoutId:o});try{r.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(o),this.pending.delete(n),i(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};Pe.instance=null;var De=Pe;var Fe=class{constructor(e){this.logger=l.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0;const e=this.configManager.getConfig()?.options,t=e?.replay,r=t?.blockedSelectors?.filter(Boolean),s=r?.length?r.join(", "):void 0,i=B(this.configManager),o=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=H(t?.maskSelectors),i=t?.replay,o="function"==typeof i?.maskTextFn?i.maskTextFn:void 0,a="function"==typeof i?.maskInputFn?i.maskInputFn:void 0;let l;return l="mask-all"===n||!r&&void 0!==o?["*",...s].join(", "):"mask-sensitive"===n?["[data-private]",...s].join(", "):void 0,{maskTextSelector:l,maskAllInputs:!r,maskTextFn:o,maskInputFn:a}}(this.configManager.getConfig()?.providedOptions),a=function(e){if(!e||!0!==e.enabled)return null;let t=e.fps??1;if("number"==typeof t&&Number.isFinite(t)){if(t<1||t>15){const e=Math.min(15,Math.max(1,t));u(`[groundcover] replay.canvas.fps ${t} is out of range [1, 15]; clamped to ${e}.`),t=e}}else u("[groundcover] replay.canvas.fps must be a finite number; falling back to 1."),t=1;return{canvasFps:t,dataURLOptions:{type:e.imageType??"image/webp",quality:e.imageQuality??.6}}}(t?.canvas),l=o.maskInputFn??("allow"===i.level?void 0:(e,t)=>Q(t,i)?"*".repeat(e.length):e);this.stopFn=n.record({...s?{blockSelector:s}:{},...o.maskTextSelector?{maskTextSelector:o.maskTextSelector}:{},maskAllInputs:o.maskAllInputs,...o.maskTextFn?{maskTextFn:o.maskTextFn}:{},...l?{maskInputFn:l}:{},...a?{recordCanvas:!0,dataURLOptions:a.dataURLOptions}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150,...a?{canvas:a.canvasFps}:{}},checkoutEveryNms:3e4,errorHandler:e=>(h(e),!0),emit:(e,t)=>{if(this.isRecording)try{this.events.push(e),t&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),this.events.length>=this.batchSize&&this.scheduleSendBatch()}catch(e){h(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=F.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{h(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(F.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.session.getSessionId(),n=De.getInstance();let s;if(n.isAvailable)try{s=await n.packReplay(e.events)}catch(t){h(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),s=e.events.map((e=>r.pack(e)))}else s=e.events.map((e=>r.pack(e)));this.session.getSessionId()===t?this.enqueueReplayEvent(s,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:s.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>r.pack(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const r={_gc_replay_data:{events:e}};t&&(r.replay_is_full_snapshot=!0,r.replay_full_snapshot_timestamp=n);const s=this.enricher.enrich({type:"replay",attributes:r});this.eventsPool.addEvent(s),this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){h(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},je=144e5,He=288e5,Be=18e5,Ue="gcSample",Ke={sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},sessionMaxDuration:je},Ye=["pointerdown","keydown","scroll","touchstart","mousemove"],$e=class{constructor(e){this.logger=l.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){h(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,Ye.forEach((e=>{try{F.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){h(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",Be,"ms");try{this.callbacks.onIdle()}catch(e){h(e)}}),Be)}catch(e){h(e)}}destroy(){if(this.installed){this.installed=!1,Ye.forEach((e=>{try{F.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){h(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){h(e)}finally{this.idleTimer=null}}}};function We(e,t,n){return"number"==typeof e&&e>0&&e<=t&&e>t-n}function Qe(e,t,n){let r=null;const s=e=>{We(e,t,n)&&(null===r||e<r)&&(r=e)};try{for(const t of e)if(t){try{s(t.timestamp)}catch(e){h(e)}try{s(t.start_timestamp)}catch(e){h(e)}}}catch(e){h(e)}return r}var Ge=class{constructor(e){this.logger=l.getInstance(),this.rotating=!1,this.session=e.session,this.pool=e.pool,this.idGenerator=e.idGenerator,this.activityEventTypes=e.activityEventTypes,this.ignoredEventTypes=e.ignoredEventTypes,this.hooks=e.hooks??{}}get isRotating(){return this.rotating}install(){this.pool.setBeforeEnqueueHook((e=>this.reconcileOnEnqueue(e))),this.pool.setFlushGate((()=>this.session.hasUserActivity()))}uninstall(e){this.pool.setBeforeEnqueueHook(null);try{e?.()}catch(e){h(e)}this.pool.setFlushGate(null)}reconcile(e,t,n){if(this.rotating)return;t&&this.session.isSessionInactive(e)&&this.rotate({reason:"inactivity gap",triggeringEvent:n});const r=this.session.getSessionElapsedMs(e),s=this.session.getSessionMaxDuration(),i=r>=s;this.logger.log("[session-lifecycle] session reconcile",{userPresent:t,elapsedMs:r,maxDurationMs:s,expired:i}),i&&this.rotate({reason:"max session duration",triggeringEvent:n}),this.hooks.onReconcile?.(t),t&&(this.session.setLastActivityMs(e),this.hooks.onPresenceStamped?.(e))}reconcileOnEnqueue(e){this.rotating||(this.ignoredEventTypes.has(e.type)?this.logger.log("[session-lifecycle] enqueue rotation check: ignoring heartbeat-style event",e.type):this.reconcile(Date.now(),this.activityEventTypes.has(e.type),e))}rotateIfStale(e,t){(this.session.isSessionInactive(e)||this.session.isSessionExpired(e))&&this.rotate({reason:t})}rotate(e){if(this.rotating)return;this.rotating=!0;const t=(e,t)=>{try{this.logger.log(`[session-lifecycle] session rotation: ${e}`),t()}catch(t){h(t),this.logger.log(`[session-lifecycle] failed to ${e} during session rotation:`,t)}};try{const n=this.session.getSessionId();let r;t("capture host rotation context",(()=>{r=this.hooks.captureRotationContext?.()}));const s=this.session.hasUserActivity();this.logger.log("[session-lifecycle] session rotation start",{reason:e.reason,previousId:n,wasConfirmed:s}),t("host beforeRotate",(()=>this.hooks.beforeRotate?.())),t(s?"flush events":"discard unconfirmed events",(()=>s?this.pool.flush():this.pool.discardBuffer())),t("rotate session ids",(()=>{const t=this.idGenerator.generateId(),r=this.resolveNewSessionStartTime(e.triggeringEvent);this.session.setSessionId(t),this.session.setSessionStartTime(r),this.session.clearSamplingDecision(),this.logger.log("[session-lifecycle] session id rotated",{from:n,to:t})})),t("host afterRotate",(()=>this.hooks.afterRotate?.(r)))}finally{this.rotating=!1,this.logger.log("[session-lifecycle] session rotation complete",{reason:e.reason})}}resolveNewSessionStartTime(e){const t=Ee(Date.now());let n=t;try{const r=Ee(Math.min(this.session.getSessionMaxDuration(),Be)),s=[Qe([e],t,r),this.pool.getEarliestEventTimestamp(t,r)];for(const e of s)We(e,t,r)&&e<n&&(n=e)}catch(e){h(e)}return n}},Xe=new Set(["dom.event"]),Je=new Set(["replay"]),Ve=class{constructor(e){this.logger=l.getInstance(),this.idGenerator=new d,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.replayDesired=!1,this.presenceMonitor=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher,this.manualEvents=new D({config:this.configManager,pool:this.eventsPool,enricher:this.enricher}),this.lifecycle=new Ge({session:this.session,pool:this.eventsPool,idGenerator:this.idGenerator,activityEventTypes:Xe,ignoredEventTypes:Je,hooks:{captureRotationContext:()=>this.isReplayRecording(),beforeRotate:()=>this.stopReplayListener(),afterRotate:e=>this.syncReplayState(e),onReconcile:e=>this.syncReplayState(e),onPresenceStamped:e=>this.presenceMonitor?.notePresence(e)}})}listenerDeps(){return{config:this.configManager,eventsPool:this.eventsPool,enricher:this.enricher}}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.lifecycle.install(),this.presenceMonitor?.destroy(),this.presenceMonitor=new $e({onPresence:e=>this.lifecycle.reconcile(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,r=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new ze(this.listenerDeps()),this.pageLoadListener.initialize(),r.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new ae(this.listenerDeps()),this.domEventsListener.initialize(),r.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new ce(this.listenerDeps()),this.logEventsListener.initialize(),r.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new qe(this.listenerDeps()),this.errorsEventsListener.initialize(),r.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new Me(this.listenerDeps()),this.networkEventsListener.initialize(),r.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new _e(this.listenerDeps()),this.performanceListener.initialize(),r.push("performance")),this.navigationListener=new Oe(this.listenerDeps(),{isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),r.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",r)}sendCustomEvent(e){this.manualEvents.sendCustomEvent(e)}emitLog(e,t,n){this.logEventsListener&&this.manualEvents.emitLog(e,t,n)}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){h(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){this.replayDesired=!0,this.isReplayRecording()?this.logger.log("[instrumentation-manager] replay recording already started"):(this.lifecycle.rotateIfStale(Date.now(),"replay start into stale session"),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer())}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] user present and replay desired — starting replay"),this.startReplayListener())}pauseReplayOnIdle(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Fe({...this.listenerDeps(),session:this.session});e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){h(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}stopReplayListener(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.lifecycle.uninstall((()=>{this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}))}};function Ze(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var et={privacy:[],tracing:["origin"],transport:[]},tt=new WeakMap,nt={nestedOptions:et,removedOptions:{}};function rt(e,t){const n=e;for(const e of Object.keys(t))Object.hasOwn(n,e)&&delete n[e]}function st(e,t){if(!e||"object"!=typeof e)return;const n=e;for(const[e,r]of Object.entries(t))Object.hasOwn(n,e)&&u(r)}function it(e){const t={};for(const n of[et,e.nestedOptions??{}])for(const[e,r]of Object.entries(n))t[e]=[...new Set([...t[e]??[],...r])];return t}function ot(e,t){if(!Ze(e))return e;const n={...e};for(const e of t)Ze(n[e])&&(n[e]={...n[e]});return n}function at(e,t,n){const r={...e,...t};for(const s of n){const n=e?.[s],i=t[s];Ze(n)&&Ze(i)?r[s]={...n,...i}:Object.hasOwn(t,s)&&!Ze(i)?r[s]=Ze(n)?{...n}:n:Ze(r[s])&&(r[s]={...r[s]})}return r}function lt(e,t,n){const r={...e,...t},s=t,i=e;for(const[e,t]of Object.entries(n)){if(!Object.hasOwn(s,e)){Ze(i[e])&&(r[e]=ot(i[e],t));continue}const n=s[e];Ze(n)?r[e]=at(i[e],n,t):r[e]=ot(i[e],t)}return r}var ct=class e{constructor(t,n={}){const r={nestedOptions:it(n),removedOptions:n.removedOptions??{}};tt.set(this,r);const{nestedOptions:s,removedOptions:i}=r,o=lt(Ke,n.defaults??{},s);this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=lt(o,t?.options||{},s),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),st(t?.options,i),rt(this.providedOptions,i),rt(this.options,i)}static normalizeSessionMaxDuration(e){return void 0===e?je:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>He?(u("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),je):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){if(t.options){const{nestedOptions:r,removedOptions:s}=(n=this,tt.get(n)??nt);st(t.options,s),this.providedOptions=lt(this.providedOptions||{},t.options,r),this.options=lt(this.options,t.options,r),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),rt(this.providedOptions,s),rt(this.options,s)}var n;void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}},ht=class{constructor(e={}){this.extension=e,this.config=null,this.logger=l.getInstance(),this.privacyCache=null}initialize(e){this.config||(this.config=new ct(e,this.extension))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){if(!this.privacyCache){const e=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=e=>!r&&(e??!0),i=s(t?.maskNetworkBodies),o=s(t?.maskNetworkQueryParams),a=s(t?.maskLogs),l=s(t?.maskErrors);return{level:n,maskNetworkBodies:i,maskNetworkQueryParams:o,maskLogs:a,maskErrors:l,shouldMaskNetworkBodies:!r&&i,shouldMaskNetworkQueryParams:!r&&o,shouldMaskLogs:!r&&a,shouldMaskErrors:!r&&l,sensitiveKeys:H(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0}}(this.config?.providedOptions);this.extension.isOpaqueNode&&(e.isOpaqueNode=this.extension.isOpaqueNode),this.privacyCache=e}return this.privacyCache}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}};function ut(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var dt={isOpaqueNode:ut,nestedOptions:{replay:["canvas"],privacy:["replay"]},defaults:{replay:{}},removedOptions:{enableMasking:"[groundcover] `options.enableMasking` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",maskFields:"[groundcover] `options.maskFields` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",eventSampleRate:"[groundcover] `options.eventSampleRate` was removed and is ignored. Events are no longer randomly sampled; event volume may increase. Use `options.sessionSampleRate` to select whole sessions; rates are not automatically converted. See the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-from-1x-to-200"}},gt=Ke.transport?.batchSize??10,ft=Ke.transport?.batchTimeout??1e4;var pt=class{constructor(e){this.events=[],this.timeoutId=null,this.logger=l.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.unusableEnrichWarned=!1,this.onBeforeEnqueue=null,this.flushGate=null,this.config=e.config,this.session=e.session,this.transporter=e.transporter,this.getDeviceAttributes=e.getDeviceAttributes,this.eventsToSkipFlush=e.eventsToSkipFlush}initialize(){try{if(this.initialized)return;this.scheduleFlush(),this.initialized=!0}catch(e){h(e)}}destroy(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.events=[],this.initialized=!1}catch(e){h(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}setFlushGate(e){this.flushGate=e}discardBuffer(){this.events=[]}getEarliestEventTimestamp(e,t){return Qe(this.events,e,t)}isFlushAllowed(){if(null===this.flushGate)return!0;try{return this.flushGate()}catch(e){return h(e),!0}}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,r=this.config.getConfig()?.options?.enrichEvent;let s=e;if(n&&!n(s))return;if(r){const e=r(s);if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"string"==typeof e.type}catch(e){return h(e),!1}}(e))return void(this.unusableEnrichWarned||(this.unusableEnrichWarned=!0,this.logger.log("[events-pool.addEvent] dropping event: enrichEvent returned an unusable value")));s=e}if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(s)}catch(e){h(e)}if(!this.isFlushAllowed()&&this.events.length>=500)return;this.events.push(s);const i=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:gt);this.events.length>=i&&!this.eventsToSkipFlush.includes(s.type)&&this.flush()}catch(e){h(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.isFlushAllowed())return void this.scheduleFlush();if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),this.events=[],this.scheduleFlush()}catch(e){h(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.isFlushAllowed())return void this.discardBuffer();if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){h(e)}}scheduleFlush(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:ft);this.timeoutId=setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){h(e)}var e}getSessionAttributes(){return this.buildSessionAttributes()}buildSessionAttributes(){const e=this.config.getConfig();let t={};try{t=this.getDeviceAttributes()}catch(e){h(e)}return{...t,cluster:e?.cluster||"",env:e?.environment||"",namespace:e?.namespace||"",releaseId:e?.releaseId||"",session_id:this.session.getSessionId(),session_start_time:this.session.getSessionStartTime(),user:e?.user||{},"service.name":e?.appId}}};function vt(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:t}var mt=class{constructor(e={}){this.logger=l.getInstance(),this.enrichAttributes=e.enrichAttributes??null,this.reservedAttributeKeys=e.reservedAttributeKeys??[],this.isOpaqueNode=e.isOpaqueNode??null,this.idGenerator=e.idGenerator??new d}getPlatformAttributes(){if(!this.enrichAttributes)return{};try{return this.enrichAttributes()??{}}catch(e){return this.logger.log("[event-enricher] platform attribute contributor threw; continuing without it",e),{}}}formatEventObject(e,t="",n=new WeakSet,r=0){try{return r>=10?{[t||"depth_limit"]:"[Depth Limit]"}:this.isOpaqueNode?.(e)?{[t||"opaque_node"]:`[${e?.constructor?.name||"OpaqueNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,i])=>{const o=t?`${t}.${s}`:s;return"object"==typeof i&&null!==i?Array.isArray(i)?e[o]=i.map(((e,t)=>"object"==typeof e&&null!==e?this.formatEventObject(e,`${o}[${t}]`,n,r+1):e)):Object.assign(e,this.formatEventObject(i,o,n,r+1)):e[o]=i,e}),{}))}catch(e){return this.logger.log("[event-enricher.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}enrich(e){const t=Ee(Date.now()),n=this.idGenerator.generateId(),r=e.spanId||this.idGenerator.generateSpanId(),s=e.traceId||this.idGenerator.generateTraceId(),i=e.parentSpanId||"",o=this.formatEventObject(e.attributes||{}),a=this.getPlatformAttributes(),l={type:e.type,id:n,spanId:r,parentSpanId:i,traceId:s,attributes:{...o,...a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=vt(e.timestamp,t),l.end_timestamp=e?.end_timestamp):l.timestamp=vt(e.timestamp,t),l}};function yt(e,t){const n=s.strToU8(e);if(!t)return{data:n,isCompressed:!1};try{return{data:s.gzipSync(n),isCompressed:!0}}catch{return{data:n,isCompressed:!1}}}var bt=class{constructor(e){this.logger=l.getInstance(),this.config=e.config,this.sendBatch=e.sendBatch,this.encodeAsync=e.encodeAsync??null}compressAsync(e,t){if(!this.encodeAsync)return Promise.resolve(yt(e,t));try{return this.encodeAsync(e,t).catch((()=>yt(e,t)))}catch{return Promise.resolve(yt(e,t))}}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const r=n.apiKey,s=this.buildEndpoint();if(!r)return void this.logger.log("No API key found");const i=JSON.stringify(e),o=!!n?.options?.transport?.compression,{data:a,isCompressed:l}=t?yt(i,o):await this.compressAsync(i,o),c={"Content-Type":"application/json",apikey:r,"Content-Encoding":l?"gzip":""};this.sendBatch(s,{method:"POST",headers:c,body:a}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n?.options?.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},wt=class{constructor(e){this.storage=e}getItem(e){try{return this.storage?.getItem(e)??null}catch(e){return h(e),null}}setItem(e,t){try{this.storage?.setItem(e,t)}catch(e){h(e)}}removeItem(e){try{this.storage?.removeItem(e)}catch(e){h(e)}}getNumericItem(e,t=0){const n=this.getItem(e);if(null===n)return t;const r=Number(n);return Number.isFinite(r)?r:t}},kt=class{constructor(e){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage=e.storage,this.getMaxDurationMs=e.getMaxDurationMs??null}getSessionId(){if(this.sessionId)return this.sessionId;return this.storage.getItem("gcId")||""}setSessionId(e){this.sessionId=e,this.storage.setItem("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:this.storage.getNumericItem("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,this.storage.setItem("gcStartTime",String(e)),this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcLastActivity")}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:this.storage.getNumericItem("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,this.storage.setItem("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs(),n=t>0?t:Se(this.getSessionStartTime());return n>0&&e-n>=Be}hasUserActivity(){return this.getLastActivityMs()>0}clearSamplingDecision(){this.storage.removeItem(Ue)}clearSessionState(){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcId"),this.storage.removeItem("gcStartTime"),this.storage.removeItem("gcLastActivity"),this.clearSamplingDecision()}getSessionMaxDuration(){return this.getMaxDurationMs?.()??je}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-Se(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}};function Et(){const e=navigator.userAgent;let t="unknown",n="unknown";const r=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{userAgent:e,browser:{name:t,version:n,platform:r,language:navigator.language,mobile:s}}}var St,It,Tt=["navigation","dom.event"],Lt=class{constructor(e){this.core=null,this.hideWired=!1,this.hideHandler=()=>{try{if("undefined"==typeof document||"hidden"!==document.visibilityState)return;this.core?.session.persistLastActivity(),this.core?.pool.flush({lifecycle:!0})}catch(e){h(e)}},this.logger=l.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.storage=new wt(function(){try{return void 0!==globalThis.sessionStorage?globalThis.sessionStorage:null}catch{return null}}()),this.idGenerator=new d;const t=new ht(dt);t.initialize(e);const n=new kt({storage:this.storage,getMaxDurationMs:()=>t.getConfig()?.options?.sessionMaxDuration});!function({session:e,idGenerator:t,providedSessionId:n}){const r=l.getInstance();try{const s=e.getSessionId();n&&n!==s?(e.setSessionId(n),e.setSessionStartTime(Ee(Date.now())),e.clearSamplingDecision(),r.log("[session-bootstrap] using provided sessionId:",n)):n?(e.setSessionId(n),r.log("[session-bootstrap] continuing provided sessionId:",n)):s||e.setSessionId(t.generateId());const i=6e4,o=Date.now(),a=Se(e.getSessionStartTime());if(a>0&&o-a>=-i){if(e.isSessionExpired(o)||e.isSessionInactive(o)){const n=e.isSessionExpired(o)?"persisted session past cap":"inactivity gap across restart",s=e.getSessionId(),i=t.generateId();e.setSessionId(i),e.setSessionStartTime(Ee(o)),e.clearSamplingDecision(),r.log(`[session-bootstrap] init-time rotation: ${n}`,{from:s,to:i})}}else e.setSessionStartTime(Ee(o))}catch(e){r.log("[session-bootstrap] session bootstrap failed:",e)}}({session:n,idGenerator:this.idGenerator,providedSessionId:e.sessionId});if(!function({storage:e,sessionSampleRate:t}){const n=l.getInstance();if(void 0===t||!Number.isFinite(t)||1===t)return!0;const r=t;try{const t=e.getItem(Ue);if(t){const e="1"===t;return n.log("[session-bootstrap] using stored sampling decision:",e),e}const s=Math.random()<r;return e.setItem(Ue,s?"1":"0"),n.log("[session-bootstrap] stored new sampling decision:",s),s}catch(e){n.log("[session-bootstrap] storage access failed:",e);const t=Math.random()<r;return n.log("[session-bootstrap] using fallback sampling decision:",t),t}}({storage:this.storage,sessionSampleRate:e.options?.sessionSampleRate}))return void this.logger.log("[session-manager] session is not sampled");const r=new bt({config:t,sendBatch:(e,t)=>fetch(e,t),encodeAsync:(e,t)=>De.withFallback((n=>n.encodeBatch(e,t)),(()=>yt(e,t)),"transporter")}),s=new pt({config:t,session:n,transporter:r,getDeviceAttributes:Et,eventsToSkipFlush:Tt}),i=function(e){return()=>{let t="";try{t=F?.document?.title||""}catch(e){h(e)}try{const n=F?.location;if(!n)return{path:"",url:"",title:t};const r=n.hash&&!n.hash.match(/^#[a-z0-9-]+$/i)&&n.hash.startsWith("#/"),s=r?n.hash:n.pathname,i=e.getPrivacy(),o=i.shouldMaskNetworkQueryParams,a={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:o&&r?M(s,a):s,url:o?M(n.href,a):n.href,title:t}}catch(e){return h(e),{path:"",url:"",title:t}}}}(t),o=new mt({enrichAttributes:()=>({location:i()}),reservedAttributeKeys:["location"],isOpaqueNode:ut,idGenerator:this.idGenerator}),a=new Ve({config:t,session:n,eventsPool:s,enricher:o});try{s.initialize(),De.getInstance(),this.wireHideHandler(),a.instrument(),this.core={config:t,session:n,pool:s,instrumentation:a}}catch(e){this.logger.log("[session-manager] initialization failed — tearing down partial startup:",e);try{a.uninstrument()}catch(e){h(e)}throw s.destroy(),this.unwireHideHandler(),this.core=null,e}}wireHideHandler(){if(!this.hideWired&&"undefined"!=typeof document){this.hideWired=!0;try{document.addEventListener("visibilitychange",this.hideHandler)}catch(e){h(e)}}}unwireHideHandler(){if(this.hideWired&&"undefined"!=typeof document){this.hideWired=!1;try{document.removeEventListener("visibilitychange",this.hideHandler)}catch(e){h(e)}}}identifyUser(e){this.logger.log("[session-manager] identifyUser called"),this.core?this.core.config.updateConfig({user:e}):this.logger.log("[session-manager] cannot identify user: SDK not initialized")}updateConfig(e){try{if(null===e||"object"!=typeof e)return void u("[groundcover] updateConfig requires a configuration object; the update was ignored.");if("appId"in e)return void u("[groundcover] updateConfig does not accept appId; the entire update was ignored. Remove appId from the update.");if(!this.core)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");this.core.config.updateConfig(e);const t=e.options,n=!!t&&Object.hasOwn(t,"privacy"),r=t&&Object.hasOwn(t,"replay")&&"object"==typeof t.replay&&null!==t.replay?t.replay:void 0,s=!!r&&Object.hasOwn(r,"blockedSelectors"),i=!!r&&Object.hasOwn(r,"canvas");(n||s||i)&&this.core.instrumentation.restartReplayForConfigChange()}catch(e){h(e)}}sendCustomEvent(e){this.core?this.core.instrumentation.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.core?this.core.instrumentation.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.core?this.core.instrumentation.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.core?this.core.instrumentation.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}emitLog(e,t,n){this.core?this.core.instrumentation.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.core?this.core.session.getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.core)try{this.core.instrumentation.flushPendingReplay(),await this.core.pool.flushSync();const t=e||this.idGenerator.generateId();this.core.session.setSessionId(t),this.core.session.setSessionStartTime(Ee(Date.now())),this.logger.log("[session-manager] session ID set successfully:",t)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.core?this.core.instrumentation.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.core?this.core.instrumentation.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){const e=this.core;e&&(e.instrumentation.uninstrument(),e.pool.destroy(),this.unwireHideHandler(),De.getInstance().terminate(),e.session.clearSessionState(),this.core=null)}},Rt=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var xt={init:function(e){if(void 0===It)try{const t=e?.appId;if(void 0!==It)return;if("string"!=typeof t||0===t.trim().length)return void u("[groundcover] init requires a nonblank appId; the SDK was not initialized.");It=t,St=new Lt({cluster:e.cluster||"",environment:e.environment||"",namespace:e.namespace,releaseId:e.releaseId,dsn:e.dsn||"",appId:t,user:e.user,apiKey:e.apiKey||"",options:e.options,sessionId:e.sessionId}),Rt.manager=St}catch(e){St||(It=void 0),h(e)}},identifyUser:function(e){St?St.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){St&&St.sendCustomEvent(e)},captureException:function(e,t){St&&St.captureException(e,t)},logger:Rt,updateConfig:function(e){if(St)try{St.updateConfig(e)}catch(e){h(e)}},startNavigation:function(e){St?St.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){St?St.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return St?St.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(St)try{await St.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){St?St.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){St?St.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=xt}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var At=xt;module.exports=At;
1
+ "use strict";var e=require("error-stack-parser"),t=require("web-vitals"),n=require("rrweb"),r=require("@rrweb/packer"),s=require("fflate");function i(e){return e&&e.__esModule?e:{default:e}}var o=i(e),a=console.log.bind(console),l=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&a(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},c=l.getInstance();function h(e){c.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}function u(e){try{console.warn(`${e} (groundcoverIgnore)`)}catch{}}var d=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)g[e]=Math.floor(16*Math.random())+48,g[e]>=58&&(g[e]+=39);return p+String.fromCharCode.apply(null,g.slice(0,16))},this.generateSpanId=f(8),this.generateId=f(16)}},g=Array(32);function f(e){return function(){for(let t=0;t<2*e;t++)g[t]=Math.floor(16*Math.random())+48,g[t]>=58&&(g[t]+=39);return String.fromCharCode.apply(null,g.slice(0,2*e))}}var p="0000000000000000";function v({text:e,maxLength:t=1e4,ellipsis:n=""}){if(null==e)return"";const r="string"==typeof e?e:String(e);return r.length<=t?r:r.substring(0,t)+n}function m(e){return(e||"").replace(/\s+/g," ").trim()}var y="[REDACTED]",b=["authorization","cookie","set-cookie"],w=/(token|key|secret|passwd|password|auth|bearer|credential)/i,k=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,E=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),S=1e5;function I(e,t){if(!e)return!1;if(k.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function T(e,t){return E.has(e.toLowerCase())||I(e,t)}function R(e){return e.includes("-")&&w.test(e)}function A(e,t){return I(e,t)||R(e)}function L(e,t){const n=e.sensitive?y:e.value;if(!t)return n;try{const r=t(e);return void 0===r?n:r}catch(e){return h(e),n}}function x(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const r=e.slice(0,n),s=e.slice(n+1);let i=r;try{i=decodeURIComponent(r)}catch{}let o=s;try{o=decodeURIComponent(s)}catch{}const a=T(i,t.sensitiveKeys),l=L({key:i,value:o,path:[i],kind:t.kind??"query",sensitive:a},t.redact);return l===o?e:`${r}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function C(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${x(e.slice(n+1),t)}`}function N(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},r=e.indexOf("#"),s=-1===r?e:e.slice(0,r),i=-1===r?"":e.slice(r+1),o=C(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${y}@`))}(s),n);return-1===r?o:`${o}#${C(i,n)}`}function M(e,t,n,r,s,i){const o=!!e&&I(e,r.sensitiveKeys);if(null!==t&&"object"==typeof t){if(o||s>8)return y;if(function(e,t){if(!e.isOpaqueNode)return!1;try{return e.isOpaqueNode(t)}catch{return!0}}(r,t))return y;if(i.has(t))return y;i.add(t);try{if(Array.isArray(t))return t.map((t=>M(e,t,n,r,s+1,i)));const o={};for(const[e,a]of Object.entries(t))o[e]=M(e,a,[...n,e],r,s+1,i);return o}catch(e){return h(e),y}finally{i.delete(t)}}return L({key:e,value:t,path:n,kind:r.kind??"log",sensitive:o},r.redact)}function q(e,t={}){if(!e)return e;if(e.length>S)return`${q(e.slice(0,S),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>A(n,t.sensitiveKeys)?`"${n}":"${y}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return T(e,t)||R(e)}(n,t.sensitiveKeys)?`${n}=${y}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>A(n,t.sensitiveKeys)?`${n}: ${y}`:e))}catch(t){h(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){h(e)}return n}function O(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=S&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(M("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?x(e,t):q(e,t)}function z(e,t={}){try{const n=M("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return h(e),{}}}function P(e,t){return"allow"!==t.level&&e?z(e,{sensitiveKeys:t.sensitiveKeys,redact:t.redact,isOpaqueNode:t.isOpaqueNode}):e}function D(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const r={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log",isOpaqueNode:e.isOpaqueNode};return{message:q(t,r),attributes:n?z(n,r):n}}var _=class{constructor(e){this.logger=l.getInstance(),this.config=e.config,this.pool=e.pool,this.enricher=e.enricher}sendCustomEvent(e){this.logger.log("[manual-event-emitter.sendCustomEvent] called",e);try{const t=this.enricher.enrich({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.pool.addEvent(t)}catch(e){h(e)}}emitLog(e,t,n){this.logger.log("[manual-event-emitter.emitLog] called",{message:e,level:t,attributes:n});try{const r={...n||{}};delete r.message,delete r.level;for(const e of this.enricher.reservedAttributeKeys)delete r[e];const{message:s,attributes:i}=D(this.config.getPrivacy(),e,r),o=this.enricher.enrich({type:"log",attributes:{...i,message:v({text:s}),level:t}});this.pool.addEvent(o)}catch(e){h(e)}}},F=globalThis,j=class{constructor(e){this.logger=l.getInstance(),this.config=e.config,this.eventsPool=e.eventsPool,this.enricher=e.enricher}};function H(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function B(e){const t=e.getPrivacy(),n=e.getConfig()?.providedOptions?.privacy;return{...t,maskSelectors:H(n?.maskSelectors)}}var U="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function K(e,t){try{return e.getAttribute(t)||""}catch{return""}}function Y(e){try{const t=U?.call(e);return"string"==typeof t?t:""}catch{return""}}function $(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function W(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>K(e,t))).filter(Boolean)}(e).some((e=>I(e,t))))}function Q(e,t){return"allow"!==t.level&&(!!e&&(!!$(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>$(e,t))))||("mask-all"===t.level||function(e){const t=Y(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&W(e,t.sensitiveKeys)))))}var G={role:"",accessibleName:"",ariaLabel:"",title:"",alt:"",placeholder:"",name:"",inputType:"",href:""},X=["button","a","input","select","textarea","label","summary",'[role~="button"]','[role~="link"]','[role~="menuitem"]','[role~="menuitemcheckbox"]','[role~="menuitemradio"]','[role~="tab"]','[role~="checkbox"]','[role~="radio"]','[role~="switch"]','[role~="option"]','[role~="treeitem"]','[role~="slider"]','[role~="spinbutton"]','[role~="combobox"]','[role~="textbox"]','[role~="searchbox"]'].join(", "),J=[X,"li","option","tr","td","th",'[role~="listitem"]','[role~="row"]','[role~="gridcell"]','[role~="cell"]'].join(", ");function V(e){return!!e&&1===e.nodeType}function Z(e){const t=Y(e).toLowerCase();return"body"===t||"html"===t}function ee(e){return v({text:e,maxLength:255})}function te(e){return v({text:e,maxLength:99,ellipsis:"…"})}function ne(e){const t=m(K(e,"role"));return t?t.split(" ")[0]??t:function(e){switch(Y(e).toLowerCase()){case"a":return K(e,"href")?"link":"";case"button":return"button";case"input":switch(K(e,"type").toLowerCase()){case"checkbox":return"checkbox";case"radio":return"radio";case"submit":case"button":case"reset":return"button";case"range":return"slider";case"number":return"spinbutton";default:return"textbox"}case"textarea":return"textbox";case"select":return"combobox";case"img":return"img";case"nav":return"navigation";case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"heading";default:return""}}(e)}function re(e){if(!V(e))return"";try{if(Z(e))return"";if(function(e){try{return e.querySelectorAll(J).length>=2}catch{return!1}}(e))return"";const t=m(e.textContent||"");return t?t.length>1e3?"":v({text:t,maxLength:255}):""}catch{return""}}function se(e){return K(e,"aria-labelledby").split(/\s+/).filter(Boolean).slice(0,5)}function ie(e,t){if(Z(e))return"";const n=function(e){const t=[];for(const n of se(e))try{const e=re(document.getElementById(n));e&&t.push(e)}catch{}return m(t.join(" "))}(e);if(n)return te(n);const r=m(K(e,"aria-label"));if(r)return te(r);const s=m(K(e,"alt"));if(s)return te(s);if(function(e){const t=Y(e).toLowerCase();if("button"===t)return!0;if("input"!==t)return!1;const n=K(e,"type").toLowerCase();return"submit"===n||"button"===n||"reset"===n}(e)){const t=m(K(e,"value"));if(t)return te(t)}const i=t??re(e);if(i)return te(i);const o=m(K(e,"title"));if(o)return te(o);const a=m(K(e,"placeholder"));return a?te(a):""}function oe(e,t){if("allow"===t.level)return!1;try{return!!e.querySelector("[data-private]")||t.maskSelectors.some((t=>{try{return null!=e.querySelector(t)}catch{return!1}}))}catch{return!1}}var ae=class extends j{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>Q(e.target,B(this.config)),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){h(e)}};this.eventHandlers.push({type:e,handler:t}),F?.addEventListener(e,t)}))}catch(e){h(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}}buildEvent(e){const t=this.getCoordinates(e),n=e.target,r=function(e){if(!V(e))return null;try{return e.closest(X)}catch{return null}}(n)??n,s=B(this.config),i=this.getShouldMaskText({target:n||null})||!!r&&(oe(r,s)||function(e,t){if("allow"===t.level)return!1;try{for(const n of se(e)){const e=document.getElementById(n);if(e&&re(e)&&(Q(e,t)||oe(e,t)))return!0}}catch{}return!1}(r,s)),o=r?this.generateSelector(r,i?{priorityAttributes:["id","class","name","type"]}:{}):"",a=this.getKeyCode(e,i),l=re(r),c=function(e,t){if(!V(e))return{...G};try{return{role:ee(ne(e)),accessibleName:ie(e,t),ariaLabel:ee(m(K(e,"aria-label"))),title:ee(m(K(e,"title"))),alt:ee(m(K(e,"alt"))),placeholder:ee(m(K(e,"placeholder"))),name:ee(K(e,"name")),inputType:ee(K(e,"type")),href:ee(K(e,"href"))}}catch{return{...G}}}(r,l),h=s.shouldMaskNetworkQueryParams?N(c.href,{sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"}):c.href,u=e=>i&&e?"*":e;this.logger.log("[dom-events-listener.buildEvent] called");const d={dom_event_selector:o,dom_event_key_code:a,dom_event_type:e.type,dom_event_coordinates:t||{clientX:0,clientY:0},dom_event_target:{id:K(r,"id"),tagName:Y(r),className:K(r,"class"),text:i?"*":l,role:c.role,accessibleName:u(c.accessibleName),ariaLabel:u(c.ariaLabel),title:u(c.title),alt:u(c.alt),placeholder:u(c.placeholder),name:c.name,inputType:c.inputType,href:u(h)}};return this.enricher.enrich({type:"dom.event",attributes:d})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,r=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===Y(e).toLowerCase())return"html";let i="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<r;){let e=Y(a).toLowerCase();try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=Y(a).toLowerCase()||"*"}l.unshift(e||"*"),i=l.join(" > ");try{if(1===n.querySelectorAll(i).length)return i}catch(e){l.shift(),i=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return i||"*"}},le=["log","info","warn","error","debug","assert","trace"],ce=class extends j{constructor(){super(...arguments),this.originalConsole=null,this.patchedConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods();const e={};le.forEach((t=>{if(!(t in console))return;const n=(...e)=>{try{this.isInitialized&&this.handleEvent(e,t)}catch(e){h(e)}finally{this.originalConsole?.[t]&&this.originalConsole[t](...e)}};console[t]=n,e[t]=n})),this.patchedConsole=e,this.isInitialized=!0}catch(e){h(e)}}destroy(){try{if(!this.isInitialized)return;le.forEach((e=>{this.originalConsole?.[e]&&this.patchedConsole?.[e]&&console[e]===this.patchedConsole[e]&&(console[e]=this.originalConsole[e])})),this.patchedConsole=null,this.isInitialized=!1}catch(e){h(e)}}handleEvent(e,t){try{const n=Array.isArray(e)?e:[e];if("assert"===t&&n[0])return;const r=this.formatMessage(n,t);if(!r||r?.includes("groundcoverIgnore"))return;const s=this.extractAttributes(n),i=this.buildEvent({message:r,level:t,attributes:s});this.queueEvent(i)}catch(e){h(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:r,attributes:s}=D(this.config.getPrivacy(),e,n);return this.enricher.enrich({type:"log",attributes:{...s,message:v({text:r}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);delete t.message,delete t.level;for(const e of this.enricher.reservedAttributeKeys)delete t[e];return t}catch(e){return void h(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return h(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{le.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){h(e)}return e}},he=class{constructor(){this.installed=[]}install(e){const t=e,n=[],r=[];try{for(const e of t){const t=e.get();r.push({spec:e,original:t});const s=e.wrap(t);e.set(s),n.push({spec:e,original:t,wrapped:s})}return this.installed.push(...n),!0}catch(e){for(const{spec:e,original:t}of r.reverse())try{e.get()!==t&&e.set(t)}catch{}return h(e),!1}}restore(){const e=this.installed;this.installed=[];for(const{spec:t,original:n,wrapped:r}of e.reverse())try{t.get()===r&&t.set(n)}catch(e){h(e)}}get isEmpty(){return 0===this.installed.length}},ue="[request body too large]",de="[request body unavailable]",ge="[response body too large]",fe="[response body unavailable]",pe="[unreadable response body]",ve="[form data]",me="[binary data]";function ye(e){return(e.split(";")[0]||"").trim().toLowerCase()}function be(e){const t=(e||"").toLowerCase();return t.includes("multipart/form-data")?ve:function(e){const t=ye(e);return!!t&&(!!t.startsWith("text/")||"application/x-www-form-urlencoded"===t||"application/javascript"===t||"application/ecmascript"===t||"application/graphql"===t||/^application\/([\w.-]+\+)?(json|xml)$/.test(t))}(t)?null:function(e){const t=ye(e);return t.startsWith("image/")?"[image data]":t.startsWith("audio/")?"[audio data]":t.startsWith("video/")?"[video data]":t.startsWith("font/")||t.startsWith("application/font")||"application/vnd.ms-fontobject"===t?"[font data]":"application/pdf"===t?"[pdf data]":"application/zip"===t||"application/gzip"===t||"application/x-gzip"===t||"application/x-tar"===t||"application/x-7z-compressed"===t||"application/x-rar-compressed"===t?"[archive data]":"application/wasm"===t?"[wasm data]":t.includes("protobuf")||t.startsWith("application/grpc")?"[protobuf data]":me}(t)}function we(e,t,n){return e&&(e.length>=t||function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=2;else if(r>=55296&&r<=56319){const r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=4,n++):t+=3}else t+=3}return t}(e)>=t)?n:e}var ke=1e6;function Ee(e){return e*ke}function Se(e){return e/ke}function Ie(e){return"string"==typeof e&&/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}function Te(e,t){const n="allow"===t.level,r=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,r])=>{const s=n.toLowerCase(),i=L({key:n,value:r,path:[n],kind:"header",sensitive:b.includes(s)||w.test(s)||I(n,t.sensitiveKeys)},t.redact);return e[n]=null===i?"":String(i),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact}),s={};for(const[e,t]of Object.entries(r))s[e]=v({text:t});return s}function Re(e,t){const{privacy:n}=t,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"query"};let{path:s,fullUrl:i}=t.resolveUrl(e.url);n.shouldMaskNetworkQueryParams&&(s=N(s,r),i=N(i,r));const o=e.method?.toUpperCase()||"UNKNOWN",a=e.method||"UNKNOWN",l=e.status?.toString(),{traceId:c,spanId:h}=function(e,t){const n={};for(const t of Object.keys(e))n[t.toLowerCase()]=e[t];const r=e=>{if(!e)return"";const t=n[e.toLowerCase()];return"string"==typeof t?t:""};let s=r(t?.traceIdHeaderName),i=r(t?.spanIdHeaderName);if(!s||!i){let e="";for(const n of t?.propagationHeaders??[])if(e=r(n),e)break;e||(e=r("traceparent"));const n=e.split("-");4===n.length&&"00"===n[0]&&(s||32!==n[1]?.length||(s=n[1]),i||16!==n[2]?.length||(i=n[2]))}return{traceId:s,spanId:i}}(e.request.headers,t.tracing),u=(e,r)=>v({text:n.shouldMaskNetworkBodies?O(e,{sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:r}):e,maxLength:t.maxBodyLength}),d={type:"HTTP",operation:{name:o},resource_name:s,status:l,subType:o,url:{full:i},http:{route:s,path:s,method:a,status:l,request:{headers:Te(e.request.headers,n),method:a},response:{headers:Te(e.response.headers,n),status_code:l}},error:e.error?.type?{type:e.error.type}:void 0,gc:{request:{body:u(e.request.body,"request-body")},response:{body:u(e.response.body,"response-body")}}},g={type:"network",timestamp:Ae(e.timestamp),end_timestamp:Ae(e.end_time),span_name:`${o} ${s}`,attributes:d};return c&&(g.traceId=c),h&&(g.spanId=h),g}function Ae(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Ee(e):void 0}function Le(e){return function(e){try{return 9===e?.nodeType}catch{return!1}}(e)?"[document data]":function(e){try{if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof FormData&&e instanceof FormData)return"[form data]";if("undefined"!=typeof Blob&&e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if(ArrayBuffer.isView(e))return"[arraybuffer data]";if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return"[stream data]";if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return h(`Failed to format body: ${e}`),"[unreadable body]"}}(e)}var xe=[".tsx",".jsx",".css"],Ce=e=>xe.some((t=>e.toLowerCase().endsWith(t))),Ne=class extends j{constructor(){super(...arguments),this.maxBodyLength=5e3,this.requestBodyReadTimeoutMs=3e3,this.responseBodyReadTimeoutMs=3e3,this.idGenerator=new d,this.patches=new he,this.active=!1,this.handleEvent=e=>{try{if(!this.active)return;if(this.shouldIgnoreRequest(e.url))return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}},this.buildEvent=e=>(this.logger.log("[network-events-listener.buildEvent] called",{event:e}),this.enricher.enrich(Re(e,{privacy:this.config.getPrivacy(),maxBodyLength:this.maxBodyLength,tracing:this.config.getConfig()?.options?.tracing,resolveUrl:e=>{try{return{path:new URL(e).pathname,fullUrl:e}}catch{return{path:e,fullUrl:new URL(e,globalThis.location.href).href}}}})))}async readBodyStreamCapped(e,t={}){if(!e)return"";const{timeoutMs:n,overflowPlaceholder:r,timeoutPlaceholder:s}=t,i=e.getReader(),o=new TextDecoder;let a,l="",c=0,h=!1,u=!1;const d=null!=n?new Promise((e=>{a=setTimeout((()=>e({timedOut:!0})),n)})):void 0;try{for(;;){const e=d?await Promise.race([i.read(),d]):await i.read();if("timedOut"in e){u=!0;break}const{done:t,value:n}=e;if(t)break;if(c+n.byteLength>=this.maxBodyLength){const e=n.subarray(0,this.maxBodyLength-c);l+=o.decode(e,{stream:!0}),h=!0;break}c+=n.byteLength,l+=o.decode(n,{stream:!0})}return l+=o.decode(),u&&null!=s?s:h&&null!=r?r:l}finally{clearTimeout(a);try{i.cancel()?.catch((()=>{}))}catch{}}}async getRequestBody(e,t){try{if(!e.body)return"";const n=be(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.requestBodyReadTimeoutMs,overflowPlaceholder:ue,timeoutPlaceholder:de})}catch{return de}}async getResponseBody(e){if(!e.body)return"";const t=e.headers?.get?.("content-type")??"";if(function(e){return"text/event-stream"===ye(e||"")}(t))return pe;const n=be(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.responseBodyReadTimeoutMs,overflowPlaceholder:ge,timeoutPlaceholder:fe})}initialize(){this.logger.log("[network-events-listener.initialize] called");const e=this.patches.install(this.xhrPatches()),t=this.patches.install([this.fetchPatch()]);this.active=e||t}destroy(){this.active=!1,this.patches.restore()}shouldIgnoreRequest(e){try{const t=this.config.getConfig();return function(e,t){try{return!(!t.endpoint||!e.includes(t.endpoint))||!!t.extraIgnore?.(e)||(t.excludedUrls??[]).some((t=>t instanceof RegExp?t.test(e):"string"==typeof t&&(t.includes("*")||t.includes("?"))?new RegExp(t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")).test(e):e===t))}catch(e){return h(e),!1}}(e,{endpoint:t?.getEndpoint(),excludedUrls:t?.options?.excludedUrls,extraIgnore:Ce})}catch(e){return h(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}xhrPatches(){const e=this,t=globalThis.XMLHttpRequest.prototype;let n;return[{get:()=>t.open,set:e=>{t.open=e},wrap:t=>function(r,s,i=!0,o,a){if(!e.active)return t.apply(this,[r,s,i,o,a]);if(n=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[r,s,i,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=r,this._requestUrl=l,this._requestHeaders={},t.apply(this,[r,s,i,o,a])}},{get:()=>t.setRequestHeader,set:e=>{t.setRequestHeader=e},wrap:t=>function(n,r){return e.active?(this._requestHeaders&&(this._requestHeaders[n]=r),t.apply(this,[n,r])):t.apply(this,[n,r])}},{get:()=>t.send,set:e=>{t.send=e},wrap:t=>function(...r){if(!e.active)return t.apply(this,r);const s=this._requestUrl?.toString();if(!s||e.shouldIgnoreRequest(s))return t.apply(this,r);if(e.shouldAddTraceHeader(s))for(const[t,n]of Object.entries(e.buildTraceHeaders()))e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n});return this._requestBody=r[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),r={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,n]=e.split(": ");t&&n&&(r[t.trim()]=n.trim())}));const s=we(Le(this._requestBody),e.maxBodyLength,ue),i=""===this.responseType||"text"===this.responseType,o=i?this.responseText:this.response,a=(i?be(r["content-type"]||""):null)??we(Le(o),e.maxBodyLength,ge),l={timestamp:n,end_time:t,method:this._requestMethod,url:this._requestUrl,status:this.status,request:{headers:this._requestHeaders||{},body:s},response:{headers:r,body:a}};e.handleEvent(l)})),t.apply(this,r)}}]}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){for(const[t,n]of Object.entries(this.buildTraceHeaders()))this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n})}buildTraceHeaders(){return function(e,t){const n={},r=(e,t)=>{Ie(e)&&(n[e]=t)};e?.origin?.name&&r(e.origin.name,e.origin.value),e?.traceIdHeaderName&&r(e.traceIdHeaderName,t.decimalTraceId),e?.spanIdHeaderName&&r(e.spanIdHeaderName,t.decimalSpanId);const s=e?.propagationHeaders,i=s?.length?s:["traceparent"];for(const e of i)r(e,t.traceparent);return n}(this.config.getConfig()?.options?.tracing,function(e){const t=e.generateSpanId(),n=e.generateTraceId();let r,s;try{r=BigInt("0x"+n).toString(10),s=BigInt("0x"+t).toString(10)}catch{r=n,s=t}return{traceparent:`00-${n}-${t}-01`,traceId:n,spanId:t,decimalTraceId:r,decimalSpanId:s}}(this.idGenerator))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}fetchPatch(){return{get:()=>globalThis.fetch,set:e=>{globalThis.fetch=e},wrap:e=>(...t)=>{if(!this.active)return e.apply(globalThis,t);const n=Date.now();let[r,s]=t;s={...s||{}},t[1]=s;const i=r instanceof Request,o=s?.method||(i?r.method:"GET"),a=r instanceof Request?r.url:r.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);s.headers=this.normalizeHeaders(i?r.headers:void 0,s.headers),l&&this.addTraceHeaders(s);const c=this.extractHeadersRecord(s.headers),h=null!=s?.body?we(Le(s.body),this.maxBodyLength,ue):"",u=null!=s?.body?Promise.resolve(h):i?this.getRequestBody(r,"content-type"in c?c["content-type"]:r.headers.get("content-type")??""):Promise.resolve("");let d;return u.then((e=>{d=e})).catch((()=>{})),e.apply(globalThis,t).then((e=>{const t=Date.now(),r={};e.headers.forEach(((e,t)=>{r[t]=e}));const s={method:o,url:a,timestamp:n,status:e.status,end_time:t,request:{headers:c,body:""},response:{headers:r,body:""}},i=()=>{u.then((e=>{s.request.body=e,this.handleEvent(s)}))};return this.getResponseBody(e).then((e=>{s.response.body=e,i()})).catch((e=>{s.response.body=pe,i(),this.logger.log("[network-events-listener.fetch] response body error",{error:e})})),e})).catch((e=>{const t=Date.now();let r="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?r="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?r="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(r="ERR_CONNECTION_REFUSED");const i={method:o,url:a,timestamp:n,status:0,end_time:t,request:{headers:c,body:d??h},response:{headers:{},body:""},error:{type:r}};throw this.handleEvent(i),e}))}}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),Ie(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),Ie(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}shouldAddTraceHeader(e){const t=(n=this.propagationCandidates(e),r=this.config.getConfig()?.options?.tracing?.propagationUrls,!!r?.length&&r.some((e=>{try{if("string"!=typeof e)return!1;const t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),r=new RegExp(`^${t}$`);return n.some((e=>r.test(e)))}catch{return!1}})));var n,r;return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:t}),t}propagationCandidates(e){try{const t=globalThis.location.href,n=new URL(e,t),r=[n.href];return"/"!==n.pathname||n.search||n.hash||r.push(n.href.slice(0,-1)),n.origin===new URL(t).origin&&r.push(n.pathname),r}catch{return[e]}}};function Me(e){try{return o.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch{return[]}}var qe=class extends j{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const r=this.buildEvent(n,t);this.queueEvent(r)}catch(e){h(e)}}}initialize(){F?.addEventListener("error",this.handleEvent),F?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){F?.removeEventListener("error",this.handleEvent),F?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return this.enricher.enrich(function(e,t,n){const r=n.shouldMaskErrors,s={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error",isOpaqueNode:n.isOpaqueNode},i=e.message||"Unknown error",o=r?q(i,s):i,a=r&&t?.metadata?z(t.metadata,s):t?.metadata;return{type:"exception",attributes:{error_type:e.name||"Error",error_message:o,error_stacktrace:Me(e),error_fingerprint:`${e.name}:${v({text:o,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:a}}}(e,t,this.config.getPrivacy()))}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}enhanceError(e,t){const{filename:n,lineno:r,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),r&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:r}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}},Oe=class extends j{constructor(e,{isEnabled:t}){if(super(e),this.currentUrl="",this.patches=new he,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&t)try{this.isAutomaticNavigationEnabled=t,this.currentUrl=F.location.href}catch(e){h(e)}}isInBrowserEnvironment(){try{return void 0!==F&&void 0!==F.location&&void 0!==F.history&&"function"==typeof F.addEventListener}catch(e){return h(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||"function"!=typeof history.pushState||"function"!=typeof history.replaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");this.patches.install([this.historyPatch("pushState"),this.historyPatch("replaceState")]),F&&"function"==typeof F.addEventListener&&(F.addEventListener("popstate",this.popStateHandler),F.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){h(e)}}historyPatch(e){return{get:()=>history[e],set:t=>{history[e]=t},wrap:e=>(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n}}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.patches.restore(),F&&"function"==typeof F.removeEventListener&&(F.removeEventListener("popstate",this.popStateHandler),F.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){h(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",F.location.href);const e=this.config.getPrivacy(),t=F.location.href,n=this.activeNavigation?.metadata,r={page_url:e.shouldMaskNetworkQueryParams?N(t,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):t,metadata:P(n,e),duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0};return this.enricher.enrich({type:"navigation",attributes:r})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}startNavigation(e){try{this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:F?.location?.href||"",metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}catch(e){h(e)}}endNavigation(e){try{if(this.logger.log("[navigation-listener.endNavigation] called",e),!this.activeNavigation)return void this.logger.log("[navigation-listener.endNavigation] no active navigation found");this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()}catch(e){h(e)}}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===F.location.href)return;let e,t;try{e=new URL(F.location.href),t=new URL(this.currentUrl)}catch(e){return void h(e)}const n=e=>e.startsWith("#/"),r=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||r&&e.hash!==t.hash)&&(this.currentUrl=F.location.href,this.handleEvent())}catch(e){h(e)}}},ze=class extends j{constructor(e){super(e),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",F),"complete"===F?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):F?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),h(e)}}destroy(){F?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),r={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,i=t.initiatorType;r.totalSize+=n,r.totalDuration+=s,r.byType[i]||(r.byType[i]={count:0,size:0,duration:0}),r.byType[i].count++,r.byType[i].size+=n,r.byType[i].duration+=s}));const s=this.config.getPrivacy(),i=s.shouldMaskNetworkQueryParams,o={sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"},a=F?.location?.href||"",l=F?.document?.referrer||"",c={page_url:i?N(a,o):a,page_load_time:t,page_referrer:i?N(l,o):l,page_resources:r};return this.enricher.enrich({type:"pageload",attributes:c})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}},Pe=class extends j{constructor(){super(...arguments),this.handleEvent=e=>{try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}}}initialize(){t.onCLS(this.handleEvent),t.onLCP(this.handleEvent),t.onFCP(this.handleEvent),t.onTTFB(this.handleEvent),t.onINP(this.handleEvent)}destroy(){}buildEvent(e){const t={performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""};return this.enricher.enrich({type:"performance",attributes:t})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}};function De(e,t){if("function"==typeof F.requestIdleCallback){const n=F.requestIdleCallback(e,{timeout:t});return()=>F.cancelIdleCallback?.(n)}let n=null,r=null,s=null;const i=()=>{null!==n&&F.cancelAnimationFrame?.(n),null!==r&&F.clearTimeout(r),null!==s&&F.clearTimeout(s),n=r=s=null},o=()=>{i(),e()};return s=F.setTimeout(o,t),"function"==typeof F.requestAnimationFrame?n=F.requestAnimationFrame((()=>{n=null,r=F.setTimeout(o,0)})):r=F.setTimeout(o,0),i}var _e=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=l.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,r){const s=e.getInstance();if(!s.isAvailable)return n();try{return await t(s)}catch(e){return l.getInstance().log(`[${r}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,r=this.worker;return new Promise(((s,i)=>{const o=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),i(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:s,reject:i,timeoutId:o});try{r.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(o),this.pending.delete(n),i(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};_e.instance=null;var Fe=_e;var je=class{constructor(e){this.logger=l.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=null,this.lastFullSnapshotAt=0,this.cancelScheduledCheckout=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.lastFullSnapshotAt=Date.now();const e=this.configManager.getConfig()?.options,t=e?.replay,r=t?.blockedSelectors?.filter(Boolean),s=r?.length?r.join(", "):void 0,i=B(this.configManager),o=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=H(t?.maskSelectors),i=t?.replay,o="function"==typeof i?.maskTextFn?i.maskTextFn:void 0,a="function"==typeof i?.maskInputFn?i.maskInputFn:void 0;let l;return l="mask-all"===n||!r&&void 0!==o?["*",...s].join(", "):"mask-sensitive"===n?["[data-private]",...s].join(", "):void 0,{maskTextSelector:l,maskAllInputs:!r,maskTextFn:o,maskInputFn:a}}(this.configManager.getConfig()?.providedOptions),a=function(e){if(!e||!0!==e.enabled)return null;let t=e.fps??1;if("number"==typeof t&&Number.isFinite(t)){if(t<1||t>15){const e=Math.min(15,Math.max(1,t));u(`[groundcover] replay.canvas.fps ${t} is out of range [1, 15]; clamped to ${e}.`),t=e}}else u("[groundcover] replay.canvas.fps must be a finite number; falling back to 1."),t=1;return{canvasFps:t,dataURLOptions:{type:e.imageType??"image/webp",quality:e.imageQuality??.6}}}(t?.canvas),l=o.maskInputFn??("allow"===i.level?void 0:(e,t)=>Q(t,i)?"*".repeat(e.length):e);this.stopFn=n.record({...s?{blockSelector:s}:{},...o.maskTextSelector?{maskTextSelector:o.maskTextSelector}:{},maskAllInputs:o.maskAllInputs,...o.maskTextFn?{maskTextFn:o.maskTextFn}:{},...l?{maskInputFn:l}:{},...a?{recordCanvas:!0,dataURLOptions:a.dataURLOptions}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150,...a?{canvas:a.canvasFps}:{}},errorHandler:e=>(h(e),!0),emit:(e,t)=>{if(this.isRecording)try{this.events.push(e),e.type===n.EventType.FullSnapshot?this.lastFullSnapshotAt=Date.now():e.type!==n.EventType.IncrementalSnapshot||e.data.source===n.IncrementalSource.Mutation&&e.data.isAttachIframe||this.maybeScheduleCheckout();const r=!0===t&&e.type===n.EventType.FullSnapshot;r&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),(this.events.length>=this.batchSize||r)&&this.scheduleSendBatch()}catch(e){h(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}maybeScheduleCheckout(){this.cancelScheduledCheckout||Date.now()-this.lastFullSnapshotAt<=3e4||(this.cancelScheduledCheckout=De((()=>{if(this.cancelScheduledCheckout=null,this.isRecording){this.lastFullSnapshotAt=Date.now();try{n.record.takeFullSnapshot(!0)}catch(e){h(e),this.logger.log("[session-replay-listener] failed to take full snapshot:",e)}}}),5e3))}clearScheduledCheckout(){this.cancelScheduledCheckout?.(),this.cancelScheduledCheckout=null}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=F.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{h(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(F.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.session.getSessionId(),n=Fe.getInstance();let s;if(n.isAvailable)try{s=await n.packReplay(e.events)}catch(t){h(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),s=e.events.map((e=>r.pack(e)))}else s=e.events.map((e=>r.pack(e)));this.session.getSessionId()===t?this.enqueueReplayEvent(s,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:s.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>r.pack(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const r={_gc_replay_data:{events:e}};t&&(r.replay_is_full_snapshot=!0,r.replay_full_snapshot_timestamp=n);const s=this.enricher.enrich({type:"replay",attributes:r});this.eventsPool.addEvent(s),this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearScheduledSend(),this.clearScheduledCheckout(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){h(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},He=144e5,Be=288e5,Ue=18e5,Ke="gcSample",Ye={sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},sessionMaxDuration:He},$e=["pointerdown","keydown","scroll","touchstart","mousemove"],We=class{constructor(e){this.logger=l.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){h(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,$e.forEach((e=>{try{F.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){h(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",Ue,"ms");try{this.callbacks.onIdle()}catch(e){h(e)}}),Ue)}catch(e){h(e)}}destroy(){if(this.installed){this.installed=!1,$e.forEach((e=>{try{F.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){h(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){h(e)}finally{this.idleTimer=null}}}};function Qe(e,t,n){return"number"==typeof e&&e>0&&e<=t&&e>t-n}function Ge(e,t,n){let r=null;const s=e=>{Qe(e,t,n)&&(null===r||e<r)&&(r=e)};try{for(const t of e)if(t){try{s(t.timestamp)}catch(e){h(e)}try{s(t.start_timestamp)}catch(e){h(e)}}}catch(e){h(e)}return r}var Xe=class{constructor(e){this.logger=l.getInstance(),this.rotating=!1,this.session=e.session,this.pool=e.pool,this.idGenerator=e.idGenerator,this.activityEventTypes=e.activityEventTypes,this.ignoredEventTypes=e.ignoredEventTypes,this.hooks=e.hooks??{}}get isRotating(){return this.rotating}install(){this.pool.setBeforeEnqueueHook((e=>this.reconcileOnEnqueue(e))),this.pool.setFlushGate((()=>this.session.hasUserActivity()))}uninstall(e){this.pool.setBeforeEnqueueHook(null);try{e?.()}catch(e){h(e)}this.pool.setFlushGate(null)}reconcile(e,t,n){if(this.rotating)return;t&&this.session.isSessionInactive(e)&&this.rotate({reason:"inactivity gap",triggeringEvent:n});const r=this.session.getSessionElapsedMs(e),s=this.session.getSessionMaxDuration(),i=r>=s;this.logger.log("[session-lifecycle] session reconcile",{userPresent:t,elapsedMs:r,maxDurationMs:s,expired:i}),i&&this.rotate({reason:"max session duration",triggeringEvent:n}),this.hooks.onReconcile?.(t),t&&(this.session.setLastActivityMs(e),this.hooks.onPresenceStamped?.(e))}reconcileOnEnqueue(e){this.rotating||(this.ignoredEventTypes.has(e.type)?this.logger.log("[session-lifecycle] enqueue rotation check: ignoring heartbeat-style event",e.type):this.reconcile(Date.now(),this.activityEventTypes.has(e.type),e))}rotateIfStale(e,t){(this.session.isSessionInactive(e)||this.session.isSessionExpired(e))&&this.rotate({reason:t})}rotate(e){if(this.rotating)return;this.rotating=!0;const t=(e,t)=>{try{this.logger.log(`[session-lifecycle] session rotation: ${e}`),t()}catch(t){h(t),this.logger.log(`[session-lifecycle] failed to ${e} during session rotation:`,t)}};try{const n=this.session.getSessionId();let r;t("capture host rotation context",(()=>{r=this.hooks.captureRotationContext?.()}));const s=this.session.hasUserActivity();this.logger.log("[session-lifecycle] session rotation start",{reason:e.reason,previousId:n,wasConfirmed:s}),t("host beforeRotate",(()=>this.hooks.beforeRotate?.())),t(s?"flush events":"discard unconfirmed events",(()=>s?this.pool.flush():this.pool.discardBuffer())),t("rotate session ids",(()=>{const t=this.idGenerator.generateId(),r=this.resolveNewSessionStartTime(e.triggeringEvent);this.session.setSessionId(t),this.session.setSessionStartTime(r),this.session.clearSamplingDecision(),this.logger.log("[session-lifecycle] session id rotated",{from:n,to:t})})),t("host afterRotate",(()=>this.hooks.afterRotate?.(r)))}finally{this.rotating=!1,this.logger.log("[session-lifecycle] session rotation complete",{reason:e.reason})}}resolveNewSessionStartTime(e){const t=Ee(Date.now());let n=t;try{const r=Ee(Math.min(this.session.getSessionMaxDuration(),Ue)),s=[Ge([e],t,r),this.pool.getEarliestEventTimestamp(t,r)];for(const e of s)Qe(e,t,r)&&e<n&&(n=e)}catch(e){h(e)}return n}},Je=new Set(["dom.event"]),Ve=new Set(["replay"]),Ze=class{constructor(e){this.logger=l.getInstance(),this.idGenerator=new d,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.replayDesired=!1,this.presenceMonitor=null,this.cancelPendingReplayResume=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher,this.manualEvents=new _({config:this.configManager,pool:this.eventsPool,enricher:this.enricher}),this.lifecycle=new Xe({session:this.session,pool:this.eventsPool,idGenerator:this.idGenerator,activityEventTypes:Je,ignoredEventTypes:Ve,hooks:{captureRotationContext:()=>this.isReplayRecording()||null!==this.cancelPendingReplayResume,beforeRotate:()=>this.stopReplayListener(),afterRotate:e=>this.syncReplayState(e),onReconcile:e=>this.syncReplayState(e),onPresenceStamped:e=>this.presenceMonitor?.notePresence(e)}})}listenerDeps(){return{config:this.configManager,eventsPool:this.eventsPool,enricher:this.enricher}}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.lifecycle.install(),this.presenceMonitor?.destroy(),this.presenceMonitor=new We({onPresence:e=>this.lifecycle.reconcile(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,r=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new ze(this.listenerDeps()),this.pageLoadListener.initialize(),r.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new ae(this.listenerDeps()),this.domEventsListener.initialize(),r.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new ce(this.listenerDeps()),this.logEventsListener.initialize(),r.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new qe(this.listenerDeps()),this.errorsEventsListener.initialize(),r.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new Ne(this.listenerDeps()),this.networkEventsListener.initialize(),r.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new Pe(this.listenerDeps()),this.performanceListener.initialize(),r.push("performance")),this.navigationListener=new Oe(this.listenerDeps(),{isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),r.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",r)}sendCustomEvent(e){this.manualEvents.sendCustomEvent(e)}emitLog(e,t,n){this.logEventsListener&&this.manualEvents.emitLog(e,t,n)}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){h(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){this.replayDesired=!0,this.isReplayRecording()?this.logger.log("[instrumentation-manager] replay recording already started"):(this.lifecycle.rotateIfStale(Date.now(),"replay start into stale session"),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer())}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&!this.cancelPendingReplayResume&&(this.logger.log("[instrumentation-manager] user present and replay desired — resuming replay at idle"),this.cancelPendingReplayResume=De((()=>{this.cancelPendingReplayResume=null,this.replayDesired&&this.startReplayListener()}),1e3))}cancelReplayResume(){this.cancelPendingReplayResume?.(),this.cancelPendingReplayResume=null}pauseReplayOnIdle(){this.cancelReplayResume(),this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new je({...this.listenerDeps(),session:this.session});e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){h(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}stopReplayListener(){this.cancelReplayResume(),this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.lifecycle.uninstall((()=>{this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.cancelReplayResume(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}))}};function et(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var tt={privacy:[],tracing:["origin"],transport:[]},nt=new WeakMap,rt={nestedOptions:tt,removedOptions:{}};function st(e,t){const n=e;for(const e of Object.keys(t))Object.hasOwn(n,e)&&delete n[e]}function it(e,t){if(!e||"object"!=typeof e)return;const n=e;for(const[e,r]of Object.entries(t))Object.hasOwn(n,e)&&u(r)}function ot(e){const t={};for(const n of[tt,e.nestedOptions??{}])for(const[e,r]of Object.entries(n))t[e]=[...new Set([...t[e]??[],...r])];return t}function at(e,t){if(!et(e))return e;const n={...e};for(const e of t)et(n[e])&&(n[e]={...n[e]});return n}function lt(e,t,n){const r={...e,...t};for(const s of n){const n=e?.[s],i=t[s];et(n)&&et(i)?r[s]={...n,...i}:Object.hasOwn(t,s)&&!et(i)?r[s]=et(n)?{...n}:n:et(r[s])&&(r[s]={...r[s]})}return r}function ct(e,t,n){const r={...e,...t},s=t,i=e;for(const[e,t]of Object.entries(n)){if(!Object.hasOwn(s,e)){et(i[e])&&(r[e]=at(i[e],t));continue}const n=s[e];et(n)?r[e]=lt(i[e],n,t):r[e]=at(i[e],t)}return r}var ht=class e{constructor(t,n={}){const r={nestedOptions:ot(n),removedOptions:n.removedOptions??{}};nt.set(this,r);const{nestedOptions:s,removedOptions:i}=r,o=ct(Ye,n.defaults??{},s);this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=ct(o,t?.options||{},s),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),it(t?.options,i),st(this.providedOptions,i),st(this.options,i)}static normalizeSessionMaxDuration(e){return void 0===e?He:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>Be?(u("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),He):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){if(t.options){const{nestedOptions:r,removedOptions:s}=(n=this,nt.get(n)??rt);it(t.options,s),this.providedOptions=ct(this.providedOptions||{},t.options,r),this.options=ct(this.options,t.options,r),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),st(this.providedOptions,s),st(this.options,s)}var n;void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}},ut=class{constructor(e={}){this.extension=e,this.config=null,this.logger=l.getInstance(),this.privacyCache=null}initialize(e){this.config||(this.config=new ht(e,this.extension))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){if(!this.privacyCache){const e=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=e=>!r&&(e??!0),i=s(t?.maskNetworkBodies),o=s(t?.maskNetworkQueryParams),a=s(t?.maskLogs),l=s(t?.maskErrors);return{level:n,maskNetworkBodies:i,maskNetworkQueryParams:o,maskLogs:a,maskErrors:l,shouldMaskNetworkBodies:!r&&i,shouldMaskNetworkQueryParams:!r&&o,shouldMaskLogs:!r&&a,shouldMaskErrors:!r&&l,sensitiveKeys:H(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0}}(this.config?.providedOptions);this.extension.isOpaqueNode&&(e.isOpaqueNode=this.extension.isOpaqueNode),this.privacyCache=e}return this.privacyCache}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}};function dt(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var gt={isOpaqueNode:dt,nestedOptions:{replay:["canvas"],privacy:["replay"]},defaults:{replay:{}},removedOptions:{enableMasking:"[groundcover] `options.enableMasking` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",maskFields:"[groundcover] `options.maskFields` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",eventSampleRate:"[groundcover] `options.eventSampleRate` was removed and is ignored. Events are no longer randomly sampled; event volume may increase. Use `options.sessionSampleRate` to select whole sessions; rates are not automatically converted. See the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-from-1x-to-200"}},ft=Ye.transport?.batchSize??10,pt=Ye.transport?.batchTimeout??1e4;var vt=class{constructor(e){this.events=[],this.timeoutId=null,this.logger=l.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.unusableEnrichWarned=!1,this.onBeforeEnqueue=null,this.flushGate=null,this.config=e.config,this.session=e.session,this.transporter=e.transporter,this.getDeviceAttributes=e.getDeviceAttributes,this.eventsToSkipFlush=e.eventsToSkipFlush}initialize(){try{if(this.initialized)return;this.scheduleFlush(),this.initialized=!0}catch(e){h(e)}}destroy(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.events=[],this.initialized=!1}catch(e){h(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}setFlushGate(e){this.flushGate=e}discardBuffer(){this.events=[]}getEarliestEventTimestamp(e,t){return Ge(this.events,e,t)}isFlushAllowed(){if(null===this.flushGate)return!0;try{return this.flushGate()}catch(e){return h(e),!0}}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,r=this.config.getConfig()?.options?.enrichEvent;let s=e;if(n&&!n(s))return;if(r){const e=r(s);if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"string"==typeof e.type}catch(e){return h(e),!1}}(e))return void(this.unusableEnrichWarned||(this.unusableEnrichWarned=!0,this.logger.log("[events-pool.addEvent] dropping event: enrichEvent returned an unusable value")));s=e}if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(s)}catch(e){h(e)}if(!this.isFlushAllowed()&&this.events.length>=500)return;this.events.push(s);const i=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:ft);this.events.length>=i&&!this.eventsToSkipFlush.includes(s.type)&&this.flush()}catch(e){h(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.isFlushAllowed())return void this.scheduleFlush();if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),this.events=[],this.scheduleFlush()}catch(e){h(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.isFlushAllowed())return void this.discardBuffer();if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){h(e)}}scheduleFlush(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:pt);this.timeoutId=setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){h(e)}var e}getSessionAttributes(){return this.buildSessionAttributes()}buildSessionAttributes(){const e=this.config.getConfig();let t={};try{t=this.getDeviceAttributes()}catch(e){h(e)}return{...t,cluster:e?.cluster||"",env:e?.environment||"",namespace:e?.namespace||"",releaseId:e?.releaseId||"",session_id:this.session.getSessionId(),session_start_time:this.session.getSessionStartTime(),user:e?.user||{},"service.name":e?.appId}}};function mt(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:t}var yt=class{constructor(e={}){this.logger=l.getInstance(),this.enrichAttributes=e.enrichAttributes??null,this.reservedAttributeKeys=e.reservedAttributeKeys??[],this.isOpaqueNode=e.isOpaqueNode??null,this.idGenerator=e.idGenerator??new d}getPlatformAttributes(){if(!this.enrichAttributes)return{};try{return this.enrichAttributes()??{}}catch(e){return this.logger.log("[event-enricher] platform attribute contributor threw; continuing without it",e),{}}}formatEventObject(e,t="",n=new WeakSet,r=0){try{return r>=10?{[t||"depth_limit"]:"[Depth Limit]"}:this.isOpaqueNode?.(e)?{[t||"opaque_node"]:`[${e?.constructor?.name||"OpaqueNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,i])=>{const o=t?`${t}.${s}`:s;return"object"==typeof i&&null!==i?Array.isArray(i)?e[o]=i.map(((e,t)=>"object"==typeof e&&null!==e?this.formatEventObject(e,`${o}[${t}]`,n,r+1):e)):Object.assign(e,this.formatEventObject(i,o,n,r+1)):e[o]=i,e}),{}))}catch(e){return this.logger.log("[event-enricher.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}enrich(e){const t=Ee(Date.now()),n=this.idGenerator.generateId(),r=e.spanId||this.idGenerator.generateSpanId(),s=e.traceId||this.idGenerator.generateTraceId(),i=e.parentSpanId||"",o=this.formatEventObject(e.attributes||{}),a=this.getPlatformAttributes(),l={type:e.type,id:n,spanId:r,parentSpanId:i,traceId:s,attributes:{...o,...a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=mt(e.timestamp,t),l.end_timestamp=e?.end_timestamp):l.timestamp=mt(e.timestamp,t),l}};function bt(e,t){const n=s.strToU8(e);if(!t)return{data:n,isCompressed:!1};try{return{data:s.gzipSync(n),isCompressed:!0}}catch{return{data:n,isCompressed:!1}}}var wt=class{constructor(e){this.logger=l.getInstance(),this.config=e.config,this.sendBatch=e.sendBatch,this.encodeAsync=e.encodeAsync??null}compressAsync(e,t){if(!this.encodeAsync)return Promise.resolve(bt(e,t));try{return this.encodeAsync(e,t).catch((()=>bt(e,t)))}catch{return Promise.resolve(bt(e,t))}}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const r=n.apiKey,s=this.buildEndpoint();if(!r)return void this.logger.log("No API key found");const i=JSON.stringify(e),o=!!n?.options?.transport?.compression,{data:a,isCompressed:l}=t?bt(i,o):await this.compressAsync(i,o),c={"Content-Type":"application/json",apikey:r,"Content-Encoding":l?"gzip":""};this.sendBatch(s,{method:"POST",headers:c,body:a}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n?.options?.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},kt=class{constructor(e){this.storage=e}getItem(e){try{return this.storage?.getItem(e)??null}catch(e){return h(e),null}}setItem(e,t){try{this.storage?.setItem(e,t)}catch(e){h(e)}}removeItem(e){try{this.storage?.removeItem(e)}catch(e){h(e)}}getNumericItem(e,t=0){const n=this.getItem(e);if(null===n)return t;const r=Number(n);return Number.isFinite(r)?r:t}},Et=class{constructor(e){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage=e.storage,this.getMaxDurationMs=e.getMaxDurationMs??null}getSessionId(){if(this.sessionId)return this.sessionId;return this.storage.getItem("gcId")||""}setSessionId(e){this.sessionId=e,this.storage.setItem("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:this.storage.getNumericItem("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,this.storage.setItem("gcStartTime",String(e)),this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcLastActivity")}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:this.storage.getNumericItem("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,this.storage.setItem("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs(),n=t>0?t:Se(this.getSessionStartTime());return n>0&&e-n>=Ue}hasUserActivity(){return this.getLastActivityMs()>0}clearSamplingDecision(){this.storage.removeItem(Ke)}clearSessionState(){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcId"),this.storage.removeItem("gcStartTime"),this.storage.removeItem("gcLastActivity"),this.clearSamplingDecision()}getSessionMaxDuration(){return this.getMaxDurationMs?.()??He}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-Se(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}};function St(){const e=navigator.userAgent;let t="unknown",n="unknown";const r=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{userAgent:e,browser:{name:t,version:n,platform:r,language:navigator.language,mobile:s}}}var It,Tt,Rt=["navigation","dom.event"],At=class{constructor(e){this.core=null,this.hideWired=!1,this.hideHandler=()=>{try{if("undefined"==typeof document||"hidden"!==document.visibilityState)return;this.core?.session.persistLastActivity(),this.core?.instrumentation.flushPendingReplay(),this.core?.pool.flush({lifecycle:!0})}catch(e){h(e)}},this.logger=l.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.storage=new kt(function(){try{return void 0!==globalThis.sessionStorage?globalThis.sessionStorage:null}catch{return null}}()),this.idGenerator=new d;const t=new ut(gt);t.initialize(e);const n=new Et({storage:this.storage,getMaxDurationMs:()=>t.getConfig()?.options?.sessionMaxDuration});!function({session:e,idGenerator:t,providedSessionId:n}){const r=l.getInstance();try{const s=e.getSessionId();n&&n!==s?(e.setSessionId(n),e.setSessionStartTime(Ee(Date.now())),e.clearSamplingDecision(),r.log("[session-bootstrap] using provided sessionId:",n)):n?(e.setSessionId(n),r.log("[session-bootstrap] continuing provided sessionId:",n)):s||e.setSessionId(t.generateId());const i=6e4,o=Date.now(),a=Se(e.getSessionStartTime());if(a>0&&o-a>=-i){if(e.isSessionExpired(o)||e.isSessionInactive(o)){const n=e.isSessionExpired(o)?"persisted session past cap":"inactivity gap across restart",s=e.getSessionId(),i=t.generateId();e.setSessionId(i),e.setSessionStartTime(Ee(o)),e.clearSamplingDecision(),r.log(`[session-bootstrap] init-time rotation: ${n}`,{from:s,to:i})}}else e.setSessionStartTime(Ee(o))}catch(e){r.log("[session-bootstrap] session bootstrap failed:",e)}}({session:n,idGenerator:this.idGenerator,providedSessionId:e.sessionId});if(!function({storage:e,sessionSampleRate:t}){const n=l.getInstance();if(void 0===t||!Number.isFinite(t)||1===t)return!0;const r=t;try{const t=e.getItem(Ke);if(t){const e="1"===t;return n.log("[session-bootstrap] using stored sampling decision:",e),e}const s=Math.random()<r;return e.setItem(Ke,s?"1":"0"),n.log("[session-bootstrap] stored new sampling decision:",s),s}catch(e){n.log("[session-bootstrap] storage access failed:",e);const t=Math.random()<r;return n.log("[session-bootstrap] using fallback sampling decision:",t),t}}({storage:this.storage,sessionSampleRate:e.options?.sessionSampleRate}))return void this.logger.log("[session-manager] session is not sampled");const r=new wt({config:t,sendBatch:(e,t)=>fetch(e,t),encodeAsync:(e,t)=>Fe.withFallback((n=>n.encodeBatch(e,t)),(()=>bt(e,t)),"transporter")}),s=new vt({config:t,session:n,transporter:r,getDeviceAttributes:St,eventsToSkipFlush:Rt}),i=function(e){return()=>{let t="";try{t=F?.document?.title||""}catch(e){h(e)}try{const n=F?.location;if(!n)return{path:"",url:"",title:t};const r=n.hash&&!n.hash.match(/^#[a-z0-9-]+$/i)&&n.hash.startsWith("#/"),s=r?n.hash:n.pathname,i=e.getPrivacy(),o=i.shouldMaskNetworkQueryParams,a={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:o&&r?N(s,a):s,url:o?N(n.href,a):n.href,title:t}}catch(e){return h(e),{path:"",url:"",title:t}}}}(t),o=new yt({enrichAttributes:()=>({location:i()}),reservedAttributeKeys:["location"],isOpaqueNode:dt,idGenerator:this.idGenerator}),a=new Ze({config:t,session:n,eventsPool:s,enricher:o});try{s.initialize(),Fe.getInstance(),this.wireHideHandler(),a.instrument(),this.core={config:t,session:n,pool:s,instrumentation:a}}catch(e){this.logger.log("[session-manager] initialization failed — tearing down partial startup:",e);try{a.uninstrument()}catch(e){h(e)}throw s.destroy(),this.unwireHideHandler(),this.core=null,e}}wireHideHandler(){if(!this.hideWired&&"undefined"!=typeof document){this.hideWired=!0;try{document.addEventListener("visibilitychange",this.hideHandler)}catch(e){h(e)}}}unwireHideHandler(){if(this.hideWired&&"undefined"!=typeof document){this.hideWired=!1;try{document.removeEventListener("visibilitychange",this.hideHandler)}catch(e){h(e)}}}identifyUser(e){this.logger.log("[session-manager] identifyUser called"),this.core?this.core.config.updateConfig({user:e}):this.logger.log("[session-manager] cannot identify user: SDK not initialized")}updateConfig(e){try{if(null===e||"object"!=typeof e)return void u("[groundcover] updateConfig requires a configuration object; the update was ignored.");if("appId"in e)return void u("[groundcover] updateConfig does not accept appId; the entire update was ignored. Remove appId from the update.");if(!this.core)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");this.core.config.updateConfig(e);const t=e.options,n=!!t&&Object.hasOwn(t,"privacy"),r=t&&Object.hasOwn(t,"replay")&&"object"==typeof t.replay&&null!==t.replay?t.replay:void 0,s=!!r&&Object.hasOwn(r,"blockedSelectors"),i=!!r&&Object.hasOwn(r,"canvas");(n||s||i)&&this.core.instrumentation.restartReplayForConfigChange()}catch(e){h(e)}}sendCustomEvent(e){this.core?this.core.instrumentation.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.core?this.core.instrumentation.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.core?this.core.instrumentation.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.core?this.core.instrumentation.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}emitLog(e,t,n){this.core?this.core.instrumentation.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.core?this.core.session.getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.core)try{this.core.instrumentation.flushPendingReplay(),await this.core.pool.flushSync();const t=e||this.idGenerator.generateId();this.core.session.setSessionId(t),this.core.session.setSessionStartTime(Ee(Date.now())),this.logger.log("[session-manager] session ID set successfully:",t)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.core?this.core.instrumentation.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.core?this.core.instrumentation.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){const e=this.core;e&&(e.instrumentation.uninstrument(),e.pool.destroy(),this.unwireHideHandler(),Fe.getInstance().terminate(),e.session.clearSessionState(),this.core=null)}},Lt=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var xt={init:function(e){if(void 0===Tt)try{const t=e?.appId;if(void 0!==Tt)return;if("string"!=typeof t||0===t.trim().length)return void u("[groundcover] init requires a nonblank appId; the SDK was not initialized.");Tt=t,It=new At({cluster:e.cluster||"",environment:e.environment||"",namespace:e.namespace,releaseId:e.releaseId,dsn:e.dsn||"",appId:t,user:e.user,apiKey:e.apiKey||"",options:e.options,sessionId:e.sessionId}),Lt.manager=It}catch(e){It||(Tt=void 0),h(e)}},identifyUser:function(e){It?It.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){It&&It.sendCustomEvent(e)},captureException:function(e,t){It&&It.captureException(e,t)},logger:Lt,updateConfig:function(e){if(It)try{It.updateConfig(e)}catch(e){h(e)}},startNavigation:function(e){It?It.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){It?It.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return It?It.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(It)try{await It.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){It?It.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){It?It.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=xt}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var Ct=xt;module.exports=Ct;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import e from"error-stack-parser";import{onCLS as t,onLCP as n,onFCP as r,onTTFB as s,onINP as i}from"web-vitals";import{record as o}from"rrweb";import{pack as a}from"@rrweb/packer";import{strToU8 as l,gzipSync as c}from"fflate";var h=console.log.bind(console),u=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&h(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},d=u.getInstance();function g(e){d.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}function f(e){try{console.warn(`${e} (groundcoverIgnore)`)}catch{}}var p=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)v[e]=Math.floor(16*Math.random())+48,v[e]>=58&&(v[e]+=39);return y+String.fromCharCode.apply(null,v.slice(0,16))},this.generateSpanId=m(8),this.generateId=m(16)}},v=Array(32);function m(e){return function(){for(let t=0;t<2*e;t++)v[t]=Math.floor(16*Math.random())+48,v[t]>=58&&(v[t]+=39);return String.fromCharCode.apply(null,v.slice(0,2*e))}}var y="0000000000000000";function b({text:e,maxLength:t=1e4,ellipsis:n=""}){if(null==e)return"";const r="string"==typeof e?e:String(e);return r.length<=t?r:r.substring(0,t)+n}function w(e){return(e||"").replace(/\s+/g," ").trim()}var E="[REDACTED]",k=["authorization","cookie","set-cookie"],S=/(token|key|secret|passwd|password|auth|bearer|credential)/i,I=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,T=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),R=1e5;function L(e,t){if(!e)return!1;if(I.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function x(e,t){return T.has(e.toLowerCase())||L(e,t)}function A(e){return e.includes("-")&&S.test(e)}function N(e,t){return L(e,t)||A(e)}function M(e,t){const n=e.sensitive?E:e.value;if(!t)return n;try{const r=t(e);return void 0===r?n:r}catch(e){return g(e),n}}function C(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const r=e.slice(0,n),s=e.slice(n+1);let i=r;try{i=decodeURIComponent(r)}catch{}let o=s;try{o=decodeURIComponent(s)}catch{}const a=x(i,t.sensitiveKeys),l=M({key:i,value:o,path:[i],kind:t.kind??"query",sensitive:a},t.redact);return l===o?e:`${r}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function q(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${C(e.slice(n+1),t)}`}function O(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},r=e.indexOf("#"),s=-1===r?e:e.slice(0,r),i=-1===r?"":e.slice(r+1),o=q(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${E}@`))}(s),n);return-1===r?o:`${o}#${q(i,n)}`}function z(e,t,n,r,s,i){const o=!!e&&L(e,r.sensitiveKeys);if(null!==t&&"object"==typeof t){if(o||s>8)return E;if(function(e,t){if(!e.isOpaqueNode)return!1;try{return e.isOpaqueNode(t)}catch{return!0}}(r,t))return E;if(i.has(t))return E;i.add(t);try{if(Array.isArray(t))return t.map((t=>z(e,t,n,r,s+1,i)));const o={};for(const[e,a]of Object.entries(t))o[e]=z(e,a,[...n,e],r,s+1,i);return o}catch(e){return g(e),E}finally{i.delete(t)}}return M({key:e,value:t,path:n,kind:r.kind??"log",sensitive:o},r.redact)}function _(e,t={}){if(!e)return e;if(e.length>R)return`${_(e.slice(0,R),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>N(n,t.sensitiveKeys)?`"${n}":"${E}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return x(e,t)||A(e)}(n,t.sensitiveKeys)?`${n}=${E}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>N(n,t.sensitiveKeys)?`${n}: ${E}`:e))}catch(t){g(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){g(e)}return n}function D(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=R&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(z("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?C(e,t):_(e,t)}function P(e,t={}){try{const n=z("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return g(e),{}}}function F(e,t){return"allow"!==t.level&&e?P(e,{sensitiveKeys:t.sensitiveKeys,redact:t.redact,isOpaqueNode:t.isOpaqueNode}):e}function j(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const r={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log",isOpaqueNode:e.isOpaqueNode};return{message:_(t,r),attributes:n?P(n,r):n}}var H=class{constructor(e){this.logger=u.getInstance(),this.config=e.config,this.pool=e.pool,this.enricher=e.enricher}sendCustomEvent(e){this.logger.log("[manual-event-emitter.sendCustomEvent] called",e);try{const t=this.enricher.enrich({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.pool.addEvent(t)}catch(e){g(e)}}emitLog(e,t,n){this.logger.log("[manual-event-emitter.emitLog] called",{message:e,level:t,attributes:n});try{const r={...n||{}};delete r.message,delete r.level;for(const e of this.enricher.reservedAttributeKeys)delete r[e];const{message:s,attributes:i}=j(this.config.getPrivacy(),e,r),o=this.enricher.enrich({type:"log",attributes:{...i,message:b({text:s}),level:t}});this.pool.addEvent(o)}catch(e){g(e)}}},B=globalThis,U=class{constructor(e){this.logger=u.getInstance(),this.config=e.config,this.eventsPool=e.eventsPool,this.enricher=e.enricher}};function K(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function Y(e){const t=e.getPrivacy(),n=e.getConfig()?.providedOptions?.privacy;return{...t,maskSelectors:K(n?.maskSelectors)}}var $="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function W(e,t){try{return e.getAttribute(t)||""}catch{return""}}function Q(e){try{const t=$?.call(e);return"string"==typeof t?t:""}catch{return""}}function G(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function X(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>W(e,t))).filter(Boolean)}(e).some((e=>L(e,t))))}function J(e,t){return"allow"!==t.level&&(!!e&&(!!G(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>G(e,t))))||("mask-all"===t.level||function(e){const t=Q(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&X(e,t.sensitiveKeys)))))}var V={role:"",accessibleName:"",ariaLabel:"",title:"",alt:"",placeholder:"",name:"",inputType:"",href:""},Z=["button","a","input","select","textarea","label","summary",'[role~="button"]','[role~="link"]','[role~="menuitem"]','[role~="menuitemcheckbox"]','[role~="menuitemradio"]','[role~="tab"]','[role~="checkbox"]','[role~="radio"]','[role~="switch"]','[role~="option"]','[role~="treeitem"]','[role~="slider"]','[role~="spinbutton"]','[role~="combobox"]','[role~="textbox"]','[role~="searchbox"]'].join(", "),ee=[Z,"li","option","tr","td","th",'[role~="listitem"]','[role~="row"]','[role~="gridcell"]','[role~="cell"]'].join(", ");function te(e){return!!e&&1===e.nodeType}function ne(e){const t=Q(e).toLowerCase();return"body"===t||"html"===t}function re(e){return b({text:e,maxLength:255})}function se(e){return b({text:e,maxLength:99,ellipsis:"…"})}function ie(e){const t=w(W(e,"role"));return t?t.split(" ")[0]??t:function(e){switch(Q(e).toLowerCase()){case"a":return W(e,"href")?"link":"";case"button":return"button";case"input":switch(W(e,"type").toLowerCase()){case"checkbox":return"checkbox";case"radio":return"radio";case"submit":case"button":case"reset":return"button";case"range":return"slider";case"number":return"spinbutton";default:return"textbox"}case"textarea":return"textbox";case"select":return"combobox";case"img":return"img";case"nav":return"navigation";case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"heading";default:return""}}(e)}function oe(e){if(!te(e))return"";try{if(ne(e))return"";if(function(e){try{return e.querySelectorAll(ee).length>=2}catch{return!1}}(e))return"";const t=w(e.textContent||"");return t?t.length>1e3?"":b({text:t,maxLength:255}):""}catch{return""}}function ae(e){return W(e,"aria-labelledby").split(/\s+/).filter(Boolean).slice(0,5)}function le(e,t){if(ne(e))return"";const n=function(e){const t=[];for(const n of ae(e))try{const e=oe(document.getElementById(n));e&&t.push(e)}catch{}return w(t.join(" "))}(e);if(n)return se(n);const r=w(W(e,"aria-label"));if(r)return se(r);const s=w(W(e,"alt"));if(s)return se(s);if(function(e){const t=Q(e).toLowerCase();if("button"===t)return!0;if("input"!==t)return!1;const n=W(e,"type").toLowerCase();return"submit"===n||"button"===n||"reset"===n}(e)){const t=w(W(e,"value"));if(t)return se(t)}const i=t??oe(e);if(i)return se(i);const o=w(W(e,"title"));if(o)return se(o);const a=w(W(e,"placeholder"));return a?se(a):""}function ce(e,t){if("allow"===t.level)return!1;try{return!!e.querySelector("[data-private]")||t.maskSelectors.some((t=>{try{return null!=e.querySelector(t)}catch{return!1}}))}catch{return!1}}var he=class extends U{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>J(e.target,Y(this.config)),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){g(e)}};this.eventHandlers.push({type:e,handler:t}),B?.addEventListener(e,t)}))}catch(e){g(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){g(e)}}buildEvent(e){const t=this.getCoordinates(e),n=e.target,r=function(e){if(!te(e))return null;try{return e.closest(Z)}catch{return null}}(n)??n,s=Y(this.config),i=this.getShouldMaskText({target:n||null})||!!r&&(ce(r,s)||function(e,t){if("allow"===t.level)return!1;try{for(const n of ae(e)){const e=document.getElementById(n);if(e&&oe(e)&&(J(e,t)||ce(e,t)))return!0}}catch{}return!1}(r,s)),o=r?this.generateSelector(r,i?{priorityAttributes:["id","class","name","type"]}:{}):"",a=this.getKeyCode(e,i),l=oe(r),c=function(e,t){if(!te(e))return{...V};try{return{role:re(ie(e)),accessibleName:le(e,t),ariaLabel:re(w(W(e,"aria-label"))),title:re(w(W(e,"title"))),alt:re(w(W(e,"alt"))),placeholder:re(w(W(e,"placeholder"))),name:re(W(e,"name")),inputType:re(W(e,"type")),href:re(W(e,"href"))}}catch{return{...V}}}(r,l),h=s.shouldMaskNetworkQueryParams?O(c.href,{sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"}):c.href,u=e=>i&&e?"*":e;this.logger.log("[dom-events-listener.buildEvent] called");const d={dom_event_selector:o,dom_event_key_code:a,dom_event_type:e.type,dom_event_coordinates:t||{clientX:0,clientY:0},dom_event_target:{id:W(r,"id"),tagName:Q(r),className:W(r,"class"),text:i?"*":l,role:c.role,accessibleName:u(c.accessibleName),ariaLabel:u(c.ariaLabel),title:u(c.title),alt:u(c.alt),placeholder:u(c.placeholder),name:c.name,inputType:c.inputType,href:u(h)}};return this.enricher.enrich({type:"dom.event",attributes:d})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,r=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===Q(e).toLowerCase())return"html";let i="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<r;){let e=Q(a).toLowerCase();try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=Q(a).toLowerCase()||"*"}l.unshift(e||"*"),i=l.join(" > ");try{if(1===n.querySelectorAll(i).length)return i}catch(e){l.shift(),i=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return i||"*"}},ue=["log","info","warn","error","debug","assert","trace"],de=class extends U{constructor(){super(...arguments),this.originalConsole=null,this.patchedConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods();const e={};ue.forEach((t=>{if(!(t in console))return;const n=(...e)=>{try{this.isInitialized&&this.handleEvent(e,t)}catch(e){g(e)}finally{this.originalConsole?.[t]&&this.originalConsole[t](...e)}};console[t]=n,e[t]=n})),this.patchedConsole=e,this.isInitialized=!0}catch(e){g(e)}}destroy(){try{if(!this.isInitialized)return;ue.forEach((e=>{this.originalConsole?.[e]&&this.patchedConsole?.[e]&&console[e]===this.patchedConsole[e]&&(console[e]=this.originalConsole[e])})),this.patchedConsole=null,this.isInitialized=!1}catch(e){g(e)}}handleEvent(e,t){try{const n=Array.isArray(e)?e:[e];if("assert"===t&&n[0])return;const r=this.formatMessage(n,t);if(!r||r?.includes("groundcoverIgnore"))return;const s=this.extractAttributes(n),i=this.buildEvent({message:r,level:t,attributes:s});this.queueEvent(i)}catch(e){g(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:r,attributes:s}=j(this.config.getPrivacy(),e,n);return this.enricher.enrich({type:"log",attributes:{...s,message:b({text:r}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);delete t.message,delete t.level;for(const e of this.enricher.reservedAttributeKeys)delete t[e];return t}catch(e){return void g(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return g(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{ue.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){g(e)}return e}},ge=class{constructor(){this.installed=[]}install(e){const t=e,n=[],r=[];try{for(const e of t){const t=e.get();r.push({spec:e,original:t});const s=e.wrap(t);e.set(s),n.push({spec:e,original:t,wrapped:s})}return this.installed.push(...n),!0}catch(e){for(const{spec:e,original:t}of r.reverse())try{e.get()!==t&&e.set(t)}catch{}return g(e),!1}}restore(){const e=this.installed;this.installed=[];for(const{spec:t,original:n,wrapped:r}of e.reverse())try{t.get()===r&&t.set(n)}catch(e){g(e)}}get isEmpty(){return 0===this.installed.length}},fe="[request body too large]",pe="[request body unavailable]",ve="[response body too large]",me="[response body unavailable]",ye="[unreadable response body]",be="[form data]",we="[binary data]";function Ee(e){return(e.split(";")[0]||"").trim().toLowerCase()}function ke(e){const t=(e||"").toLowerCase();return t.includes("multipart/form-data")?be:function(e){const t=Ee(e);return!!t&&(!!t.startsWith("text/")||"application/x-www-form-urlencoded"===t||"application/javascript"===t||"application/ecmascript"===t||"application/graphql"===t||/^application\/([\w.-]+\+)?(json|xml)$/.test(t))}(t)?null:function(e){const t=Ee(e);return t.startsWith("image/")?"[image data]":t.startsWith("audio/")?"[audio data]":t.startsWith("video/")?"[video data]":t.startsWith("font/")||t.startsWith("application/font")||"application/vnd.ms-fontobject"===t?"[font data]":"application/pdf"===t?"[pdf data]":"application/zip"===t||"application/gzip"===t||"application/x-gzip"===t||"application/x-tar"===t||"application/x-7z-compressed"===t||"application/x-rar-compressed"===t?"[archive data]":"application/wasm"===t?"[wasm data]":t.includes("protobuf")||t.startsWith("application/grpc")?"[protobuf data]":we}(t)}function Se(e,t,n){return e&&(e.length>=t||function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=2;else if(r>=55296&&r<=56319){const r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=4,n++):t+=3}else t+=3}return t}(e)>=t)?n:e}var Ie=1e6;function Te(e){return e*Ie}function Re(e){return e/Ie}function Le(e){return"string"==typeof e&&/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}function xe(e,t){const n="allow"===t.level,r=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,r])=>{const s=n.toLowerCase(),i=M({key:n,value:r,path:[n],kind:"header",sensitive:k.includes(s)||S.test(s)||L(n,t.sensitiveKeys)},t.redact);return e[n]=null===i?"":String(i),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact}),s={};for(const[e,t]of Object.entries(r))s[e]=b({text:t});return s}function Ae(e,t){const{privacy:n}=t,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"query"};let{path:s,fullUrl:i}=t.resolveUrl(e.url);n.shouldMaskNetworkQueryParams&&(s=O(s,r),i=O(i,r));const o=e.method?.toUpperCase()||"UNKNOWN",a=e.method||"UNKNOWN",l=e.status?.toString(),{traceId:c,spanId:h}=function(e,t){const n={};for(const t of Object.keys(e))n[t.toLowerCase()]=e[t];const r=e=>{if(!e)return"";const t=n[e.toLowerCase()];return"string"==typeof t?t:""};let s=r(t?.traceIdHeaderName),i=r(t?.spanIdHeaderName);if(!s||!i){let e="";for(const n of t?.propagationHeaders??[])if(e=r(n),e)break;e||(e=r("traceparent"));const n=e.split("-");4===n.length&&"00"===n[0]&&(s||32!==n[1]?.length||(s=n[1]),i||16!==n[2]?.length||(i=n[2]))}return{traceId:s,spanId:i}}(e.request.headers,t.tracing),u=(e,r)=>b({text:n.shouldMaskNetworkBodies?D(e,{sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:r}):e,maxLength:t.maxBodyLength}),d={type:"HTTP",operation:{name:o},resource_name:s,status:l,subType:o,url:{full:i},http:{route:s,path:s,method:a,status:l,request:{headers:xe(e.request.headers,n),method:a},response:{headers:xe(e.response.headers,n),status_code:l}},error:e.error?.type?{type:e.error.type}:void 0,gc:{request:{body:u(e.request.body,"request-body")},response:{body:u(e.response.body,"response-body")}}},g={type:"network",timestamp:Ne(e.timestamp),end_timestamp:Ne(e.end_time),span_name:`${o} ${s}`,attributes:d};return c&&(g.traceId=c),h&&(g.spanId=h),g}function Ne(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Te(e):void 0}function Me(e){return function(e){try{return 9===e?.nodeType}catch{return!1}}(e)?"[document data]":function(e){try{if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof FormData&&e instanceof FormData)return"[form data]";if("undefined"!=typeof Blob&&e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if(ArrayBuffer.isView(e))return"[arraybuffer data]";if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return"[stream data]";if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return g(`Failed to format body: ${e}`),"[unreadable body]"}}(e)}var Ce=[".tsx",".jsx",".css"],qe=e=>Ce.some((t=>e.toLowerCase().endsWith(t))),Oe=class extends U{constructor(){super(...arguments),this.maxBodyLength=5e3,this.requestBodyReadTimeoutMs=3e3,this.responseBodyReadTimeoutMs=3e3,this.idGenerator=new p,this.patches=new ge,this.active=!1,this.handleEvent=e=>{try{if(!this.active)return;if(this.shouldIgnoreRequest(e.url))return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){g(e)}},this.buildEvent=e=>(this.logger.log("[network-events-listener.buildEvent] called",{event:e}),this.enricher.enrich(Ae(e,{privacy:this.config.getPrivacy(),maxBodyLength:this.maxBodyLength,tracing:this.config.getConfig()?.options?.tracing,resolveUrl:e=>{try{return{path:new URL(e).pathname,fullUrl:e}}catch{return{path:e,fullUrl:new URL(e,globalThis.location.href).href}}}})))}async readBodyStreamCapped(e,t={}){if(!e)return"";const{timeoutMs:n,overflowPlaceholder:r,timeoutPlaceholder:s}=t,i=e.getReader(),o=new TextDecoder;let a,l="",c=0,h=!1,u=!1;const d=null!=n?new Promise((e=>{a=setTimeout((()=>e({timedOut:!0})),n)})):void 0;try{for(;;){const e=d?await Promise.race([i.read(),d]):await i.read();if("timedOut"in e){u=!0;break}const{done:t,value:n}=e;if(t)break;if(c+n.byteLength>=this.maxBodyLength){const e=n.subarray(0,this.maxBodyLength-c);l+=o.decode(e,{stream:!0}),h=!0;break}c+=n.byteLength,l+=o.decode(n,{stream:!0})}return l+=o.decode(),u&&null!=s?s:h&&null!=r?r:l}finally{clearTimeout(a);try{i.cancel()?.catch((()=>{}))}catch{}}}async getRequestBody(e,t){try{if(!e.body)return"";const n=ke(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.requestBodyReadTimeoutMs,overflowPlaceholder:fe,timeoutPlaceholder:pe})}catch{return pe}}async getResponseBody(e){if(!e.body)return"";const t=e.headers?.get?.("content-type")??"";if(function(e){return"text/event-stream"===Ee(e||"")}(t))return ye;const n=ke(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.responseBodyReadTimeoutMs,overflowPlaceholder:ve,timeoutPlaceholder:me})}initialize(){this.logger.log("[network-events-listener.initialize] called");const e=this.patches.install(this.xhrPatches()),t=this.patches.install([this.fetchPatch()]);this.active=e||t}destroy(){this.active=!1,this.patches.restore()}shouldIgnoreRequest(e){try{const t=this.config.getConfig();return function(e,t){try{return!(!t.endpoint||!e.includes(t.endpoint))||!!t.extraIgnore?.(e)||(t.excludedUrls??[]).some((t=>t instanceof RegExp?t.test(e):"string"==typeof t&&(t.includes("*")||t.includes("?"))?new RegExp(t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")).test(e):e===t))}catch(e){return g(e),!1}}(e,{endpoint:t?.getEndpoint(),excludedUrls:t?.options?.excludedUrls,extraIgnore:qe})}catch(e){return g(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}xhrPatches(){const e=this,t=globalThis.XMLHttpRequest.prototype;let n;return[{get:()=>t.open,set:e=>{t.open=e},wrap:t=>function(r,s,i=!0,o,a){if(!e.active)return t.apply(this,[r,s,i,o,a]);if(n=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[r,s,i,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=r,this._requestUrl=l,this._requestHeaders={},t.apply(this,[r,s,i,o,a])}},{get:()=>t.setRequestHeader,set:e=>{t.setRequestHeader=e},wrap:t=>function(n,r){return e.active?(this._requestHeaders&&(this._requestHeaders[n]=r),t.apply(this,[n,r])):t.apply(this,[n,r])}},{get:()=>t.send,set:e=>{t.send=e},wrap:t=>function(...r){if(!e.active)return t.apply(this,r);const s=this._requestUrl?.toString();if(!s||e.shouldIgnoreRequest(s))return t.apply(this,r);if(e.shouldAddTraceHeader(s))for(const[t,n]of Object.entries(e.buildTraceHeaders()))e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n});return this._requestBody=r[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),r={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,n]=e.split(": ");t&&n&&(r[t.trim()]=n.trim())}));const s=Se(Me(this._requestBody),e.maxBodyLength,fe),i=""===this.responseType||"text"===this.responseType,o=i?this.responseText:this.response,a=(i?ke(r["content-type"]||""):null)??Se(Me(o),e.maxBodyLength,ve),l={timestamp:n,end_time:t,method:this._requestMethod,url:this._requestUrl,status:this.status,request:{headers:this._requestHeaders||{},body:s},response:{headers:r,body:a}};e.handleEvent(l)})),t.apply(this,r)}}]}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){for(const[t,n]of Object.entries(this.buildTraceHeaders()))this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n})}buildTraceHeaders(){return function(e,t){const n={},r=(e,t)=>{Le(e)&&(n[e]=t)};e?.origin?.name&&r(e.origin.name,e.origin.value),e?.traceIdHeaderName&&r(e.traceIdHeaderName,t.decimalTraceId),e?.spanIdHeaderName&&r(e.spanIdHeaderName,t.decimalSpanId);const s=e?.propagationHeaders,i=s?.length?s:["traceparent"];for(const e of i)r(e,t.traceparent);return n}(this.config.getConfig()?.options?.tracing,function(e){const t=e.generateSpanId(),n=e.generateTraceId();let r,s;try{r=BigInt("0x"+n).toString(10),s=BigInt("0x"+t).toString(10)}catch{r=n,s=t}return{traceparent:`00-${n}-${t}-01`,traceId:n,spanId:t,decimalTraceId:r,decimalSpanId:s}}(this.idGenerator))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}fetchPatch(){return{get:()=>globalThis.fetch,set:e=>{globalThis.fetch=e},wrap:e=>(...t)=>{if(!this.active)return e.apply(globalThis,t);const n=Date.now();let[r,s]=t;s={...s||{}},t[1]=s;const i=r instanceof Request,o=s?.method||(i?r.method:"GET"),a=r instanceof Request?r.url:r.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);s.headers=this.normalizeHeaders(i?r.headers:void 0,s.headers),l&&this.addTraceHeaders(s);const c=this.extractHeadersRecord(s.headers),h=null!=s?.body?Se(Me(s.body),this.maxBodyLength,fe):"",u=null!=s?.body?Promise.resolve(h):i?this.getRequestBody(r,"content-type"in c?c["content-type"]:r.headers.get("content-type")??""):Promise.resolve("");let d;return u.then((e=>{d=e})).catch((()=>{})),e.apply(globalThis,t).then((e=>{const t=Date.now(),r={};e.headers.forEach(((e,t)=>{r[t]=e}));const s={method:o,url:a,timestamp:n,status:e.status,end_time:t,request:{headers:c,body:""},response:{headers:r,body:""}},i=()=>{u.then((e=>{s.request.body=e,this.handleEvent(s)}))};return this.getResponseBody(e).then((e=>{s.response.body=e,i()})).catch((e=>{s.response.body=ye,i(),this.logger.log("[network-events-listener.fetch] response body error",{error:e})})),e})).catch((e=>{const t=Date.now();let r="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?r="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?r="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(r="ERR_CONNECTION_REFUSED");const i={method:o,url:a,timestamp:n,status:0,end_time:t,request:{headers:c,body:d??h},response:{headers:{},body:""},error:{type:r}};throw this.handleEvent(i),e}))}}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),Le(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),Le(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}shouldAddTraceHeader(e){const t=(n=this.propagationCandidates(e),r=this.config.getConfig()?.options?.tracing?.propagationUrls,!!r?.length&&r.some((e=>{try{if("string"!=typeof e)return!1;const t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),r=new RegExp(`^${t}$`);return n.some((e=>r.test(e)))}catch{return!1}})));var n,r;return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:t}),t}propagationCandidates(e){try{const t=globalThis.location.href,n=new URL(e,t),r=[n.href];return"/"!==n.pathname||n.search||n.hash||r.push(n.href.slice(0,-1)),n.origin===new URL(t).origin&&r.push(n.pathname),r}catch{return[e]}}};function ze(t){try{return e.parse(t).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch{return[]}}var _e=class extends U{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const r=this.buildEvent(n,t);this.queueEvent(r)}catch(e){g(e)}}}initialize(){B?.addEventListener("error",this.handleEvent),B?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){B?.removeEventListener("error",this.handleEvent),B?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return this.enricher.enrich(function(e,t,n){const r=n.shouldMaskErrors,s={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error",isOpaqueNode:n.isOpaqueNode},i=e.message||"Unknown error",o=r?_(i,s):i,a=r&&t?.metadata?P(t.metadata,s):t?.metadata;return{type:"exception",attributes:{error_type:e.name||"Error",error_message:o,error_stacktrace:ze(e),error_fingerprint:`${e.name}:${b({text:o,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:a}}}(e,t,this.config.getPrivacy()))}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}enhanceError(e,t){const{filename:n,lineno:r,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),r&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:r}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}},De=class extends U{constructor(e,{isEnabled:t}){if(super(e),this.currentUrl="",this.patches=new ge,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&t)try{this.isAutomaticNavigationEnabled=t,this.currentUrl=B.location.href}catch(e){g(e)}}isInBrowserEnvironment(){try{return void 0!==B&&void 0!==B.location&&void 0!==B.history&&"function"==typeof B.addEventListener}catch(e){return g(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||"function"!=typeof history.pushState||"function"!=typeof history.replaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");this.patches.install([this.historyPatch("pushState"),this.historyPatch("replaceState")]),B&&"function"==typeof B.addEventListener&&(B.addEventListener("popstate",this.popStateHandler),B.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){g(e)}}historyPatch(e){return{get:()=>history[e],set:t=>{history[e]=t},wrap:e=>(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n}}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.patches.restore(),B&&"function"==typeof B.removeEventListener&&(B.removeEventListener("popstate",this.popStateHandler),B.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){g(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){g(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",B.location.href);const e=this.config.getPrivacy(),t=B.location.href,n=this.activeNavigation?.metadata,r={page_url:e.shouldMaskNetworkQueryParams?O(t,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):t,metadata:F(n,e),duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0};return this.enricher.enrich({type:"navigation",attributes:r})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}startNavigation(e){try{this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:B?.location?.href||"",metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}catch(e){g(e)}}endNavigation(e){try{if(this.logger.log("[navigation-listener.endNavigation] called",e),!this.activeNavigation)return void this.logger.log("[navigation-listener.endNavigation] no active navigation found");this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()}catch(e){g(e)}}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===B.location.href)return;let e,t;try{e=new URL(B.location.href),t=new URL(this.currentUrl)}catch(e){return void g(e)}const n=e=>e.startsWith("#/"),r=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||r&&e.hash!==t.hash)&&(this.currentUrl=B.location.href,this.handleEvent())}catch(e){g(e)}}},Pe=class extends U{constructor(e){super(e),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",B),"complete"===B?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):B?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),g(e)}}destroy(){B?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){g(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),r={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,i=t.initiatorType;r.totalSize+=n,r.totalDuration+=s,r.byType[i]||(r.byType[i]={count:0,size:0,duration:0}),r.byType[i].count++,r.byType[i].size+=n,r.byType[i].duration+=s}));const s=this.config.getPrivacy(),i=s.shouldMaskNetworkQueryParams,o={sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"},a=B?.location?.href||"",l=B?.document?.referrer||"",c={page_url:i?O(a,o):a,page_load_time:t,page_referrer:i?O(l,o):l,page_resources:r};return this.enricher.enrich({type:"pageload",attributes:c})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}},Fe=class extends U{constructor(){super(...arguments),this.handleEvent=e=>{try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){g(e)}}}initialize(){t(this.handleEvent),n(this.handleEvent),r(this.handleEvent),s(this.handleEvent),i(this.handleEvent)}destroy(){}buildEvent(e){const t={performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""};return this.enricher.enrich({type:"performance",attributes:t})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){g(e)}}},je=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=u.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,r){const s=e.getInstance();if(!s.isAvailable)return n();try{return await t(s)}catch(e){return u.getInstance().log(`[${r}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,r=this.worker;return new Promise(((s,i)=>{const o=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),i(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:s,reject:i,timeoutId:o});try{r.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(o),this.pending.delete(n),i(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};je.instance=null;var He=je;var Be=class{constructor(e){this.logger=u.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0;const e=this.configManager.getConfig()?.options,t=e?.replay,n=t?.blockedSelectors?.filter(Boolean),r=n?.length?n.join(", "):void 0,s=Y(this.configManager),i=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=K(t?.maskSelectors),i=t?.replay,o="function"==typeof i?.maskTextFn?i.maskTextFn:void 0,a="function"==typeof i?.maskInputFn?i.maskInputFn:void 0;let l;return l="mask-all"===n||!r&&void 0!==o?["*",...s].join(", "):"mask-sensitive"===n?["[data-private]",...s].join(", "):void 0,{maskTextSelector:l,maskAllInputs:!r,maskTextFn:o,maskInputFn:a}}(this.configManager.getConfig()?.providedOptions),a=function(e){if(!e||!0!==e.enabled)return null;let t=e.fps??1;if("number"==typeof t&&Number.isFinite(t)){if(t<1||t>15){const e=Math.min(15,Math.max(1,t));f(`[groundcover] replay.canvas.fps ${t} is out of range [1, 15]; clamped to ${e}.`),t=e}}else f("[groundcover] replay.canvas.fps must be a finite number; falling back to 1."),t=1;return{canvasFps:t,dataURLOptions:{type:e.imageType??"image/webp",quality:e.imageQuality??.6}}}(t?.canvas),l=i.maskInputFn??("allow"===s.level?void 0:(e,t)=>J(t,s)?"*".repeat(e.length):e);this.stopFn=o({...r?{blockSelector:r}:{},...i.maskTextSelector?{maskTextSelector:i.maskTextSelector}:{},maskAllInputs:i.maskAllInputs,...i.maskTextFn?{maskTextFn:i.maskTextFn}:{},...l?{maskInputFn:l}:{},...a?{recordCanvas:!0,dataURLOptions:a.dataURLOptions}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150,...a?{canvas:a.canvasFps}:{}},checkoutEveryNms:3e4,errorHandler:e=>(g(e),!0),emit:(e,t)=>{if(this.isRecording)try{this.events.push(e),t&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),this.events.length>=this.batchSize&&this.scheduleSendBatch()}catch(e){g(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){g(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=B.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{g(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(B.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.session.getSessionId(),n=He.getInstance();let r;if(n.isAvailable)try{r=await n.packReplay(e.events)}catch(t){g(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),r=e.events.map((e=>a(e)))}else r=e.events.map((e=>a(e)));this.session.getSessionId()===t?this.enqueueReplayEvent(r,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:r.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>a(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const r={_gc_replay_data:{events:e}};t&&(r.replay_is_full_snapshot=!0,r.replay_full_snapshot_timestamp=n);const s=this.enricher.enrich({type:"replay",attributes:r});this.eventsPool.addEvent(s),this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){g(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){g(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},Ue=144e5,Ke=288e5,Ye=18e5,$e="gcSample",We={sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},sessionMaxDuration:Ue},Qe=["pointerdown","keydown","scroll","touchstart","mousemove"],Ge=class{constructor(e){this.logger=u.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){g(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,Qe.forEach((e=>{try{B.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){g(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",Ye,"ms");try{this.callbacks.onIdle()}catch(e){g(e)}}),Ye)}catch(e){g(e)}}destroy(){if(this.installed){this.installed=!1,Qe.forEach((e=>{try{B.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){g(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){g(e)}finally{this.idleTimer=null}}}};function Xe(e,t,n){return"number"==typeof e&&e>0&&e<=t&&e>t-n}function Je(e,t,n){let r=null;const s=e=>{Xe(e,t,n)&&(null===r||e<r)&&(r=e)};try{for(const t of e)if(t){try{s(t.timestamp)}catch(e){g(e)}try{s(t.start_timestamp)}catch(e){g(e)}}}catch(e){g(e)}return r}var Ve=class{constructor(e){this.logger=u.getInstance(),this.rotating=!1,this.session=e.session,this.pool=e.pool,this.idGenerator=e.idGenerator,this.activityEventTypes=e.activityEventTypes,this.ignoredEventTypes=e.ignoredEventTypes,this.hooks=e.hooks??{}}get isRotating(){return this.rotating}install(){this.pool.setBeforeEnqueueHook((e=>this.reconcileOnEnqueue(e))),this.pool.setFlushGate((()=>this.session.hasUserActivity()))}uninstall(e){this.pool.setBeforeEnqueueHook(null);try{e?.()}catch(e){g(e)}this.pool.setFlushGate(null)}reconcile(e,t,n){if(this.rotating)return;t&&this.session.isSessionInactive(e)&&this.rotate({reason:"inactivity gap",triggeringEvent:n});const r=this.session.getSessionElapsedMs(e),s=this.session.getSessionMaxDuration(),i=r>=s;this.logger.log("[session-lifecycle] session reconcile",{userPresent:t,elapsedMs:r,maxDurationMs:s,expired:i}),i&&this.rotate({reason:"max session duration",triggeringEvent:n}),this.hooks.onReconcile?.(t),t&&(this.session.setLastActivityMs(e),this.hooks.onPresenceStamped?.(e))}reconcileOnEnqueue(e){this.rotating||(this.ignoredEventTypes.has(e.type)?this.logger.log("[session-lifecycle] enqueue rotation check: ignoring heartbeat-style event",e.type):this.reconcile(Date.now(),this.activityEventTypes.has(e.type),e))}rotateIfStale(e,t){(this.session.isSessionInactive(e)||this.session.isSessionExpired(e))&&this.rotate({reason:t})}rotate(e){if(this.rotating)return;this.rotating=!0;const t=(e,t)=>{try{this.logger.log(`[session-lifecycle] session rotation: ${e}`),t()}catch(t){g(t),this.logger.log(`[session-lifecycle] failed to ${e} during session rotation:`,t)}};try{const n=this.session.getSessionId();let r;t("capture host rotation context",(()=>{r=this.hooks.captureRotationContext?.()}));const s=this.session.hasUserActivity();this.logger.log("[session-lifecycle] session rotation start",{reason:e.reason,previousId:n,wasConfirmed:s}),t("host beforeRotate",(()=>this.hooks.beforeRotate?.())),t(s?"flush events":"discard unconfirmed events",(()=>s?this.pool.flush():this.pool.discardBuffer())),t("rotate session ids",(()=>{const t=this.idGenerator.generateId(),r=this.resolveNewSessionStartTime(e.triggeringEvent);this.session.setSessionId(t),this.session.setSessionStartTime(r),this.session.clearSamplingDecision(),this.logger.log("[session-lifecycle] session id rotated",{from:n,to:t})})),t("host afterRotate",(()=>this.hooks.afterRotate?.(r)))}finally{this.rotating=!1,this.logger.log("[session-lifecycle] session rotation complete",{reason:e.reason})}}resolveNewSessionStartTime(e){const t=Te(Date.now());let n=t;try{const r=Te(Math.min(this.session.getSessionMaxDuration(),Ye)),s=[Je([e],t,r),this.pool.getEarliestEventTimestamp(t,r)];for(const e of s)Xe(e,t,r)&&e<n&&(n=e)}catch(e){g(e)}return n}},Ze=new Set(["dom.event"]),et=new Set(["replay"]),tt=class{constructor(e){this.logger=u.getInstance(),this.idGenerator=new p,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.replayDesired=!1,this.presenceMonitor=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher,this.manualEvents=new H({config:this.configManager,pool:this.eventsPool,enricher:this.enricher}),this.lifecycle=new Ve({session:this.session,pool:this.eventsPool,idGenerator:this.idGenerator,activityEventTypes:Ze,ignoredEventTypes:et,hooks:{captureRotationContext:()=>this.isReplayRecording(),beforeRotate:()=>this.stopReplayListener(),afterRotate:e=>this.syncReplayState(e),onReconcile:e=>this.syncReplayState(e),onPresenceStamped:e=>this.presenceMonitor?.notePresence(e)}})}listenerDeps(){return{config:this.configManager,eventsPool:this.eventsPool,enricher:this.enricher}}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.lifecycle.install(),this.presenceMonitor?.destroy(),this.presenceMonitor=new Ge({onPresence:e=>this.lifecycle.reconcile(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,r=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new Pe(this.listenerDeps()),this.pageLoadListener.initialize(),r.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new he(this.listenerDeps()),this.domEventsListener.initialize(),r.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new de(this.listenerDeps()),this.logEventsListener.initialize(),r.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new _e(this.listenerDeps()),this.errorsEventsListener.initialize(),r.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new Oe(this.listenerDeps()),this.networkEventsListener.initialize(),r.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new Fe(this.listenerDeps()),this.performanceListener.initialize(),r.push("performance")),this.navigationListener=new De(this.listenerDeps(),{isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),r.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",r)}sendCustomEvent(e){this.manualEvents.sendCustomEvent(e)}emitLog(e,t,n){this.logEventsListener&&this.manualEvents.emitLog(e,t,n)}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){g(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){this.replayDesired=!0,this.isReplayRecording()?this.logger.log("[instrumentation-manager] replay recording already started"):(this.lifecycle.rotateIfStale(Date.now(),"replay start into stale session"),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer())}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] user present and replay desired — starting replay"),this.startReplayListener())}pauseReplayOnIdle(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Be({...this.listenerDeps(),session:this.session});e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){g(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}stopReplayListener(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.lifecycle.uninstall((()=>{this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}))}};function nt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var rt={privacy:[],tracing:["origin"],transport:[]},st=new WeakMap,it={nestedOptions:rt,removedOptions:{}};function ot(e,t){const n=e;for(const e of Object.keys(t))Object.hasOwn(n,e)&&delete n[e]}function at(e,t){if(!e||"object"!=typeof e)return;const n=e;for(const[e,r]of Object.entries(t))Object.hasOwn(n,e)&&f(r)}function lt(e){const t={};for(const n of[rt,e.nestedOptions??{}])for(const[e,r]of Object.entries(n))t[e]=[...new Set([...t[e]??[],...r])];return t}function ct(e,t){if(!nt(e))return e;const n={...e};for(const e of t)nt(n[e])&&(n[e]={...n[e]});return n}function ht(e,t,n){const r={...e,...t};for(const s of n){const n=e?.[s],i=t[s];nt(n)&&nt(i)?r[s]={...n,...i}:Object.hasOwn(t,s)&&!nt(i)?r[s]=nt(n)?{...n}:n:nt(r[s])&&(r[s]={...r[s]})}return r}function ut(e,t,n){const r={...e,...t},s=t,i=e;for(const[e,t]of Object.entries(n)){if(!Object.hasOwn(s,e)){nt(i[e])&&(r[e]=ct(i[e],t));continue}const n=s[e];nt(n)?r[e]=ht(i[e],n,t):r[e]=ct(i[e],t)}return r}var dt=class e{constructor(t,n={}){const r={nestedOptions:lt(n),removedOptions:n.removedOptions??{}};st.set(this,r);const{nestedOptions:s,removedOptions:i}=r,o=ut(We,n.defaults??{},s);this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=ut(o,t?.options||{},s),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),at(t?.options,i),ot(this.providedOptions,i),ot(this.options,i)}static normalizeSessionMaxDuration(e){return void 0===e?Ue:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>Ke?(f("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),Ue):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){if(t.options){const{nestedOptions:r,removedOptions:s}=(n=this,st.get(n)??it);at(t.options,s),this.providedOptions=ut(this.providedOptions||{},t.options,r),this.options=ut(this.options,t.options,r),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),ot(this.providedOptions,s),ot(this.options,s)}var n;void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}},gt=class{constructor(e={}){this.extension=e,this.config=null,this.logger=u.getInstance(),this.privacyCache=null}initialize(e){this.config||(this.config=new dt(e,this.extension))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){if(!this.privacyCache){const e=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=e=>!r&&(e??!0),i=s(t?.maskNetworkBodies),o=s(t?.maskNetworkQueryParams),a=s(t?.maskLogs),l=s(t?.maskErrors);return{level:n,maskNetworkBodies:i,maskNetworkQueryParams:o,maskLogs:a,maskErrors:l,shouldMaskNetworkBodies:!r&&i,shouldMaskNetworkQueryParams:!r&&o,shouldMaskLogs:!r&&a,shouldMaskErrors:!r&&l,sensitiveKeys:K(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0}}(this.config?.providedOptions);this.extension.isOpaqueNode&&(e.isOpaqueNode=this.extension.isOpaqueNode),this.privacyCache=e}return this.privacyCache}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}};function ft(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var pt={isOpaqueNode:ft,nestedOptions:{replay:["canvas"],privacy:["replay"]},defaults:{replay:{}},removedOptions:{enableMasking:"[groundcover] `options.enableMasking` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",maskFields:"[groundcover] `options.maskFields` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",eventSampleRate:"[groundcover] `options.eventSampleRate` was removed and is ignored. Events are no longer randomly sampled; event volume may increase. Use `options.sessionSampleRate` to select whole sessions; rates are not automatically converted. See the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-from-1x-to-200"}},vt=We.transport?.batchSize??10,mt=We.transport?.batchTimeout??1e4;var yt=class{constructor(e){this.events=[],this.timeoutId=null,this.logger=u.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.unusableEnrichWarned=!1,this.onBeforeEnqueue=null,this.flushGate=null,this.config=e.config,this.session=e.session,this.transporter=e.transporter,this.getDeviceAttributes=e.getDeviceAttributes,this.eventsToSkipFlush=e.eventsToSkipFlush}initialize(){try{if(this.initialized)return;this.scheduleFlush(),this.initialized=!0}catch(e){g(e)}}destroy(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.events=[],this.initialized=!1}catch(e){g(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}setFlushGate(e){this.flushGate=e}discardBuffer(){this.events=[]}getEarliestEventTimestamp(e,t){return Je(this.events,e,t)}isFlushAllowed(){if(null===this.flushGate)return!0;try{return this.flushGate()}catch(e){return g(e),!0}}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,r=this.config.getConfig()?.options?.enrichEvent;let s=e;if(n&&!n(s))return;if(r){const e=r(s);if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"string"==typeof e.type}catch(e){return g(e),!1}}(e))return void(this.unusableEnrichWarned||(this.unusableEnrichWarned=!0,this.logger.log("[events-pool.addEvent] dropping event: enrichEvent returned an unusable value")));s=e}if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(s)}catch(e){g(e)}if(!this.isFlushAllowed()&&this.events.length>=500)return;this.events.push(s);const i=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:vt);this.events.length>=i&&!this.eventsToSkipFlush.includes(s.type)&&this.flush()}catch(e){g(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.isFlushAllowed())return void this.scheduleFlush();if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),this.events=[],this.scheduleFlush()}catch(e){g(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.isFlushAllowed())return void this.discardBuffer();if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){g(e)}}scheduleFlush(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:mt);this.timeoutId=setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){g(e)}var e}getSessionAttributes(){return this.buildSessionAttributes()}buildSessionAttributes(){const e=this.config.getConfig();let t={};try{t=this.getDeviceAttributes()}catch(e){g(e)}return{...t,cluster:e?.cluster||"",env:e?.environment||"",namespace:e?.namespace||"",releaseId:e?.releaseId||"",session_id:this.session.getSessionId(),session_start_time:this.session.getSessionStartTime(),user:e?.user||{},"service.name":e?.appId}}};function bt(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:t}var wt=class{constructor(e={}){this.logger=u.getInstance(),this.enrichAttributes=e.enrichAttributes??null,this.reservedAttributeKeys=e.reservedAttributeKeys??[],this.isOpaqueNode=e.isOpaqueNode??null,this.idGenerator=e.idGenerator??new p}getPlatformAttributes(){if(!this.enrichAttributes)return{};try{return this.enrichAttributes()??{}}catch(e){return this.logger.log("[event-enricher] platform attribute contributor threw; continuing without it",e),{}}}formatEventObject(e,t="",n=new WeakSet,r=0){try{return r>=10?{[t||"depth_limit"]:"[Depth Limit]"}:this.isOpaqueNode?.(e)?{[t||"opaque_node"]:`[${e?.constructor?.name||"OpaqueNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,i])=>{const o=t?`${t}.${s}`:s;return"object"==typeof i&&null!==i?Array.isArray(i)?e[o]=i.map(((e,t)=>"object"==typeof e&&null!==e?this.formatEventObject(e,`${o}[${t}]`,n,r+1):e)):Object.assign(e,this.formatEventObject(i,o,n,r+1)):e[o]=i,e}),{}))}catch(e){return this.logger.log("[event-enricher.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}enrich(e){const t=Te(Date.now()),n=this.idGenerator.generateId(),r=e.spanId||this.idGenerator.generateSpanId(),s=e.traceId||this.idGenerator.generateTraceId(),i=e.parentSpanId||"",o=this.formatEventObject(e.attributes||{}),a=this.getPlatformAttributes(),l={type:e.type,id:n,spanId:r,parentSpanId:i,traceId:s,attributes:{...o,...a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=bt(e.timestamp,t),l.end_timestamp=e?.end_timestamp):l.timestamp=bt(e.timestamp,t),l}};function Et(e,t){const n=l(e);if(!t)return{data:n,isCompressed:!1};try{return{data:c(n),isCompressed:!0}}catch{return{data:n,isCompressed:!1}}}var kt=class{constructor(e){this.logger=u.getInstance(),this.config=e.config,this.sendBatch=e.sendBatch,this.encodeAsync=e.encodeAsync??null}compressAsync(e,t){if(!this.encodeAsync)return Promise.resolve(Et(e,t));try{return this.encodeAsync(e,t).catch((()=>Et(e,t)))}catch{return Promise.resolve(Et(e,t))}}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const r=n.apiKey,s=this.buildEndpoint();if(!r)return void this.logger.log("No API key found");const i=JSON.stringify(e),o=!!n?.options?.transport?.compression,{data:a,isCompressed:l}=t?Et(i,o):await this.compressAsync(i,o),c={"Content-Type":"application/json",apikey:r,"Content-Encoding":l?"gzip":""};this.sendBatch(s,{method:"POST",headers:c,body:a}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n?.options?.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},St=class{constructor(e){this.storage=e}getItem(e){try{return this.storage?.getItem(e)??null}catch(e){return g(e),null}}setItem(e,t){try{this.storage?.setItem(e,t)}catch(e){g(e)}}removeItem(e){try{this.storage?.removeItem(e)}catch(e){g(e)}}getNumericItem(e,t=0){const n=this.getItem(e);if(null===n)return t;const r=Number(n);return Number.isFinite(r)?r:t}},It=class{constructor(e){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage=e.storage,this.getMaxDurationMs=e.getMaxDurationMs??null}getSessionId(){if(this.sessionId)return this.sessionId;return this.storage.getItem("gcId")||""}setSessionId(e){this.sessionId=e,this.storage.setItem("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:this.storage.getNumericItem("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,this.storage.setItem("gcStartTime",String(e)),this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcLastActivity")}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:this.storage.getNumericItem("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,this.storage.setItem("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs(),n=t>0?t:Re(this.getSessionStartTime());return n>0&&e-n>=Ye}hasUserActivity(){return this.getLastActivityMs()>0}clearSamplingDecision(){this.storage.removeItem($e)}clearSessionState(){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcId"),this.storage.removeItem("gcStartTime"),this.storage.removeItem("gcLastActivity"),this.clearSamplingDecision()}getSessionMaxDuration(){return this.getMaxDurationMs?.()??Ue}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-Re(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}};function Tt(){const e=navigator.userAgent;let t="unknown",n="unknown";const r=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{userAgent:e,browser:{name:t,version:n,platform:r,language:navigator.language,mobile:s}}}var Rt,Lt,xt=["navigation","dom.event"],At=class{constructor(e){this.core=null,this.hideWired=!1,this.hideHandler=()=>{try{if("undefined"==typeof document||"hidden"!==document.visibilityState)return;this.core?.session.persistLastActivity(),this.core?.pool.flush({lifecycle:!0})}catch(e){g(e)}},this.logger=u.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.storage=new St(function(){try{return void 0!==globalThis.sessionStorage?globalThis.sessionStorage:null}catch{return null}}()),this.idGenerator=new p;const t=new gt(pt);t.initialize(e);const n=new It({storage:this.storage,getMaxDurationMs:()=>t.getConfig()?.options?.sessionMaxDuration});!function({session:e,idGenerator:t,providedSessionId:n}){const r=u.getInstance();try{const s=e.getSessionId();n&&n!==s?(e.setSessionId(n),e.setSessionStartTime(Te(Date.now())),e.clearSamplingDecision(),r.log("[session-bootstrap] using provided sessionId:",n)):n?(e.setSessionId(n),r.log("[session-bootstrap] continuing provided sessionId:",n)):s||e.setSessionId(t.generateId());const i=6e4,o=Date.now(),a=Re(e.getSessionStartTime());if(a>0&&o-a>=-i){if(e.isSessionExpired(o)||e.isSessionInactive(o)){const n=e.isSessionExpired(o)?"persisted session past cap":"inactivity gap across restart",s=e.getSessionId(),i=t.generateId();e.setSessionId(i),e.setSessionStartTime(Te(o)),e.clearSamplingDecision(),r.log(`[session-bootstrap] init-time rotation: ${n}`,{from:s,to:i})}}else e.setSessionStartTime(Te(o))}catch(e){r.log("[session-bootstrap] session bootstrap failed:",e)}}({session:n,idGenerator:this.idGenerator,providedSessionId:e.sessionId});if(!function({storage:e,sessionSampleRate:t}){const n=u.getInstance();if(void 0===t||!Number.isFinite(t)||1===t)return!0;const r=t;try{const t=e.getItem($e);if(t){const e="1"===t;return n.log("[session-bootstrap] using stored sampling decision:",e),e}const s=Math.random()<r;return e.setItem($e,s?"1":"0"),n.log("[session-bootstrap] stored new sampling decision:",s),s}catch(e){n.log("[session-bootstrap] storage access failed:",e);const t=Math.random()<r;return n.log("[session-bootstrap] using fallback sampling decision:",t),t}}({storage:this.storage,sessionSampleRate:e.options?.sessionSampleRate}))return void this.logger.log("[session-manager] session is not sampled");const r=new kt({config:t,sendBatch:(e,t)=>fetch(e,t),encodeAsync:(e,t)=>He.withFallback((n=>n.encodeBatch(e,t)),(()=>Et(e,t)),"transporter")}),s=new yt({config:t,session:n,transporter:r,getDeviceAttributes:Tt,eventsToSkipFlush:xt}),i=function(e){return()=>{let t="";try{t=B?.document?.title||""}catch(e){g(e)}try{const n=B?.location;if(!n)return{path:"",url:"",title:t};const r=n.hash&&!n.hash.match(/^#[a-z0-9-]+$/i)&&n.hash.startsWith("#/"),s=r?n.hash:n.pathname,i=e.getPrivacy(),o=i.shouldMaskNetworkQueryParams,a={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:o&&r?O(s,a):s,url:o?O(n.href,a):n.href,title:t}}catch(e){return g(e),{path:"",url:"",title:t}}}}(t),o=new wt({enrichAttributes:()=>({location:i()}),reservedAttributeKeys:["location"],isOpaqueNode:ft,idGenerator:this.idGenerator}),a=new tt({config:t,session:n,eventsPool:s,enricher:o});try{s.initialize(),He.getInstance(),this.wireHideHandler(),a.instrument(),this.core={config:t,session:n,pool:s,instrumentation:a}}catch(e){this.logger.log("[session-manager] initialization failed — tearing down partial startup:",e);try{a.uninstrument()}catch(e){g(e)}throw s.destroy(),this.unwireHideHandler(),this.core=null,e}}wireHideHandler(){if(!this.hideWired&&"undefined"!=typeof document){this.hideWired=!0;try{document.addEventListener("visibilitychange",this.hideHandler)}catch(e){g(e)}}}unwireHideHandler(){if(this.hideWired&&"undefined"!=typeof document){this.hideWired=!1;try{document.removeEventListener("visibilitychange",this.hideHandler)}catch(e){g(e)}}}identifyUser(e){this.logger.log("[session-manager] identifyUser called"),this.core?this.core.config.updateConfig({user:e}):this.logger.log("[session-manager] cannot identify user: SDK not initialized")}updateConfig(e){try{if(null===e||"object"!=typeof e)return void f("[groundcover] updateConfig requires a configuration object; the update was ignored.");if("appId"in e)return void f("[groundcover] updateConfig does not accept appId; the entire update was ignored. Remove appId from the update.");if(!this.core)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");this.core.config.updateConfig(e);const t=e.options,n=!!t&&Object.hasOwn(t,"privacy"),r=t&&Object.hasOwn(t,"replay")&&"object"==typeof t.replay&&null!==t.replay?t.replay:void 0,s=!!r&&Object.hasOwn(r,"blockedSelectors"),i=!!r&&Object.hasOwn(r,"canvas");(n||s||i)&&this.core.instrumentation.restartReplayForConfigChange()}catch(e){g(e)}}sendCustomEvent(e){this.core?this.core.instrumentation.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.core?this.core.instrumentation.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.core?this.core.instrumentation.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.core?this.core.instrumentation.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}emitLog(e,t,n){this.core?this.core.instrumentation.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.core?this.core.session.getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.core)try{this.core.instrumentation.flushPendingReplay(),await this.core.pool.flushSync();const t=e||this.idGenerator.generateId();this.core.session.setSessionId(t),this.core.session.setSessionStartTime(Te(Date.now())),this.logger.log("[session-manager] session ID set successfully:",t)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.core?this.core.instrumentation.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.core?this.core.instrumentation.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){const e=this.core;e&&(e.instrumentation.uninstrument(),e.pool.destroy(),this.unwireHideHandler(),He.getInstance().terminate(),e.session.clearSessionState(),this.core=null)}},Nt=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var Mt={init:function(e){if(void 0===Lt)try{const t=e?.appId;if(void 0!==Lt)return;if("string"!=typeof t||0===t.trim().length)return void f("[groundcover] init requires a nonblank appId; the SDK was not initialized.");Lt=t,Rt=new At({cluster:e.cluster||"",environment:e.environment||"",namespace:e.namespace,releaseId:e.releaseId,dsn:e.dsn||"",appId:t,user:e.user,apiKey:e.apiKey||"",options:e.options,sessionId:e.sessionId}),Nt.manager=Rt}catch(e){Rt||(Lt=void 0),g(e)}},identifyUser:function(e){Rt?Rt.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){Rt&&Rt.sendCustomEvent(e)},captureException:function(e,t){Rt&&Rt.captureException(e,t)},logger:Nt,updateConfig:function(e){if(Rt)try{Rt.updateConfig(e)}catch(e){g(e)}},startNavigation:function(e){Rt?Rt.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){Rt?Rt.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return Rt?Rt.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(Rt)try{await Rt.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){Rt?Rt.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){Rt?Rt.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Mt}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var Ct=Mt;export{Ct as default};
1
+ import e from"error-stack-parser";import{onCLS as t,onLCP as n,onFCP as r,onTTFB as s,onINP as i}from"web-vitals";import{record as o,EventType as a,IncrementalSource as l}from"rrweb";import{pack as c}from"@rrweb/packer";import{strToU8 as h,gzipSync as u}from"fflate";var d=console.log.bind(console),g=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&d(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},f=g.getInstance();function p(e){f.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}function m(e){try{console.warn(`${e} (groundcoverIgnore)`)}catch{}}var v=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)y[e]=Math.floor(16*Math.random())+48,y[e]>=58&&(y[e]+=39);return w+String.fromCharCode.apply(null,y.slice(0,16))},this.generateSpanId=b(8),this.generateId=b(16)}},y=Array(32);function b(e){return function(){for(let t=0;t<2*e;t++)y[t]=Math.floor(16*Math.random())+48,y[t]>=58&&(y[t]+=39);return String.fromCharCode.apply(null,y.slice(0,2*e))}}var w="0000000000000000";function k({text:e,maxLength:t=1e4,ellipsis:n=""}){if(null==e)return"";const r="string"==typeof e?e:String(e);return r.length<=t?r:r.substring(0,t)+n}function E(e){return(e||"").replace(/\s+/g," ").trim()}var S="[REDACTED]",I=["authorization","cookie","set-cookie"],T=/(token|key|secret|passwd|password|auth|bearer|credential)/i,R=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,A=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),L=1e5;function x(e,t){if(!e)return!1;if(R.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function C(e,t){return A.has(e.toLowerCase())||x(e,t)}function N(e){return e.includes("-")&&T.test(e)}function M(e,t){return x(e,t)||N(e)}function q(e,t){const n=e.sensitive?S:e.value;if(!t)return n;try{const r=t(e);return void 0===r?n:r}catch(e){return p(e),n}}function O(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const r=e.slice(0,n),s=e.slice(n+1);let i=r;try{i=decodeURIComponent(r)}catch{}let o=s;try{o=decodeURIComponent(s)}catch{}const a=C(i,t.sensitiveKeys),l=q({key:i,value:o,path:[i],kind:t.kind??"query",sensitive:a},t.redact);return l===o?e:`${r}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function z(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${O(e.slice(n+1),t)}`}function P(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},r=e.indexOf("#"),s=-1===r?e:e.slice(0,r),i=-1===r?"":e.slice(r+1),o=z(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${S}@`))}(s),n);return-1===r?o:`${o}#${z(i,n)}`}function D(e,t,n,r,s,i){const o=!!e&&x(e,r.sensitiveKeys);if(null!==t&&"object"==typeof t){if(o||s>8)return S;if(function(e,t){if(!e.isOpaqueNode)return!1;try{return e.isOpaqueNode(t)}catch{return!0}}(r,t))return S;if(i.has(t))return S;i.add(t);try{if(Array.isArray(t))return t.map((t=>D(e,t,n,r,s+1,i)));const o={};for(const[e,a]of Object.entries(t))o[e]=D(e,a,[...n,e],r,s+1,i);return o}catch(e){return p(e),S}finally{i.delete(t)}}return q({key:e,value:t,path:n,kind:r.kind??"log",sensitive:o},r.redact)}function _(e,t={}){if(!e)return e;if(e.length>L)return`${_(e.slice(0,L),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>M(n,t.sensitiveKeys)?`"${n}":"${S}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return C(e,t)||N(e)}(n,t.sensitiveKeys)?`${n}=${S}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>M(n,t.sensitiveKeys)?`${n}: ${S}`:e))}catch(t){p(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){p(e)}return n}function F(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=L&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(D("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?O(e,t):_(e,t)}function j(e,t={}){try{const n=D("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return p(e),{}}}function H(e,t){return"allow"!==t.level&&e?j(e,{sensitiveKeys:t.sensitiveKeys,redact:t.redact,isOpaqueNode:t.isOpaqueNode}):e}function B(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const r={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log",isOpaqueNode:e.isOpaqueNode};return{message:_(t,r),attributes:n?j(n,r):n}}var U=class{constructor(e){this.logger=g.getInstance(),this.config=e.config,this.pool=e.pool,this.enricher=e.enricher}sendCustomEvent(e){this.logger.log("[manual-event-emitter.sendCustomEvent] called",e);try{const t=this.enricher.enrich({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.pool.addEvent(t)}catch(e){p(e)}}emitLog(e,t,n){this.logger.log("[manual-event-emitter.emitLog] called",{message:e,level:t,attributes:n});try{const r={...n||{}};delete r.message,delete r.level;for(const e of this.enricher.reservedAttributeKeys)delete r[e];const{message:s,attributes:i}=B(this.config.getPrivacy(),e,r),o=this.enricher.enrich({type:"log",attributes:{...i,message:k({text:s}),level:t}});this.pool.addEvent(o)}catch(e){p(e)}}},K=globalThis,Y=class{constructor(e){this.logger=g.getInstance(),this.config=e.config,this.eventsPool=e.eventsPool,this.enricher=e.enricher}};function $(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function W(e){const t=e.getPrivacy(),n=e.getConfig()?.providedOptions?.privacy;return{...t,maskSelectors:$(n?.maskSelectors)}}var Q="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function G(e,t){try{return e.getAttribute(t)||""}catch{return""}}function X(e){try{const t=Q?.call(e);return"string"==typeof t?t:""}catch{return""}}function J(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function V(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>G(e,t))).filter(Boolean)}(e).some((e=>x(e,t))))}function Z(e,t){return"allow"!==t.level&&(!!e&&(!!J(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>J(e,t))))||("mask-all"===t.level||function(e){const t=X(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&V(e,t.sensitiveKeys)))))}var ee={role:"",accessibleName:"",ariaLabel:"",title:"",alt:"",placeholder:"",name:"",inputType:"",href:""},te=["button","a","input","select","textarea","label","summary",'[role~="button"]','[role~="link"]','[role~="menuitem"]','[role~="menuitemcheckbox"]','[role~="menuitemradio"]','[role~="tab"]','[role~="checkbox"]','[role~="radio"]','[role~="switch"]','[role~="option"]','[role~="treeitem"]','[role~="slider"]','[role~="spinbutton"]','[role~="combobox"]','[role~="textbox"]','[role~="searchbox"]'].join(", "),ne=[te,"li","option","tr","td","th",'[role~="listitem"]','[role~="row"]','[role~="gridcell"]','[role~="cell"]'].join(", ");function re(e){return!!e&&1===e.nodeType}function se(e){const t=X(e).toLowerCase();return"body"===t||"html"===t}function ie(e){return k({text:e,maxLength:255})}function oe(e){return k({text:e,maxLength:99,ellipsis:"…"})}function ae(e){const t=E(G(e,"role"));return t?t.split(" ")[0]??t:function(e){switch(X(e).toLowerCase()){case"a":return G(e,"href")?"link":"";case"button":return"button";case"input":switch(G(e,"type").toLowerCase()){case"checkbox":return"checkbox";case"radio":return"radio";case"submit":case"button":case"reset":return"button";case"range":return"slider";case"number":return"spinbutton";default:return"textbox"}case"textarea":return"textbox";case"select":return"combobox";case"img":return"img";case"nav":return"navigation";case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"heading";default:return""}}(e)}function le(e){if(!re(e))return"";try{if(se(e))return"";if(function(e){try{return e.querySelectorAll(ne).length>=2}catch{return!1}}(e))return"";const t=E(e.textContent||"");return t?t.length>1e3?"":k({text:t,maxLength:255}):""}catch{return""}}function ce(e){return G(e,"aria-labelledby").split(/\s+/).filter(Boolean).slice(0,5)}function he(e,t){if(se(e))return"";const n=function(e){const t=[];for(const n of ce(e))try{const e=le(document.getElementById(n));e&&t.push(e)}catch{}return E(t.join(" "))}(e);if(n)return oe(n);const r=E(G(e,"aria-label"));if(r)return oe(r);const s=E(G(e,"alt"));if(s)return oe(s);if(function(e){const t=X(e).toLowerCase();if("button"===t)return!0;if("input"!==t)return!1;const n=G(e,"type").toLowerCase();return"submit"===n||"button"===n||"reset"===n}(e)){const t=E(G(e,"value"));if(t)return oe(t)}const i=t??le(e);if(i)return oe(i);const o=E(G(e,"title"));if(o)return oe(o);const a=E(G(e,"placeholder"));return a?oe(a):""}function ue(e,t){if("allow"===t.level)return!1;try{return!!e.querySelector("[data-private]")||t.maskSelectors.some((t=>{try{return null!=e.querySelector(t)}catch{return!1}}))}catch{return!1}}var de=class extends Y{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>Z(e.target,W(this.config)),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){p(e)}};this.eventHandlers.push({type:e,handler:t}),K?.addEventListener(e,t)}))}catch(e){p(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){p(e)}}buildEvent(e){const t=this.getCoordinates(e),n=e.target,r=function(e){if(!re(e))return null;try{return e.closest(te)}catch{return null}}(n)??n,s=W(this.config),i=this.getShouldMaskText({target:n||null})||!!r&&(ue(r,s)||function(e,t){if("allow"===t.level)return!1;try{for(const n of ce(e)){const e=document.getElementById(n);if(e&&le(e)&&(Z(e,t)||ue(e,t)))return!0}}catch{}return!1}(r,s)),o=r?this.generateSelector(r,i?{priorityAttributes:["id","class","name","type"]}:{}):"",a=this.getKeyCode(e,i),l=le(r),c=function(e,t){if(!re(e))return{...ee};try{return{role:ie(ae(e)),accessibleName:he(e,t),ariaLabel:ie(E(G(e,"aria-label"))),title:ie(E(G(e,"title"))),alt:ie(E(G(e,"alt"))),placeholder:ie(E(G(e,"placeholder"))),name:ie(G(e,"name")),inputType:ie(G(e,"type")),href:ie(G(e,"href"))}}catch{return{...ee}}}(r,l),h=s.shouldMaskNetworkQueryParams?P(c.href,{sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"}):c.href,u=e=>i&&e?"*":e;this.logger.log("[dom-events-listener.buildEvent] called");const d={dom_event_selector:o,dom_event_key_code:a,dom_event_type:e.type,dom_event_coordinates:t||{clientX:0,clientY:0},dom_event_target:{id:G(r,"id"),tagName:X(r),className:G(r,"class"),text:i?"*":l,role:c.role,accessibleName:u(c.accessibleName),ariaLabel:u(c.ariaLabel),title:u(c.title),alt:u(c.alt),placeholder:u(c.placeholder),name:c.name,inputType:c.inputType,href:u(h)}};return this.enricher.enrich({type:"dom.event",attributes:d})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,r=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===X(e).toLowerCase())return"html";let i="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<r;){let e=X(a).toLowerCase();try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=X(a).toLowerCase()||"*"}l.unshift(e||"*"),i=l.join(" > ");try{if(1===n.querySelectorAll(i).length)return i}catch(e){l.shift(),i=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return i||"*"}},ge=["log","info","warn","error","debug","assert","trace"],fe=class extends Y{constructor(){super(...arguments),this.originalConsole=null,this.patchedConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods();const e={};ge.forEach((t=>{if(!(t in console))return;const n=(...e)=>{try{this.isInitialized&&this.handleEvent(e,t)}catch(e){p(e)}finally{this.originalConsole?.[t]&&this.originalConsole[t](...e)}};console[t]=n,e[t]=n})),this.patchedConsole=e,this.isInitialized=!0}catch(e){p(e)}}destroy(){try{if(!this.isInitialized)return;ge.forEach((e=>{this.originalConsole?.[e]&&this.patchedConsole?.[e]&&console[e]===this.patchedConsole[e]&&(console[e]=this.originalConsole[e])})),this.patchedConsole=null,this.isInitialized=!1}catch(e){p(e)}}handleEvent(e,t){try{const n=Array.isArray(e)?e:[e];if("assert"===t&&n[0])return;const r=this.formatMessage(n,t);if(!r||r?.includes("groundcoverIgnore"))return;const s=this.extractAttributes(n),i=this.buildEvent({message:r,level:t,attributes:s});this.queueEvent(i)}catch(e){p(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:r,attributes:s}=B(this.config.getPrivacy(),e,n);return this.enricher.enrich({type:"log",attributes:{...s,message:k({text:r}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);delete t.message,delete t.level;for(const e of this.enricher.reservedAttributeKeys)delete t[e];return t}catch(e){return void p(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return p(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{ge.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){p(e)}return e}},pe=class{constructor(){this.installed=[]}install(e){const t=e,n=[],r=[];try{for(const e of t){const t=e.get();r.push({spec:e,original:t});const s=e.wrap(t);e.set(s),n.push({spec:e,original:t,wrapped:s})}return this.installed.push(...n),!0}catch(e){for(const{spec:e,original:t}of r.reverse())try{e.get()!==t&&e.set(t)}catch{}return p(e),!1}}restore(){const e=this.installed;this.installed=[];for(const{spec:t,original:n,wrapped:r}of e.reverse())try{t.get()===r&&t.set(n)}catch(e){p(e)}}get isEmpty(){return 0===this.installed.length}},me="[request body too large]",ve="[request body unavailable]",ye="[response body too large]",be="[response body unavailable]",we="[unreadable response body]",ke="[form data]",Ee="[binary data]";function Se(e){return(e.split(";")[0]||"").trim().toLowerCase()}function Ie(e){const t=(e||"").toLowerCase();return t.includes("multipart/form-data")?ke:function(e){const t=Se(e);return!!t&&(!!t.startsWith("text/")||"application/x-www-form-urlencoded"===t||"application/javascript"===t||"application/ecmascript"===t||"application/graphql"===t||/^application\/([\w.-]+\+)?(json|xml)$/.test(t))}(t)?null:function(e){const t=Se(e);return t.startsWith("image/")?"[image data]":t.startsWith("audio/")?"[audio data]":t.startsWith("video/")?"[video data]":t.startsWith("font/")||t.startsWith("application/font")||"application/vnd.ms-fontobject"===t?"[font data]":"application/pdf"===t?"[pdf data]":"application/zip"===t||"application/gzip"===t||"application/x-gzip"===t||"application/x-tar"===t||"application/x-7z-compressed"===t||"application/x-rar-compressed"===t?"[archive data]":"application/wasm"===t?"[wasm data]":t.includes("protobuf")||t.startsWith("application/grpc")?"[protobuf data]":Ee}(t)}function Te(e,t,n){return e&&(e.length>=t||function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r<128)t+=1;else if(r<2048)t+=2;else if(r>=55296&&r<=56319){const r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=4,n++):t+=3}else t+=3}return t}(e)>=t)?n:e}var Re=1e6;function Ae(e){return e*Re}function Le(e){return e/Re}function xe(e){return"string"==typeof e&&/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}function Ce(e,t){const n="allow"===t.level,r=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,r])=>{const s=n.toLowerCase(),i=q({key:n,value:r,path:[n],kind:"header",sensitive:I.includes(s)||T.test(s)||x(n,t.sensitiveKeys)},t.redact);return e[n]=null===i?"":String(i),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact}),s={};for(const[e,t]of Object.entries(r))s[e]=k({text:t});return s}function Ne(e,t){const{privacy:n}=t,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"query"};let{path:s,fullUrl:i}=t.resolveUrl(e.url);n.shouldMaskNetworkQueryParams&&(s=P(s,r),i=P(i,r));const o=e.method?.toUpperCase()||"UNKNOWN",a=e.method||"UNKNOWN",l=e.status?.toString(),{traceId:c,spanId:h}=function(e,t){const n={};for(const t of Object.keys(e))n[t.toLowerCase()]=e[t];const r=e=>{if(!e)return"";const t=n[e.toLowerCase()];return"string"==typeof t?t:""};let s=r(t?.traceIdHeaderName),i=r(t?.spanIdHeaderName);if(!s||!i){let e="";for(const n of t?.propagationHeaders??[])if(e=r(n),e)break;e||(e=r("traceparent"));const n=e.split("-");4===n.length&&"00"===n[0]&&(s||32!==n[1]?.length||(s=n[1]),i||16!==n[2]?.length||(i=n[2]))}return{traceId:s,spanId:i}}(e.request.headers,t.tracing),u=(e,r)=>k({text:n.shouldMaskNetworkBodies?F(e,{sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:r}):e,maxLength:t.maxBodyLength}),d={type:"HTTP",operation:{name:o},resource_name:s,status:l,subType:o,url:{full:i},http:{route:s,path:s,method:a,status:l,request:{headers:Ce(e.request.headers,n),method:a},response:{headers:Ce(e.response.headers,n),status_code:l}},error:e.error?.type?{type:e.error.type}:void 0,gc:{request:{body:u(e.request.body,"request-body")},response:{body:u(e.response.body,"response-body")}}},g={type:"network",timestamp:Me(e.timestamp),end_timestamp:Me(e.end_time),span_name:`${o} ${s}`,attributes:d};return c&&(g.traceId=c),h&&(g.spanId=h),g}function Me(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Ae(e):void 0}function qe(e){return function(e){try{return 9===e?.nodeType}catch{return!1}}(e)?"[document data]":function(e){try{if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof FormData&&e instanceof FormData)return"[form data]";if("undefined"!=typeof Blob&&e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if(ArrayBuffer.isView(e))return"[arraybuffer data]";if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return"[stream data]";if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return p(`Failed to format body: ${e}`),"[unreadable body]"}}(e)}var Oe=[".tsx",".jsx",".css"],ze=e=>Oe.some((t=>e.toLowerCase().endsWith(t))),Pe=class extends Y{constructor(){super(...arguments),this.maxBodyLength=5e3,this.requestBodyReadTimeoutMs=3e3,this.responseBodyReadTimeoutMs=3e3,this.idGenerator=new v,this.patches=new pe,this.active=!1,this.handleEvent=e=>{try{if(!this.active)return;if(this.shouldIgnoreRequest(e.url))return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){p(e)}},this.buildEvent=e=>(this.logger.log("[network-events-listener.buildEvent] called",{event:e}),this.enricher.enrich(Ne(e,{privacy:this.config.getPrivacy(),maxBodyLength:this.maxBodyLength,tracing:this.config.getConfig()?.options?.tracing,resolveUrl:e=>{try{return{path:new URL(e).pathname,fullUrl:e}}catch{return{path:e,fullUrl:new URL(e,globalThis.location.href).href}}}})))}async readBodyStreamCapped(e,t={}){if(!e)return"";const{timeoutMs:n,overflowPlaceholder:r,timeoutPlaceholder:s}=t,i=e.getReader(),o=new TextDecoder;let a,l="",c=0,h=!1,u=!1;const d=null!=n?new Promise((e=>{a=setTimeout((()=>e({timedOut:!0})),n)})):void 0;try{for(;;){const e=d?await Promise.race([i.read(),d]):await i.read();if("timedOut"in e){u=!0;break}const{done:t,value:n}=e;if(t)break;if(c+n.byteLength>=this.maxBodyLength){const e=n.subarray(0,this.maxBodyLength-c);l+=o.decode(e,{stream:!0}),h=!0;break}c+=n.byteLength,l+=o.decode(n,{stream:!0})}return l+=o.decode(),u&&null!=s?s:h&&null!=r?r:l}finally{clearTimeout(a);try{i.cancel()?.catch((()=>{}))}catch{}}}async getRequestBody(e,t){try{if(!e.body)return"";const n=Ie(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.requestBodyReadTimeoutMs,overflowPlaceholder:me,timeoutPlaceholder:ve})}catch{return ve}}async getResponseBody(e){if(!e.body)return"";const t=e.headers?.get?.("content-type")??"";if(function(e){return"text/event-stream"===Se(e||"")}(t))return we;const n=Ie(t);return null!=n?n:await this.readBodyStreamCapped(e.clone().body,{timeoutMs:this.responseBodyReadTimeoutMs,overflowPlaceholder:ye,timeoutPlaceholder:be})}initialize(){this.logger.log("[network-events-listener.initialize] called");const e=this.patches.install(this.xhrPatches()),t=this.patches.install([this.fetchPatch()]);this.active=e||t}destroy(){this.active=!1,this.patches.restore()}shouldIgnoreRequest(e){try{const t=this.config.getConfig();return function(e,t){try{return!(!t.endpoint||!e.includes(t.endpoint))||!!t.extraIgnore?.(e)||(t.excludedUrls??[]).some((t=>t instanceof RegExp?t.test(e):"string"==typeof t&&(t.includes("*")||t.includes("?"))?new RegExp(t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")).test(e):e===t))}catch(e){return p(e),!1}}(e,{endpoint:t?.getEndpoint(),excludedUrls:t?.options?.excludedUrls,extraIgnore:ze})}catch(e){return p(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}xhrPatches(){const e=this,t=globalThis.XMLHttpRequest.prototype;let n;return[{get:()=>t.open,set:e=>{t.open=e},wrap:t=>function(r,s,i=!0,o,a){if(!e.active)return t.apply(this,[r,s,i,o,a]);if(n=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[r,s,i,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=r,this._requestUrl=l,this._requestHeaders={},t.apply(this,[r,s,i,o,a])}},{get:()=>t.setRequestHeader,set:e=>{t.setRequestHeader=e},wrap:t=>function(n,r){return e.active?(this._requestHeaders&&(this._requestHeaders[n]=r),t.apply(this,[n,r])):t.apply(this,[n,r])}},{get:()=>t.send,set:e=>{t.send=e},wrap:t=>function(...r){if(!e.active)return t.apply(this,r);const s=this._requestUrl?.toString();if(!s||e.shouldIgnoreRequest(s))return t.apply(this,r);if(e.shouldAddTraceHeader(s))for(const[t,n]of Object.entries(e.buildTraceHeaders()))e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n});return this._requestBody=r[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),r={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,n]=e.split(": ");t&&n&&(r[t.trim()]=n.trim())}));const s=Te(qe(this._requestBody),e.maxBodyLength,me),i=""===this.responseType||"text"===this.responseType,o=i?this.responseText:this.response,a=(i?Ie(r["content-type"]||""):null)??Te(qe(o),e.maxBodyLength,ye),l={timestamp:n,end_time:t,method:this._requestMethod,url:this._requestUrl,status:this.status,request:{headers:this._requestHeaders||{},body:s},response:{headers:r,body:a}};e.handleEvent(l)})),t.apply(this,r)}}]}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){for(const[t,n]of Object.entries(this.buildTraceHeaders()))this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n})}buildTraceHeaders(){return function(e,t){const n={},r=(e,t)=>{xe(e)&&(n[e]=t)};e?.origin?.name&&r(e.origin.name,e.origin.value),e?.traceIdHeaderName&&r(e.traceIdHeaderName,t.decimalTraceId),e?.spanIdHeaderName&&r(e.spanIdHeaderName,t.decimalSpanId);const s=e?.propagationHeaders,i=s?.length?s:["traceparent"];for(const e of i)r(e,t.traceparent);return n}(this.config.getConfig()?.options?.tracing,function(e){const t=e.generateSpanId(),n=e.generateTraceId();let r,s;try{r=BigInt("0x"+n).toString(10),s=BigInt("0x"+t).toString(10)}catch{r=n,s=t}return{traceparent:`00-${n}-${t}-01`,traceId:n,spanId:t,decimalTraceId:r,decimalSpanId:s}}(this.idGenerator))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}fetchPatch(){return{get:()=>globalThis.fetch,set:e=>{globalThis.fetch=e},wrap:e=>(...t)=>{if(!this.active)return e.apply(globalThis,t);const n=Date.now();let[r,s]=t;s={...s||{}},t[1]=s;const i=r instanceof Request,o=s?.method||(i?r.method:"GET"),a=r instanceof Request?r.url:r.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);s.headers=this.normalizeHeaders(i?r.headers:void 0,s.headers),l&&this.addTraceHeaders(s);const c=this.extractHeadersRecord(s.headers),h=null!=s?.body?Te(qe(s.body),this.maxBodyLength,me):"",u=null!=s?.body?Promise.resolve(h):i?this.getRequestBody(r,"content-type"in c?c["content-type"]:r.headers.get("content-type")??""):Promise.resolve("");let d;return u.then((e=>{d=e})).catch((()=>{})),e.apply(globalThis,t).then((e=>{const t=Date.now(),r={};e.headers.forEach(((e,t)=>{r[t]=e}));const s={method:o,url:a,timestamp:n,status:e.status,end_time:t,request:{headers:c,body:""},response:{headers:r,body:""}},i=()=>{u.then((e=>{s.request.body=e,this.handleEvent(s)}))};return this.getResponseBody(e).then((e=>{s.response.body=e,i()})).catch((e=>{s.response.body=we,i(),this.logger.log("[network-events-listener.fetch] response body error",{error:e})})),e})).catch((e=>{const t=Date.now();let r="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?r="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?r="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(r="ERR_CONNECTION_REFUSED");const i={method:o,url:a,timestamp:n,status:0,end_time:t,request:{headers:c,body:d??h},response:{headers:{},body:""},error:{type:r}};throw this.handleEvent(i),e}))}}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),xe(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),xe(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}shouldAddTraceHeader(e){const t=(n=this.propagationCandidates(e),r=this.config.getConfig()?.options?.tracing?.propagationUrls,!!r?.length&&r.some((e=>{try{if("string"!=typeof e)return!1;const t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),r=new RegExp(`^${t}$`);return n.some((e=>r.test(e)))}catch{return!1}})));var n,r;return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:t}),t}propagationCandidates(e){try{const t=globalThis.location.href,n=new URL(e,t),r=[n.href];return"/"!==n.pathname||n.search||n.hash||r.push(n.href.slice(0,-1)),n.origin===new URL(t).origin&&r.push(n.pathname),r}catch{return[e]}}};function De(t){try{return e.parse(t).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch{return[]}}var _e=class extends Y{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const r=this.buildEvent(n,t);this.queueEvent(r)}catch(e){p(e)}}}initialize(){K?.addEventListener("error",this.handleEvent),K?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){K?.removeEventListener("error",this.handleEvent),K?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return this.enricher.enrich(function(e,t,n){const r=n.shouldMaskErrors,s={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error",isOpaqueNode:n.isOpaqueNode},i=e.message||"Unknown error",o=r?_(i,s):i,a=r&&t?.metadata?j(t.metadata,s):t?.metadata;return{type:"exception",attributes:{error_type:e.name||"Error",error_message:o,error_stacktrace:De(e),error_fingerprint:`${e.name}:${k({text:o,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:a}}}(e,t,this.config.getPrivacy()))}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}enhanceError(e,t){const{filename:n,lineno:r,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),r&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:r}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}},Fe=class extends Y{constructor(e,{isEnabled:t}){if(super(e),this.currentUrl="",this.patches=new pe,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&t)try{this.isAutomaticNavigationEnabled=t,this.currentUrl=K.location.href}catch(e){p(e)}}isInBrowserEnvironment(){try{return void 0!==K&&void 0!==K.location&&void 0!==K.history&&"function"==typeof K.addEventListener}catch(e){return p(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||"function"!=typeof history.pushState||"function"!=typeof history.replaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");this.patches.install([this.historyPatch("pushState"),this.historyPatch("replaceState")]),K&&"function"==typeof K.addEventListener&&(K.addEventListener("popstate",this.popStateHandler),K.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){p(e)}}historyPatch(e){return{get:()=>history[e],set:t=>{history[e]=t},wrap:e=>(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n}}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.patches.restore(),K&&"function"==typeof K.removeEventListener&&(K.removeEventListener("popstate",this.popStateHandler),K.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){p(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){p(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",K.location.href);const e=this.config.getPrivacy(),t=K.location.href,n=this.activeNavigation?.metadata,r={page_url:e.shouldMaskNetworkQueryParams?P(t,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):t,metadata:H(n,e),duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0};return this.enricher.enrich({type:"navigation",attributes:r})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}startNavigation(e){try{this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:K?.location?.href||"",metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}catch(e){p(e)}}endNavigation(e){try{if(this.logger.log("[navigation-listener.endNavigation] called",e),!this.activeNavigation)return void this.logger.log("[navigation-listener.endNavigation] no active navigation found");this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()}catch(e){p(e)}}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===K.location.href)return;let e,t;try{e=new URL(K.location.href),t=new URL(this.currentUrl)}catch(e){return void p(e)}const n=e=>e.startsWith("#/"),r=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||r&&e.hash!==t.hash)&&(this.currentUrl=K.location.href,this.handleEvent())}catch(e){p(e)}}},je=class extends Y{constructor(e){super(e),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",K),"complete"===K?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):K?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),p(e)}}destroy(){K?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){p(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),r={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,i=t.initiatorType;r.totalSize+=n,r.totalDuration+=s,r.byType[i]||(r.byType[i]={count:0,size:0,duration:0}),r.byType[i].count++,r.byType[i].size+=n,r.byType[i].duration+=s}));const s=this.config.getPrivacy(),i=s.shouldMaskNetworkQueryParams,o={sensitiveKeys:s.sensitiveKeys,redact:s.redact,kind:"query"},a=K?.location?.href||"",l=K?.document?.referrer||"",c={page_url:i?P(a,o):a,page_load_time:t,page_referrer:i?P(l,o):l,page_resources:r};return this.enricher.enrich({type:"pageload",attributes:c})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}},He=class extends Y{constructor(){super(...arguments),this.handleEvent=e=>{try{const t=this.buildEvent(e);this.queueEvent(t)}catch(e){p(e)}}}initialize(){t(this.handleEvent),n(this.handleEvent),r(this.handleEvent),s(this.handleEvent),i(this.handleEvent)}destroy(){}buildEvent(e){const t={performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""};return this.enricher.enrich({type:"performance",attributes:t})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){p(e)}}};function Be(e,t){if("function"==typeof K.requestIdleCallback){const n=K.requestIdleCallback(e,{timeout:t});return()=>K.cancelIdleCallback?.(n)}let n=null,r=null,s=null;const i=()=>{null!==n&&K.cancelAnimationFrame?.(n),null!==r&&K.clearTimeout(r),null!==s&&K.clearTimeout(s),n=r=s=null},o=()=>{i(),e()};return s=K.setTimeout(o,t),"function"==typeof K.requestAnimationFrame?n=K.requestAnimationFrame((()=>{n=null,r=K.setTimeout(o,0)})):r=K.setTimeout(o,0),i}var Ue=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=g.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,r){const s=e.getInstance();if(!s.isAvailable)return n();try{return await t(s)}catch(e){return g.getInstance().log(`[${r}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,r=this.worker;return new Promise(((s,i)=>{const o=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),i(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:s,reject:i,timeoutId:o});try{r.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(o),this.pending.delete(n),i(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};Ue.instance=null;var Ke=Ue;var Ye=class{constructor(e){this.logger=g.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=null,this.lastFullSnapshotAt=0,this.cancelScheduledCheckout=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.lastFullSnapshotAt=Date.now();const e=this.configManager.getConfig()?.options,t=e?.replay,n=t?.blockedSelectors?.filter(Boolean),r=n?.length?n.join(", "):void 0,s=W(this.configManager),i=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=$(t?.maskSelectors),i=t?.replay,o="function"==typeof i?.maskTextFn?i.maskTextFn:void 0,a="function"==typeof i?.maskInputFn?i.maskInputFn:void 0;let l;return l="mask-all"===n||!r&&void 0!==o?["*",...s].join(", "):"mask-sensitive"===n?["[data-private]",...s].join(", "):void 0,{maskTextSelector:l,maskAllInputs:!r,maskTextFn:o,maskInputFn:a}}(this.configManager.getConfig()?.providedOptions),c=function(e){if(!e||!0!==e.enabled)return null;let t=e.fps??1;if("number"==typeof t&&Number.isFinite(t)){if(t<1||t>15){const e=Math.min(15,Math.max(1,t));m(`[groundcover] replay.canvas.fps ${t} is out of range [1, 15]; clamped to ${e}.`),t=e}}else m("[groundcover] replay.canvas.fps must be a finite number; falling back to 1."),t=1;return{canvasFps:t,dataURLOptions:{type:e.imageType??"image/webp",quality:e.imageQuality??.6}}}(t?.canvas),h=i.maskInputFn??("allow"===s.level?void 0:(e,t)=>Z(t,s)?"*".repeat(e.length):e);this.stopFn=o({...r?{blockSelector:r}:{},...i.maskTextSelector?{maskTextSelector:i.maskTextSelector}:{},maskAllInputs:i.maskAllInputs,...i.maskTextFn?{maskTextFn:i.maskTextFn}:{},...h?{maskInputFn:h}:{},...c?{recordCanvas:!0,dataURLOptions:c.dataURLOptions}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150,...c?{canvas:c.canvasFps}:{}},errorHandler:e=>(p(e),!0),emit:(e,t)=>{if(this.isRecording)try{this.events.push(e),e.type===a.FullSnapshot?this.lastFullSnapshotAt=Date.now():e.type!==a.IncrementalSnapshot||e.data.source===l.Mutation&&e.data.isAttachIframe||this.maybeScheduleCheckout();const n=!0===t&&e.type===a.FullSnapshot;n&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),(this.events.length>=this.batchSize||n)&&this.scheduleSendBatch()}catch(e){p(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){p(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}maybeScheduleCheckout(){this.cancelScheduledCheckout||Date.now()-this.lastFullSnapshotAt<=3e4||(this.cancelScheduledCheckout=Be((()=>{if(this.cancelScheduledCheckout=null,this.isRecording){this.lastFullSnapshotAt=Date.now();try{o.takeFullSnapshot(!0)}catch(e){p(e),this.logger.log("[session-replay-listener] failed to take full snapshot:",e)}}}),5e3))}clearScheduledCheckout(){this.cancelScheduledCheckout?.(),this.cancelScheduledCheckout=null}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=K.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{p(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(K.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.session.getSessionId(),n=Ke.getInstance();let r;if(n.isAvailable)try{r=await n.packReplay(e.events)}catch(t){p(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),r=e.events.map((e=>c(e)))}else r=e.events.map((e=>c(e)));this.session.getSessionId()===t?this.enqueueReplayEvent(r,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:r.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>c(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const r={_gc_replay_data:{events:e}};t&&(r.replay_is_full_snapshot=!0,r.replay_full_snapshot_timestamp=n);const s=this.enricher.enrich({type:"replay",attributes:r});this.eventsPool.addEvent(s),this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){p(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearScheduledSend(),this.clearScheduledCheckout(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){p(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},$e=144e5,We=288e5,Qe=18e5,Ge="gcSample",Xe={sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},sessionMaxDuration:$e},Je=["pointerdown","keydown","scroll","touchstart","mousemove"],Ve=class{constructor(e){this.logger=g.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){p(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,Je.forEach((e=>{try{K.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){p(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",Qe,"ms");try{this.callbacks.onIdle()}catch(e){p(e)}}),Qe)}catch(e){p(e)}}destroy(){if(this.installed){this.installed=!1,Je.forEach((e=>{try{K.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){p(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){p(e)}finally{this.idleTimer=null}}}};function Ze(e,t,n){return"number"==typeof e&&e>0&&e<=t&&e>t-n}function et(e,t,n){let r=null;const s=e=>{Ze(e,t,n)&&(null===r||e<r)&&(r=e)};try{for(const t of e)if(t){try{s(t.timestamp)}catch(e){p(e)}try{s(t.start_timestamp)}catch(e){p(e)}}}catch(e){p(e)}return r}var tt=class{constructor(e){this.logger=g.getInstance(),this.rotating=!1,this.session=e.session,this.pool=e.pool,this.idGenerator=e.idGenerator,this.activityEventTypes=e.activityEventTypes,this.ignoredEventTypes=e.ignoredEventTypes,this.hooks=e.hooks??{}}get isRotating(){return this.rotating}install(){this.pool.setBeforeEnqueueHook((e=>this.reconcileOnEnqueue(e))),this.pool.setFlushGate((()=>this.session.hasUserActivity()))}uninstall(e){this.pool.setBeforeEnqueueHook(null);try{e?.()}catch(e){p(e)}this.pool.setFlushGate(null)}reconcile(e,t,n){if(this.rotating)return;t&&this.session.isSessionInactive(e)&&this.rotate({reason:"inactivity gap",triggeringEvent:n});const r=this.session.getSessionElapsedMs(e),s=this.session.getSessionMaxDuration(),i=r>=s;this.logger.log("[session-lifecycle] session reconcile",{userPresent:t,elapsedMs:r,maxDurationMs:s,expired:i}),i&&this.rotate({reason:"max session duration",triggeringEvent:n}),this.hooks.onReconcile?.(t),t&&(this.session.setLastActivityMs(e),this.hooks.onPresenceStamped?.(e))}reconcileOnEnqueue(e){this.rotating||(this.ignoredEventTypes.has(e.type)?this.logger.log("[session-lifecycle] enqueue rotation check: ignoring heartbeat-style event",e.type):this.reconcile(Date.now(),this.activityEventTypes.has(e.type),e))}rotateIfStale(e,t){(this.session.isSessionInactive(e)||this.session.isSessionExpired(e))&&this.rotate({reason:t})}rotate(e){if(this.rotating)return;this.rotating=!0;const t=(e,t)=>{try{this.logger.log(`[session-lifecycle] session rotation: ${e}`),t()}catch(t){p(t),this.logger.log(`[session-lifecycle] failed to ${e} during session rotation:`,t)}};try{const n=this.session.getSessionId();let r;t("capture host rotation context",(()=>{r=this.hooks.captureRotationContext?.()}));const s=this.session.hasUserActivity();this.logger.log("[session-lifecycle] session rotation start",{reason:e.reason,previousId:n,wasConfirmed:s}),t("host beforeRotate",(()=>this.hooks.beforeRotate?.())),t(s?"flush events":"discard unconfirmed events",(()=>s?this.pool.flush():this.pool.discardBuffer())),t("rotate session ids",(()=>{const t=this.idGenerator.generateId(),r=this.resolveNewSessionStartTime(e.triggeringEvent);this.session.setSessionId(t),this.session.setSessionStartTime(r),this.session.clearSamplingDecision(),this.logger.log("[session-lifecycle] session id rotated",{from:n,to:t})})),t("host afterRotate",(()=>this.hooks.afterRotate?.(r)))}finally{this.rotating=!1,this.logger.log("[session-lifecycle] session rotation complete",{reason:e.reason})}}resolveNewSessionStartTime(e){const t=Ae(Date.now());let n=t;try{const r=Ae(Math.min(this.session.getSessionMaxDuration(),Qe)),s=[et([e],t,r),this.pool.getEarliestEventTimestamp(t,r)];for(const e of s)Ze(e,t,r)&&e<n&&(n=e)}catch(e){p(e)}return n}},nt=new Set(["dom.event"]),rt=new Set(["replay"]),st=class{constructor(e){this.logger=g.getInstance(),this.idGenerator=new v,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.replayDesired=!1,this.presenceMonitor=null,this.cancelPendingReplayResume=null,this.configManager=e.config,this.session=e.session,this.eventsPool=e.eventsPool,this.enricher=e.enricher,this.manualEvents=new U({config:this.configManager,pool:this.eventsPool,enricher:this.enricher}),this.lifecycle=new tt({session:this.session,pool:this.eventsPool,idGenerator:this.idGenerator,activityEventTypes:nt,ignoredEventTypes:rt,hooks:{captureRotationContext:()=>this.isReplayRecording()||null!==this.cancelPendingReplayResume,beforeRotate:()=>this.stopReplayListener(),afterRotate:e=>this.syncReplayState(e),onReconcile:e=>this.syncReplayState(e),onPresenceStamped:e=>this.presenceMonitor?.notePresence(e)}})}listenerDeps(){return{config:this.configManager,eventsPool:this.eventsPool,enricher:this.enricher}}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.lifecycle.install(),this.presenceMonitor?.destroy(),this.presenceMonitor=new Ve({onPresence:e=>this.lifecycle.reconcile(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,r=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new je(this.listenerDeps()),this.pageLoadListener.initialize(),r.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new de(this.listenerDeps()),this.domEventsListener.initialize(),r.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new fe(this.listenerDeps()),this.logEventsListener.initialize(),r.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new _e(this.listenerDeps()),this.errorsEventsListener.initialize(),r.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new Pe(this.listenerDeps()),this.networkEventsListener.initialize(),r.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new He(this.listenerDeps()),this.performanceListener.initialize(),r.push("performance")),this.navigationListener=new Fe(this.listenerDeps(),{isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),r.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",r)}sendCustomEvent(e){this.manualEvents.sendCustomEvent(e)}emitLog(e,t,n){this.logEventsListener&&this.manualEvents.emitLog(e,t,n)}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){p(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){this.replayDesired=!0,this.isReplayRecording()?this.logger.log("[instrumentation-manager] replay recording already started"):(this.lifecycle.rotateIfStale(Date.now(),"replay start into stale session"),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer())}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&!this.cancelPendingReplayResume&&(this.logger.log("[instrumentation-manager] user present and replay desired — resuming replay at idle"),this.cancelPendingReplayResume=Be((()=>{this.cancelPendingReplayResume=null,this.replayDesired&&this.startReplayListener()}),1e3))}cancelReplayResume(){this.cancelPendingReplayResume?.(),this.cancelPendingReplayResume=null}pauseReplayOnIdle(){this.cancelReplayResume(),this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Ye({...this.listenerDeps(),session:this.session});e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){p(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}stopReplayListener(){this.cancelReplayResume(),this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.lifecycle.uninstall((()=>{this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.cancelReplayResume(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}))}};function it(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var ot={privacy:[],tracing:["origin"],transport:[]},at=new WeakMap,lt={nestedOptions:ot,removedOptions:{}};function ct(e,t){const n=e;for(const e of Object.keys(t))Object.hasOwn(n,e)&&delete n[e]}function ht(e,t){if(!e||"object"!=typeof e)return;const n=e;for(const[e,r]of Object.entries(t))Object.hasOwn(n,e)&&m(r)}function ut(e){const t={};for(const n of[ot,e.nestedOptions??{}])for(const[e,r]of Object.entries(n))t[e]=[...new Set([...t[e]??[],...r])];return t}function dt(e,t){if(!it(e))return e;const n={...e};for(const e of t)it(n[e])&&(n[e]={...n[e]});return n}function gt(e,t,n){const r={...e,...t};for(const s of n){const n=e?.[s],i=t[s];it(n)&&it(i)?r[s]={...n,...i}:Object.hasOwn(t,s)&&!it(i)?r[s]=it(n)?{...n}:n:it(r[s])&&(r[s]={...r[s]})}return r}function ft(e,t,n){const r={...e,...t},s=t,i=e;for(const[e,t]of Object.entries(n)){if(!Object.hasOwn(s,e)){it(i[e])&&(r[e]=dt(i[e],t));continue}const n=s[e];it(n)?r[e]=gt(i[e],n,t):r[e]=dt(i[e],t)}return r}var pt=class e{constructor(t,n={}){const r={nestedOptions:ut(n),removedOptions:n.removedOptions??{}};at.set(this,r);const{nestedOptions:s,removedOptions:i}=r,o=ft(Xe,n.defaults??{},s);this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=ft(o,t?.options||{},s),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),ht(t?.options,i),ct(this.providedOptions,i),ct(this.options,i)}static normalizeSessionMaxDuration(e){return void 0===e?$e:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>We?(m("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),$e):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){if(t.options){const{nestedOptions:r,removedOptions:s}=(n=this,at.get(n)??lt);ht(t.options,s),this.providedOptions=ft(this.providedOptions||{},t.options,r),this.options=ft(this.options,t.options,r),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),ct(this.providedOptions,s),ct(this.options,s)}var n;void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}},mt=class{constructor(e={}){this.extension=e,this.config=null,this.logger=g.getInstance(),this.privacyCache=null}initialize(e){this.config||(this.config=new pt(e,this.extension))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){if(!this.privacyCache){const e=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",r="allow"===n,s=e=>!r&&(e??!0),i=s(t?.maskNetworkBodies),o=s(t?.maskNetworkQueryParams),a=s(t?.maskLogs),l=s(t?.maskErrors);return{level:n,maskNetworkBodies:i,maskNetworkQueryParams:o,maskLogs:a,maskErrors:l,shouldMaskNetworkBodies:!r&&i,shouldMaskNetworkQueryParams:!r&&o,shouldMaskLogs:!r&&a,shouldMaskErrors:!r&&l,sensitiveKeys:$(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0}}(this.config?.providedOptions);this.extension.isOpaqueNode&&(e.isOpaqueNode=this.extension.isOpaqueNode),this.privacyCache=e}return this.privacyCache}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}};function vt(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var yt={isOpaqueNode:vt,nestedOptions:{replay:["canvas"],privacy:["replay"]},defaults:{replay:{}},removedOptions:{enableMasking:"[groundcover] `options.enableMasking` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",maskFields:"[groundcover] `options.maskFields` was removed in 1.0.0 and is ignored. Configure masking via `options.privacy` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100",eventSampleRate:"[groundcover] `options.eventSampleRate` was removed and is ignored. Events are no longer randomly sampled; event volume may increase. Use `options.sessionSampleRate` to select whole sessions; rates are not automatically converted. See the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-from-1x-to-200"}},bt=Xe.transport?.batchSize??10,wt=Xe.transport?.batchTimeout??1e4;var kt=class{constructor(e){this.events=[],this.timeoutId=null,this.logger=g.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.unusableEnrichWarned=!1,this.onBeforeEnqueue=null,this.flushGate=null,this.config=e.config,this.session=e.session,this.transporter=e.transporter,this.getDeviceAttributes=e.getDeviceAttributes,this.eventsToSkipFlush=e.eventsToSkipFlush}initialize(){try{if(this.initialized)return;this.scheduleFlush(),this.initialized=!0}catch(e){p(e)}}destroy(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.events=[],this.initialized=!1}catch(e){p(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}setFlushGate(e){this.flushGate=e}discardBuffer(){this.events=[]}getEarliestEventTimestamp(e,t){return et(this.events,e,t)}isFlushAllowed(){if(null===this.flushGate)return!0;try{return this.flushGate()}catch(e){return p(e),!0}}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,r=this.config.getConfig()?.options?.enrichEvent;let s=e;if(n&&!n(s))return;if(r){const e=r(s);if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"string"==typeof e.type}catch(e){return p(e),!1}}(e))return void(this.unusableEnrichWarned||(this.unusableEnrichWarned=!0,this.logger.log("[events-pool.addEvent] dropping event: enrichEvent returned an unusable value")));s=e}if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(s)}catch(e){p(e)}if(!this.isFlushAllowed()&&this.events.length>=500)return;this.events.push(s);const i=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:bt);this.events.length>=i&&!this.eventsToSkipFlush.includes(s.type)&&this.flush()}catch(e){p(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.isFlushAllowed())return void this.scheduleFlush();if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),this.events=[],this.scheduleFlush()}catch(e){p(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.isFlushAllowed())return void this.discardBuffer();if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){p(e)}}scheduleFlush(){try{null!==this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:wt);this.timeoutId=setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){p(e)}var e}getSessionAttributes(){return this.buildSessionAttributes()}buildSessionAttributes(){const e=this.config.getConfig();let t={};try{t=this.getDeviceAttributes()}catch(e){p(e)}return{...t,cluster:e?.cluster||"",env:e?.environment||"",namespace:e?.namespace||"",releaseId:e?.releaseId||"",session_id:this.session.getSessionId(),session_start_time:this.session.getSessionStartTime(),user:e?.user||{},"service.name":e?.appId}}};function Et(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:t}var St=class{constructor(e={}){this.logger=g.getInstance(),this.enrichAttributes=e.enrichAttributes??null,this.reservedAttributeKeys=e.reservedAttributeKeys??[],this.isOpaqueNode=e.isOpaqueNode??null,this.idGenerator=e.idGenerator??new v}getPlatformAttributes(){if(!this.enrichAttributes)return{};try{return this.enrichAttributes()??{}}catch(e){return this.logger.log("[event-enricher] platform attribute contributor threw; continuing without it",e),{}}}formatEventObject(e,t="",n=new WeakSet,r=0){try{return r>=10?{[t||"depth_limit"]:"[Depth Limit]"}:this.isOpaqueNode?.(e)?{[t||"opaque_node"]:`[${e?.constructor?.name||"OpaqueNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,i])=>{const o=t?`${t}.${s}`:s;return"object"==typeof i&&null!==i?Array.isArray(i)?e[o]=i.map(((e,t)=>"object"==typeof e&&null!==e?this.formatEventObject(e,`${o}[${t}]`,n,r+1):e)):Object.assign(e,this.formatEventObject(i,o,n,r+1)):e[o]=i,e}),{}))}catch(e){return this.logger.log("[event-enricher.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}enrich(e){const t=Ae(Date.now()),n=this.idGenerator.generateId(),r=e.spanId||this.idGenerator.generateSpanId(),s=e.traceId||this.idGenerator.generateTraceId(),i=e.parentSpanId||"",o=this.formatEventObject(e.attributes||{}),a=this.getPlatformAttributes(),l={type:e.type,id:n,spanId:r,parentSpanId:i,traceId:s,attributes:{...o,...a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=Et(e.timestamp,t),l.end_timestamp=e?.end_timestamp):l.timestamp=Et(e.timestamp,t),l}};function It(e,t){const n=h(e);if(!t)return{data:n,isCompressed:!1};try{return{data:u(n),isCompressed:!0}}catch{return{data:n,isCompressed:!1}}}var Tt=class{constructor(e){this.logger=g.getInstance(),this.config=e.config,this.sendBatch=e.sendBatch,this.encodeAsync=e.encodeAsync??null}compressAsync(e,t){if(!this.encodeAsync)return Promise.resolve(It(e,t));try{return this.encodeAsync(e,t).catch((()=>It(e,t)))}catch{return Promise.resolve(It(e,t))}}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const r=n.apiKey,s=this.buildEndpoint();if(!r)return void this.logger.log("No API key found");const i=JSON.stringify(e),o=!!n?.options?.transport?.compression,{data:a,isCompressed:l}=t?It(i,o):await this.compressAsync(i,o),c={"Content-Type":"application/json",apikey:r,"Content-Encoding":l?"gzip":""};this.sendBatch(s,{method:"POST",headers:c,body:a}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n?.options?.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},Rt=class{constructor(e){this.storage=e}getItem(e){try{return this.storage?.getItem(e)??null}catch(e){return p(e),null}}setItem(e,t){try{this.storage?.setItem(e,t)}catch(e){p(e)}}removeItem(e){try{this.storage?.removeItem(e)}catch(e){p(e)}}getNumericItem(e,t=0){const n=this.getItem(e);if(null===n)return t;const r=Number(n);return Number.isFinite(r)?r:t}},At=class{constructor(e){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage=e.storage,this.getMaxDurationMs=e.getMaxDurationMs??null}getSessionId(){if(this.sessionId)return this.sessionId;return this.storage.getItem("gcId")||""}setSessionId(e){this.sessionId=e,this.storage.setItem("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:this.storage.getNumericItem("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,this.storage.setItem("gcStartTime",String(e)),this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcLastActivity")}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:this.storage.getNumericItem("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,this.storage.setItem("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs(),n=t>0?t:Le(this.getSessionStartTime());return n>0&&e-n>=Qe}hasUserActivity(){return this.getLastActivityMs()>0}clearSamplingDecision(){this.storage.removeItem(Ge)}clearSessionState(){this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.storage.removeItem("gcId"),this.storage.removeItem("gcStartTime"),this.storage.removeItem("gcLastActivity"),this.clearSamplingDecision()}getSessionMaxDuration(){return this.getMaxDurationMs?.()??$e}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-Le(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}};function Lt(){const e=navigator.userAgent;let t="unknown",n="unknown";const r=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{userAgent:e,browser:{name:t,version:n,platform:r,language:navigator.language,mobile:s}}}var xt,Ct,Nt=["navigation","dom.event"],Mt=class{constructor(e){this.core=null,this.hideWired=!1,this.hideHandler=()=>{try{if("undefined"==typeof document||"hidden"!==document.visibilityState)return;this.core?.session.persistLastActivity(),this.core?.instrumentation.flushPendingReplay(),this.core?.pool.flush({lifecycle:!0})}catch(e){p(e)}},this.logger=g.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.storage=new Rt(function(){try{return void 0!==globalThis.sessionStorage?globalThis.sessionStorage:null}catch{return null}}()),this.idGenerator=new v;const t=new mt(yt);t.initialize(e);const n=new At({storage:this.storage,getMaxDurationMs:()=>t.getConfig()?.options?.sessionMaxDuration});!function({session:e,idGenerator:t,providedSessionId:n}){const r=g.getInstance();try{const s=e.getSessionId();n&&n!==s?(e.setSessionId(n),e.setSessionStartTime(Ae(Date.now())),e.clearSamplingDecision(),r.log("[session-bootstrap] using provided sessionId:",n)):n?(e.setSessionId(n),r.log("[session-bootstrap] continuing provided sessionId:",n)):s||e.setSessionId(t.generateId());const i=6e4,o=Date.now(),a=Le(e.getSessionStartTime());if(a>0&&o-a>=-i){if(e.isSessionExpired(o)||e.isSessionInactive(o)){const n=e.isSessionExpired(o)?"persisted session past cap":"inactivity gap across restart",s=e.getSessionId(),i=t.generateId();e.setSessionId(i),e.setSessionStartTime(Ae(o)),e.clearSamplingDecision(),r.log(`[session-bootstrap] init-time rotation: ${n}`,{from:s,to:i})}}else e.setSessionStartTime(Ae(o))}catch(e){r.log("[session-bootstrap] session bootstrap failed:",e)}}({session:n,idGenerator:this.idGenerator,providedSessionId:e.sessionId});if(!function({storage:e,sessionSampleRate:t}){const n=g.getInstance();if(void 0===t||!Number.isFinite(t)||1===t)return!0;const r=t;try{const t=e.getItem(Ge);if(t){const e="1"===t;return n.log("[session-bootstrap] using stored sampling decision:",e),e}const s=Math.random()<r;return e.setItem(Ge,s?"1":"0"),n.log("[session-bootstrap] stored new sampling decision:",s),s}catch(e){n.log("[session-bootstrap] storage access failed:",e);const t=Math.random()<r;return n.log("[session-bootstrap] using fallback sampling decision:",t),t}}({storage:this.storage,sessionSampleRate:e.options?.sessionSampleRate}))return void this.logger.log("[session-manager] session is not sampled");const r=new Tt({config:t,sendBatch:(e,t)=>fetch(e,t),encodeAsync:(e,t)=>Ke.withFallback((n=>n.encodeBatch(e,t)),(()=>It(e,t)),"transporter")}),s=new kt({config:t,session:n,transporter:r,getDeviceAttributes:Lt,eventsToSkipFlush:Nt}),i=function(e){return()=>{let t="";try{t=K?.document?.title||""}catch(e){p(e)}try{const n=K?.location;if(!n)return{path:"",url:"",title:t};const r=n.hash&&!n.hash.match(/^#[a-z0-9-]+$/i)&&n.hash.startsWith("#/"),s=r?n.hash:n.pathname,i=e.getPrivacy(),o=i.shouldMaskNetworkQueryParams,a={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:o&&r?P(s,a):s,url:o?P(n.href,a):n.href,title:t}}catch(e){return p(e),{path:"",url:"",title:t}}}}(t),o=new St({enrichAttributes:()=>({location:i()}),reservedAttributeKeys:["location"],isOpaqueNode:vt,idGenerator:this.idGenerator}),a=new st({config:t,session:n,eventsPool:s,enricher:o});try{s.initialize(),Ke.getInstance(),this.wireHideHandler(),a.instrument(),this.core={config:t,session:n,pool:s,instrumentation:a}}catch(e){this.logger.log("[session-manager] initialization failed — tearing down partial startup:",e);try{a.uninstrument()}catch(e){p(e)}throw s.destroy(),this.unwireHideHandler(),this.core=null,e}}wireHideHandler(){if(!this.hideWired&&"undefined"!=typeof document){this.hideWired=!0;try{document.addEventListener("visibilitychange",this.hideHandler)}catch(e){p(e)}}}unwireHideHandler(){if(this.hideWired&&"undefined"!=typeof document){this.hideWired=!1;try{document.removeEventListener("visibilitychange",this.hideHandler)}catch(e){p(e)}}}identifyUser(e){this.logger.log("[session-manager] identifyUser called"),this.core?this.core.config.updateConfig({user:e}):this.logger.log("[session-manager] cannot identify user: SDK not initialized")}updateConfig(e){try{if(null===e||"object"!=typeof e)return void m("[groundcover] updateConfig requires a configuration object; the update was ignored.");if("appId"in e)return void m("[groundcover] updateConfig does not accept appId; the entire update was ignored. Remove appId from the update.");if(!this.core)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");this.core.config.updateConfig(e);const t=e.options,n=!!t&&Object.hasOwn(t,"privacy"),r=t&&Object.hasOwn(t,"replay")&&"object"==typeof t.replay&&null!==t.replay?t.replay:void 0,s=!!r&&Object.hasOwn(r,"blockedSelectors"),i=!!r&&Object.hasOwn(r,"canvas");(n||s||i)&&this.core.instrumentation.restartReplayForConfigChange()}catch(e){p(e)}}sendCustomEvent(e){this.core?this.core.instrumentation.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.core?this.core.instrumentation.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.core?this.core.instrumentation.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.core?this.core.instrumentation.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}emitLog(e,t,n){this.core?this.core.instrumentation.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.core?this.core.session.getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.core)try{this.core.instrumentation.flushPendingReplay(),await this.core.pool.flushSync();const t=e||this.idGenerator.generateId();this.core.session.setSessionId(t),this.core.session.setSessionStartTime(Ae(Date.now())),this.logger.log("[session-manager] session ID set successfully:",t)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.core?this.core.instrumentation.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.core?this.core.instrumentation.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){const e=this.core;e&&(e.instrumentation.uninstrument(),e.pool.destroy(),this.unwireHideHandler(),Ke.getInstance().terminate(),e.session.clearSessionState(),this.core=null)}},qt=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var Ot={init:function(e){if(void 0===Ct)try{const t=e?.appId;if(void 0!==Ct)return;if("string"!=typeof t||0===t.trim().length)return void m("[groundcover] init requires a nonblank appId; the SDK was not initialized.");Ct=t,xt=new Mt({cluster:e.cluster||"",environment:e.environment||"",namespace:e.namespace,releaseId:e.releaseId,dsn:e.dsn||"",appId:t,user:e.user,apiKey:e.apiKey||"",options:e.options,sessionId:e.sessionId}),qt.manager=xt}catch(e){xt||(Ct=void 0),p(e)}},identifyUser:function(e){xt?xt.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){xt&&xt.sendCustomEvent(e)},captureException:function(e,t){xt&&xt.captureException(e,t)},logger:qt,updateConfig:function(e){if(xt)try{xt.updateConfig(e)}catch(e){p(e)}},startNavigation:function(e){xt?xt.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){xt?xt.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return xt?xt.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(xt)try{await xt.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){xt?xt.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){xt?xt.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Ot}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var zt=Ot;export{zt as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@groundcover/browser",
3
- "version": "2.1.0-rc.1",
3
+ "version": "2.1.1-rc.0",
4
4
  "description": "groundcover Real User Monitoring (RUM) SDK for the browser \u2014 performance, errors, logs, distributed tracing and session replay",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",