@tracelog/lib 2.2.0 → 2.2.1
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/dist/browser/tracelog.esm.js +146 -184
- package/dist/browser/tracelog.esm.js.map +1 -1
- package/dist/browser/tracelog.js +1 -1
- package/dist/browser/tracelog.js.map +1 -1
- package/dist/public-api.cjs +23 -60
- package/dist/public-api.cjs.map +1 -1
- package/dist/public-api.d.mts +1 -2
- package/dist/public-api.d.ts +1 -2
- package/dist/public-api.js +24 -60
- package/dist/public-api.js.map +1 -1
- package/package.json +1 -1
package/dist/browser/tracelog.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(h){"use strict";const y="data-tlog",ut=["button","a",'input[type="button"]','input[type="submit"]','input[type="reset"]','input[type="checkbox"]','input[type="radio"]',"select","textarea",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="option"]','[role="checkbox"]','[role="radio"]','[role="switch"]',"[routerLink]","[ng-click]","[data-action]","[data-click]","[data-navigate]","[data-toggle]","[onclick]",".btn",".button",".clickable",".nav-link",".menu-item","[data-testid]",'[tabindex="0"]'],dt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],ht=["token","auth","key","session","reset","password","api_key","apikey","secret","access_token","refresh_token","verification","code","otp"],g={INVALID_SESSION_TIMEOUT:"Session timeout must be between 30000ms (30 seconds) and 86400000ms (24 hours)",INVALID_SAMPLING_RATE:"Sampling rate must be between 0 and 1",INVALID_ERROR_SAMPLING_RATE:"Error sampling must be between 0 and 1",INVALID_TRACELOG_PROJECT_ID:"TraceLog project ID is required when integration is enabled",INVALID_CUSTOM_API_URL:"Custom API URL is required when integration is enabled",INVALID_GLOBAL_METADATA:"Global metadata must be an object",INVALID_SENSITIVE_QUERY_PARAMS:"Sensitive query params must be an array of strings",INVALID_PRIMARY_SCROLL_SELECTOR:"Primary scroll selector must be a non-empty string",INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX:"Invalid CSS selector syntax for primaryScrollSelector",INVALID_PAGE_VIEW_THROTTLE:"Page view throttle must be a non-negative number",INVALID_CLICK_THROTTLE:"Click throttle must be a non-negative number",INVALID_MAX_SAME_EVENT_PER_MINUTE:"Max same event per minute must be a positive number",INVALID_VIEWPORT_CONFIG:"Viewport config must be an object",INVALID_VIEWPORT_ELEMENTS:"Viewport elements must be a non-empty array",INVALID_VIEWPORT_ELEMENT:"Each viewport element must have a valid selector string",INVALID_VIEWPORT_ELEMENT_ID:"Viewport element id must be a non-empty string",INVALID_VIEWPORT_ELEMENT_NAME:"Viewport element name must be a non-empty string",INVALID_VIEWPORT_THRESHOLD:"Viewport threshold must be a number between 0 and 1",INVALID_VIEWPORT_MIN_DWELL_TIME:"Viewport minDwellTime must be a non-negative number",INVALID_VIEWPORT_COOLDOWN_PERIOD:"Viewport cooldownPeriod must be a non-negative number",INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS:"Viewport maxTrackedElements must be a positive number"},ft=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/on\w+\s*=/gi,/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,/<embed\b[^>]*>/gi,/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi],w="tlog",F=`${w}:qa_mode`,Me=`${w}:uid`,Le="tlog_mode",Ce="qa",Re="qa_off",mt=s=>s?`${w}:${s}:queue`:`${w}:queue`,gt=s=>s?`${w}:${s}:session`:`${w}:session`,Et=s=>s?`${w}:${s}:broadcast`:`${w}:broadcast`,Ne=(s,e)=>`${w}:${s}:session_counts:${e}`,Oe=10080*60*1e3,Pe=`${w}:session_counts_last_cleanup`,De=3600*1e3;var D=(s=>(s.Localhost="localhost:8080",s.Fail="localhost:9999",s))(D||{}),b=(s=>(s.Mobile="mobile",s.Tablet="tablet",s.Desktop="desktop",s.Unknown="unknown",s))(b||{}),X=(s=>(s.EVENT="event",s.QUEUE="queue",s))(X||{});class N extends Error{constructor(e,t){super(e),this.statusCode=t,this.name="PermanentError",Error.captureStackTrace&&Error.captureStackTrace(this,N)}}var d=(s=>(s.PAGE_VIEW="page_view",s.CLICK="click",s.SCROLL="scroll",s.SESSION_START="session_start",s.CUSTOM="custom",s.WEB_VITALS="web_vitals",s.ERROR="error",s.VIEWPORT_VISIBLE="viewport_visible",s))(d||{}),$=(s=>(s.UP="up",s.DOWN="down",s))($||{}),V=(s=>(s.JS_ERROR="js_error",s.PROMISE_REJECTION="promise_rejection",s))(V||{}),B=(s=>(s.QA="qa",s))(B||{});const St=s=>s.type===d.SCROLL&&"scroll_data"in s&&s.scroll_data.is_primary===!0,Tt=s=>s.type===d.SCROLL&&"scroll_data"in s&&s.scroll_data.is_primary===!1;class k extends Error{constructor(e,t,r){super(e),this.errorCode=t,this.layer=r,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class m extends k{constructor(e,t="config"){super(e,"APP_CONFIG_INVALID",t)}}class Ve extends k{constructor(e,t="config"){super(e,"SESSION_TIMEOUT_INVALID",t)}}class ne extends k{constructor(e,t="config"){super(e,"SAMPLING_RATE_INVALID",t)}}class U extends k{constructor(e,t="config"){super(e,"INTEGRATION_INVALID",t)}}class pt extends k{constructor(e,t,r="runtime"){super(e,"INITIALIZATION_TIMEOUT",r),this.timeoutMs=t}}const ke="background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",Ue="background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",_t="background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",vt=(s,e)=>{if(e){if(e instanceof Error){const t=e.message.replace(/\s+at\s+.*$/gm,"").replace(/\s*\([^()]+:\d+:\d+\)/g,"");return`[TraceLog] ${s}: ${t}`}if(e instanceof Error)return`[TraceLog] ${s}: ${e.message}`;if(typeof e=="string")return`[TraceLog] ${s}: ${e}`;if(typeof e=="object")try{return`[TraceLog] ${s}: ${JSON.stringify(e)}`}catch{return`[TraceLog] ${s}: [Unable to serialize error]`}return`[TraceLog] ${s}: ${String(e)}`}return`[TraceLog] ${s}`},It=()=>{if(typeof window>"u"||typeof sessionStorage>"u")return!1;try{return sessionStorage.getItem(F)==="true"}catch{return!1}},a=(s,e,t)=>{const{error:r,data:n,showToClient:i=!1,style:o,visibility:l}=t??{},c=r?vt(e,r):`[TraceLog] ${e}`,u=s==="error"?"error":s==="warn"?"warn":"log";if(!wt(l,i))return;const E=yt(l,o),p=n!==void 0?ie(n):void 0;bt(u,c,E,p)},wt=(s,e)=>s==="critical"?!0:s==="qa"||e?It():!1,yt=(s,e)=>e!==void 0&&e!==""?e:s==="critical"?_t:"",bt=(s,e,t,r)=>{const n=t!==void 0&&t!=="",i=n?`%c${e}`:e;r!==void 0?n?console[s](i,t,r):console[s](i,r):n?console[s](i,t):console[s](i)},ie=s=>{const e={},t=["token","password","secret","key","apikey","api_key","sessionid","session_id"];for(const[r,n]of Object.entries(s)){const i=r.toLowerCase();if(t.some(o=>i.includes(o))){e[r]="[REDACTED]";continue}n!==null&&typeof n=="object"&&!Array.isArray(n)?e[r]=ie(n):Array.isArray(n)?e[r]=n.map(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?ie(o):o):e[r]=n}return e};let oe,He;const At=()=>{typeof window<"u"&&!oe&&(oe=window.matchMedia("(pointer: coarse)"),He=window.matchMedia("(hover: none)"))},Q="Unknown",Mt=s=>{const e=s.userAgentData?.platform;if(e!=null&&e!==""){if(/windows/i.test(e))return"Windows";if(/macos/i.test(e))return"macOS";if(/android/i.test(e))return"Android";if(/linux/i.test(e))return"Linux";if(/chromeos/i.test(e))return"ChromeOS";if(/ios/i.test(e))return"iOS"}const t=navigator.userAgent;return/Windows/i.test(t)?"Windows":/iPhone|iPad|iPod/i.test(t)?"iOS":/Mac OS X|Macintosh/i.test(t)?"macOS":/Android/i.test(t)?"Android":/CrOS/i.test(t)?"ChromeOS":/Linux/i.test(t)?"Linux":Q},Lt=s=>{const e=s.userAgentData?.brands;if(e!=null&&e.length>0){const n=e.filter(i=>!/not.?a.?brand|chromium/i.test(i.brand))[0];if(n!=null){const i=n.brand;return/google chrome/i.test(i)?"Chrome":/microsoft edge/i.test(i)?"Edge":/opera/i.test(i)?"Opera":i}}const t=navigator.userAgent;return/Edg\//i.test(t)?"Edge":/OPR\//i.test(t)?"Opera":/Chrome/i.test(t)?"Chrome":/Firefox/i.test(t)?"Firefox":/Safari/i.test(t)&&!/Chrome/i.test(t)?"Safari":Q},Ct=()=>{try{const s=navigator;if(s.userAgentData!=null&&typeof s.userAgentData.mobile=="boolean"){const c=s.userAgentData.platform;return c!=null&&c!==""&&/ipad|tablet/i.test(c)?b.Tablet:s.userAgentData.mobile?b.Mobile:b.Desktop}At();const e=window.innerWidth,t=oe?.matches??!1,r=He?.matches??!1,n="ontouchstart"in window||navigator.maxTouchPoints>0,i=navigator.userAgent.toLowerCase(),o=/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(i),l=/tablet|ipad|android(?!.*mobile)/.test(i);return e<=767||o&&n?b.Mobile:e>=768&&e<=1024||l||t&&r&&n?b.Tablet:b.Desktop}catch(s){return a("debug","Device detection failed, defaulting to desktop",{error:s}),b.Desktop}},Rt=()=>{try{const s=navigator;return{type:Ct(),os:Mt(s),browser:Lt(s)}}catch(s){return a("debug","Device info detection failed, using defaults",{error:s}),{type:b.Desktop,os:Q,browser:Q}}},ae=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/gi,/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,/\b[A-Z]{2}\d{2}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/gi,/\b[sp]k_(test|live)_[a-zA-Z0-9]{10,}\b/gi,/Bearer\s+[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?(?:\.[A-Za-z0-9_-]+)?/gi,/:\/\/[^:/]+:([^@]+)@/gi],xe=500,Fe=5e3,j=50,Nt=j*2,$e=1,Ot=1e3,Pt=10,Be=5e3,Dt=6e4,Vt={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},le={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},We={LCP:4e3,FCP:3e3,CLS:.25,INP:500,TTFB:1800,LONG_TASK:50},z="needs-improvement",ce=(s=z)=>{switch(s){case"all":return{LCP:0,FCP:0,CLS:0,INP:0,TTFB:0,LONG_TASK:0};case"needs-improvement":return le;case"poor":return We;default:return le}},kt=1e3,Ut=50,Ht="2.1.2",Ge=()=>typeof window<"u"&&typeof sessionStorage<"u",xt=()=>{try{const s=new URLSearchParams(window.location.search);s.delete(Le);const e=s.toString(),t=window.location.pathname+(e?"?"+e:"")+window.location.hash;window.history.replaceState({},"",t)}catch{}},Ft=()=>{if(!Ge())return!1;try{const e=new URLSearchParams(window.location.search).get(Le),t=sessionStorage.getItem(F);let r=null;return e===Ce?(r=!0,sessionStorage.setItem(F,"true"),a("info","QA Mode ACTIVE",{visibility:"qa",style:ke})):e===Re&&(r=!1,sessionStorage.setItem(F,"false"),a("info","QA Mode DISABLED",{visibility:"qa",style:Ue})),(e===Ce||e===Re)&&xt(),r??t==="true"}catch{return!1}},$t=s=>{if(Ge())try{sessionStorage.setItem(F,s?"true":"false"),a("info",s?"QA Mode ACTIVE":"QA Mode DISABLED",{visibility:"qa",style:s?ke:Ue})}catch{a("debug","Cannot set QA mode: sessionStorage unavailable")}},Bt=["co.uk","org.uk","com.au","net.au","com.br","co.nz","co.jp","com.mx","co.in","com.cn","co.za"],Xe=s=>{const e=s.toLowerCase().split(".");if(e.length<=2)return s.toLowerCase();const t=e.slice(-2).join(".");return Bt.includes(t)?e.slice(-3).join("."):e.slice(-2).join(".")},Wt=(s,e)=>s===e?!0:Xe(s)===Xe(e),ue=()=>{const s=document.referrer;if(!s)return"Direct";try{const e=new URL(s).hostname.toLowerCase(),t=window.location.hostname.toLowerCase();return Wt(e,t)?"Direct":s}catch(e){return a("debug","Failed to parse referrer URL, using raw value",{error:e,data:{referrer:s}}),s}},de=()=>{const s=new URLSearchParams(window.location.search),e={};return dt.forEach(r=>{const n=s.get(r);if(n){const i=r.split("utm_")[1];e[i]=n}}),Object.keys(e).length?e:void 0},Gt=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)});let K=0,Y=0;const Xt=()=>{let s=Date.now();s<Y&&(s=Y),s===Y?K=(K+1)%1e3:K=0,Y=s;const e=K.toString().padStart(3,"0");let t="";try{if(typeof crypto<"u"&&crypto.getRandomValues){const r=crypto.getRandomValues(new Uint8Array(3));r&&(t=Array.from(r,n=>n.toString(16).padStart(2,"0")).join(""))}}catch{}return t||(t=Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")),`${s}-${e}-${t}`},Qe=(s,e=!1)=>{try{const t=new URL(s),r=t.protocol==="https:",n=t.protocol==="http:";return r||e&&n}catch{return!1}},Qt=s=>{try{const t=new URL(window.location.href).hostname;if(!t||typeof t!="string")throw new Error("Invalid hostname");if(t==="localhost"||t==="127.0.0.1"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t))throw new Error("SaaS integration not supported on localhost or IP addresses. Use custom backend integration instead.");const r=t.split(".");if(!r||!Array.isArray(r)||r.length===0||r.length===1&&r[0]==="")throw new Error("Invalid hostname structure");if(r.length===1)throw new Error("Single-part domain not supported for SaaS integration");let n;if(r.length===2?n=r.join("."):n=r.slice(-2).join("."),!n||n.split(".").length<2)throw new Error("Invalid domain structure for SaaS");const i=`https://${s}.${n}/collect`;if(!Qe(i))throw new Error("Generated URL failed validation");return i}catch(e){throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error?e.message:String(e)}`)}},jt=s=>{const e={};s.integrations?.tracelog?.projectId&&(e.saas=Qt(s.integrations.tracelog.projectId));const t=s.integrations?.custom?.collectApiUrl;if(t){const r=s.integrations?.custom?.allowHttp??!1;if(!Qe(t,r))throw new Error("Invalid custom API URL");e.custom=t}return e},he=(s,e=[])=>{if(!s||typeof s!="string")return a("warn","Invalid URL provided to normalizeUrl",{data:{type:typeof s}}),s||"";try{const t=new URL(s),r=t.searchParams,n=[...new Set([...ht,...e])];let i=!1;const o=[];return n.forEach(c=>{r.has(c)&&(r.delete(c),i=!0,o.push(c))}),!i&&s.includes("?")?s:(t.search=r.toString(),t.toString())}catch(t){return a("warn","URL normalization failed, returning original",{error:t,data:{urlLength:s?.length}}),s}},je=s=>{if(!s||typeof s!="string"||s.trim().length===0)return"";let e=s;s.length>1e3&&(e=s.slice(0,Math.max(0,1e3)));let t=0;for(const n of ft){const i=e;e=e.replace(n,""),i!==e&&t++}return t>0&&a("warn","XSS patterns detected and removed",{data:{patternMatches:t,valueLength:s.length}}),e=e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'").replaceAll("/","/"),e.trim()},fe=(s,e=0)=>{if(e>3||s==null)return null;if(typeof s=="string")return je(s);if(typeof s=="number")return!Number.isFinite(s)||s<-Number.MAX_SAFE_INTEGER||s>Number.MAX_SAFE_INTEGER?0:s;if(typeof s=="boolean")return s;if(Array.isArray(s))return s.slice(0,100).map(n=>fe(n,e+1)).filter(n=>n!==null);if(typeof s=="object"){const t={},n=Object.entries(s).slice(0,20);for(const[i,o]of n){const l=je(i);if(l){const c=fe(o,e+1);c!==null&&(t[l]=c)}}return t}return null},zt=s=>{if(typeof s!="object"||s===null)return{};try{const e=fe(s);return typeof e=="object"&&e!==null?e:{}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`[TraceLog] Metadata sanitization failed: ${t}`)}},Kt=s=>{if(s!==void 0&&(s===null||typeof s!="object"))throw new m("Configuration must be an object","config");if(s){if(s.sessionTimeout!==void 0&&(typeof s.sessionTimeout!="number"||s.sessionTimeout<3e4||s.sessionTimeout>864e5))throw new Ve(g.INVALID_SESSION_TIMEOUT,"config");if(s.globalMetadata!==void 0&&(typeof s.globalMetadata!="object"||s.globalMetadata===null))throw new m(g.INVALID_GLOBAL_METADATA,"config");if(s.integrations&&qt(s.integrations),s.sensitiveQueryParams!==void 0){if(!Array.isArray(s.sensitiveQueryParams))throw new m(g.INVALID_SENSITIVE_QUERY_PARAMS,"config");for(const e of s.sensitiveQueryParams)if(typeof e!="string")throw new m("All sensitive query params must be strings","config")}if(s.errorSampling!==void 0&&(typeof s.errorSampling!="number"||s.errorSampling<0||s.errorSampling>1))throw new ne(g.INVALID_ERROR_SAMPLING_RATE,"config");if(s.samplingRate!==void 0&&(typeof s.samplingRate!="number"||s.samplingRate<0||s.samplingRate>1))throw new ne(g.INVALID_SAMPLING_RATE,"config");if(s.primaryScrollSelector!==void 0){if(typeof s.primaryScrollSelector!="string"||!s.primaryScrollSelector.trim())throw new m(g.INVALID_PRIMARY_SCROLL_SELECTOR,"config");if(s.primaryScrollSelector!=="window")try{document.querySelector(s.primaryScrollSelector)}catch{throw new m(`${g.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${s.primaryScrollSelector}"`,"config")}}if(s.pageViewThrottleMs!==void 0&&(typeof s.pageViewThrottleMs!="number"||s.pageViewThrottleMs<0))throw new m(g.INVALID_PAGE_VIEW_THROTTLE,"config");if(s.clickThrottleMs!==void 0&&(typeof s.clickThrottleMs!="number"||s.clickThrottleMs<0))throw new m(g.INVALID_CLICK_THROTTLE,"config");if(s.maxSameEventPerMinute!==void 0&&(typeof s.maxSameEventPerMinute!="number"||s.maxSameEventPerMinute<=0))throw new m(g.INVALID_MAX_SAME_EVENT_PER_MINUTE,"config");if(s.viewport!==void 0&&Yt(s.viewport),s.webVitalsMode!==void 0){if(typeof s.webVitalsMode!="string")throw new m(`Invalid webVitalsMode type: ${typeof s.webVitalsMode}. Must be a string`,"config");const e=["all","needs-improvement","poor"];if(!e.includes(s.webVitalsMode))throw new m(`Invalid webVitalsMode: "${s.webVitalsMode}". Must be one of: ${e.join(", ")}`,"config")}if(s.webVitalsThresholds!==void 0){if(typeof s.webVitalsThresholds!="object"||s.webVitalsThresholds===null||Array.isArray(s.webVitalsThresholds))throw new m("webVitalsThresholds must be an object","config");const e=["LCP","FCP","CLS","INP","TTFB","LONG_TASK"];for(const[t,r]of Object.entries(s.webVitalsThresholds)){if(!e.includes(t))throw new m(`Invalid Web Vitals threshold key: "${t}". Must be one of: ${e.join(", ")}`,"config");if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new m(`Invalid Web Vitals threshold value for ${t}: ${r}. Must be a non-negative finite number`,"config")}}}},Yt=s=>{if(typeof s!="object"||s===null)throw new m(g.INVALID_VIEWPORT_CONFIG,"config");if(!s.elements||!Array.isArray(s.elements))throw new m(g.INVALID_VIEWPORT_ELEMENTS,"config");if(s.elements.length===0)throw new m(g.INVALID_VIEWPORT_ELEMENTS,"config");const e=new Set;for(const t of s.elements){if(!t.selector||typeof t.selector!="string"||!t.selector.trim())throw new m(g.INVALID_VIEWPORT_ELEMENT,"config");const r=t.selector.trim();if(e.has(r))throw new m(`Duplicate viewport selector found: "${r}". Each selector should appear only once.`,"config");if(e.add(r),t.id!==void 0&&(typeof t.id!="string"||!t.id.trim()))throw new m(g.INVALID_VIEWPORT_ELEMENT_ID,"config");if(t.name!==void 0&&(typeof t.name!="string"||!t.name.trim()))throw new m(g.INVALID_VIEWPORT_ELEMENT_NAME,"config")}if(s.threshold!==void 0&&(typeof s.threshold!="number"||s.threshold<0||s.threshold>1))throw new m(g.INVALID_VIEWPORT_THRESHOLD,"config");if(s.minDwellTime!==void 0&&(typeof s.minDwellTime!="number"||s.minDwellTime<0))throw new m(g.INVALID_VIEWPORT_MIN_DWELL_TIME,"config");if(s.cooldownPeriod!==void 0&&(typeof s.cooldownPeriod!="number"||s.cooldownPeriod<0))throw new m(g.INVALID_VIEWPORT_COOLDOWN_PERIOD,"config");if(s.maxTrackedElements!==void 0&&(typeof s.maxTrackedElements!="number"||s.maxTrackedElements<=0))throw new m(g.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS,"config")},qt=s=>{if(s){if(s.tracelog&&(!s.tracelog.projectId||typeof s.tracelog.projectId!="string"||s.tracelog.projectId.trim()===""))throw new U(g.INVALID_TRACELOG_PROJECT_ID,"config");if(s.custom){if(!s.custom.collectApiUrl||typeof s.custom.collectApiUrl!="string"||s.custom.collectApiUrl.trim()==="")throw new U(g.INVALID_CUSTOM_API_URL,"config");if(s.custom.allowHttp!==void 0&&typeof s.custom.allowHttp!="boolean")throw new U("allowHttp must be a boolean","config");const e=s.custom.collectApiUrl.trim();if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new U('Custom API URL must start with "http://" or "https://"',"config");if(!(s.custom.allowHttp??!1)&&e.startsWith("http://"))throw new U("Custom API URL must use HTTPS in production. Set allowHttp: true in integration config to allow HTTP (not recommended)","config")}}},Jt=s=>{Kt(s);const e={...s??{},sessionTimeout:s?.sessionTimeout??9e5,globalMetadata:s?.globalMetadata??{},sensitiveQueryParams:s?.sensitiveQueryParams??[],errorSampling:s?.errorSampling??$e,samplingRate:s?.samplingRate??1,pageViewThrottleMs:s?.pageViewThrottleMs??1e3,clickThrottleMs:s?.clickThrottleMs??300,maxSameEventPerMinute:s?.maxSameEventPerMinute??60};return e.integrations?.custom&&(e.integrations.custom={...e.integrations.custom,allowHttp:e.integrations.custom.allowHttp??!1}),e.viewport&&(e.viewport={...e.viewport,threshold:e.viewport.threshold??.5,minDwellTime:e.viewport.minDwellTime??2e3,cooldownPeriod:e.viewport.cooldownPeriod??6e4,maxTrackedElements:e.viewport.maxTrackedElements??100}),e},Zt=s=>{if(typeof s=="string")return!0;if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const e=Object.entries(s);if(e.length>20)return!1;for(const[,t]of e){if(t==null)continue;const r=typeof t;if(r!=="string"&&r!=="number"&&r!=="boolean")return!1}return!0}return!1},ze=(s,e=0)=>{if(typeof s!="object"||s===null||e>1)return!1;for(const t of Object.values(s)){if(t==null)continue;const r=typeof t;if(!(r==="string"||r==="number"||r==="boolean")){if(Array.isArray(t)){if(t.length===0)continue;if(typeof t[0]=="string"){if(!t.every(o=>typeof o=="string"))return!1}else if(!t.every(o=>Zt(o)))return!1;continue}if(r==="object"&&e===0){if(!ze(t,e+1))return!1;continue}return!1}}return!0},er=s=>typeof s!="string"?{valid:!1,error:"Event name must be a string"}:s.length===0?{valid:!1,error:"Event name cannot be empty"}:s.length>120?{valid:!1,error:"Event name is too long (max 120 characters)"}:s.includes("<")||s.includes(">")||s.includes("&")?{valid:!1,error:"Event name contains invalid characters"}:["constructor","prototype","__proto__","eval","function","var","let","const"].includes(s.toLowerCase())?{valid:!1,error:"Event name cannot be a reserved word"}:{valid:!0},Ke=(s,e,t)=>{const r=zt(e),n=t&&t==="customEvent"?`${t} "${s}" metadata error`:`${s} metadata error`;if(!ze(r))return{valid:!1,error:`${n}: object has invalid types. Valid types are string, number, boolean or string arrays.`};let i;try{i=JSON.stringify(r)}catch{return{valid:!1,error:`${n}: object contains circular references or cannot be serialized.`}}if(i.length>8192)return{valid:!1,error:`${n}: object is too large (max ${8192/1024} KB).`};if(Object.keys(r).length>10)return{valid:!1,error:`${n}: object has too many keys (max 10 keys).`};for(const[l,c]of Object.entries(r)){if(Array.isArray(c)){if(c.length>10)return{valid:!1,error:`${n}: array property "${l}" is too large (max 10 items).`};for(const u of c)if(typeof u=="string"&&u.length>500)return{valid:!1,error:`${n}: array property "${l}" contains strings that are too long (max 500 characters).`}}if(typeof c=="string"&&c.length>1e3)return{valid:!1,error:`${n}: property "${l}" is too long (max 1000 characters).`}}return{valid:!0,sanitizedMetadata:r}},Ye=(s,e,t)=>{if(Array.isArray(e)){const r=[],n=t&&t==="customEvent"?`${t} "${s}" metadata error`:`${s} metadata error`;for(let i=0;i<e.length;i++){const o=e[i];if(typeof o!="object"||o===null||Array.isArray(o))return{valid:!1,error:`${n}: array item at index ${i} must be an object.`};const l=Ke(s,o,t);if(!l.valid)return{valid:!1,error:`${n}: array item at index ${i} is invalid: ${l.error}`};l.sanitizedMetadata&&r.push(l.sanitizedMetadata)}return{valid:!0,sanitizedMetadata:r}}return Ke(s,e,t)},tr=(s,e)=>{const t=er(s);if(!t.valid)return a("error","Event name validation failed",{data:{eventName:s,error:t.error}}),t;if(!e)return{valid:!0};const r=Ye(s,e,"customEvent");return r.valid||a("error","Event metadata validation failed",{data:{eventName:s,error:r.error}}),r};class rr{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}off(e,t){const r=this.listeners.get(e);if(r){const n=r.indexOf(t);n>-1&&r.splice(n,1)}}emit(e,t){const r=this.listeners.get(e);r&&r.forEach(n=>{n(t)})}removeAllListeners(){this.listeners.clear()}}function qe(s,e,t){try{const r=e(s);return r===null?null:typeof r=="object"&&r!==null&&"type"in r?r:(a("warn",`beforeSend transformer returned invalid data, using original [${t}]`),s)}catch(r){return a("error",`beforeSend transformer threw error, using original event [${t}]`,{error:r,visibility:"critical"}),s}}function sr(s,e,t){return s.map(r=>qe(r,e,t)).filter(r=>r!==null)}function Je(s,e,t){try{const r=e(s);return r===null?(a("debug",`Batch filtered by beforeBatch transformer [${t}]`,{data:{eventCount:s.events.length}}),null):typeof r=="object"&&r!==null&&Array.isArray(r.events)?r:(a("warn",`beforeBatch transformer returned invalid data, using original [${t}]`,{data:{eventCount:s.events.length}}),s)}catch(r){return a("error",`beforeBatch transformer threw error, using original batch [${t}]`,{error:r,data:{eventCount:s.events.length},visibility:"critical"}),s}}const me={};class I{get(e){return me[e]}set(e,t){me[e]=t}getState(){return{...me}}}class Ze extends I{storeManager;integrationId;apiUrl;transformers;staticHeaders;customHeadersProvider;lastPermanentErrorLog=null;recoveryInProgress=!1;lastMetadataTimestamp=0;pendingControllers=new Set;constructor(e,t,r,n={},i={},o){if(super(),t&&!r||!t&&r)throw new Error("SenderManager: integrationId and apiUrl must either both be provided or both be undefined");this.storeManager=e,this.integrationId=t,this.apiUrl=r,this.transformers=n,this.staticHeaders=i,this.customHeadersProvider=o}getIntegrationId(){return this.integrationId}setCustomHeadersProvider(e){this.customHeadersProvider=e}removeCustomHeadersProvider(){this.customHeadersProvider=void 0}getCustomHeaders(){if(this.integrationId!=="custom")return{};let e={};if(this.customHeadersProvider)try{const t=this.customHeadersProvider();typeof t=="object"&&t!==null&&!Array.isArray(t)?e=t:a("warn","Custom headers provider returned invalid value, expected object",{data:{received:typeof t}})}catch(t){a("warn","Custom headers provider threw an error, using static headers only",{error:t})}return{...this.staticHeaders,...e}}getQueueStorageKey(){const e=this.get("userId")||"anonymous",t=mt(e);return this.integrationId?`${t}:${this.integrationId}`:t}sendEventsQueueSync(e){return this.shouldSkipSend()?!0:this.apiUrl?.includes(D.Fail)?(a("warn",`Fail mode: simulating network failure (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),!1):this.apiUrl?.includes(D.Localhost)?(a("debug",`Success mode: simulating successful send (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),!0):this.sendQueueSyncInternal(e)}async sendEventsQueue(e,t){try{const r=await this.send(e);return r?(this.clearPersistedEvents(),t?.onSuccess?.(e.events.length,e.events,e)):(this.persistEvents(e),t?.onFailure?.()),r}catch(r){return r instanceof N?(this.logPermanentError("Permanent error, not retrying",r),this.clearPersistedEvents(),t?.onFailure?.(),!1):(this.persistEvents(e),t?.onFailure?.(),!1)}}async recoverPersistedEvents(e){if(this.recoveryInProgress){a("debug","Recovery already in progress, skipping duplicate attempt");return}this.recoveryInProgress=!0;try{const t=this.getPersistedData();if(!t||!this.isDataRecent(t)||t.events.length===0){this.clearPersistedEvents();return}const r=this.createRecoveryBody(t);await this.send(r)?(this.clearPersistedEvents(),e?.onSuccess?.(t.events.length,t.events,r)):e?.onFailure?.()}catch(t){if(t instanceof N){this.logPermanentError("Permanent error during recovery, clearing persisted events",t),this.clearPersistedEvents(),e?.onFailure?.();return}a("error","Failed to recover persisted events",{error:t})}finally{this.recoveryInProgress=!1}}stop(){}applyBeforeSendTransformer(e){if(this.integrationId==="saas")return e;const t=this.transformers.beforeSend;if(!t)return e;const r=sr(e.events,t,this.integrationId||"SenderManager");return r.length===0?null:{...e,events:r}}applyBeforeBatchTransformer(e){if(this.integrationId==="saas")return e;const t=this.transformers.beforeBatch;return t?Je(e,t,this.integrationId||"SenderManager"):e}async backoffDelay(e){const t=100*Math.pow(2,e),r=Math.random()*100,n=t+r;return new Promise(i=>setTimeout(i,n))}async send(e){if(this.shouldSkipSend())return this.simulateSuccessfulSend();const t=this.applyBeforeSendTransformer(e);if(!t)return!0;const r=this.applyBeforeBatchTransformer(t);if(!r)return!0;if(this.apiUrl?.includes(D.Fail))return a("debug",`Fail mode: simulating network failure${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),!1;if(this.apiUrl?.includes(D.Localhost))return a("debug",`Success mode: simulating successful send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),!0;const{url:n,payload:i}=this.prepareRequest(r);for(let o=1;o<=3;o++)try{return(await this.sendWithTimeout(n,i)).ok?(o>1&&a("info",`Send succeeded after ${o-1} retry attempt(s)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length,attempt:o}}),!0):!1}catch(l){const c=o===3;if(l instanceof N)throw l;if(a(c?"error":"warn",`Send attempt ${o} failed${this.integrationId?` [${this.integrationId}]`:""}${c?" (all retries exhausted)":", will retry"}`,{error:l,data:{events:e.events.length,url:n.replace(/\/\/[^/]+/,"//[DOMAIN]"),attempt:o,maxAttempts:3}}),!c){await this.backoffDelay(o);continue}return!1}return!1}async sendWithTimeout(e,t){const r=new AbortController;this.pendingControllers.add(r);const n=setTimeout(()=>{r.abort()},15e3);try{const i=this.getCustomHeaders(),o=await fetch(e,{method:"POST",body:t,keepalive:!0,credentials:"include",signal:r.signal,headers:{...i,"Content-Type":"application/json"}});if(!o.ok)throw o.status>=400&&o.status<500&&o.status!==408&&o.status!==429?new N(`HTTP ${o.status}: ${o.statusText}`,o.status):new Error(`HTTP ${o.status}: ${o.statusText}`);return o}finally{clearTimeout(n),this.pendingControllers.delete(r)}}sendQueueSyncInternal(e){const t=this.applyBeforeSendTransformer(e);if(!t)return!0;const r=this.applyBeforeBatchTransformer(t);if(!r)return!0;const{url:n,payload:i}=this.prepareRequest(r);if(i.length>65536)return a("warn",`Payload exceeds sendBeacon limit, persisting for recovery${this.integrationId?` [${this.integrationId}]`:""}`,{data:{size:i.length,limit:65536,events:r.events.length}}),this.persistEvents(r),!1;const o=new Blob([i],{type:"application/json"});if(!this.isSendBeaconAvailable())return a("warn",`sendBeacon not available, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(r),!1;const l=navigator.sendBeacon(n,o);return l||(a("warn",`sendBeacon rejected request, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(r)),l}prepareRequest(e){let t=Date.now();t<this.lastMetadataTimestamp&&(t=this.lastMetadataTimestamp),this.lastMetadataTimestamp=t;const r={...e,_metadata:{referer:typeof window<"u"?window.location.href:void 0,timestamp:t,client_version:Ht}};return{url:this.apiUrl||"",payload:JSON.stringify(r)}}getPersistedData(){try{const e=this.getQueueStorageKey(),t=this.storeManager.getItem(e);if(t)return JSON.parse(t)}catch(e){a("debug",`Failed to parse persisted data${this.integrationId?` [${this.integrationId}]`:""}`,{error:e}),this.clearPersistedEvents()}return null}isDataRecent(e){return!e.timestamp||typeof e.timestamp!="number"?!1:(Date.now()-e.timestamp)/(1e3*60*60)<2}createRecoveryBody(e){const{timestamp:t,...r}=e;return r}persistEvents(e){try{const t=this.getPersistedData();if(t&&t.timestamp){const i=Date.now()-t.timestamp;if(i<1e3)return a("debug",`Skipping persistence, another tab recently persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{data:{timeSinceExisting:i}}),!0}const r={...e,timestamp:Date.now()},n=this.getQueueStorageKey();return this.storeManager.setItem(n,JSON.stringify(r)),!!this.storeManager.getItem(n)}catch(t){return a("debug",`Failed to persist events${this.integrationId?` [${this.integrationId}]`:""}`,{error:t}),!1}}clearPersistedEvents(){try{const e=this.getQueueStorageKey();this.storeManager.removeItem(e)}catch(e){a("debug",`Failed to clear persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{error:e})}}shouldSkipSend(){return!this.apiUrl}async simulateSuccessfulSend(){const e=Math.random()*400+100;return await new Promise(t=>setTimeout(t,e)),!0}isSendBeaconAvailable(){return typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}logPermanentError(e,t){const r=Date.now();(!this.lastPermanentErrorLog||this.lastPermanentErrorLog.statusCode!==t.statusCode||r-this.lastPermanentErrorLog.timestamp>=Dt)&&(a("error",`${e}${this.integrationId?` [${this.integrationId}]`:""}`,{data:{status:t.statusCode,message:t.message}}),this.lastPermanentErrorLog={statusCode:t.statusCode,timestamp:r})}}class nr extends I{bootTime;bootTimestamp;hasPerformanceNow;lastClockSkewCheck=0;detectedSkew=0;constructor(){if(super(),typeof window>"u"){this.hasPerformanceNow=!1,this.bootTime=0,this.bootTimestamp=0;return}this.hasPerformanceNow=typeof performance<"u"&&typeof performance.now=="function",this.hasPerformanceNow?(this.bootTime=performance.now(),this.bootTimestamp=Date.now(),a("debug","TimeManager initialized with monotonic clock",{data:{bootTime:this.bootTime.toFixed(3),bootTimestamp:this.bootTimestamp}})):(this.bootTime=0,this.bootTimestamp=Date.now(),a("debug","performance.now() not available, falling back to Date.now()"))}now(){if(!this.hasPerformanceNow)return Date.now();const e=performance.now()-this.bootTime;return Math.round(this.bootTimestamp+e)}getClockSkew(){if(!this.hasPerformanceNow)return 0;const e=Date.now();if(e-this.lastClockSkewCheck<5e3)return this.detectedSkew;this.lastClockSkewCheck=e;const t=this.now(),r=Date.now();return this.detectedSkew=r-t,Math.abs(this.detectedSkew)>3e4&&a("warn","Significant clock skew detected",{data:{skewMs:this.detectedSkew,skewMinutes:(this.detectedSkew/1e3/60).toFixed(2),monotonicTime:new Date(t).toISOString(),systemTime:new Date(r).toISOString()}}),this.detectedSkew}validateTimestamp(e){const r=this.now(),n=e-r;return n>12e4?{valid:!1,error:`Timestamp is ${(n/1e3/60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`}:{valid:!0}}getBootInfo(){return{bootTime:this.bootTime,bootTimestamp:this.bootTimestamp,hasPerformanceNow:this.hasPerformanceNow,clockSkew:this.getClockSkew()}}}class ir extends I{dataSenders;emitter;transformers;timeManager;recentEventFingerprints=new Map;perEventRateLimits=new Map;eventsQueue=[];pendingEventsBuffer=[];sendIntervalId=null;rateLimitCounter=0;rateLimitWindowStart=0;lastSessionId=null;sessionEventCounts={total:0,[d.CLICK]:0,[d.PAGE_VIEW]:0,[d.CUSTOM]:0,[d.VIEWPORT_VISIBLE]:0,[d.SCROLL]:0};saveSessionCountsDebounced=null;constructor(e,t=null,r={},n={},i){super(),this.emitter=t,this.transformers=r,this.timeManager=new nr,this.dataSenders=[];const o=this.get("collectApiUrls");o?.saas&&this.dataSenders.push(new Ze(e,"saas",o.saas,r)),o?.custom&&this.dataSenders.push(new Ze(e,"custom",o.custom,r,n,i)),this.saveSessionCountsDebounced=this.debounce(l=>{this.saveSessionCounts(l)},500),this.cleanupExpiredSessionCounts()}async recoverPersistedEvents(){const e=this.dataSenders.map(async t=>t.recoverPersistedEvents({onSuccess:(r,n,i)=>{if(n&&n.length>0){const o=n.map(l=>l.id);this.removeProcessedEvents(o),i&&this.emitEventsQueue(i)}},onFailure:()=>{a("debug","Failed to recover persisted events")}}));await Promise.allSettled(e)}track({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:i,custom_event:o,web_vitals:l,error_data:c,viewport_data:u,page_view:T}){if(!e){a("error","Event type is required - event will be ignored");return}const E=this.get("sessionId");if(!E){this.pendingEventsBuffer.length>=100&&(this.pendingEventsBuffer.shift(),a("debug","Pending events buffer full - dropping oldest event",{data:{maxBufferSize:100}})),this.pendingEventsBuffer.push({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:i,custom_event:o,web_vitals:l,error_data:c,viewport_data:u,page_view:T});return}this.lastSessionId!==E&&(this.lastSessionId=E,this.sessionEventCounts=this.loadSessionCounts(E));const p=e===d.SESSION_START;if(p&&a("debug","Processing SESSION_START event",{data:{sessionId:E}}),!p&&!this.checkRateLimit())return;const S=e;if(!p){if(this.sessionEventCounts.total>=1e3){a("warn","Session event limit reached",{data:{type:S,total:this.sessionEventCounts.total,limit:1e3}});return}const v=this.getTypeLimitForEvent(S);if(v){const Ae=this.sessionEventCounts[S];if(Ae!==void 0&&Ae>=v){a("warn","Session event type limit reached",{data:{type:S,count:Ae,limit:v}});return}}}if(S===d.CUSTOM&&o?.name){const v=this.get("config")?.maxSameEventPerMinute??60;if(!this.checkPerEventRateLimit(o.name,v))return}const ct=S===d.SESSION_START,se=t||this.get("pageUrl"),G=this.buildEventPayload({type:S,page_url:se,from_page_url:r,scroll_data:n,click_data:i,custom_event:o,web_vitals:l,error_data:c,viewport_data:u,page_view:T});if(G&&!(!p&&!this.shouldSample())){if(ct){const v=this.get("sessionId");if(!v){a("error","Session start event requires sessionId - event will be ignored");return}if(this.get("hasStartSession")){a("debug","Duplicate session_start detected",{data:{sessionId:v}});return}this.set("hasStartSession",!0)}if(!this.isDuplicateEvent(G)){if(this.get("mode")===B.QA){if(S===d.CUSTOM&&o){a("info",`Custom Event: ${o.name}`,{visibility:"qa",data:{name:o.name,...o.metadata&&{metadata:o.metadata}}}),this.emitEvent(G);return}if(S===d.VIEWPORT_VISIBLE&&u){const v=u.name||u.id||u.selector;a("info",`Viewport Visible: ${v}`,{visibility:"qa",data:{selector:u.selector,...u.name&&{name:u.name},...u.id&&{id:u.id},visibilityRatio:u.visibilityRatio,dwellTime:u.dwellTime}}),this.emitEvent(G);return}}if(this.addToQueue(G),!p){this.sessionEventCounts.total++,this.sessionEventCounts[S]!==void 0&&this.sessionEventCounts[S]++;const v=this.get("sessionId");v&&this.saveSessionCountsDebounced&&this.saveSessionCountsDebounced(v)}}}}stop(){this.sendIntervalId&&(clearInterval(this.sendIntervalId),this.sendIntervalId=null);const e=this.get("sessionId");e&&this.saveSessionCounts(e),this.eventsQueue=[],this.pendingEventsBuffer=[],this.recentEventFingerprints.clear(),this.rateLimitCounter=0,this.rateLimitWindowStart=0,this.perEventRateLimits.clear(),this.sessionEventCounts={total:0,[d.CLICK]:0,[d.PAGE_VIEW]:0,[d.CUSTOM]:0,[d.VIEWPORT_VISIBLE]:0,[d.SCROLL]:0},this.lastSessionId=null,this.set("hasStartSession",!1),this.dataSenders.forEach(t=>{t.stop()})}async flushImmediately(){return this.flushEvents(!1)}flushImmediatelySync(){return this.flushEvents(!0)}setCustomHeadersProvider(e){for(const t of this.dataSenders)t.getIntegrationId()==="custom"&&t.setCustomHeadersProvider(e)}removeCustomHeadersProvider(){for(const e of this.dataSenders)e.getIntegrationId()==="custom"&&e.removeCustomHeadersProvider()}getQueueLength(){return this.eventsQueue.length}getQueueEvents(){return[...this.eventsQueue]}async flushQueue(){await this.flushImmediately()}clearQueue(){this.eventsQueue=[]}flushPendingEvents(){if(this.pendingEventsBuffer.length===0)return;if(!this.get("sessionId")){a("debug","Cannot flush pending events: session not initialized - keeping in buffer",{data:{bufferedEventCount:this.pendingEventsBuffer.length}});return}const t=[...this.pendingEventsBuffer];this.pendingEventsBuffer=[],t.forEach(r=>{this.track(r)})}clearSendInterval(){this.sendIntervalId&&(clearInterval(this.sendIntervalId),this.sendIntervalId=null)}isSuccessfulResult(e){return e.status==="fulfilled"&&e.value===!0}flushEvents(e){if(this.eventsQueue.length===0)return e?!0:Promise.resolve(!0);const t=this.buildEventsPayload(),r=[...this.eventsQueue],n=r.map(i=>i.id);if(this.dataSenders.length===0)return this.removeProcessedEvents(n),this.clearSendInterval(),this.emitEventsQueue(t),e?!0:Promise.resolve(!0);if(e){const o=this.dataSenders.map(l=>l.sendEventsQueueSync(t)).some(l=>l);return o?(this.removeProcessedEvents(n),this.clearSendInterval(),this.emitEventsQueue(t)):(this.clearSendInterval(),a("debug","Sync flush complete failure, events kept in queue for retry",{data:{eventCount:n.length}})),o}else{const i=this.dataSenders.map(async o=>o.sendEventsQueue(t,{onSuccess:()=>{},onFailure:()=>{}}));return Promise.allSettled(i).then(o=>{const l=o.some(c=>this.isSuccessfulResult(c));return l?(this.removeProcessedEvents(n),this.clearSendInterval(),this.emitEventsQueue(t)):a("debug","Async flush complete failure, events kept in queue for retry",{data:{eventCount:r.length}}),l})}}async sendEventsQueue(){if(!this.get("sessionId")||this.eventsQueue.length===0)return;const e=this.buildEventsPayload();if(this.dataSenders.length===0){this.emitEventsQueue(e);return}const t=[...this.eventsQueue],r=t.map(l=>l.id),n=this.dataSenders.map(async l=>l.sendEventsQueue(e,{onSuccess:()=>{},onFailure:()=>{}})),i=await Promise.allSettled(n);if(i.some(l=>this.isSuccessfulResult(l))){this.removeProcessedEvents(r),this.emitEventsQueue(e);const l=i.filter(c=>!this.isSuccessfulResult(c)).length;l>0&&a("debug","Periodic send completed with some failures, removed from queue and persisted per-integration",{data:{eventCount:t.length,failedCount:l}})}else a("debug","Periodic send complete failure, events kept in queue for retry",{data:{eventCount:t.length}});this.eventsQueue.length===0&&this.clearSendInterval()}buildEventsPayload(){const e=new Map,t=[];for(const c of this.eventsQueue){const u=this.createEventSignature(c);e.has(u)||t.push(u),e.set(u,c)}const r=t.map(c=>e.get(c)).filter(c=>!!c).sort((c,u)=>c.type===d.SESSION_START&&u.type!==d.SESSION_START?-1:u.type===d.SESSION_START&&c.type!==d.SESSION_START?1:c.timestamp-u.timestamp);let n={user_id:this.get("userId"),session_id:this.get("sessionId"),device:this.get("device"),events:r,...this.get("config")?.globalMetadata&&{global_metadata:this.get("config")?.globalMetadata}};const i=this.get("collectApiUrls"),o=!!(i?.custom||i?.saas),l=this.transformers.beforeBatch;if(!o&&l){const c=Je(n,l,"EventManager");c!==null&&(n=c)}return n}buildEventPayload(e){const t=e.page_url??this.get("pageUrl"),r=this.timeManager.now(),n=this.timeManager.validateTimestamp(r);n.valid||a("warn","Event timestamp validation failed",{data:{type:e.type,error:n.error}});const i=this.get("sessionReferrer"),o=this.get("sessionUtm");let l={id:Xt(),type:e.type,page_url:t,timestamp:r,...i&&{referrer:i},...e.from_page_url&&{from_page_url:e.from_page_url},...e.scroll_data&&{scroll_data:e.scroll_data},...e.click_data&&{click_data:e.click_data},...e.custom_event&&{custom_event:e.custom_event},...e.web_vitals&&{web_vitals:e.web_vitals},...e.error_data&&{error_data:e.error_data},...e.viewport_data&&{viewport_data:e.viewport_data},...e.page_view&&{page_view:e.page_view},...o&&{utm:o}};const c=this.get("collectApiUrls"),u=!!c?.custom,T=!!c?.saas,E=u||T,p=u&&T,S=this.transformers.beforeSend;if(S&&(!E||u&&!p)){const se=qe(l,S,"EventManager");if(se===null)return null;l=se}return l}isDuplicateEvent(e){const t=Date.now(),r=this.createEventFingerprint(e),n=this.recentEventFingerprints.get(r);return n&&t-n<1e3?(this.recentEventFingerprints.set(r,t),!0):(this.recentEventFingerprints.set(r,t),this.recentEventFingerprints.size>1500&&this.pruneOldFingerprints(),this.recentEventFingerprints.size>3e3&&(this.recentEventFingerprints.clear(),this.recentEventFingerprints.set(r,t),a("debug","Event fingerprint cache exceeded hard limit, cleared",{data:{hardLimit:3e3}})),!1)}pruneOldFingerprints(){const e=Date.now(),t=1e3*10;for(const[r,n]of this.recentEventFingerprints.entries())e-n>t&&this.recentEventFingerprints.delete(r);a("debug","Pruned old event fingerprints",{data:{remaining:this.recentEventFingerprints.size,cutoffMs:t}})}createEventFingerprint(e){let t=`${e.type}_${e.page_url}`;if(e.click_data){const r=Math.round((e.click_data.x||0)/10)*10,n=Math.round((e.click_data.y||0)/10)*10;t+=`_click_${r}_${n}`}return e.scroll_data&&(t+=`_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`),e.custom_event&&(t+=`_custom_${e.custom_event.name}`),e.web_vitals&&(t+=`_vitals_${e.web_vitals.type}`),e.error_data&&(t+=`_error_${e.error_data.type}_${e.error_data.message}`),t}createEventSignature(e){return this.createEventFingerprint(e)}addToQueue(e){if(this.emitEvent(e),this.eventsQueue.push(e),this.eventsQueue.length>100){const t=this.eventsQueue.findIndex(n=>n.type!==d.SESSION_START),r=t>=0?this.eventsQueue.splice(t,1)[0]:this.eventsQueue.shift();a("warn","Event queue overflow, oldest non-critical event removed",{data:{maxLength:100,currentLength:this.eventsQueue.length,removedEventType:r?.type,wasCritical:r?.type===d.SESSION_START}})}this.sendIntervalId||this.startSendInterval(),this.eventsQueue.length>=50&&this.sendEventsQueue()}startSendInterval(){this.sendIntervalId=window.setInterval(()=>{this.eventsQueue.length>0&&this.sendEventsQueue()},1e4)}shouldSample(){const e=this.get("config")?.samplingRate??1;return Math.random()<e}checkRateLimit(){const e=Date.now();return e-this.rateLimitWindowStart>1e3&&(this.rateLimitCounter=0,this.rateLimitWindowStart=e),this.rateLimitCounter>=50?!1:(this.rateLimitCounter++,!0)}checkPerEventRateLimit(e,t){const r=Date.now(),i=(this.perEventRateLimits.get(e)??[]).filter(o=>r-o<6e4);return i.length>=t?(a("warn","Per-event rate limit exceeded for custom event",{data:{eventName:e,limit:t,window:`${6e4/1e3}s`}}),!1):(i.push(r),this.perEventRateLimits.set(e,i),!0)}getTypeLimitForEvent(e){return{[d.CLICK]:500,[d.PAGE_VIEW]:100,[d.CUSTOM]:500,[d.VIEWPORT_VISIBLE]:200,[d.SCROLL]:120}[e]??null}removeProcessedEvents(e){const t=new Set(e);this.eventsQueue=this.eventsQueue.filter(r=>!t.has(r.id))}emitEvent(e){this.emitter&&this.emitter.emit(X.EVENT,e)}emitEventsQueue(e){this.emitter&&this.emitter.emit(X.QUEUE,e)}debounce(e,t){let r=null;return((...n)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...n),r=null},t)})}getInitialCounts(){return{total:0,[d.CLICK]:0,[d.PAGE_VIEW]:0,[d.CUSTOM]:0,[d.VIEWPORT_VISIBLE]:0,[d.SCROLL]:0}}loadSessionCounts(e){if(typeof window>"u"||typeof localStorage>"u")return this.getInitialCounts();const t=this.get("userId")||"anonymous",r=Ne(t,e);try{const n=localStorage.getItem(r);if(!n)return this.getInitialCounts();const i=JSON.parse(n);return i._timestamp&&Date.now()-i._timestamp>Oe?(a("debug","Session counts expired, clearing",{data:{sessionId:e,age:Date.now()-i._timestamp}}),localStorage.removeItem(r),this.getInitialCounts()):typeof i.total=="number"&&typeof i[d.CLICK]=="number"&&typeof i[d.PAGE_VIEW]=="number"&&typeof i[d.CUSTOM]=="number"&&typeof i[d.VIEWPORT_VISIBLE]=="number"&&typeof i[d.SCROLL]=="number"?{total:i.total,[d.CLICK]:i[d.CLICK],[d.PAGE_VIEW]:i[d.PAGE_VIEW],[d.CUSTOM]:i[d.CUSTOM],[d.VIEWPORT_VISIBLE]:i[d.VIEWPORT_VISIBLE],[d.SCROLL]:i[d.SCROLL]}:(a("warn","Invalid session counts structure in localStorage, resetting",{data:{sessionId:e,parsed:i}}),localStorage.removeItem(r),a("debug","Session counts removed due to invalid/corrupted data",{data:{sessionId:e,parsed:i}}),this.getInitialCounts())}catch(n){return a("warn","Failed to load session counts from localStorage",{error:n,data:{sessionId:e}}),this.getInitialCounts()}}cleanupExpiredSessionCounts(){if(!(typeof window>"u"||typeof localStorage>"u"))try{const e=localStorage.getItem(Pe);if(e){const i=Date.now()-parseInt(e,10);if(i<De){a("debug","Skipping session counts cleanup (throttled)",{data:{timeSinceLastCleanup:i,throttleMs:De}});return}}const t=this.get("userId")||"anonymous",r=`${w}:${t}:session_counts:`,n=[];for(let i=0;i<localStorage.length;i++){const o=localStorage.key(i);if(o?.startsWith(r))try{const l=localStorage.getItem(o);if(l){const c=JSON.parse(l);c._timestamp&&Date.now()-c._timestamp>Oe&&n.push(o)}}catch{}}n.forEach(i=>{localStorage.removeItem(i),a("debug","Cleaned up expired session counts",{data:{key:i}})}),n.length>0&&a("info",`Cleaned up ${n.length} expired session counts entries`),localStorage.setItem(Pe,Date.now().toString())}catch(e){a("warn","Failed to cleanup expired session counts",{error:e})}}saveSessionCounts(e){const t=this.get("userId")||"anonymous",r=Ne(t,e);try{const n={...this.sessionEventCounts,_timestamp:Date.now(),_version:1};localStorage.setItem(r,JSON.stringify(n))}catch(n){a("warn","Failed to persist session counts to localStorage",{error:n,data:{sessionId:e}})}}}class or{static getId(e){const t=e.getItem(Me);if(t)return t;const r=Gt();return e.setItem(Me,r),r}}const ar=/^\d{13}-[a-z0-9]{9}$/;class lr extends I{storageManager;eventManager;projectId;activityHandler=null;visibilityChangeHandler=null;sessionTimeoutId=null;broadcastChannel=null;isTracking=!1;needsRenewal=!1;constructor(e,t,r){super(),this.storageManager=e,this.eventManager=t,this.projectId=r}initCrossTabSync(){if(typeof BroadcastChannel>"u"){a("debug","BroadcastChannel not supported");return}const e=this.getProjectId();this.broadcastChannel=new BroadcastChannel(Et(e)),this.broadcastChannel.onmessage=t=>{const{action:r,sessionId:n,timestamp:i,projectId:o}=t.data??{};o===e&&(r==="session_start"&&n&&typeof i=="number"&&i>Date.now()-5e3?(this.set("sessionId",n),this.persistSession(n,i),this.isTracking&&this.setupSessionTimeout()):r&&r!=="session_start"&&a("debug","Ignored BroadcastChannel message with unknown action",{data:{action:r}}))}}shareSession(e){this.broadcastChannel&&typeof this.broadcastChannel.postMessage=="function"&&this.broadcastChannel.postMessage({action:"session_start",projectId:this.getProjectId(),sessionId:e,timestamp:Date.now()})}cleanupCrossTabSync(){this.broadcastChannel&&(typeof this.broadcastChannel.close=="function"&&this.broadcastChannel.close(),this.broadcastChannel=null)}recoverSession(){const e=this.loadStoredSession();if(!e)return null;if(!ar.test(e.id))return a("warn","Invalid session ID format recovered from storage, clearing",{data:{sessionId:e.id}}),this.clearStoredSession(),null;const t=this.get("config")?.sessionTimeout??9e5;return Date.now()-e.lastActivity>t?(this.clearStoredSession(),null):e.id}persistSession(e,t=Date.now(),r,n){this.saveStoredSession({id:e,lastActivity:t,...r&&{referrer:r},...n&&{utm:n}})}clearStoredSession(){const e=this.getSessionStorageKey();this.storageManager.removeItem(e)}loadStoredSession(){const e=this.getSessionStorageKey(),t=this.storageManager.getItem(e);if(!t)return null;try{const r=JSON.parse(t);return!r.id||typeof r.lastActivity!="number"?null:r}catch{return this.storageManager.removeItem(e),null}}saveStoredSession(e){const t=this.getSessionStorageKey();this.storageManager.setItem(t,JSON.stringify(e))}getSessionStorageKey(){return gt(this.getProjectId())}getProjectId(){return this.projectId}startTracking(){if(this.isTracking){a("debug","Session tracking already active");return}const e=this.recoverSession(),t=e??this.generateSessionId();let r,n;if(e){const i=this.loadStoredSession();r=i?.referrer??ue(),n=i?.utm??de()}else r=ue(),n=de();a("debug","Session tracking initialized",{data:{sessionId:t,wasRecovered:!!e,willEmitSessionStart:!e,sessionReferrer:r,hasUtm:!!n}}),this.isTracking=!0;try{this.set("sessionId",t),this.set("sessionReferrer",r),this.set("sessionUtm",n),this.persistSession(t,Date.now(),r,n),this.initCrossTabSync(),this.shareSession(t),e?a("debug","Session recovered, skipping SESSION_START",{data:{sessionId:t}}):(a("debug","Emitting SESSION_START event",{data:{sessionId:t}}),this.eventManager.track({type:d.SESSION_START})),this.setupSessionTimeout(),this.setupActivityListeners(),this.setupLifecycleListeners()}catch(i){throw this.isTracking=!1,this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.set("sessionId",null),i}}generateSessionId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}setupSessionTimeout(){this.clearSessionTimeout();const e=this.get("config")?.sessionTimeout??9e5;this.sessionTimeoutId=setTimeout(()=>{this.enterRenewalMode()},e)}resetSessionTimeout(){this.setupSessionTimeout();const e=this.get("sessionId");e&&this.persistSession(e,Date.now(),this.get("sessionReferrer"),this.get("sessionUtm"))}clearSessionTimeout(){this.sessionTimeoutId&&(clearTimeout(this.sessionTimeoutId),this.sessionTimeoutId=null)}setupActivityListeners(){this.activityHandler=()=>{this.needsRenewal?this.renewSession():this.resetSessionTimeout()},document.addEventListener("click",this.activityHandler,{passive:!0}),document.addEventListener("keydown",this.activityHandler,{passive:!0}),document.addEventListener("scroll",this.activityHandler,{passive:!0})}renewSession(){this.needsRenewal=!1;const e=this.generateSessionId(),t=ue(),r=de();a("debug","Renewing session after timeout",{data:{newSessionId:e}}),this.set("sessionId",e),this.set("sessionReferrer",t),this.set("sessionUtm",r),this.persistSession(e,Date.now(),t,r),this.cleanupCrossTabSync(),this.initCrossTabSync(),this.shareSession(e),this.eventManager.track({type:d.SESSION_START}),this.eventManager.flushPendingEvents(),this.setupSessionTimeout()}cleanupActivityListeners(){this.activityHandler&&(document.removeEventListener("click",this.activityHandler),document.removeEventListener("keydown",this.activityHandler),document.removeEventListener("scroll",this.activityHandler),this.activityHandler=null)}setupLifecycleListeners(){this.visibilityChangeHandler||(this.visibilityChangeHandler=()=>{if(document.hidden)this.clearSessionTimeout();else{if(this.isSessionStale()){a("debug","Session expired during suspend, entering renewal mode"),this.enterRenewalMode();return}this.get("sessionId")&&this.setupSessionTimeout()}},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}isSessionStale(){if(this.needsRenewal||!this.get("sessionId"))return!1;const t=this.loadStoredSession();if(!t)return!1;const r=this.get("config")?.sessionTimeout??9e5;return Date.now()-t.lastActivity>r}cleanupLifecycleListeners(){this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null)}enterRenewalMode(){this.clearSessionTimeout(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",!1),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=!0,a("debug","Session timed out, entering renewal mode")}resetSessionState(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",!1),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=!1,this.isTracking=!1}stopTracking(){this.resetSessionState()}destroy(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupCrossTabSync(),this.cleanupLifecycleListeners(),this.isTracking=!1,this.needsRenewal=!1,this.set("hasStartSession",!1)}}class cr extends I{eventManager;storageManager;sessionManager=null;destroyed=!1;constructor(e,t){super(),this.eventManager=t,this.storageManager=e}startTracking(){if(this.isActive())return;if(this.destroyed){a("debug","Cannot start tracking on destroyed handler");return}const t=this.get("config")?.integrations?.tracelog?.projectId??"custom";try{this.sessionManager=new lr(this.storageManager,this.eventManager,t),this.sessionManager.startTracking(),this.eventManager.flushPendingEvents()}catch(r){if(this.sessionManager){try{this.sessionManager.destroy()}catch{}this.sessionManager=null}throw a("error","Failed to start session tracking",{error:r}),r}}isActive(){return this.sessionManager!==null&&!this.destroyed}cleanupSessionManager(){this.sessionManager&&(this.sessionManager.stopTracking(),this.sessionManager.destroy(),this.sessionManager=null)}stopTracking(){this.cleanupSessionManager()}destroy(){this.destroyed||(this.sessionManager&&(this.sessionManager.destroy(),this.sessionManager=null),this.destroyed=!0)}}class ur extends I{eventManager;onTrack;originalPushState;originalReplaceState;lastPageViewTime=0;constructor(e,t){super(),this.eventManager=e,this.onTrack=t}startTracking(){this.trackInitialPageView(),window.addEventListener("popstate",this.trackCurrentPage,!0),window.addEventListener("hashchange",this.trackCurrentPage,!0),this.patchHistory("pushState"),this.patchHistory("replaceState")}stopTracking(){window.removeEventListener("popstate",this.trackCurrentPage,!0),window.removeEventListener("hashchange",this.trackCurrentPage,!0),this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.lastPageViewTime=0}patchHistory(e){const t=window.history[e];e==="pushState"&&!this.originalPushState?this.originalPushState=t:e==="replaceState"&&!this.originalReplaceState&&(this.originalReplaceState=t),window.history[e]=(...r)=>{t.apply(window.history,r),this.trackCurrentPage()}}trackCurrentPage=()=>{const e=window.location.href,t=he(e,this.get("config").sensitiveQueryParams);if(this.get("pageUrl")===t)return;const r=Date.now(),n=this.get("config").pageViewThrottleMs??1e3;if(r-this.lastPageViewTime<n)return;this.lastPageViewTime=r,this.onTrack();const i=this.get("pageUrl");this.set("pageUrl",t);const o=this.extractPageViewData();this.eventManager.track({type:d.PAGE_VIEW,page_url:this.get("pageUrl"),from_page_url:i,...o&&{page_view:o}})};trackInitialPageView(){const e=he(window.location.href,this.get("config").sensitiveQueryParams),t=this.extractPageViewData();this.lastPageViewTime=Date.now(),this.eventManager.track({type:d.PAGE_VIEW,page_url:e,...t&&{page_view:t}}),this.onTrack()}extractPageViewData(){const{pathname:e,search:t,hash:r}=window.location,{referrer:n}=document,{title:i}=document;return!n&&!i&&!e&&!t&&!r?void 0:{...n&&{referrer:n},...i&&{title:i},...e&&{pathname:e},...t&&{search:t},...r&&{hash:r}}}}class dr extends I{eventManager;lastClickTimes=new Map;clickHandler;lastPruneTime=0;constructor(e){super(),this.eventManager=e}startTracking(){this.clickHandler||(this.clickHandler=e=>{const t=e,r=t.target,n=typeof HTMLElement<"u"&&r instanceof HTMLElement?r:typeof HTMLElement<"u"&&r instanceof Node&&r.parentElement instanceof HTMLElement?r.parentElement:null;if(!n){a("debug","Click target not found or not an element");return}if(this.shouldIgnoreElement(n))return;const i=this.get("config")?.clickThrottleMs??300;if(i>0&&!this.checkClickThrottle(n,i))return;const o=this.findTrackingElement(n),l=this.getRelevantClickElement(n),c=this.calculateClickCoordinates(t,n);if(o){const T=this.extractTrackingData(o);if(T){const E=this.createCustomEventData(T);this.eventManager.track({type:d.CUSTOM,custom_event:{name:E.name,...E.value&&{metadata:{value:E.value}}}})}}const u=this.generateClickData(n,l,c);this.eventManager.track({type:d.CLICK,click_data:u})},window.addEventListener("click",this.clickHandler,!0))}stopTracking(){this.clickHandler&&(window.removeEventListener("click",this.clickHandler,!0),this.clickHandler=void 0),this.lastClickTimes.clear(),this.lastPruneTime=0}shouldIgnoreElement(e){return e.hasAttribute(`${y}-ignore`)?!0:e.closest(`[${y}-ignore]`)!==null}checkClickThrottle(e,t){const r=this.getElementSignature(e),n=Date.now();this.pruneThrottleCache(n);const i=this.lastClickTimes.get(r);return i!==void 0&&n-i<t?(a("debug","ClickHandler: Click suppressed by throttle",{data:{signature:r,throttleRemaining:t-(n-i)}}),!1):(this.lastClickTimes.set(r,n),!0)}pruneThrottleCache(e){if(e-this.lastPruneTime<3e4)return;this.lastPruneTime=e;const t=e-3e5;for(const[r,n]of this.lastClickTimes.entries())n<t&&this.lastClickTimes.delete(r);if(this.lastClickTimes.size>1e3){const r=Array.from(this.lastClickTimes.entries()).sort((o,l)=>o[1]-l[1]),n=this.lastClickTimes.size-1e3,i=r.slice(0,n);for(const[o]of i)this.lastClickTimes.delete(o);a("debug","ClickHandler: Pruned throttle cache",{data:{removed:i.length,remaining:this.lastClickTimes.size}})}}getElementSignature(e){if(e.id)return`#${e.id}`;const t=e.getAttribute("data-testid");if(t)return`[data-testid="${t}"]`;const r=e.getAttribute(`${y}-name`);return r?`[${y}-name="${r}"]`:this.getElementPath(e)}getElementPath(e){const t=[];let r=e;for(;r&&r!==document.body;){let n=r.tagName.toLowerCase();if(r.className){const i=r.className.split(" ")[0];i&&(n+=`.${i}`)}t.unshift(n),r=r.parentElement}return t.join(">")||"unknown"}findTrackingElement(e){return e.hasAttribute(`${y}-name`)?e:e.closest(`[${y}-name]`)}getRelevantClickElement(e){for(const t of ut)try{if(e.matches(t))return e;const r=e.closest(t);if(r)return r}catch(r){a("debug","Invalid selector in element search",{error:r,data:{selector:t}});continue}return e}clamp(e){return Math.max(0,Math.min(1,Number(e.toFixed(3))))}calculateClickCoordinates(e,t){const r=t.getBoundingClientRect(),n=e.clientX,i=e.clientY,o=r.width>0?this.clamp((n-r.left)/r.width):0,l=r.height>0?this.clamp((i-r.top)/r.height):0;return{x:n,y:i,relativeX:o,relativeY:l}}extractTrackingData(e){const t=e.getAttribute(`${y}-name`),r=e.getAttribute(`${y}-value`);if(t)return{element:e,name:t,...r&&{value:r}}}generateClickData(e,t,r){const{x:n,y:i,relativeX:o,relativeY:l}=r,c=this.getRelevantText(e,t),u=this.extractElementAttributes(t);return{x:n,y:i,relativeX:o,relativeY:l,tag:t.tagName.toLowerCase(),...t.id&&{id:t.id},...t.className&&{class:t.className},...c&&{text:c},...u.href&&{href:u.href},...u.title&&{title:u.title},...u.alt&&{alt:u.alt},...u.role&&{role:u.role},...u["aria-label"]&&{ariaLabel:u["aria-label"]},...Object.keys(u).length>0&&{dataAttributes:u}}}sanitizeText(e){let t=e;for(const r of ae){const n=new RegExp(r.source,r.flags);t=t.replace(n,"[REDACTED]")}return t}getRelevantText(e,t){const r=e.textContent?.trim()??"",n=t.textContent?.trim()??"";if(!r&&!n)return"";let i="";return r&&r.length<=255?i=r:n.length<=255?i=n:i=n.slice(0,252)+"...",this.sanitizeText(i)}extractElementAttributes(e){const t=["id","class","data-testid","aria-label","title","href","type","name","alt","role"],r={};for(const n of t){const i=e.getAttribute(n);i&&(r[n]=i)}return r}createCustomEventData(e){return{name:e.name,...e.value&&{value:e.value}}}}class hr extends I{eventManager;containers=[];limitWarningLogged=!1;minDepthChange=5;minIntervalMs=500;maxEventsPerSession=120;containerDiscoveryTimeoutId=null;constructor(e){super(),this.eventManager=e}startTracking(){this.limitWarningLogged=!1,this.applyConfigOverrides(),this.set("scrollEventCount",0),this.tryDetectScrollContainers(0)}stopTracking(){this.containerDiscoveryTimeoutId!==null&&(clearTimeout(this.containerDiscoveryTimeoutId),this.containerDiscoveryTimeoutId=null);for(const e of this.containers)this.clearContainerTimer(e),e.element===window?window.removeEventListener("scroll",e.listener):e.element.removeEventListener("scroll",e.listener);this.containers.length=0,this.set("scrollEventCount",0),this.limitWarningLogged=!1}tryDetectScrollContainers(e){const t=this.findScrollableElements();if(this.isWindowScrollable()&&this.setupScrollContainer(window,"window"),t.length>0){for(const r of t){const n=this.getElementSelector(r);this.setupScrollContainer(r,n)}this.applyPrimaryScrollSelectorIfConfigured();return}if(e<5){this.containerDiscoveryTimeoutId=window.setTimeout(()=>{this.containerDiscoveryTimeoutId=null,this.tryDetectScrollContainers(e+1)},200);return}this.containers.length===0&&this.setupScrollContainer(window,"window"),this.applyPrimaryScrollSelectorIfConfigured()}applyPrimaryScrollSelectorIfConfigured(){const e=this.get("config");e?.primaryScrollSelector&&this.applyPrimaryScrollSelector(e.primaryScrollSelector)}findScrollableElements(){if(!document.body)return[];const e=[],t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const i=n;if(!i.isConnected||!i.offsetParent)return NodeFilter.FILTER_SKIP;const o=getComputedStyle(i);return o.overflowY==="auto"||o.overflowY==="scroll"||o.overflow==="auto"||o.overflow==="scroll"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let r;for(;(r=t.nextNode())&&e.length<10;){const n=r;this.isElementScrollable(n)&&e.push(n)}return e}getElementSelector(e){if(e===window)return"window";const t=e;if(t.id)return`#${t.id}`;if(t.className&&typeof t.className=="string"){const r=t.className.split(" ").filter(n=>n.trim())[0];if(r)return`.${r}`}return t.tagName.toLowerCase()}determineIfPrimary(e){return this.isWindowScrollable()?e===window:this.containers.length===0}setupScrollContainer(e,t){if(this.containers.some(u=>u.element===e)||e!==window&&!this.isElementScrollable(e))return;const n=this.getScrollTop(e),i=this.calculateScrollDepth(n,this.getScrollHeight(e),this.getViewportHeight(e)),o=this.determineIfPrimary(e),l={element:e,selector:t,isPrimary:o,lastScrollPos:n,lastDepth:i,lastDirection:$.DOWN,lastEventTime:0,firstScrollEventTime:null,maxDepthReached:i,debounceTimer:null,listener:null},c=()=>{this.get("suppressNextScroll")||(l.firstScrollEventTime===null&&(l.firstScrollEventTime=Date.now()),this.clearContainerTimer(l),l.debounceTimer=window.setTimeout(()=>{const u=this.calculateScrollData(l);if(u){const T=Date.now();this.processScrollEvent(l,u,T)}l.debounceTimer=null},250))};l.listener=c,this.containers.push(l),e===window?window.addEventListener("scroll",c,{passive:!0}):e.addEventListener("scroll",c,{passive:!0})}processScrollEvent(e,t,r){if(!this.shouldEmitScrollEvent(e,t,r))return;e.lastEventTime=r,e.lastDepth=t.depth,e.lastDirection=t.direction;const n=this.get("scrollEventCount")??0;this.set("scrollEventCount",n+1),this.eventManager.track({type:d.SCROLL,scroll_data:{...t,container_selector:e.selector,is_primary:e.isPrimary}})}shouldEmitScrollEvent(e,t,r){return this.hasReachedSessionLimit()?(this.logLimitOnce(),!1):!(!this.hasElapsedMinimumInterval(e,r)||!this.hasSignificantDepthChange(e,t.depth))}hasReachedSessionLimit(){return(this.get("scrollEventCount")??0)>=this.maxEventsPerSession}hasElapsedMinimumInterval(e,t){return e.lastEventTime===0?!0:t-e.lastEventTime>=this.minIntervalMs}hasSignificantDepthChange(e,t){return Math.abs(t-e.lastDepth)>=this.minDepthChange}logLimitOnce(){this.limitWarningLogged||(this.limitWarningLogged=!0,a("debug","Max scroll events per session reached",{data:{limit:this.maxEventsPerSession}}))}applyConfigOverrides(){this.minDepthChange=5,this.minIntervalMs=500,this.maxEventsPerSession=120}isWindowScrollable(){return document.documentElement.scrollHeight>window.innerHeight}clearContainerTimer(e){e.debounceTimer!==null&&(clearTimeout(e.debounceTimer),e.debounceTimer=null)}getScrollDirection(e,t){return e>t?$.DOWN:$.UP}calculateScrollDepth(e,t,r){if(t<=r)return 0;const n=t-r;return Math.min(100,Math.max(0,Math.floor(e/n*100)))}calculateScrollData(e){const{element:t,lastScrollPos:r,lastEventTime:n}=e,i=this.getScrollTop(t),o=Date.now(),l=Math.abs(i-r);if(l<10||t===window&&!this.isWindowScrollable())return null;const c=this.getViewportHeight(t),u=this.getScrollHeight(t),T=this.getScrollDirection(i,r),E=this.calculateScrollDepth(i,u,c);let p;n>0?p=o-n:e.firstScrollEventTime!==null?p=o-e.firstScrollEventTime:p=250;const S=Math.round(l/p*1e3);return E>e.maxDepthReached&&(e.maxDepthReached=E),e.lastScrollPos=i,{depth:E,direction:T,velocity:S,max_depth_reached:e.maxDepthReached}}getScrollTop(e){return e===window?window.scrollY:e.scrollTop}getViewportHeight(e){return e===window?window.innerHeight:e.clientHeight}getScrollHeight(e){return e===window?document.documentElement.scrollHeight:e.scrollHeight}isElementScrollable(e){const t=getComputedStyle(e),r=t.overflowY==="auto"||t.overflowY==="scroll"||t.overflow==="auto"||t.overflow==="scroll",n=e.scrollHeight>e.clientHeight;return r&&n}applyPrimaryScrollSelector(e){let t;if(e==="window")t=window;else{const n=document.querySelector(e);if(!(n instanceof HTMLElement)){a("debug",`Selector "${e}" did not match an HTMLElement`);return}t=n}this.containers.forEach(n=>{this.updateContainerPrimary(n,n.element===t)}),!this.containers.some(n=>n.element===t)&&t instanceof HTMLElement&&this.isElementScrollable(t)&&this.setupScrollContainer(t,e)}updateContainerPrimary(e,t){e.isPrimary=t}}class fr extends I{eventManager;trackedElements=new Map;observer=null;mutationObserver=null;mutationDebounceTimer=null;config=null;constructor(e){super(),this.eventManager=e}startTracking(){const e=this.get("config");if(this.config=e.viewport??null,!this.config?.elements||this.config.elements.length===0)return;const t=this.config.threshold??.5,r=this.config.minDwellTime??1e3;if(t<0||t>1){a("debug","ViewportHandler: Invalid threshold, must be between 0 and 1");return}if(r<0){a("debug","ViewportHandler: Invalid minDwellTime, must be non-negative");return}if(typeof IntersectionObserver>"u"){a("debug","ViewportHandler: IntersectionObserver not supported in this browser");return}this.observer=new IntersectionObserver(this.handleIntersection,{threshold:t}),this.observeElements(),this.setupMutationObserver()}stopTracking(){this.observer&&(this.observer.disconnect(),this.observer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.mutationDebounceTimer!==null&&(window.clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null);for(const e of this.trackedElements.values())e.timeoutId!==null&&window.clearTimeout(e.timeoutId);this.trackedElements.clear()}observeElements(){if(!this.config||!this.observer)return;const e=this.config.maxTrackedElements??100;let t=this.trackedElements.size;for(const r of this.config.elements)try{const n=document.querySelectorAll(r.selector);for(const i of Array.from(n)){if(t>=e){a("debug","ViewportHandler: Maximum tracked elements reached",{data:{limit:e,selector:r.selector,message:"Some elements will not be tracked. Consider more specific selectors."}});return}i.hasAttribute(`${y}-ignore`)||this.trackedElements.has(i)||(this.trackedElements.set(i,{element:i,selector:r.selector,id:r.id,name:r.name,startTime:null,timeoutId:null,lastFiredTime:null}),this.observer?.observe(i),t++)}}catch(n){a("debug",`ViewportHandler: Invalid selector "${r.selector}"`,{error:n})}a("debug","ViewportHandler: Elements tracked",{data:{count:t,limit:e}})}handleIntersection=e=>{if(!this.config)return;const t=this.config.minDwellTime??1e3;for(const r of e){const n=this.trackedElements.get(r.target);n&&(r.isIntersecting?n.startTime===null&&(n.startTime=performance.now(),n.timeoutId=window.setTimeout(()=>{const i=Math.round(r.intersectionRatio*100)/100;this.fireViewportEvent(n,i)},t)):n.startTime!==null&&(n.timeoutId!==null&&(window.clearTimeout(n.timeoutId),n.timeoutId=null),n.startTime=null))}};fireViewportEvent(e,t){if(e.startTime===null)return;const r=Math.round(performance.now()-e.startTime);if(e.element.hasAttribute(`${y}-ignore`))return;const n=this.config?.cooldownPeriod??6e4,i=Date.now();if(e.lastFiredTime!==null&&i-e.lastFiredTime<n){a("debug","ViewportHandler: Event suppressed by cooldown period",{data:{selector:e.selector,cooldownRemaining:n-(i-e.lastFiredTime)}}),e.startTime=null,e.timeoutId=null;return}const o={selector:e.selector,dwellTime:r,visibilityRatio:t,...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name}};this.eventManager.track({type:d.VIEWPORT_VISIBLE,viewport_data:o}),e.startTime=null,e.timeoutId=null,e.lastFiredTime=i}setupMutationObserver(){if(!(!this.config||typeof MutationObserver>"u")){if(!document.body){a("debug","ViewportHandler: document.body not available, skipping MutationObserver setup");return}this.mutationObserver=new MutationObserver(e=>{let t=!1;for(const r of e)r.type==="childList"&&(r.addedNodes.length>0&&(t=!0),r.removedNodes.length>0&&this.cleanupRemovedNodes(r.removedNodes));t&&(this.mutationDebounceTimer!==null&&window.clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.observeElements(),this.mutationDebounceTimer=null},100))}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0})}}cleanupRemovedNodes(e){e.forEach(t=>{if(t.nodeType!==1)return;const r=t,n=this.trackedElements.get(r);n&&(n.timeoutId!==null&&window.clearTimeout(n.timeoutId),this.observer?.unobserve(r),this.trackedElements.delete(r)),Array.from(this.trackedElements.keys()).filter(o=>r.contains(o)).forEach(o=>{const l=this.trackedElements.get(o);l&&l.timeoutId!==null&&window.clearTimeout(l.timeoutId),this.observer?.unobserve(o),this.trackedElements.delete(o)})})}}class mr{storage;sessionStorageRef;fallbackStorage=new Map;fallbackSessionStorage=new Map;hasQuotaExceededError=!1;constructor(){this.storage=this.initializeStorage("localStorage"),this.sessionStorageRef=this.initializeStorage("sessionStorage"),this.storage||a("debug","localStorage not available, using memory fallback"),this.sessionStorageRef||a("debug","sessionStorage not available, using memory fallback")}getItem(e){try{return this.storage?this.storage.getItem(e):this.fallbackStorage.get(e)??null}catch{return this.fallbackStorage.get(e)??null}}setItem(e,t){this.fallbackStorage.set(e,t);try{if(this.storage){this.storage.setItem(e,t);return}}catch(r){if(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")if(this.hasQuotaExceededError=!0,a("warn","localStorage quota exceeded, attempting cleanup",{data:{key:e,valueSize:t.length}}),this.cleanupOldData())try{if(this.storage){this.storage.setItem(e,t);return}}catch(o){a("error","localStorage quota exceeded even after cleanup - data will not persist",{error:o,data:{key:e,valueSize:t.length}})}else a("error","localStorage quota exceeded and no data to cleanup - data will not persist",{error:r,data:{key:e,valueSize:t.length}})}}removeItem(e){try{this.storage&&this.storage.removeItem(e)}catch{}this.fallbackStorage.delete(e)}clear(){if(!this.storage){this.fallbackStorage.clear();return}try{const e=[];for(let t=0;t<this.storage.length;t++){const r=this.storage.key(t);r?.startsWith("tracelog_")&&e.push(r)}e.forEach(t=>{this.storage.removeItem(t)}),this.fallbackStorage.clear()}catch(e){a("error","Failed to clear storage",{error:e}),this.fallbackStorage.clear()}}isAvailable(){return this.storage!==null}hasQuotaError(){return this.hasQuotaExceededError}cleanupOldData(){if(!this.storage)return!1;try{const e=[],t=[];for(let i=0;i<this.storage.length;i++){const o=this.storage.key(i);o?.startsWith("tracelog_")&&(e.push(o),o.startsWith("tracelog_persisted_events_")&&t.push(o))}if(t.length>0)return t.forEach(i=>{try{this.storage.removeItem(i)}catch{}}),!0;const r=["tracelog_session_","tracelog_user_id","tracelog_device_id","tracelog_config"],n=e.filter(i=>!r.some(o=>i.startsWith(o)));return n.length>0?(n.slice(0,5).forEach(o=>{try{this.storage.removeItem(o)}catch{}}),!0):!1}catch(e){return a("error","Failed to cleanup old data",{error:e}),!1}}initializeStorage(e){if(typeof window>"u")return null;try{const t=e==="localStorage"?window.localStorage:window.sessionStorage,r="__tracelog_test__";return t.setItem(r,"test"),t.removeItem(r),t}catch{return null}}getSessionItem(e){try{return this.sessionStorageRef?this.sessionStorageRef.getItem(e):this.fallbackSessionStorage.get(e)??null}catch{return this.fallbackSessionStorage.get(e)??null}}setSessionItem(e,t){this.fallbackSessionStorage.set(e,t);try{if(this.sessionStorageRef){this.sessionStorageRef.setItem(e,t);return}}catch(r){(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")&&a("error","sessionStorage quota exceeded - data will not persist",{error:r,data:{key:e,valueSize:t.length}})}}removeSessionItem(e){try{this.sessionStorageRef&&this.sessionStorageRef.removeItem(e)}catch{}this.fallbackSessionStorage.delete(e)}}class gr extends I{eventManager;reportedByNav=new Map;navigationHistory=[];observers=[];vitalThresholds;lastLongTaskSentAt=0;navigationCounter=0;constructor(e){super(),this.eventManager=e,this.vitalThresholds=ce(z)}async startTracking(){const e=this.get("config"),t=e?.webVitalsMode??z;this.vitalThresholds=ce(t),e?.webVitalsThresholds&&(this.vitalThresholds={...this.vitalThresholds,...e.webVitalsThresholds}),await this.initWebVitals(),this.observeLongTasks()}stopTracking(){this.observers.forEach((e,t)=>{try{e.disconnect()}catch(r){a("debug","Failed to disconnect performance observer",{error:r,data:{observerIndex:t}})}}),this.observers.length=0,this.reportedByNav.clear(),this.navigationHistory.length=0}observeWebVitalsFallback(){this.reportTTFB(),this.safeObserve("largest-contentful-paint",r=>{const n=r.getEntries(),i=n[n.length-1];i&&this.sendVital({type:"LCP",value:Number(i.startTime.toFixed(2))})},{type:"largest-contentful-paint",buffered:!0},!0);let e=0,t=this.getNavigationId();this.safeObserve("layout-shift",r=>{const n=this.getNavigationId();n!==t&&(e=0,t=n);const i=r.getEntries();for(const o of i){if(o.hadRecentInput===!0)continue;const l=typeof o.value=="number"?o.value:0;e+=l}this.sendVital({type:"CLS",value:Number(e.toFixed(2))})},{type:"layout-shift",buffered:!0}),this.safeObserve("paint",r=>{for(const n of r.getEntries())n.name==="first-contentful-paint"&&this.sendVital({type:"FCP",value:Number(n.startTime.toFixed(2))})},{type:"paint",buffered:!0},!0),this.safeObserve("event",r=>{let n=0;const i=r.getEntries();for(const o of i){const l=(o.processingEnd??0)-(o.startTime??0);n=Math.max(n,l)}n>0&&this.sendVital({type:"INP",value:Number(n.toFixed(2))})},{type:"event",buffered:!0})}async initWebVitals(){try{const{onLCP:e,onCLS:t,onFCP:r,onTTFB:n,onINP:i}=await Promise.resolve().then(()=>Vr),o=l=>c=>{const u=Number(c.value.toFixed(2));this.sendVital({type:l,value:u})};e(o("LCP"),{reportAllChanges:!1}),t(o("CLS"),{reportAllChanges:!1}),r(o("FCP"),{reportAllChanges:!1}),n(o("TTFB"),{reportAllChanges:!1}),i(o("INP"),{reportAllChanges:!1})}catch(e){a("debug","Failed to load web-vitals library, using fallback",{error:e}),this.observeWebVitalsFallback()}}reportTTFB(){try{const e=performance.getEntriesByType("navigation")[0];if(!e)return;const t=e.responseStart;typeof t=="number"&&Number.isFinite(t)&&this.sendVital({type:"TTFB",value:Number(t.toFixed(2))})}catch(e){a("debug","Failed to report TTFB",{error:e})}}observeLongTasks(){this.safeObserve("longtask",e=>{const t=e.getEntries();for(const r of t){const n=Number(r.duration.toFixed(2)),i=Date.now();i-this.lastLongTaskSentAt>=kt&&(this.shouldSendVital("LONG_TASK",n)&&this.trackWebVital("LONG_TASK",n),this.lastLongTaskSentAt=i)}},{type:"longtask",buffered:!0})}sendVital(e){if(!this.shouldSendVital(e.type,e.value))return;const t=this.getNavigationId();if(t){const r=this.reportedByNav.get(t);if(r?.has(e.type))return;if(r)r.add(e.type);else if(this.reportedByNav.set(t,new Set([e.type])),this.navigationHistory.push(t),this.navigationHistory.length>Ut){const i=this.navigationHistory.shift();i&&this.reportedByNav.delete(i)}}this.trackWebVital(e.type,e.value)}trackWebVital(e,t){if(!Number.isFinite(t)){a("debug","Invalid web vital value",{data:{type:e,value:t}});return}this.eventManager.track({type:d.WEB_VITALS,web_vitals:{type:e,value:t}})}getNavigationId(){try{const e=performance.getEntriesByType("navigation")[0];if(!e)return null;const t=e.startTime||performance.now(),r=++this.navigationCounter,n=`${t.toFixed(2)}_${window.location.pathname}`;return r>1?`${n}_${r}`:n}catch(e){return a("debug","Failed to get navigation ID",{error:e}),null}}isObserverSupported(e){if(typeof PerformanceObserver>"u")return!1;const t=PerformanceObserver.supportedEntryTypes;return!t||t.includes(e)}safeObserve(e,t,r,n=!1){try{if(!this.isObserverSupported(e))return!1;const i=new PerformanceObserver((o,l)=>{try{t(o,l)}catch(c){a("debug","Observer callback failed",{error:c,data:{type:e}})}if(n)try{l.disconnect()}catch{}});return i.observe(r??{type:e,buffered:!0}),n||this.observers.push(i),!0}catch(i){return a("debug","Failed to create performance observer",{error:i,data:{type:e}}),!1}}shouldSendVital(e,t){if(typeof t!="number"||!Number.isFinite(t))return a("debug","Invalid web vital value",{data:{type:e,value:t}}),!1;const r=this.vitalThresholds[e];return!(typeof r=="number"&&t<=r)}}class Er extends I{eventManager;recentErrors=new Map;errorBurstCounter=0;burstWindowStart=0;burstBackoffUntil=0;constructor(e){super(),this.eventManager=e}startTracking(){window.addEventListener("error",this.handleError),window.addEventListener("unhandledrejection",this.handleRejection)}stopTracking(){window.removeEventListener("error",this.handleError),window.removeEventListener("unhandledrejection",this.handleRejection),this.recentErrors.clear(),this.errorBurstCounter=0,this.burstWindowStart=0,this.burstBackoffUntil=0}shouldSample(){const e=Date.now();if(e<this.burstBackoffUntil)return!1;if(e-this.burstWindowStart>Ot&&(this.errorBurstCounter=0,this.burstWindowStart=e),this.errorBurstCounter++,this.errorBurstCounter>Pt)return this.burstBackoffUntil=e+Be,a("debug","Error burst detected - entering cooldown",{data:{errorsInWindow:this.errorBurstCounter,cooldownMs:Be}}),!1;const r=this.get("config")?.errorSampling??$e;return Math.random()<r}handleError=e=>{if(!this.shouldSample())return;const t=this.sanitize(e.message||"Unknown error");this.shouldSuppressError(V.JS_ERROR,t)||this.eventManager.track({type:d.ERROR,error_data:{type:V.JS_ERROR,message:t,...e.filename&&{filename:e.filename},...e.lineno&&{line:e.lineno},...e.colno&&{column:e.colno}}})};handleRejection=e=>{if(!this.shouldSample())return;const t=this.extractRejectionMessage(e.reason),r=this.sanitize(t);this.shouldSuppressError(V.PROMISE_REJECTION,r)||this.eventManager.track({type:d.ERROR,error_data:{type:V.PROMISE_REJECTION,message:r}})};extractRejectionMessage(e){if(!e)return"Unknown rejection";if(typeof e=="string")return e;if(e instanceof Error)return e.stack??e.message??e.toString();if(typeof e=="object"&&"message"in e)return String(e.message);try{return JSON.stringify(e)}catch{return String(e)}}sanitize(e){let t=e.length>xe?e.slice(0,xe)+"...":e;for(const r of ae){const n=new RegExp(r.source,r.flags);t=t.replace(n,"[REDACTED]")}return t}shouldSuppressError(e,t){const r=Date.now(),n=`${e}:${t}`,i=this.recentErrors.get(n);return i&&r-i<Fe?(this.recentErrors.set(n,r),!0):(this.recentErrors.set(n,r),this.recentErrors.size>Nt?(this.recentErrors.clear(),this.recentErrors.set(n,r),!1):(this.recentErrors.size>j&&this.pruneOldErrors(),!1))}pruneOldErrors(){const e=Date.now();for(const[n,i]of this.recentErrors.entries())e-i>Fe&&this.recentErrors.delete(n);if(this.recentErrors.size<=j)return;const t=Array.from(this.recentErrors.entries()).sort((n,i)=>n[1]-i[1]),r=this.recentErrors.size-j;for(let n=0;n<r;n+=1){const i=t[n];i&&this.recentErrors.delete(i[0])}}}class Sr extends I{isInitialized=!1;suppressNextScrollTimer=null;emitter=new rr;transformers={};customHeadersProvider;managers={};handlers={};get initialized(){return this.isInitialized}async init(e={}){if(!this.isInitialized){this.managers.storage=new mr;try{this.setupState(e);const t=e.integrations?.custom?.headers??{};this.managers.event=new ir(this.managers.storage,this.emitter,this.transformers,t,this.customHeadersProvider),this.initializeHandlers(),await this.managers.event.recoverPersistedEvents().catch(r=>{a("warn","Failed to recover persisted events",{error:r})}),this.isInitialized=!0}catch(t){this.destroy(!0);const r=t instanceof Error?t.message:String(t);throw new Error(`[TraceLog] TraceLog initialization failed: ${r}`)}}}sendCustomEvent(e,t){if(!this.managers.event){a("warn","Cannot send custom event: TraceLog not initialized",{data:{name:e}});return}let r=t;t&&typeof t=="object"&&!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&(r=Object.assign({},t));const{valid:n,error:i,sanitizedMetadata:o}=tr(e,r);if(!n){if(this.get("mode")===B.QA)throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${i}`);return}this.managers.event.track({type:d.CUSTOM,custom_event:{name:e,...o&&{metadata:o}}})}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setTransformer(e,t){if(typeof t!="function")throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof t}`);this.transformers[e]=t}removeTransformer(e){delete this.transformers[e]}getTransformer(e){return this.transformers[e]}setCustomHeaders(e){if(typeof e!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof e}`);this.customHeadersProvider=e,this.managers.event&&this.managers.event.setCustomHeadersProvider(e)}removeCustomHeaders(){this.customHeadersProvider=void 0,this.managers.event&&this.managers.event.removeCustomHeadersProvider()}destroy(e=!1){!this.isInitialized&&!e||(Object.values(this.handlers).filter(Boolean).forEach(t=>{try{t.stopTracking()}catch(r){a("warn","Failed to stop tracking",{error:r})}}),this.suppressNextScrollTimer&&(clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=null),this.managers.event?.stop(),this.emitter.removeAllListeners(),this.transformers.beforeSend=void 0,this.transformers.beforeBatch=void 0,this.customHeadersProvider=void 0,this.set("suppressNextScroll",!1),this.set("sessionId",null),this.isInitialized=!1,this.handlers={},this.managers={})}setupState(e={}){this.set("config",e);const t=or.getId(this.managers.storage);this.set("userId",t);const r=jt(e);this.set("collectApiUrls",r);const n=Rt();this.set("device",n);const i=he(window.location.href,e.sensitiveQueryParams);this.set("pageUrl",i),Ft()&&this.set("mode",B.QA)}getConfig(){return this.get("config")}getCollectApiUrls(){return this.get("collectApiUrls")}getEventManager(){return this.managers.event}validateGlobalMetadata(e){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,error:"Global metadata must be a plain object"};const t=Ye("Global",e,"globalMetadata");return t.valid?{valid:!0}:{valid:!1,error:t.error}}updateGlobalMetadata(e){const t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);const n={...this.get("config"),globalMetadata:e};this.set("config",n),a("debug","Global metadata updated (replaced)",{data:{keys:Object.keys(e)}})}mergeGlobalMetadata(e){const t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);const r=this.get("config"),i={...r.globalMetadata??{},...e},o={...r,globalMetadata:i};this.set("config",o),a("debug","Global metadata updated (merged)",{data:{keys:Object.keys(e)}})}initializeHandlers(){const e=this.get("config");this.handlers.session=new cr(this.managers.storage,this.managers.event),this.handlers.session.startTracking();const t=()=>{this.set("suppressNextScroll",!0),this.suppressNextScrollTimer&&clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=window.setTimeout(()=>{this.set("suppressNextScroll",!1)},500)};this.handlers.pageView=new ur(this.managers.event,t),this.handlers.pageView.startTracking(),this.handlers.click=new dr(this.managers.event),this.handlers.click.startTracking(),this.handlers.scroll=new hr(this.managers.event),this.handlers.scroll.startTracking(),this.handlers.performance=new gr(this.managers.event),this.handlers.performance.startTracking().catch(r=>{a("warn","Failed to start performance tracking",{error:r})}),this.handlers.error=new Er(this.managers.event),this.handlers.error.startTracking(),e.viewport&&(this.handlers.viewport=new fr(this.managers.event),this.handlers.viewport.startTracking())}}const O=[],C=[];let P=null,f=null,R=!1,_=!1;const Tr=async s=>{if(!(typeof window>"u"||typeof document>"u")&&(_=!1,window.__traceLogDisabled!==!0&&!f&&!R)){R=!0;try{const e=Jt(s??{}),t=new Sr;try{O.forEach(({event:i,callback:o})=>{t.on(i,o)}),O.length=0,C.forEach(({hook:i,fn:o})=>{i==="beforeSend"?t.setTransformer("beforeSend",o):t.setTransformer("beforeBatch",o)}),C.length=0,P&&(t.setCustomHeaders(P),P=null);const r=t.init(e),n=new Promise((i,o)=>{setTimeout(()=>{o(new Error("[TraceLog] Initialization timeout after 10000ms"))},1e4)});await Promise.race([r,n]),f=t}catch(r){try{t.destroy(!0)}catch(n){a("error","Failed to cleanup partially initialized app",{error:n})}throw r}}catch(e){throw f=null,e}finally{R=!1}}},pr=(s,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!f)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(_)throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");f.sendCustomEvent(s,e)}},_r=(s,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!f||R){O.push({event:s,callback:e});return}f.on(s,e)}},vr=(s,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!f){const t=O.findIndex(r=>r.event===s&&r.callback===e);t!==-1&&O.splice(t,1);return}f.off(s,e)}};function Ir(s,e){if(!(typeof window>"u"||typeof document>"u")){if(typeof e!="function")throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof e}`);if(!f||R){const t=C.findIndex(r=>r.hook===s);t!==-1&&C.splice(t,1),C.push({hook:s,fn:e});return}if(_)throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");s==="beforeSend"?f.setTransformer("beforeSend",e):f.setTransformer("beforeBatch",e)}}const wr={init:Tr,event:pr,on:_r,off:vr,setTransformer:Ir,removeTransformer:s=>{if(!(typeof window>"u"||typeof document>"u")){if(!f){const e=C.findIndex(t=>t.hook===s);e!==-1&&C.splice(e,1);return}if(_)throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");f.removeTransformer(s)}},setCustomHeaders:s=>{if(!(typeof window>"u"||typeof document>"u")){if(typeof s!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof s}`);if(!f||R){P=s;return}if(_)throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");f.setCustomHeaders(s)}},removeCustomHeaders:()=>{if(!(typeof window>"u"||typeof document>"u")){if(!f){P=null;return}if(_)throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");f.removeCustomHeaders()}},isInitialized:()=>typeof window>"u"||typeof document>"u"?!1:f!==null,destroy:()=>{if(!(typeof window>"u"||typeof document>"u")){if(_)throw new Error("[TraceLog] Destroy operation already in progress");if(!f){_=!1;return}_=!0;try{f.destroy(),f=null,R=!1,O.length=0,C.length=0,P=null,_=!1}catch(s){f=null,R=!1,O.length=0,C.length=0,P=null,_=!1,a("warn","Error during destroy, forced cleanup completed",{error:s})}}},setQaMode:s=>{typeof window>"u"||typeof document>"u"||$t(s)},updateGlobalMetadata:s=>{if(!(typeof window>"u"||typeof document>"u")){if(!f)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(_)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");f.updateGlobalMetadata(s)}},mergeGlobalMetadata:s=>{if(!(typeof window>"u"||typeof document>"u")){if(!f)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(_)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");f.mergeGlobalMetadata(s)}}};var ge,et=-1,H=function(s){addEventListener("pageshow",(function(e){e.persisted&&(et=e.timeStamp,s(e))}),!0)},Ee=function(){var s=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(s&&s.responseStart>0&&s.responseStart<performance.now())return s},q=function(){var s=Ee();return s&&s.activationStart||0},A=function(s,e){var t=Ee(),r="navigate";return et>=0?r="back-forward-cache":t&&(document.prerendering||q()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:s,value:e===void 0?-1:e,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},W=function(s,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(s)){var r=new PerformanceObserver((function(n){Promise.resolve().then((function(){e(n.getEntries())}))}));return r.observe(Object.assign({type:s,buffered:!0},t||{})),r}}catch{}},M=function(s,e,t,r){var n,i;return function(o){e.value>=0&&(o||r)&&((i=e.value-(n||0))||n===void 0)&&(n=e.value,e.delta=i,e.rating=(function(l,c){return l>c[1]?"poor":l>c[0]?"needs-improvement":"good"})(e.value,t),s(e))}},Se=function(s){requestAnimationFrame((function(){return requestAnimationFrame((function(){return s()}))}))},J=function(s){document.addEventListener("visibilitychange",(function(){document.visibilityState==="hidden"&&s()}))},Te=function(s){var e=!1;return function(){e||(s(),e=!0)}},x=-1,tt=function(){return document.visibilityState!=="hidden"||document.prerendering?1/0:0},Z=function(s){document.visibilityState==="hidden"&&x>-1&&(x=s.type==="visibilitychange"?s.timeStamp:0,yr())},rt=function(){addEventListener("visibilitychange",Z,!0),addEventListener("prerenderingchange",Z,!0)},yr=function(){removeEventListener("visibilitychange",Z,!0),removeEventListener("prerenderingchange",Z,!0)},st=function(){return x<0&&(x=tt(),rt(),H((function(){setTimeout((function(){x=tt(),rt()}),0)}))),{get firstHiddenTime(){return x}}},ee=function(s){document.prerendering?addEventListener("prerenderingchange",(function(){return s()}),!0):s()},pe=[1800,3e3],nt=function(s,e){e=e||{},ee((function(){var t,r=st(),n=A("FCP"),i=W("paint",(function(o){o.forEach((function(l){l.name==="first-contentful-paint"&&(i.disconnect(),l.startTime<r.firstHiddenTime&&(n.value=Math.max(l.startTime-q(),0),n.entries.push(l),t(!0)))}))}));i&&(t=M(s,n,pe,e.reportAllChanges),H((function(o){n=A("FCP"),t=M(s,n,pe,e.reportAllChanges),Se((function(){n.value=performance.now()-o.timeStamp,t(!0)}))})))}))},_e=[.1,.25],br=function(s,e){e=e||{},nt(Te((function(){var t,r=A("CLS",0),n=0,i=[],o=function(c){c.forEach((function(u){if(!u.hadRecentInput){var T=i[0],E=i[i.length-1];n&&u.startTime-E.startTime<1e3&&u.startTime-T.startTime<5e3?(n+=u.value,i.push(u)):(n=u.value,i=[u])}})),n>r.value&&(r.value=n,r.entries=i,t())},l=W("layout-shift",o);l&&(t=M(s,r,_e,e.reportAllChanges),J((function(){o(l.takeRecords()),t(!0)})),H((function(){n=0,r=A("CLS",0),t=M(s,r,_e,e.reportAllChanges),Se((function(){return t()}))})),setTimeout(t,0))})))},it=0,ve=1/0,te=0,Ar=function(s){s.forEach((function(e){e.interactionId&&(ve=Math.min(ve,e.interactionId),te=Math.max(te,e.interactionId),it=te?(te-ve)/7+1:0)}))},ot=function(){return ge?it:performance.interactionCount||0},Mr=function(){"interactionCount"in performance||ge||(ge=W("event",Ar,{type:"event",buffered:!0,durationThreshold:0}))},L=[],re=new Map,at=0,Lr=function(){var s=Math.min(L.length-1,Math.floor((ot()-at)/50));return L[s]},Cr=[],Rr=function(s){if(Cr.forEach((function(n){return n(s)})),s.interactionId||s.entryType==="first-input"){var e=L[L.length-1],t=re.get(s.interactionId);if(t||L.length<10||s.duration>e.latency){if(t)s.duration>t.latency?(t.entries=[s],t.latency=s.duration):s.duration===t.latency&&s.startTime===t.entries[0].startTime&&t.entries.push(s);else{var r={id:s.interactionId,latency:s.duration,entries:[s]};re.set(r.id,r),L.push(r)}L.sort((function(n,i){return i.latency-n.latency})),L.length>10&&L.splice(10).forEach((function(n){return re.delete(n.id)}))}}},lt=function(s){var e=self.requestIdleCallback||self.setTimeout,t=-1;return s=Te(s),document.visibilityState==="hidden"?s():(t=e(s),J(s)),t},Ie=[200,500],Nr=function(s,e){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(e=e||{},ee((function(){var t;Mr();var r,n=A("INP"),i=function(l){lt((function(){l.forEach(Rr);var c=Lr();c&&c.latency!==n.value&&(n.value=c.latency,n.entries=c.entries,r())}))},o=W("event",i,{durationThreshold:(t=e.durationThreshold)!==null&&t!==void 0?t:40});r=M(s,n,Ie,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),J((function(){i(o.takeRecords()),r(!0)})),H((function(){at=ot(),L.length=0,re.clear(),n=A("INP"),r=M(s,n,Ie,e.reportAllChanges)})))})))},we=[2500,4e3],ye={},Or=function(s,e){e=e||{},ee((function(){var t,r=st(),n=A("LCP"),i=function(c){e.reportAllChanges||(c=c.slice(-1)),c.forEach((function(u){u.startTime<r.firstHiddenTime&&(n.value=Math.max(u.startTime-q(),0),n.entries=[u],t())}))},o=W("largest-contentful-paint",i);if(o){t=M(s,n,we,e.reportAllChanges);var l=Te((function(){ye[n.id]||(i(o.takeRecords()),o.disconnect(),ye[n.id]=!0,t(!0))}));["keydown","click"].forEach((function(c){addEventListener(c,(function(){return lt(l)}),{once:!0,capture:!0})})),J(l),H((function(c){n=A("LCP"),t=M(s,n,we,e.reportAllChanges),Se((function(){n.value=performance.now()-c.timeStamp,ye[n.id]=!0,t(!0)}))}))}}))},be=[800,1800],Pr=function s(e){document.prerendering?ee((function(){return s(e)})):document.readyState!=="complete"?addEventListener("load",(function(){return s(e)}),!0):setTimeout(e,0)},Dr=function(s,e){e=e||{};var t=A("TTFB"),r=M(s,t,be,e.reportAllChanges);Pr((function(){var n=Ee();n&&(t.value=Math.max(n.responseStart-q(),0),t.entries=[n],r(!0),H((function(){t=A("TTFB",0),(r=M(s,t,be,e.reportAllChanges))(!0)})))}))};const Vr=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:_e,FCPThresholds:pe,INPThresholds:Ie,LCPThresholds:we,TTFBThresholds:be,onCLS:br,onFCP:nt,onINP:Nr,onLCP:Or,onTTFB:Dr},Symbol.toStringTag,{value:"Module"}));h.AppConfigValidationError=m,h.DEFAULT_SESSION_TIMEOUT=9e5,h.DEFAULT_WEB_VITALS_MODE=z,h.DeviceType=b,h.EmitterEvent=X,h.ErrorType=V,h.EventType=d,h.InitializationTimeoutError=pt,h.IntegrationValidationError=U,h.MAX_ARRAY_LENGTH=100,h.MAX_CUSTOM_EVENT_ARRAY_SIZE=10,h.MAX_CUSTOM_EVENT_KEYS=10,h.MAX_CUSTOM_EVENT_NAME_LENGTH=120,h.MAX_CUSTOM_EVENT_STRING_SIZE=8192,h.MAX_METADATA_NESTING_DEPTH=1,h.MAX_NESTED_OBJECT_KEYS=20,h.MAX_STRING_LENGTH=1e3,h.MAX_STRING_LENGTH_IN_ARRAY=500,h.Mode=B,h.PII_PATTERNS=ae,h.PermanentError=N,h.SamplingRateValidationError=ne,h.ScrollDirection=$,h.SessionTimeoutValidationError=Ve,h.SpecialApiUrl=D,h.TraceLogValidationError=k,h.WEB_VITALS_GOOD_THRESHOLDS=Vt,h.WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS=le,h.WEB_VITALS_POOR_THRESHOLDS=We,h.getWebVitalsThresholds=ce,h.isPrimaryScrollEvent=St,h.isSecondaryScrollEvent=Tt,h.tracelog=wr,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})})(this.TraceLog=this.TraceLog||{});typeof window<"u"&&window.TraceLog?.tracelog&&(window.tracelog=window.TraceLog.tracelog);
|
|
1
|
+
(function(h){"use strict";const y="data-tlog",ut=["button","a",'input[type="button"]','input[type="submit"]','input[type="reset"]','input[type="checkbox"]','input[type="radio"]',"select","textarea",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="option"]','[role="checkbox"]','[role="radio"]','[role="switch"]',"[routerLink]","[ng-click]","[data-action]","[data-click]","[data-navigate]","[data-toggle]","[onclick]",".btn",".button",".clickable",".nav-link",".menu-item","[data-testid]",'[tabindex="0"]'],dt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],ht=["token","auth","key","session","reset","password","api_key","apikey","secret","access_token","refresh_token","verification","code","otp"],g={INVALID_SESSION_TIMEOUT:"Session timeout must be between 30000ms (30 seconds) and 86400000ms (24 hours)",INVALID_SAMPLING_RATE:"Sampling rate must be between 0 and 1",INVALID_ERROR_SAMPLING_RATE:"Error sampling must be between 0 and 1",INVALID_TRACELOG_PROJECT_ID:"TraceLog project ID is required when integration is enabled",INVALID_CUSTOM_API_URL:"Custom API URL is required when integration is enabled",INVALID_GLOBAL_METADATA:"Global metadata must be an object",INVALID_SENSITIVE_QUERY_PARAMS:"Sensitive query params must be an array of strings",INVALID_PRIMARY_SCROLL_SELECTOR:"Primary scroll selector must be a non-empty string",INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX:"Invalid CSS selector syntax for primaryScrollSelector",INVALID_PAGE_VIEW_THROTTLE:"Page view throttle must be a non-negative number",INVALID_CLICK_THROTTLE:"Click throttle must be a non-negative number",INVALID_MAX_SAME_EVENT_PER_MINUTE:"Max same event per minute must be a positive number",INVALID_VIEWPORT_CONFIG:"Viewport config must be an object",INVALID_VIEWPORT_ELEMENTS:"Viewport elements must be a non-empty array",INVALID_VIEWPORT_ELEMENT:"Each viewport element must have a valid selector string",INVALID_VIEWPORT_ELEMENT_ID:"Viewport element id must be a non-empty string",INVALID_VIEWPORT_ELEMENT_NAME:"Viewport element name must be a non-empty string",INVALID_VIEWPORT_THRESHOLD:"Viewport threshold must be a number between 0 and 1",INVALID_VIEWPORT_MIN_DWELL_TIME:"Viewport minDwellTime must be a non-negative number",INVALID_VIEWPORT_COOLDOWN_PERIOD:"Viewport cooldownPeriod must be a non-negative number",INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS:"Viewport maxTrackedElements must be a positive number"},ft=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/on\w+\s*=/gi,/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,/<embed\b[^>]*>/gi,/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi],w="tlog",F=`${w}:qa_mode`,Le=`${w}:uid`,Ce="tlog_mode",Re="qa",Ne="qa_off",mt=s=>s?`${w}:${s}:queue`:`${w}:queue`,gt=s=>s?`${w}:${s}:session`:`${w}:session`,Et=s=>s?`${w}:${s}:broadcast`:`${w}:broadcast`,Oe=(s,e)=>`${w}:${s}:session_counts:${e}`,Pe=10080*60*1e3,De=`${w}:session_counts_last_cleanup`,Ve=3600*1e3;var D=(s=>(s.Localhost="localhost:8080",s.Fail="localhost:9999",s))(D||{}),b=(s=>(s.Mobile="mobile",s.Tablet="tablet",s.Desktop="desktop",s.Unknown="unknown",s))(b||{}),X=(s=>(s.EVENT="event",s.QUEUE="queue",s))(X||{});class N extends Error{constructor(e,t){super(e),this.statusCode=t,this.name="PermanentError",Error.captureStackTrace&&Error.captureStackTrace(this,N)}}var d=(s=>(s.PAGE_VIEW="page_view",s.CLICK="click",s.SCROLL="scroll",s.SESSION_START="session_start",s.CUSTOM="custom",s.WEB_VITALS="web_vitals",s.ERROR="error",s.VIEWPORT_VISIBLE="viewport_visible",s))(d||{}),$=(s=>(s.UP="up",s.DOWN="down",s))($||{}),V=(s=>(s.JS_ERROR="js_error",s.PROMISE_REJECTION="promise_rejection",s))(V||{}),B=(s=>(s.QA="qa",s))(B||{});const St=s=>s.type===d.SCROLL&&"scroll_data"in s&&s.scroll_data.is_primary===!0,Tt=s=>s.type===d.SCROLL&&"scroll_data"in s&&s.scroll_data.is_primary===!1;class k extends Error{constructor(e,t,r){super(e),this.errorCode=t,this.layer=r,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class m extends k{constructor(e,t="config"){super(e,"APP_CONFIG_INVALID",t)}}class ke extends k{constructor(e,t="config"){super(e,"SESSION_TIMEOUT_INVALID",t)}}class ne extends k{constructor(e,t="config"){super(e,"SAMPLING_RATE_INVALID",t)}}class U extends k{constructor(e,t="config"){super(e,"INTEGRATION_INVALID",t)}}class pt extends k{constructor(e,t,r="runtime"){super(e,"INITIALIZATION_TIMEOUT",r),this.timeoutMs=t}}const Ue="background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",He="background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",_t="background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",vt=(s,e)=>{if(e){if(e instanceof Error){const t=e.message.replace(/\s+at\s+.*$/gm,"").replace(/\s*\([^()]+:\d+:\d+\)/g,"");return`[TraceLog] ${s}: ${t}`}if(e instanceof Error)return`[TraceLog] ${s}: ${e.message}`;if(typeof e=="string")return`[TraceLog] ${s}: ${e}`;if(typeof e=="object")try{return`[TraceLog] ${s}: ${JSON.stringify(e)}`}catch{return`[TraceLog] ${s}: [Unable to serialize error]`}return`[TraceLog] ${s}: ${String(e)}`}return`[TraceLog] ${s}`},It=()=>{if(typeof window>"u"||typeof sessionStorage>"u")return!1;try{return sessionStorage.getItem(F)==="true"}catch{return!1}},a=(s,e,t)=>{const{error:r,data:n,showToClient:i=!1,style:o,visibility:l}=t??{},c=r?vt(e,r):`[TraceLog] ${e}`,u=s==="error"?"error":s==="warn"?"warn":"log";if(!wt(l,i))return;const E=yt(l,o),p=n!==void 0?ie(n):void 0;bt(u,c,E,p)},wt=(s,e)=>s==="critical"?!0:s==="qa"||e?It():!1,yt=(s,e)=>e!==void 0&&e!==""?e:s==="critical"?_t:"",bt=(s,e,t,r)=>{const n=t!==void 0&&t!=="",i=n?`%c${e}`:e;r!==void 0?n?console[s](i,t,r):console[s](i,r):n?console[s](i,t):console[s](i)},ie=s=>{const e={},t=["token","password","secret","key","apikey","api_key","sessionid","session_id"];for(const[r,n]of Object.entries(s)){const i=r.toLowerCase();if(t.some(o=>i.includes(o))){e[r]="[REDACTED]";continue}n!==null&&typeof n=="object"&&!Array.isArray(n)?e[r]=ie(n):Array.isArray(n)?e[r]=n.map(o=>o!==null&&typeof o=="object"&&!Array.isArray(o)?ie(o):o):e[r]=n}return e};let oe,xe;const At=()=>{typeof window<"u"&&!oe&&(oe=window.matchMedia("(pointer: coarse)"),xe=window.matchMedia("(hover: none)"))},Q="Unknown",Mt=s=>{const e=s.userAgentData?.platform;if(e!=null&&e!==""){if(/windows/i.test(e))return"Windows";if(/macos/i.test(e))return"macOS";if(/android/i.test(e))return"Android";if(/linux/i.test(e))return"Linux";if(/chromeos/i.test(e))return"ChromeOS";if(/ios/i.test(e))return"iOS"}const t=navigator.userAgent;return/Windows/i.test(t)?"Windows":/iPhone|iPad|iPod/i.test(t)?"iOS":/Mac OS X|Macintosh/i.test(t)?"macOS":/Android/i.test(t)?"Android":/CrOS/i.test(t)?"ChromeOS":/Linux/i.test(t)?"Linux":Q},Lt=s=>{const e=s.userAgentData?.brands;if(e!=null&&e.length>0){const n=e.filter(i=>!/not.?a.?brand|chromium/i.test(i.brand))[0];if(n!=null){const i=n.brand;return/google chrome/i.test(i)?"Chrome":/microsoft edge/i.test(i)?"Edge":/opera/i.test(i)?"Opera":i}}const t=navigator.userAgent;return/Edg\//i.test(t)?"Edge":/OPR\//i.test(t)?"Opera":/Chrome/i.test(t)?"Chrome":/Firefox/i.test(t)?"Firefox":/Safari/i.test(t)&&!/Chrome/i.test(t)?"Safari":Q},Ct=()=>{try{const s=navigator;if(s.userAgentData!=null&&typeof s.userAgentData.mobile=="boolean"){const c=s.userAgentData.platform;return c!=null&&c!==""&&/ipad|tablet/i.test(c)?b.Tablet:s.userAgentData.mobile?b.Mobile:b.Desktop}At();const e=window.innerWidth,t=oe?.matches??!1,r=xe?.matches??!1,n="ontouchstart"in window||navigator.maxTouchPoints>0,i=navigator.userAgent.toLowerCase(),o=/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(i),l=/tablet|ipad|android(?!.*mobile)/.test(i);return e<=767||o&&n?b.Mobile:e>=768&&e<=1024||l||t&&r&&n?b.Tablet:b.Desktop}catch(s){return a("debug","Device detection failed, defaulting to desktop",{error:s}),b.Desktop}},Rt=()=>{try{const s=navigator;return{type:Ct(),os:Mt(s),browser:Lt(s)}}catch(s){return a("debug","Device info detection failed, using defaults",{error:s}),{type:b.Desktop,os:Q,browser:Q}}},ae=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/gi,/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,/\b[A-Z]{2}\d{2}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/gi,/\b[sp]k_(test|live)_[a-zA-Z0-9]{10,}\b/gi,/Bearer\s+[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?(?:\.[A-Za-z0-9_-]+)?/gi,/:\/\/[^:/]+:([^@]+)@/gi],Fe=500,$e=5e3,z=50,Nt=z*2,Be=1,Ot=1e3,Pt=10,We=5e3,Dt=6e4,Vt={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},le={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},Ge={LCP:4e3,FCP:3e3,CLS:.25,INP:500,TTFB:1800,LONG_TASK:50},j="needs-improvement",ce=(s=j)=>{switch(s){case"all":return{LCP:0,FCP:0,CLS:0,INP:0,TTFB:0,LONG_TASK:0};case"needs-improvement":return le;case"poor":return Ge;default:return le}},kt=1e3,Ut=50,Ht="2.2.0",Xe=()=>typeof window<"u"&&typeof sessionStorage<"u",xt=()=>{try{const s=new URLSearchParams(window.location.search);s.delete(Ce);const e=s.toString(),t=window.location.pathname+(e?"?"+e:"")+window.location.hash;window.history.replaceState({},"",t)}catch{}},Ft=()=>{if(!Xe())return!1;try{const e=new URLSearchParams(window.location.search).get(Ce),t=sessionStorage.getItem(F);let r=null;return e===Re?(r=!0,sessionStorage.setItem(F,"true"),a("info","QA Mode ACTIVE",{visibility:"qa",style:Ue})):e===Ne&&(r=!1,sessionStorage.setItem(F,"false"),a("info","QA Mode DISABLED",{visibility:"qa",style:He})),(e===Re||e===Ne)&&xt(),r??t==="true"}catch{return!1}},$t=s=>{if(Xe())try{sessionStorage.setItem(F,s?"true":"false"),a("info",s?"QA Mode ACTIVE":"QA Mode DISABLED",{visibility:"qa",style:s?Ue:He})}catch{a("debug","Cannot set QA mode: sessionStorage unavailable")}},Bt=["co.uk","org.uk","com.au","net.au","com.br","co.nz","co.jp","com.mx","co.in","com.cn","co.za"],Qe=s=>{const e=s.toLowerCase().split(".");if(e.length<=2)return s.toLowerCase();const t=e.slice(-2).join(".");return Bt.includes(t)?e.slice(-3).join("."):e.slice(-2).join(".")},Wt=(s,e)=>s===e?!0:Qe(s)===Qe(e),ue=()=>{const s=document.referrer;if(!s)return"Direct";try{const e=new URL(s).hostname.toLowerCase(),t=window.location.hostname.toLowerCase();return Wt(e,t)?"Direct":s}catch(e){return a("debug","Failed to parse referrer URL, using raw value",{error:e,data:{referrer:s}}),s}},de=()=>{const s=new URLSearchParams(window.location.search),e={};return dt.forEach(r=>{const n=s.get(r);if(n){const i=r.split("utm_")[1];e[i]=n}}),Object.keys(e).length?e:void 0},Gt=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)});let K=0,Y=0;const Xt=()=>{let s=Date.now();s<Y&&(s=Y),s===Y?K=(K+1)%1e3:K=0,Y=s;const e=K.toString().padStart(3,"0");let t="";try{if(typeof crypto<"u"&&crypto.getRandomValues){const r=crypto.getRandomValues(new Uint8Array(3));r&&(t=Array.from(r,n=>n.toString(16).padStart(2,"0")).join(""))}}catch{}return t||(t=Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")),`${s}-${e}-${t}`},ze=(s,e=!1)=>{try{const t=new URL(s),r=t.protocol==="https:",n=t.protocol==="http:";return r||e&&n}catch{return!1}},Qt=s=>{try{const t=new URL(window.location.href).hostname;if(!t||typeof t!="string")throw new Error("Invalid hostname");if(t==="localhost"||t==="127.0.0.1"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t))throw new Error("SaaS integration not supported on localhost or IP addresses. Use custom backend integration instead.");const r=t.split(".");if(!r||!Array.isArray(r)||r.length===0||r.length===1&&r[0]==="")throw new Error("Invalid hostname structure");if(r.length===1)throw new Error("Single-part domain not supported for SaaS integration");let n;if(r.length===2?n=r.join("."):n=r.slice(-2).join("."),!n||n.split(".").length<2)throw new Error("Invalid domain structure for SaaS");const i=`https://${s}.${n}/collect`;if(!ze(i))throw new Error("Generated URL failed validation");return i}catch(e){throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error?e.message:String(e)}`)}},zt=s=>{const e={};s.integrations?.tracelog?.projectId&&(e.saas=Qt(s.integrations.tracelog.projectId));const t=s.integrations?.custom?.collectApiUrl;if(t){const r=s.integrations?.custom?.allowHttp??!1;if(!ze(t,r))throw new Error("Invalid custom API URL");e.custom=t}return e},he=(s,e=[])=>{if(!s||typeof s!="string")return a("warn","Invalid URL provided to normalizeUrl",{data:{type:typeof s}}),s||"";try{const t=new URL(s),r=t.searchParams,n=[...new Set([...ht,...e])];let i=!1;const o=[];return n.forEach(c=>{r.has(c)&&(r.delete(c),i=!0,o.push(c))}),!i&&s.includes("?")?s:(t.search=r.toString(),t.toString())}catch(t){return a("warn","URL normalization failed, returning original",{error:t,data:{urlLength:s?.length}}),s}},je=s=>{if(!s||typeof s!="string"||s.trim().length===0)return"";let e=s;s.length>1e3&&(e=s.slice(0,Math.max(0,1e3)));let t=0;for(const n of ft){const i=e;e=e.replace(n,""),i!==e&&t++}return t>0&&a("warn","XSS patterns detected and removed",{data:{patternMatches:t,valueLength:s.length}}),e=e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'").replaceAll("/","/"),e.trim()},fe=(s,e=0)=>{if(s==null)return null;if(typeof s=="string")return je(s);if(typeof s=="number")return!Number.isFinite(s)||s<-Number.MAX_SAFE_INTEGER||s>Number.MAX_SAFE_INTEGER?0:s;if(typeof s=="boolean")return s;if(e>10)return null;if(Array.isArray(s))return s.slice(0,100).map(n=>fe(n,e+1)).filter(n=>n!==null);if(typeof s=="object"){const t={},n=Object.entries(s).slice(0,20);for(const[i,o]of n){const l=je(i);if(l){const c=fe(o,e+1);c!==null&&(t[l]=c)}}return t}return null},jt=s=>{if(typeof s!="object"||s===null)return{};try{const e=fe(s);return typeof e=="object"&&e!==null?e:{}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`[TraceLog] Metadata sanitization failed: ${t}`)}},Kt=s=>{if(s!==void 0&&(s===null||typeof s!="object"))throw new m("Configuration must be an object","config");if(s){if(s.sessionTimeout!==void 0&&(typeof s.sessionTimeout!="number"||s.sessionTimeout<3e4||s.sessionTimeout>864e5))throw new ke(g.INVALID_SESSION_TIMEOUT,"config");if(s.globalMetadata!==void 0&&(typeof s.globalMetadata!="object"||s.globalMetadata===null))throw new m(g.INVALID_GLOBAL_METADATA,"config");if(s.integrations&&qt(s.integrations),s.sensitiveQueryParams!==void 0){if(!Array.isArray(s.sensitiveQueryParams))throw new m(g.INVALID_SENSITIVE_QUERY_PARAMS,"config");for(const e of s.sensitiveQueryParams)if(typeof e!="string")throw new m("All sensitive query params must be strings","config")}if(s.errorSampling!==void 0&&(typeof s.errorSampling!="number"||s.errorSampling<0||s.errorSampling>1))throw new ne(g.INVALID_ERROR_SAMPLING_RATE,"config");if(s.samplingRate!==void 0&&(typeof s.samplingRate!="number"||s.samplingRate<0||s.samplingRate>1))throw new ne(g.INVALID_SAMPLING_RATE,"config");if(s.primaryScrollSelector!==void 0){if(typeof s.primaryScrollSelector!="string"||!s.primaryScrollSelector.trim())throw new m(g.INVALID_PRIMARY_SCROLL_SELECTOR,"config");if(s.primaryScrollSelector!=="window")try{document.querySelector(s.primaryScrollSelector)}catch{throw new m(`${g.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${s.primaryScrollSelector}"`,"config")}}if(s.pageViewThrottleMs!==void 0&&(typeof s.pageViewThrottleMs!="number"||s.pageViewThrottleMs<0))throw new m(g.INVALID_PAGE_VIEW_THROTTLE,"config");if(s.clickThrottleMs!==void 0&&(typeof s.clickThrottleMs!="number"||s.clickThrottleMs<0))throw new m(g.INVALID_CLICK_THROTTLE,"config");if(s.maxSameEventPerMinute!==void 0&&(typeof s.maxSameEventPerMinute!="number"||s.maxSameEventPerMinute<=0))throw new m(g.INVALID_MAX_SAME_EVENT_PER_MINUTE,"config");if(s.viewport!==void 0&&Yt(s.viewport),s.webVitalsMode!==void 0){if(typeof s.webVitalsMode!="string")throw new m(`Invalid webVitalsMode type: ${typeof s.webVitalsMode}. Must be a string`,"config");const e=["all","needs-improvement","poor"];if(!e.includes(s.webVitalsMode))throw new m(`Invalid webVitalsMode: "${s.webVitalsMode}". Must be one of: ${e.join(", ")}`,"config")}if(s.webVitalsThresholds!==void 0){if(typeof s.webVitalsThresholds!="object"||s.webVitalsThresholds===null||Array.isArray(s.webVitalsThresholds))throw new m("webVitalsThresholds must be an object","config");const e=["LCP","FCP","CLS","INP","TTFB","LONG_TASK"];for(const[t,r]of Object.entries(s.webVitalsThresholds)){if(!e.includes(t))throw new m(`Invalid Web Vitals threshold key: "${t}". Must be one of: ${e.join(", ")}`,"config");if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new m(`Invalid Web Vitals threshold value for ${t}: ${r}. Must be a non-negative finite number`,"config")}}}},Yt=s=>{if(typeof s!="object"||s===null)throw new m(g.INVALID_VIEWPORT_CONFIG,"config");if(!s.elements||!Array.isArray(s.elements))throw new m(g.INVALID_VIEWPORT_ELEMENTS,"config");if(s.elements.length===0)throw new m(g.INVALID_VIEWPORT_ELEMENTS,"config");const e=new Set;for(const t of s.elements){if(!t.selector||typeof t.selector!="string"||!t.selector.trim())throw new m(g.INVALID_VIEWPORT_ELEMENT,"config");const r=t.selector.trim();if(e.has(r))throw new m(`Duplicate viewport selector found: "${r}". Each selector should appear only once.`,"config");if(e.add(r),t.id!==void 0&&(typeof t.id!="string"||!t.id.trim()))throw new m(g.INVALID_VIEWPORT_ELEMENT_ID,"config");if(t.name!==void 0&&(typeof t.name!="string"||!t.name.trim()))throw new m(g.INVALID_VIEWPORT_ELEMENT_NAME,"config")}if(s.threshold!==void 0&&(typeof s.threshold!="number"||s.threshold<0||s.threshold>1))throw new m(g.INVALID_VIEWPORT_THRESHOLD,"config");if(s.minDwellTime!==void 0&&(typeof s.minDwellTime!="number"||s.minDwellTime<0))throw new m(g.INVALID_VIEWPORT_MIN_DWELL_TIME,"config");if(s.cooldownPeriod!==void 0&&(typeof s.cooldownPeriod!="number"||s.cooldownPeriod<0))throw new m(g.INVALID_VIEWPORT_COOLDOWN_PERIOD,"config");if(s.maxTrackedElements!==void 0&&(typeof s.maxTrackedElements!="number"||s.maxTrackedElements<=0))throw new m(g.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS,"config")},qt=s=>{if(s){if(s.tracelog&&(!s.tracelog.projectId||typeof s.tracelog.projectId!="string"||s.tracelog.projectId.trim()===""))throw new U(g.INVALID_TRACELOG_PROJECT_ID,"config");if(s.custom){if(!s.custom.collectApiUrl||typeof s.custom.collectApiUrl!="string"||s.custom.collectApiUrl.trim()==="")throw new U(g.INVALID_CUSTOM_API_URL,"config");if(s.custom.allowHttp!==void 0&&typeof s.custom.allowHttp!="boolean")throw new U("allowHttp must be a boolean","config");const e=s.custom.collectApiUrl.trim();if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new U('Custom API URL must start with "http://" or "https://"',"config");if(!(s.custom.allowHttp??!1)&&e.startsWith("http://"))throw new U("Custom API URL must use HTTPS in production. Set allowHttp: true in integration config to allow HTTP (not recommended)","config")}}},Jt=s=>{Kt(s);const e={...s??{},sessionTimeout:s?.sessionTimeout??9e5,globalMetadata:s?.globalMetadata??{},sensitiveQueryParams:s?.sensitiveQueryParams??[],errorSampling:s?.errorSampling??Be,samplingRate:s?.samplingRate??1,pageViewThrottleMs:s?.pageViewThrottleMs??1e3,clickThrottleMs:s?.clickThrottleMs??300,maxSameEventPerMinute:s?.maxSameEventPerMinute??60};return e.integrations?.custom&&(e.integrations.custom={...e.integrations.custom,allowHttp:e.integrations.custom.allowHttp??!1}),e.viewport&&(e.viewport={...e.viewport,threshold:e.viewport.threshold??.5,minDwellTime:e.viewport.minDwellTime??2e3,cooldownPeriod:e.viewport.cooldownPeriod??6e4,maxTrackedElements:e.viewport.maxTrackedElements??100}),e},me=(s,e=new Set)=>{if(s==null)return!0;const t=typeof s;return t==="string"||t==="number"||t==="boolean"?!0:t==="function"||t==="symbol"||t==="bigint"||e.has(s)?!1:(e.add(s),Array.isArray(s)?s.every(r=>me(r,e)):t==="object"?Object.values(s).every(r=>me(r,e)):!1)},Zt=s=>typeof s!="object"||s===null?!1:me(s),er=s=>typeof s!="string"?{valid:!1,error:"Event name must be a string"}:s.length===0?{valid:!1,error:"Event name cannot be empty"}:s.length>120?{valid:!1,error:"Event name is too long (max 120 characters)"}:s.includes("<")||s.includes(">")||s.includes("&")?{valid:!1,error:"Event name contains invalid characters"}:["constructor","prototype","__proto__","eval","function","var","let","const"].includes(s.toLowerCase())?{valid:!1,error:"Event name cannot be a reserved word"}:{valid:!0},Ke=(s,e,t)=>{const r=jt(e),n=t&&t==="customEvent"?`${t} "${s}" metadata error`:`${s} metadata error`;if(!Zt(r))return{valid:!1,error:`${n}: object has invalid types. Valid types are string, number, boolean or string arrays.`};let i;try{i=JSON.stringify(r)}catch{return{valid:!1,error:`${n}: object contains circular references or cannot be serialized.`}}if(i.length>8192)return{valid:!1,error:`${n}: object is too large (max ${8192/1024} KB).`};if(Object.keys(r).length>10)return{valid:!1,error:`${n}: object has too many keys (max 10 keys).`};for(const[l,c]of Object.entries(r)){if(Array.isArray(c)){if(c.length>10)return{valid:!1,error:`${n}: array property "${l}" is too large (max 10 items).`};for(const u of c)if(typeof u=="string"&&u.length>500)return{valid:!1,error:`${n}: array property "${l}" contains strings that are too long (max 500 characters).`}}if(typeof c=="string"&&c.length>1e3)return{valid:!1,error:`${n}: property "${l}" is too long (max 1000 characters).`}}return{valid:!0,sanitizedMetadata:r}},Ye=(s,e,t)=>{if(Array.isArray(e)){const r=[],n=t&&t==="customEvent"?`${t} "${s}" metadata error`:`${s} metadata error`;for(let i=0;i<e.length;i++){const o=e[i];if(typeof o!="object"||o===null||Array.isArray(o))return{valid:!1,error:`${n}: array item at index ${i} must be an object.`};const l=Ke(s,o,t);if(!l.valid)return{valid:!1,error:`${n}: array item at index ${i} is invalid: ${l.error}`};l.sanitizedMetadata&&r.push(l.sanitizedMetadata)}return{valid:!0,sanitizedMetadata:r}}return Ke(s,e,t)},tr=(s,e)=>{const t=er(s);if(!t.valid)return a("error","Event name validation failed",{data:{eventName:s,error:t.error}}),t;if(!e)return{valid:!0};const r=Ye(s,e,"customEvent");return r.valid||a("error","Event metadata validation failed",{data:{eventName:s,error:r.error}}),r};class rr{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}off(e,t){const r=this.listeners.get(e);if(r){const n=r.indexOf(t);n>-1&&r.splice(n,1)}}emit(e,t){const r=this.listeners.get(e);r&&r.forEach(n=>{n(t)})}removeAllListeners(){this.listeners.clear()}}function qe(s,e,t){try{const r=e(s);return r===null?null:typeof r=="object"&&r!==null&&"type"in r?r:(a("warn",`beforeSend transformer returned invalid data, using original [${t}]`),s)}catch(r){return a("error",`beforeSend transformer threw error, using original event [${t}]`,{error:r,visibility:"critical"}),s}}function sr(s,e,t){return s.map(r=>qe(r,e,t)).filter(r=>r!==null)}function Je(s,e,t){try{const r=e(s);return r===null?(a("debug",`Batch filtered by beforeBatch transformer [${t}]`,{data:{eventCount:s.events.length}}),null):typeof r=="object"&&r!==null&&Array.isArray(r.events)?r:(a("warn",`beforeBatch transformer returned invalid data, using original [${t}]`,{data:{eventCount:s.events.length}}),s)}catch(r){return a("error",`beforeBatch transformer threw error, using original batch [${t}]`,{error:r,data:{eventCount:s.events.length},visibility:"critical"}),s}}const ge={};class I{get(e){return ge[e]}set(e,t){ge[e]=t}getState(){return{...ge}}}class Ze extends I{storeManager;integrationId;apiUrl;transformers;staticHeaders;customHeadersProvider;lastPermanentErrorLog=null;recoveryInProgress=!1;lastMetadataTimestamp=0;pendingControllers=new Set;constructor(e,t,r,n={},i={},o){if(super(),t&&!r||!t&&r)throw new Error("SenderManager: integrationId and apiUrl must either both be provided or both be undefined");this.storeManager=e,this.integrationId=t,this.apiUrl=r,this.transformers=n,this.staticHeaders=i,this.customHeadersProvider=o}getIntegrationId(){return this.integrationId}setCustomHeadersProvider(e){this.customHeadersProvider=e}removeCustomHeadersProvider(){this.customHeadersProvider=void 0}getCustomHeaders(){if(this.integrationId!=="custom")return{};let e={};if(this.customHeadersProvider)try{const t=this.customHeadersProvider();typeof t=="object"&&t!==null&&!Array.isArray(t)?e=t:a("warn","Custom headers provider returned invalid value, expected object",{data:{received:typeof t}})}catch(t){a("warn","Custom headers provider threw an error, using static headers only",{error:t})}return{...this.staticHeaders,...e}}getQueueStorageKey(){const e=this.get("userId")||"anonymous",t=mt(e);return this.integrationId?`${t}:${this.integrationId}`:t}sendEventsQueueSync(e){return this.shouldSkipSend()?!0:this.apiUrl?.includes(D.Fail)?(a("warn",`Fail mode: simulating network failure (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),!1):this.apiUrl?.includes(D.Localhost)?(a("debug",`Success mode: simulating successful send (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),!0):this.sendQueueSyncInternal(e)}async sendEventsQueue(e,t){try{const r=await this.send(e);return r?(this.clearPersistedEvents(),t?.onSuccess?.(e.events.length,e.events,e)):(this.persistEvents(e),t?.onFailure?.()),r}catch(r){return r instanceof N?(this.logPermanentError("Permanent error, not retrying",r),this.clearPersistedEvents(),t?.onFailure?.(),!1):(this.persistEvents(e),t?.onFailure?.(),!1)}}async recoverPersistedEvents(e){if(this.recoveryInProgress){a("debug","Recovery already in progress, skipping duplicate attempt");return}this.recoveryInProgress=!0;try{const t=this.getPersistedData();if(!t||!this.isDataRecent(t)||t.events.length===0){this.clearPersistedEvents();return}const r=this.createRecoveryBody(t);await this.send(r)?(this.clearPersistedEvents(),e?.onSuccess?.(t.events.length,t.events,r)):e?.onFailure?.()}catch(t){if(t instanceof N){this.logPermanentError("Permanent error during recovery, clearing persisted events",t),this.clearPersistedEvents(),e?.onFailure?.();return}a("error","Failed to recover persisted events",{error:t})}finally{this.recoveryInProgress=!1}}stop(){}applyBeforeSendTransformer(e){if(this.integrationId==="saas")return e;const t=this.transformers.beforeSend;if(!t)return e;const r=sr(e.events,t,this.integrationId||"SenderManager");return r.length===0?null:{...e,events:r}}applyBeforeBatchTransformer(e){if(this.integrationId==="saas")return e;const t=this.transformers.beforeBatch;return t?Je(e,t,this.integrationId||"SenderManager"):e}async backoffDelay(e){const t=100*Math.pow(2,e),r=Math.random()*100,n=t+r;return new Promise(i=>setTimeout(i,n))}async send(e){if(this.shouldSkipSend())return this.simulateSuccessfulSend();const t=this.applyBeforeSendTransformer(e);if(!t)return!0;const r=this.applyBeforeBatchTransformer(t);if(!r)return!0;if(this.apiUrl?.includes(D.Fail))return a("debug",`Fail mode: simulating network failure${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),!1;if(this.apiUrl?.includes(D.Localhost))return a("debug",`Success mode: simulating successful send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),!0;const{url:n,payload:i}=this.prepareRequest(r);for(let o=1;o<=3;o++)try{return(await this.sendWithTimeout(n,i)).ok?(o>1&&a("info",`Send succeeded after ${o-1} retry attempt(s)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length,attempt:o}}),!0):!1}catch(l){const c=o===3;if(l instanceof N)throw l;if(a(c?"error":"warn",`Send attempt ${o} failed${this.integrationId?` [${this.integrationId}]`:""}${c?" (all retries exhausted)":", will retry"}`,{error:l,data:{events:e.events.length,url:n.replace(/\/\/[^/]+/,"//[DOMAIN]"),attempt:o,maxAttempts:3}}),!c){await this.backoffDelay(o);continue}return!1}return!1}async sendWithTimeout(e,t){const r=new AbortController;this.pendingControllers.add(r);const n=setTimeout(()=>{r.abort()},15e3);try{const i=this.getCustomHeaders(),o=await fetch(e,{method:"POST",body:t,keepalive:!0,credentials:"include",signal:r.signal,headers:{...i,"Content-Type":"application/json"}});if(!o.ok)throw o.status>=400&&o.status<500&&o.status!==408&&o.status!==429?new N(`HTTP ${o.status}: ${o.statusText}`,o.status):new Error(`HTTP ${o.status}: ${o.statusText}`);return o}finally{clearTimeout(n),this.pendingControllers.delete(r)}}sendQueueSyncInternal(e){const t=this.applyBeforeSendTransformer(e);if(!t)return!0;const r=this.applyBeforeBatchTransformer(t);if(!r)return!0;const{url:n,payload:i}=this.prepareRequest(r);if(i.length>65536)return a("warn",`Payload exceeds sendBeacon limit, persisting for recovery${this.integrationId?` [${this.integrationId}]`:""}`,{data:{size:i.length,limit:65536,events:r.events.length}}),this.persistEvents(r),!1;const o=new Blob([i],{type:"application/json"});if(!this.isSendBeaconAvailable())return a("warn",`sendBeacon not available, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(r),!1;const l=navigator.sendBeacon(n,o);return l||(a("warn",`sendBeacon rejected request, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(r)),l}prepareRequest(e){let t=Date.now();t<this.lastMetadataTimestamp&&(t=this.lastMetadataTimestamp),this.lastMetadataTimestamp=t;const r={...e,_metadata:{referer:typeof window<"u"?window.location.href:void 0,timestamp:t,client_version:Ht}};return{url:this.apiUrl||"",payload:JSON.stringify(r)}}getPersistedData(){try{const e=this.getQueueStorageKey(),t=this.storeManager.getItem(e);if(t)return JSON.parse(t)}catch(e){a("debug",`Failed to parse persisted data${this.integrationId?` [${this.integrationId}]`:""}`,{error:e}),this.clearPersistedEvents()}return null}isDataRecent(e){return!e.timestamp||typeof e.timestamp!="number"?!1:(Date.now()-e.timestamp)/(1e3*60*60)<2}createRecoveryBody(e){const{timestamp:t,...r}=e;return r}persistEvents(e){try{const t=this.getPersistedData();if(t&&t.timestamp){const i=Date.now()-t.timestamp;if(i<1e3)return a("debug",`Skipping persistence, another tab recently persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{data:{timeSinceExisting:i}}),!0}const r={...e,timestamp:Date.now()},n=this.getQueueStorageKey();return this.storeManager.setItem(n,JSON.stringify(r)),!!this.storeManager.getItem(n)}catch(t){return a("debug",`Failed to persist events${this.integrationId?` [${this.integrationId}]`:""}`,{error:t}),!1}}clearPersistedEvents(){try{const e=this.getQueueStorageKey();this.storeManager.removeItem(e)}catch(e){a("debug",`Failed to clear persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{error:e})}}shouldSkipSend(){return!this.apiUrl}async simulateSuccessfulSend(){const e=Math.random()*400+100;return await new Promise(t=>setTimeout(t,e)),!0}isSendBeaconAvailable(){return typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}logPermanentError(e,t){const r=Date.now();(!this.lastPermanentErrorLog||this.lastPermanentErrorLog.statusCode!==t.statusCode||r-this.lastPermanentErrorLog.timestamp>=Dt)&&(a("error",`${e}${this.integrationId?` [${this.integrationId}]`:""}`,{data:{status:t.statusCode,message:t.message}}),this.lastPermanentErrorLog={statusCode:t.statusCode,timestamp:r})}}class nr extends I{bootTime;bootTimestamp;hasPerformanceNow;lastClockSkewCheck=0;detectedSkew=0;constructor(){if(super(),typeof window>"u"){this.hasPerformanceNow=!1,this.bootTime=0,this.bootTimestamp=0;return}this.hasPerformanceNow=typeof performance<"u"&&typeof performance.now=="function",this.hasPerformanceNow?(this.bootTime=performance.now(),this.bootTimestamp=Date.now(),a("debug","TimeManager initialized with monotonic clock",{data:{bootTime:this.bootTime.toFixed(3),bootTimestamp:this.bootTimestamp}})):(this.bootTime=0,this.bootTimestamp=Date.now(),a("debug","performance.now() not available, falling back to Date.now()"))}now(){if(!this.hasPerformanceNow)return Date.now();const e=performance.now()-this.bootTime;return Math.round(this.bootTimestamp+e)}getClockSkew(){if(!this.hasPerformanceNow)return 0;const e=Date.now();if(e-this.lastClockSkewCheck<5e3)return this.detectedSkew;this.lastClockSkewCheck=e;const t=this.now(),r=Date.now();return this.detectedSkew=r-t,Math.abs(this.detectedSkew)>3e4&&a("warn","Significant clock skew detected",{data:{skewMs:this.detectedSkew,skewMinutes:(this.detectedSkew/1e3/60).toFixed(2),monotonicTime:new Date(t).toISOString(),systemTime:new Date(r).toISOString()}}),this.detectedSkew}validateTimestamp(e){const r=this.now(),n=e-r;return n>12e4?{valid:!1,error:`Timestamp is ${(n/1e3/60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`}:{valid:!0}}getBootInfo(){return{bootTime:this.bootTime,bootTimestamp:this.bootTimestamp,hasPerformanceNow:this.hasPerformanceNow,clockSkew:this.getClockSkew()}}}class ir extends I{dataSenders;emitter;transformers;timeManager;recentEventFingerprints=new Map;perEventRateLimits=new Map;eventsQueue=[];pendingEventsBuffer=[];sendIntervalId=null;rateLimitCounter=0;rateLimitWindowStart=0;lastSessionId=null;sessionEventCounts={total:0,[d.CLICK]:0,[d.PAGE_VIEW]:0,[d.CUSTOM]:0,[d.VIEWPORT_VISIBLE]:0,[d.SCROLL]:0};saveSessionCountsDebounced=null;constructor(e,t=null,r={},n={},i){super(),this.emitter=t,this.transformers=r,this.timeManager=new nr,this.dataSenders=[];const o=this.get("collectApiUrls");o?.saas&&this.dataSenders.push(new Ze(e,"saas",o.saas,r)),o?.custom&&this.dataSenders.push(new Ze(e,"custom",o.custom,r,n,i)),this.saveSessionCountsDebounced=this.debounce(l=>{this.saveSessionCounts(l)},500),this.cleanupExpiredSessionCounts()}async recoverPersistedEvents(){const e=this.dataSenders.map(async t=>t.recoverPersistedEvents({onSuccess:(r,n,i)=>{if(n&&n.length>0){const o=n.map(l=>l.id);this.removeProcessedEvents(o),i&&this.emitEventsQueue(i)}},onFailure:()=>{a("debug","Failed to recover persisted events")}}));await Promise.allSettled(e)}track({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:i,custom_event:o,web_vitals:l,error_data:c,viewport_data:u,page_view:T}){if(!e){a("error","Event type is required - event will be ignored");return}const E=this.get("sessionId");if(!E){this.pendingEventsBuffer.length>=100&&(this.pendingEventsBuffer.shift(),a("debug","Pending events buffer full - dropping oldest event",{data:{maxBufferSize:100}})),this.pendingEventsBuffer.push({type:e,page_url:t,from_page_url:r,scroll_data:n,click_data:i,custom_event:o,web_vitals:l,error_data:c,viewport_data:u,page_view:T});return}this.lastSessionId!==E&&(this.lastSessionId=E,this.sessionEventCounts=this.loadSessionCounts(E));const p=e===d.SESSION_START;if(p&&a("debug","Processing SESSION_START event",{data:{sessionId:E}}),!p&&!this.checkRateLimit())return;const S=e;if(!p){if(this.sessionEventCounts.total>=1e3){a("warn","Session event limit reached",{data:{type:S,total:this.sessionEventCounts.total,limit:1e3}});return}const v=this.getTypeLimitForEvent(S);if(v){const Me=this.sessionEventCounts[S];if(Me!==void 0&&Me>=v){a("warn","Session event type limit reached",{data:{type:S,count:Me,limit:v}});return}}}if(S===d.CUSTOM&&o?.name){const v=this.get("config")?.maxSameEventPerMinute??60;if(!this.checkPerEventRateLimit(o.name,v))return}const ct=S===d.SESSION_START,se=t||this.get("pageUrl"),G=this.buildEventPayload({type:S,page_url:se,from_page_url:r,scroll_data:n,click_data:i,custom_event:o,web_vitals:l,error_data:c,viewport_data:u,page_view:T});if(G&&!(!p&&!this.shouldSample())){if(ct){const v=this.get("sessionId");if(!v){a("error","Session start event requires sessionId - event will be ignored");return}if(this.get("hasStartSession")){a("debug","Duplicate session_start detected",{data:{sessionId:v}});return}this.set("hasStartSession",!0)}if(!this.isDuplicateEvent(G)){if(this.get("mode")===B.QA){if(S===d.CUSTOM&&o){a("info",`Custom Event: ${o.name}`,{visibility:"qa",data:{name:o.name,...o.metadata&&{metadata:o.metadata}}}),this.emitEvent(G);return}if(S===d.VIEWPORT_VISIBLE&&u){const v=u.name||u.id||u.selector;a("info",`Viewport Visible: ${v}`,{visibility:"qa",data:{selector:u.selector,...u.name&&{name:u.name},...u.id&&{id:u.id},visibilityRatio:u.visibilityRatio,dwellTime:u.dwellTime}}),this.emitEvent(G);return}}if(this.addToQueue(G),!p){this.sessionEventCounts.total++,this.sessionEventCounts[S]!==void 0&&this.sessionEventCounts[S]++;const v=this.get("sessionId");v&&this.saveSessionCountsDebounced&&this.saveSessionCountsDebounced(v)}}}}stop(){this.sendIntervalId&&(clearInterval(this.sendIntervalId),this.sendIntervalId=null);const e=this.get("sessionId");e&&this.saveSessionCounts(e),this.eventsQueue=[],this.pendingEventsBuffer=[],this.recentEventFingerprints.clear(),this.rateLimitCounter=0,this.rateLimitWindowStart=0,this.perEventRateLimits.clear(),this.sessionEventCounts={total:0,[d.CLICK]:0,[d.PAGE_VIEW]:0,[d.CUSTOM]:0,[d.VIEWPORT_VISIBLE]:0,[d.SCROLL]:0},this.lastSessionId=null,this.set("hasStartSession",!1),this.dataSenders.forEach(t=>{t.stop()})}async flushImmediately(){return this.flushEvents(!1)}flushImmediatelySync(){return this.flushEvents(!0)}setCustomHeadersProvider(e){for(const t of this.dataSenders)t.getIntegrationId()==="custom"&&t.setCustomHeadersProvider(e)}removeCustomHeadersProvider(){for(const e of this.dataSenders)e.getIntegrationId()==="custom"&&e.removeCustomHeadersProvider()}getQueueLength(){return this.eventsQueue.length}getQueueEvents(){return[...this.eventsQueue]}async flushQueue(){await this.flushImmediately()}clearQueue(){this.eventsQueue=[]}flushPendingEvents(){if(this.pendingEventsBuffer.length===0)return;if(!this.get("sessionId")){a("debug","Cannot flush pending events: session not initialized - keeping in buffer",{data:{bufferedEventCount:this.pendingEventsBuffer.length}});return}const t=[...this.pendingEventsBuffer];this.pendingEventsBuffer=[],t.forEach(r=>{this.track(r)})}clearSendInterval(){this.sendIntervalId&&(clearInterval(this.sendIntervalId),this.sendIntervalId=null)}isSuccessfulResult(e){return e.status==="fulfilled"&&e.value===!0}flushEvents(e){if(this.eventsQueue.length===0)return e?!0:Promise.resolve(!0);const t=this.buildEventsPayload(),r=[...this.eventsQueue],n=r.map(i=>i.id);if(this.dataSenders.length===0)return this.removeProcessedEvents(n),this.clearSendInterval(),this.emitEventsQueue(t),e?!0:Promise.resolve(!0);if(e){const o=this.dataSenders.map(l=>l.sendEventsQueueSync(t)).some(l=>l);return o?(this.removeProcessedEvents(n),this.clearSendInterval(),this.emitEventsQueue(t)):(this.clearSendInterval(),a("debug","Sync flush complete failure, events kept in queue for retry",{data:{eventCount:n.length}})),o}else{const i=this.dataSenders.map(async o=>o.sendEventsQueue(t,{onSuccess:()=>{},onFailure:()=>{}}));return Promise.allSettled(i).then(o=>{const l=o.some(c=>this.isSuccessfulResult(c));return l?(this.removeProcessedEvents(n),this.clearSendInterval(),this.emitEventsQueue(t)):a("debug","Async flush complete failure, events kept in queue for retry",{data:{eventCount:r.length}}),l})}}async sendEventsQueue(){if(!this.get("sessionId")||this.eventsQueue.length===0)return;const e=this.buildEventsPayload();if(this.dataSenders.length===0){this.emitEventsQueue(e);return}const t=[...this.eventsQueue],r=t.map(l=>l.id),n=this.dataSenders.map(async l=>l.sendEventsQueue(e,{onSuccess:()=>{},onFailure:()=>{}})),i=await Promise.allSettled(n);if(i.some(l=>this.isSuccessfulResult(l))){this.removeProcessedEvents(r),this.emitEventsQueue(e);const l=i.filter(c=>!this.isSuccessfulResult(c)).length;l>0&&a("debug","Periodic send completed with some failures, removed from queue and persisted per-integration",{data:{eventCount:t.length,failedCount:l}})}else a("debug","Periodic send complete failure, events kept in queue for retry",{data:{eventCount:t.length}});this.eventsQueue.length===0&&this.clearSendInterval()}buildEventsPayload(){const e=new Map,t=[];for(const c of this.eventsQueue){const u=this.createEventSignature(c);e.has(u)||t.push(u),e.set(u,c)}const r=t.map(c=>e.get(c)).filter(c=>!!c).sort((c,u)=>c.type===d.SESSION_START&&u.type!==d.SESSION_START?-1:u.type===d.SESSION_START&&c.type!==d.SESSION_START?1:c.timestamp-u.timestamp);let n={user_id:this.get("userId"),session_id:this.get("sessionId"),device:this.get("device"),events:r,...this.get("config")?.globalMetadata&&{global_metadata:this.get("config")?.globalMetadata}};const i=this.get("collectApiUrls"),o=!!(i?.custom||i?.saas),l=this.transformers.beforeBatch;if(!o&&l){const c=Je(n,l,"EventManager");c!==null&&(n=c)}return n}buildEventPayload(e){const t=e.page_url??this.get("pageUrl"),r=this.timeManager.now(),n=this.timeManager.validateTimestamp(r);n.valid||a("warn","Event timestamp validation failed",{data:{type:e.type,error:n.error}});const i=this.get("sessionReferrer"),o=this.get("sessionUtm");let l={id:Xt(),type:e.type,page_url:t,timestamp:r,...i&&{referrer:i},...e.from_page_url&&{from_page_url:e.from_page_url},...e.scroll_data&&{scroll_data:e.scroll_data},...e.click_data&&{click_data:e.click_data},...e.custom_event&&{custom_event:e.custom_event},...e.web_vitals&&{web_vitals:e.web_vitals},...e.error_data&&{error_data:e.error_data},...e.viewport_data&&{viewport_data:e.viewport_data},...e.page_view&&{page_view:e.page_view},...o&&{utm:o}};const c=this.get("collectApiUrls"),u=!!c?.custom,T=!!c?.saas,E=u||T,p=u&&T,S=this.transformers.beforeSend;if(S&&(!E||u&&!p)){const se=qe(l,S,"EventManager");if(se===null)return null;l=se}return l}isDuplicateEvent(e){const t=Date.now(),r=this.createEventFingerprint(e),n=this.recentEventFingerprints.get(r);return n&&t-n<1e3?(this.recentEventFingerprints.set(r,t),!0):(this.recentEventFingerprints.set(r,t),this.recentEventFingerprints.size>1500&&this.pruneOldFingerprints(),this.recentEventFingerprints.size>3e3&&(this.recentEventFingerprints.clear(),this.recentEventFingerprints.set(r,t),a("debug","Event fingerprint cache exceeded hard limit, cleared",{data:{hardLimit:3e3}})),!1)}pruneOldFingerprints(){const e=Date.now(),t=1e3*10;for(const[r,n]of this.recentEventFingerprints.entries())e-n>t&&this.recentEventFingerprints.delete(r);a("debug","Pruned old event fingerprints",{data:{remaining:this.recentEventFingerprints.size,cutoffMs:t}})}createEventFingerprint(e){let t=`${e.type}_${e.page_url}`;if(e.click_data){const r=Math.round((e.click_data.x||0)/10)*10,n=Math.round((e.click_data.y||0)/10)*10;t+=`_click_${r}_${n}`}return e.scroll_data&&(t+=`_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`),e.custom_event&&(t+=`_custom_${e.custom_event.name}`),e.web_vitals&&(t+=`_vitals_${e.web_vitals.type}`),e.error_data&&(t+=`_error_${e.error_data.type}_${e.error_data.message}`),t}createEventSignature(e){return this.createEventFingerprint(e)}addToQueue(e){if(this.emitEvent(e),this.eventsQueue.push(e),this.eventsQueue.length>100){const t=this.eventsQueue.findIndex(n=>n.type!==d.SESSION_START),r=t>=0?this.eventsQueue.splice(t,1)[0]:this.eventsQueue.shift();a("warn","Event queue overflow, oldest non-critical event removed",{data:{maxLength:100,currentLength:this.eventsQueue.length,removedEventType:r?.type,wasCritical:r?.type===d.SESSION_START}})}this.sendIntervalId||this.startSendInterval(),this.eventsQueue.length>=50&&this.sendEventsQueue()}startSendInterval(){this.sendIntervalId=window.setInterval(()=>{this.eventsQueue.length>0&&this.sendEventsQueue()},1e4)}shouldSample(){const e=this.get("config")?.samplingRate??1;return Math.random()<e}checkRateLimit(){const e=Date.now();return e-this.rateLimitWindowStart>1e3&&(this.rateLimitCounter=0,this.rateLimitWindowStart=e),this.rateLimitCounter>=50?!1:(this.rateLimitCounter++,!0)}checkPerEventRateLimit(e,t){const r=Date.now(),i=(this.perEventRateLimits.get(e)??[]).filter(o=>r-o<6e4);return i.length>=t?(a("warn","Per-event rate limit exceeded for custom event",{data:{eventName:e,limit:t,window:`${6e4/1e3}s`}}),!1):(i.push(r),this.perEventRateLimits.set(e,i),!0)}getTypeLimitForEvent(e){return{[d.CLICK]:500,[d.PAGE_VIEW]:100,[d.CUSTOM]:500,[d.VIEWPORT_VISIBLE]:200,[d.SCROLL]:120}[e]??null}removeProcessedEvents(e){const t=new Set(e);this.eventsQueue=this.eventsQueue.filter(r=>!t.has(r.id))}emitEvent(e){this.emitter&&this.emitter.emit(X.EVENT,e)}emitEventsQueue(e){this.emitter&&this.emitter.emit(X.QUEUE,e)}debounce(e,t){let r=null;return((...n)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...n),r=null},t)})}getInitialCounts(){return{total:0,[d.CLICK]:0,[d.PAGE_VIEW]:0,[d.CUSTOM]:0,[d.VIEWPORT_VISIBLE]:0,[d.SCROLL]:0}}loadSessionCounts(e){if(typeof window>"u"||typeof localStorage>"u")return this.getInitialCounts();const t=this.get("userId")||"anonymous",r=Oe(t,e);try{const n=localStorage.getItem(r);if(!n)return this.getInitialCounts();const i=JSON.parse(n);return i._timestamp&&Date.now()-i._timestamp>Pe?(a("debug","Session counts expired, clearing",{data:{sessionId:e,age:Date.now()-i._timestamp}}),localStorage.removeItem(r),this.getInitialCounts()):typeof i.total=="number"&&typeof i[d.CLICK]=="number"&&typeof i[d.PAGE_VIEW]=="number"&&typeof i[d.CUSTOM]=="number"&&typeof i[d.VIEWPORT_VISIBLE]=="number"&&typeof i[d.SCROLL]=="number"?{total:i.total,[d.CLICK]:i[d.CLICK],[d.PAGE_VIEW]:i[d.PAGE_VIEW],[d.CUSTOM]:i[d.CUSTOM],[d.VIEWPORT_VISIBLE]:i[d.VIEWPORT_VISIBLE],[d.SCROLL]:i[d.SCROLL]}:(a("warn","Invalid session counts structure in localStorage, resetting",{data:{sessionId:e,parsed:i}}),localStorage.removeItem(r),a("debug","Session counts removed due to invalid/corrupted data",{data:{sessionId:e,parsed:i}}),this.getInitialCounts())}catch(n){return a("warn","Failed to load session counts from localStorage",{error:n,data:{sessionId:e}}),this.getInitialCounts()}}cleanupExpiredSessionCounts(){if(!(typeof window>"u"||typeof localStorage>"u"))try{const e=localStorage.getItem(De);if(e){const i=Date.now()-parseInt(e,10);if(i<Ve){a("debug","Skipping session counts cleanup (throttled)",{data:{timeSinceLastCleanup:i,throttleMs:Ve}});return}}const t=this.get("userId")||"anonymous",r=`${w}:${t}:session_counts:`,n=[];for(let i=0;i<localStorage.length;i++){const o=localStorage.key(i);if(o?.startsWith(r))try{const l=localStorage.getItem(o);if(l){const c=JSON.parse(l);c._timestamp&&Date.now()-c._timestamp>Pe&&n.push(o)}}catch{}}n.forEach(i=>{localStorage.removeItem(i),a("debug","Cleaned up expired session counts",{data:{key:i}})}),n.length>0&&a("info",`Cleaned up ${n.length} expired session counts entries`),localStorage.setItem(De,Date.now().toString())}catch(e){a("warn","Failed to cleanup expired session counts",{error:e})}}saveSessionCounts(e){const t=this.get("userId")||"anonymous",r=Oe(t,e);try{const n={...this.sessionEventCounts,_timestamp:Date.now(),_version:1};localStorage.setItem(r,JSON.stringify(n))}catch(n){a("warn","Failed to persist session counts to localStorage",{error:n,data:{sessionId:e}})}}}class or{static getId(e){const t=e.getItem(Le);if(t)return t;const r=Gt();return e.setItem(Le,r),r}}const ar=/^\d{13}-[a-z0-9]{9}$/;class lr extends I{storageManager;eventManager;projectId;activityHandler=null;visibilityChangeHandler=null;sessionTimeoutId=null;broadcastChannel=null;isTracking=!1;needsRenewal=!1;constructor(e,t,r){super(),this.storageManager=e,this.eventManager=t,this.projectId=r}initCrossTabSync(){if(typeof BroadcastChannel>"u"){a("debug","BroadcastChannel not supported");return}const e=this.getProjectId();this.broadcastChannel=new BroadcastChannel(Et(e)),this.broadcastChannel.onmessage=t=>{const{action:r,sessionId:n,timestamp:i,projectId:o}=t.data??{};o===e&&(r==="session_start"&&n&&typeof i=="number"&&i>Date.now()-5e3?(this.set("sessionId",n),this.persistSession(n,i),this.isTracking&&this.setupSessionTimeout()):r&&r!=="session_start"&&a("debug","Ignored BroadcastChannel message with unknown action",{data:{action:r}}))}}shareSession(e){this.broadcastChannel&&typeof this.broadcastChannel.postMessage=="function"&&this.broadcastChannel.postMessage({action:"session_start",projectId:this.getProjectId(),sessionId:e,timestamp:Date.now()})}cleanupCrossTabSync(){this.broadcastChannel&&(typeof this.broadcastChannel.close=="function"&&this.broadcastChannel.close(),this.broadcastChannel=null)}recoverSession(){const e=this.loadStoredSession();if(!e)return null;if(!ar.test(e.id))return a("warn","Invalid session ID format recovered from storage, clearing",{data:{sessionId:e.id}}),this.clearStoredSession(),null;const t=this.get("config")?.sessionTimeout??9e5;return Date.now()-e.lastActivity>t?(this.clearStoredSession(),null):e.id}persistSession(e,t=Date.now(),r,n){this.saveStoredSession({id:e,lastActivity:t,...r&&{referrer:r},...n&&{utm:n}})}clearStoredSession(){const e=this.getSessionStorageKey();this.storageManager.removeItem(e)}loadStoredSession(){const e=this.getSessionStorageKey(),t=this.storageManager.getItem(e);if(!t)return null;try{const r=JSON.parse(t);return!r.id||typeof r.lastActivity!="number"?null:r}catch{return this.storageManager.removeItem(e),null}}saveStoredSession(e){const t=this.getSessionStorageKey();this.storageManager.setItem(t,JSON.stringify(e))}getSessionStorageKey(){return gt(this.getProjectId())}getProjectId(){return this.projectId}startTracking(){if(this.isTracking){a("debug","Session tracking already active");return}const e=this.recoverSession(),t=e??this.generateSessionId();let r,n;if(e){const i=this.loadStoredSession();r=i?.referrer??ue(),n=i?.utm??de()}else r=ue(),n=de();a("debug","Session tracking initialized",{data:{sessionId:t,wasRecovered:!!e,willEmitSessionStart:!e,sessionReferrer:r,hasUtm:!!n}}),this.isTracking=!0;try{this.set("sessionId",t),this.set("sessionReferrer",r),this.set("sessionUtm",n),this.persistSession(t,Date.now(),r,n),this.initCrossTabSync(),this.shareSession(t),e?a("debug","Session recovered, skipping SESSION_START",{data:{sessionId:t}}):(a("debug","Emitting SESSION_START event",{data:{sessionId:t}}),this.eventManager.track({type:d.SESSION_START})),this.setupSessionTimeout(),this.setupActivityListeners(),this.setupLifecycleListeners()}catch(i){throw this.isTracking=!1,this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.set("sessionId",null),i}}generateSessionId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}setupSessionTimeout(){this.clearSessionTimeout();const e=this.get("config")?.sessionTimeout??9e5;this.sessionTimeoutId=setTimeout(()=>{this.enterRenewalMode()},e)}resetSessionTimeout(){this.setupSessionTimeout();const e=this.get("sessionId");e&&this.persistSession(e,Date.now(),this.get("sessionReferrer"),this.get("sessionUtm"))}clearSessionTimeout(){this.sessionTimeoutId&&(clearTimeout(this.sessionTimeoutId),this.sessionTimeoutId=null)}setupActivityListeners(){this.activityHandler=()=>{this.needsRenewal?this.renewSession():this.resetSessionTimeout()},document.addEventListener("click",this.activityHandler,{passive:!0}),document.addEventListener("keydown",this.activityHandler,{passive:!0}),document.addEventListener("scroll",this.activityHandler,{passive:!0})}renewSession(){this.needsRenewal=!1;const e=this.generateSessionId(),t=ue(),r=de();a("debug","Renewing session after timeout",{data:{newSessionId:e}}),this.set("sessionId",e),this.set("sessionReferrer",t),this.set("sessionUtm",r),this.persistSession(e,Date.now(),t,r),this.cleanupCrossTabSync(),this.initCrossTabSync(),this.shareSession(e),this.eventManager.track({type:d.SESSION_START}),this.eventManager.flushPendingEvents(),this.setupSessionTimeout()}cleanupActivityListeners(){this.activityHandler&&(document.removeEventListener("click",this.activityHandler),document.removeEventListener("keydown",this.activityHandler),document.removeEventListener("scroll",this.activityHandler),this.activityHandler=null)}setupLifecycleListeners(){this.visibilityChangeHandler||(this.visibilityChangeHandler=()=>{if(document.hidden)this.clearSessionTimeout();else{if(this.isSessionStale()){a("debug","Session expired during suspend, entering renewal mode"),this.enterRenewalMode();return}this.get("sessionId")&&this.setupSessionTimeout()}},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}isSessionStale(){if(this.needsRenewal||!this.get("sessionId"))return!1;const t=this.loadStoredSession();if(!t)return!1;const r=this.get("config")?.sessionTimeout??9e5;return Date.now()-t.lastActivity>r}cleanupLifecycleListeners(){this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null)}enterRenewalMode(){this.clearSessionTimeout(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",!1),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=!0,a("debug","Session timed out, entering renewal mode")}resetSessionState(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.clearStoredSession(),this.set("sessionId",null),this.set("hasStartSession",!1),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=!1,this.isTracking=!1}stopTracking(){this.resetSessionState()}destroy(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupCrossTabSync(),this.cleanupLifecycleListeners(),this.isTracking=!1,this.needsRenewal=!1,this.set("hasStartSession",!1)}}class cr extends I{eventManager;storageManager;sessionManager=null;destroyed=!1;constructor(e,t){super(),this.eventManager=t,this.storageManager=e}startTracking(){if(this.isActive())return;if(this.destroyed){a("debug","Cannot start tracking on destroyed handler");return}const t=this.get("config")?.integrations?.tracelog?.projectId??"custom";try{this.sessionManager=new lr(this.storageManager,this.eventManager,t),this.sessionManager.startTracking(),this.eventManager.flushPendingEvents()}catch(r){if(this.sessionManager){try{this.sessionManager.destroy()}catch{}this.sessionManager=null}throw a("error","Failed to start session tracking",{error:r}),r}}isActive(){return this.sessionManager!==null&&!this.destroyed}cleanupSessionManager(){this.sessionManager&&(this.sessionManager.stopTracking(),this.sessionManager.destroy(),this.sessionManager=null)}stopTracking(){this.cleanupSessionManager()}destroy(){this.destroyed||(this.sessionManager&&(this.sessionManager.destroy(),this.sessionManager=null),this.destroyed=!0)}}class ur extends I{eventManager;onTrack;originalPushState;originalReplaceState;lastPageViewTime=0;constructor(e,t){super(),this.eventManager=e,this.onTrack=t}startTracking(){this.trackInitialPageView(),window.addEventListener("popstate",this.trackCurrentPage,!0),window.addEventListener("hashchange",this.trackCurrentPage,!0),this.patchHistory("pushState"),this.patchHistory("replaceState")}stopTracking(){window.removeEventListener("popstate",this.trackCurrentPage,!0),window.removeEventListener("hashchange",this.trackCurrentPage,!0),this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.lastPageViewTime=0}patchHistory(e){const t=window.history[e];e==="pushState"&&!this.originalPushState?this.originalPushState=t:e==="replaceState"&&!this.originalReplaceState&&(this.originalReplaceState=t),window.history[e]=(...r)=>{t.apply(window.history,r),this.trackCurrentPage()}}trackCurrentPage=()=>{const e=window.location.href,t=he(e,this.get("config").sensitiveQueryParams);if(this.get("pageUrl")===t)return;const r=Date.now(),n=this.get("config").pageViewThrottleMs??1e3;if(r-this.lastPageViewTime<n)return;this.lastPageViewTime=r,this.onTrack();const i=this.get("pageUrl");this.set("pageUrl",t);const o=this.extractPageViewData();this.eventManager.track({type:d.PAGE_VIEW,page_url:this.get("pageUrl"),from_page_url:i,...o&&{page_view:o}})};trackInitialPageView(){const e=he(window.location.href,this.get("config").sensitiveQueryParams),t=this.extractPageViewData();this.lastPageViewTime=Date.now(),this.eventManager.track({type:d.PAGE_VIEW,page_url:e,...t&&{page_view:t}}),this.onTrack()}extractPageViewData(){const{pathname:e,search:t,hash:r}=window.location,{referrer:n}=document,{title:i}=document;return!n&&!i&&!e&&!t&&!r?void 0:{...n&&{referrer:n},...i&&{title:i},...e&&{pathname:e},...t&&{search:t},...r&&{hash:r}}}}class dr extends I{eventManager;lastClickTimes=new Map;clickHandler;lastPruneTime=0;constructor(e){super(),this.eventManager=e}startTracking(){this.clickHandler||(this.clickHandler=e=>{const t=e,r=t.target,n=typeof HTMLElement<"u"&&r instanceof HTMLElement?r:typeof HTMLElement<"u"&&r instanceof Node&&r.parentElement instanceof HTMLElement?r.parentElement:null;if(!n){a("debug","Click target not found or not an element");return}if(this.shouldIgnoreElement(n))return;const i=this.get("config")?.clickThrottleMs??300;if(i>0&&!this.checkClickThrottle(n,i))return;const o=this.findTrackingElement(n),l=this.getRelevantClickElement(n),c=this.calculateClickCoordinates(t,n);if(o){const T=this.extractTrackingData(o);if(T){const E=this.createCustomEventData(T);this.eventManager.track({type:d.CUSTOM,custom_event:{name:E.name,...E.value&&{metadata:{value:E.value}}}})}}const u=this.generateClickData(n,l,c);this.eventManager.track({type:d.CLICK,click_data:u})},window.addEventListener("click",this.clickHandler,!0))}stopTracking(){this.clickHandler&&(window.removeEventListener("click",this.clickHandler,!0),this.clickHandler=void 0),this.lastClickTimes.clear(),this.lastPruneTime=0}shouldIgnoreElement(e){return e.hasAttribute(`${y}-ignore`)?!0:e.closest(`[${y}-ignore]`)!==null}checkClickThrottle(e,t){const r=this.getElementSignature(e),n=Date.now();this.pruneThrottleCache(n);const i=this.lastClickTimes.get(r);return i!==void 0&&n-i<t?(a("debug","ClickHandler: Click suppressed by throttle",{data:{signature:r,throttleRemaining:t-(n-i)}}),!1):(this.lastClickTimes.set(r,n),!0)}pruneThrottleCache(e){if(e-this.lastPruneTime<3e4)return;this.lastPruneTime=e;const t=e-3e5;for(const[r,n]of this.lastClickTimes.entries())n<t&&this.lastClickTimes.delete(r);if(this.lastClickTimes.size>1e3){const r=Array.from(this.lastClickTimes.entries()).sort((o,l)=>o[1]-l[1]),n=this.lastClickTimes.size-1e3,i=r.slice(0,n);for(const[o]of i)this.lastClickTimes.delete(o);a("debug","ClickHandler: Pruned throttle cache",{data:{removed:i.length,remaining:this.lastClickTimes.size}})}}getElementSignature(e){if(e.id)return`#${e.id}`;const t=e.getAttribute("data-testid");if(t)return`[data-testid="${t}"]`;const r=e.getAttribute(`${y}-name`);return r?`[${y}-name="${r}"]`:this.getElementPath(e)}getElementPath(e){const t=[];let r=e;for(;r&&r!==document.body;){let n=r.tagName.toLowerCase();if(r.className){const i=r.className.split(" ")[0];i&&(n+=`.${i}`)}t.unshift(n),r=r.parentElement}return t.join(">")||"unknown"}findTrackingElement(e){return e.hasAttribute(`${y}-name`)?e:e.closest(`[${y}-name]`)}getRelevantClickElement(e){for(const t of ut)try{if(e.matches(t))return e;const r=e.closest(t);if(r)return r}catch(r){a("debug","Invalid selector in element search",{error:r,data:{selector:t}});continue}return e}clamp(e){return Math.max(0,Math.min(1,Number(e.toFixed(3))))}calculateClickCoordinates(e,t){const r=t.getBoundingClientRect(),n=e.clientX,i=e.clientY,o=r.width>0?this.clamp((n-r.left)/r.width):0,l=r.height>0?this.clamp((i-r.top)/r.height):0;return{x:n,y:i,relativeX:o,relativeY:l}}extractTrackingData(e){const t=e.getAttribute(`${y}-name`),r=e.getAttribute(`${y}-value`);if(t)return{element:e,name:t,...r&&{value:r}}}generateClickData(e,t,r){const{x:n,y:i,relativeX:o,relativeY:l}=r,c=this.getRelevantText(e,t),u=this.extractElementAttributes(t);return{x:n,y:i,relativeX:o,relativeY:l,tag:t.tagName.toLowerCase(),...t.id&&{id:t.id},...t.className&&{class:t.className},...c&&{text:c},...u.href&&{href:u.href},...u.title&&{title:u.title},...u.alt&&{alt:u.alt},...u.role&&{role:u.role},...u["aria-label"]&&{ariaLabel:u["aria-label"]},...Object.keys(u).length>0&&{dataAttributes:u}}}sanitizeText(e){let t=e;for(const r of ae){const n=new RegExp(r.source,r.flags);t=t.replace(n,"[REDACTED]")}return t}getRelevantText(e,t){const r=e.textContent?.trim()??"",n=t.textContent?.trim()??"";if(!r&&!n)return"";let i="";return r&&r.length<=255?i=r:n.length<=255?i=n:i=n.slice(0,252)+"...",this.sanitizeText(i)}extractElementAttributes(e){const t=["id","class","data-testid","aria-label","title","href","type","name","alt","role"],r={};for(const n of t){const i=e.getAttribute(n);i&&(r[n]=i)}return r}createCustomEventData(e){return{name:e.name,...e.value&&{value:e.value}}}}class hr extends I{eventManager;containers=[];limitWarningLogged=!1;minDepthChange=5;minIntervalMs=500;maxEventsPerSession=120;containerDiscoveryTimeoutId=null;constructor(e){super(),this.eventManager=e}startTracking(){this.limitWarningLogged=!1,this.applyConfigOverrides(),this.set("scrollEventCount",0),this.tryDetectScrollContainers(0)}stopTracking(){this.containerDiscoveryTimeoutId!==null&&(clearTimeout(this.containerDiscoveryTimeoutId),this.containerDiscoveryTimeoutId=null);for(const e of this.containers)this.clearContainerTimer(e),e.element===window?window.removeEventListener("scroll",e.listener):e.element.removeEventListener("scroll",e.listener);this.containers.length=0,this.set("scrollEventCount",0),this.limitWarningLogged=!1}tryDetectScrollContainers(e){const t=this.findScrollableElements();if(this.isWindowScrollable()&&this.setupScrollContainer(window,"window"),t.length>0){for(const r of t){const n=this.getElementSelector(r);this.setupScrollContainer(r,n)}this.applyPrimaryScrollSelectorIfConfigured();return}if(e<5){this.containerDiscoveryTimeoutId=window.setTimeout(()=>{this.containerDiscoveryTimeoutId=null,this.tryDetectScrollContainers(e+1)},200);return}this.containers.length===0&&this.setupScrollContainer(window,"window"),this.applyPrimaryScrollSelectorIfConfigured()}applyPrimaryScrollSelectorIfConfigured(){const e=this.get("config");e?.primaryScrollSelector&&this.applyPrimaryScrollSelector(e.primaryScrollSelector)}findScrollableElements(){if(!document.body)return[];const e=[],t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const i=n;if(!i.isConnected||!i.offsetParent)return NodeFilter.FILTER_SKIP;const o=getComputedStyle(i);return o.overflowY==="auto"||o.overflowY==="scroll"||o.overflow==="auto"||o.overflow==="scroll"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let r;for(;(r=t.nextNode())&&e.length<10;){const n=r;this.isElementScrollable(n)&&e.push(n)}return e}getElementSelector(e){if(e===window)return"window";const t=e;if(t.id)return`#${t.id}`;if(t.className&&typeof t.className=="string"){const r=t.className.split(" ").filter(n=>n.trim())[0];if(r)return`.${r}`}return t.tagName.toLowerCase()}determineIfPrimary(e){return this.isWindowScrollable()?e===window:this.containers.length===0}setupScrollContainer(e,t){if(this.containers.some(u=>u.element===e)||e!==window&&!this.isElementScrollable(e))return;const n=this.getScrollTop(e),i=this.calculateScrollDepth(n,this.getScrollHeight(e),this.getViewportHeight(e)),o=this.determineIfPrimary(e),l={element:e,selector:t,isPrimary:o,lastScrollPos:n,lastDepth:i,lastDirection:$.DOWN,lastEventTime:0,firstScrollEventTime:null,maxDepthReached:i,debounceTimer:null,listener:null},c=()=>{this.get("suppressNextScroll")||(l.firstScrollEventTime===null&&(l.firstScrollEventTime=Date.now()),this.clearContainerTimer(l),l.debounceTimer=window.setTimeout(()=>{const u=this.calculateScrollData(l);if(u){const T=Date.now();this.processScrollEvent(l,u,T)}l.debounceTimer=null},250))};l.listener=c,this.containers.push(l),e===window?window.addEventListener("scroll",c,{passive:!0}):e.addEventListener("scroll",c,{passive:!0})}processScrollEvent(e,t,r){if(!this.shouldEmitScrollEvent(e,t,r))return;e.lastEventTime=r,e.lastDepth=t.depth,e.lastDirection=t.direction;const n=this.get("scrollEventCount")??0;this.set("scrollEventCount",n+1),this.eventManager.track({type:d.SCROLL,scroll_data:{...t,container_selector:e.selector,is_primary:e.isPrimary}})}shouldEmitScrollEvent(e,t,r){return this.hasReachedSessionLimit()?(this.logLimitOnce(),!1):!(!this.hasElapsedMinimumInterval(e,r)||!this.hasSignificantDepthChange(e,t.depth))}hasReachedSessionLimit(){return(this.get("scrollEventCount")??0)>=this.maxEventsPerSession}hasElapsedMinimumInterval(e,t){return e.lastEventTime===0?!0:t-e.lastEventTime>=this.minIntervalMs}hasSignificantDepthChange(e,t){return Math.abs(t-e.lastDepth)>=this.minDepthChange}logLimitOnce(){this.limitWarningLogged||(this.limitWarningLogged=!0,a("debug","Max scroll events per session reached",{data:{limit:this.maxEventsPerSession}}))}applyConfigOverrides(){this.minDepthChange=5,this.minIntervalMs=500,this.maxEventsPerSession=120}isWindowScrollable(){return document.documentElement.scrollHeight>window.innerHeight}clearContainerTimer(e){e.debounceTimer!==null&&(clearTimeout(e.debounceTimer),e.debounceTimer=null)}getScrollDirection(e,t){return e>t?$.DOWN:$.UP}calculateScrollDepth(e,t,r){if(t<=r)return 0;const n=t-r;return Math.min(100,Math.max(0,Math.floor(e/n*100)))}calculateScrollData(e){const{element:t,lastScrollPos:r,lastEventTime:n}=e,i=this.getScrollTop(t),o=Date.now(),l=Math.abs(i-r);if(l<10||t===window&&!this.isWindowScrollable())return null;const c=this.getViewportHeight(t),u=this.getScrollHeight(t),T=this.getScrollDirection(i,r),E=this.calculateScrollDepth(i,u,c);let p;n>0?p=o-n:e.firstScrollEventTime!==null?p=o-e.firstScrollEventTime:p=250;const S=Math.round(l/p*1e3);return E>e.maxDepthReached&&(e.maxDepthReached=E),e.lastScrollPos=i,{depth:E,direction:T,velocity:S,max_depth_reached:e.maxDepthReached}}getScrollTop(e){return e===window?window.scrollY:e.scrollTop}getViewportHeight(e){return e===window?window.innerHeight:e.clientHeight}getScrollHeight(e){return e===window?document.documentElement.scrollHeight:e.scrollHeight}isElementScrollable(e){const t=getComputedStyle(e),r=t.overflowY==="auto"||t.overflowY==="scroll"||t.overflow==="auto"||t.overflow==="scroll",n=e.scrollHeight>e.clientHeight;return r&&n}applyPrimaryScrollSelector(e){let t;if(e==="window")t=window;else{const n=document.querySelector(e);if(!(n instanceof HTMLElement)){a("debug",`Selector "${e}" did not match an HTMLElement`);return}t=n}this.containers.forEach(n=>{this.updateContainerPrimary(n,n.element===t)}),!this.containers.some(n=>n.element===t)&&t instanceof HTMLElement&&this.isElementScrollable(t)&&this.setupScrollContainer(t,e)}updateContainerPrimary(e,t){e.isPrimary=t}}class fr extends I{eventManager;trackedElements=new Map;observer=null;mutationObserver=null;mutationDebounceTimer=null;config=null;constructor(e){super(),this.eventManager=e}startTracking(){const e=this.get("config");if(this.config=e.viewport??null,!this.config?.elements||this.config.elements.length===0)return;const t=this.config.threshold??.5,r=this.config.minDwellTime??1e3;if(t<0||t>1){a("debug","ViewportHandler: Invalid threshold, must be between 0 and 1");return}if(r<0){a("debug","ViewportHandler: Invalid minDwellTime, must be non-negative");return}if(typeof IntersectionObserver>"u"){a("debug","ViewportHandler: IntersectionObserver not supported in this browser");return}this.observer=new IntersectionObserver(this.handleIntersection,{threshold:t}),this.observeElements(),this.setupMutationObserver()}stopTracking(){this.observer&&(this.observer.disconnect(),this.observer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.mutationDebounceTimer!==null&&(window.clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null);for(const e of this.trackedElements.values())e.timeoutId!==null&&window.clearTimeout(e.timeoutId);this.trackedElements.clear()}observeElements(){if(!this.config||!this.observer)return;const e=this.config.maxTrackedElements??100;let t=this.trackedElements.size;for(const r of this.config.elements)try{const n=document.querySelectorAll(r.selector);for(const i of Array.from(n)){if(t>=e){a("debug","ViewportHandler: Maximum tracked elements reached",{data:{limit:e,selector:r.selector,message:"Some elements will not be tracked. Consider more specific selectors."}});return}i.hasAttribute(`${y}-ignore`)||this.trackedElements.has(i)||(this.trackedElements.set(i,{element:i,selector:r.selector,id:r.id,name:r.name,startTime:null,timeoutId:null,lastFiredTime:null}),this.observer?.observe(i),t++)}}catch(n){a("debug",`ViewportHandler: Invalid selector "${r.selector}"`,{error:n})}a("debug","ViewportHandler: Elements tracked",{data:{count:t,limit:e}})}handleIntersection=e=>{if(!this.config)return;const t=this.config.minDwellTime??1e3;for(const r of e){const n=this.trackedElements.get(r.target);n&&(r.isIntersecting?n.startTime===null&&(n.startTime=performance.now(),n.timeoutId=window.setTimeout(()=>{const i=Math.round(r.intersectionRatio*100)/100;this.fireViewportEvent(n,i)},t)):n.startTime!==null&&(n.timeoutId!==null&&(window.clearTimeout(n.timeoutId),n.timeoutId=null),n.startTime=null))}};fireViewportEvent(e,t){if(e.startTime===null)return;const r=Math.round(performance.now()-e.startTime);if(e.element.hasAttribute(`${y}-ignore`))return;const n=this.config?.cooldownPeriod??6e4,i=Date.now();if(e.lastFiredTime!==null&&i-e.lastFiredTime<n){a("debug","ViewportHandler: Event suppressed by cooldown period",{data:{selector:e.selector,cooldownRemaining:n-(i-e.lastFiredTime)}}),e.startTime=null,e.timeoutId=null;return}const o={selector:e.selector,dwellTime:r,visibilityRatio:t,...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name}};this.eventManager.track({type:d.VIEWPORT_VISIBLE,viewport_data:o}),e.startTime=null,e.timeoutId=null,e.lastFiredTime=i}setupMutationObserver(){if(!(!this.config||typeof MutationObserver>"u")){if(!document.body){a("debug","ViewportHandler: document.body not available, skipping MutationObserver setup");return}this.mutationObserver=new MutationObserver(e=>{let t=!1;for(const r of e)r.type==="childList"&&(r.addedNodes.length>0&&(t=!0),r.removedNodes.length>0&&this.cleanupRemovedNodes(r.removedNodes));t&&(this.mutationDebounceTimer!==null&&window.clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.observeElements(),this.mutationDebounceTimer=null},100))}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0})}}cleanupRemovedNodes(e){e.forEach(t=>{if(t.nodeType!==1)return;const r=t,n=this.trackedElements.get(r);n&&(n.timeoutId!==null&&window.clearTimeout(n.timeoutId),this.observer?.unobserve(r),this.trackedElements.delete(r)),Array.from(this.trackedElements.keys()).filter(o=>r.contains(o)).forEach(o=>{const l=this.trackedElements.get(o);l&&l.timeoutId!==null&&window.clearTimeout(l.timeoutId),this.observer?.unobserve(o),this.trackedElements.delete(o)})})}}class mr{storage;sessionStorageRef;fallbackStorage=new Map;fallbackSessionStorage=new Map;hasQuotaExceededError=!1;constructor(){this.storage=this.initializeStorage("localStorage"),this.sessionStorageRef=this.initializeStorage("sessionStorage"),this.storage||a("debug","localStorage not available, using memory fallback"),this.sessionStorageRef||a("debug","sessionStorage not available, using memory fallback")}getItem(e){try{return this.storage?this.storage.getItem(e):this.fallbackStorage.get(e)??null}catch{return this.fallbackStorage.get(e)??null}}setItem(e,t){this.fallbackStorage.set(e,t);try{if(this.storage){this.storage.setItem(e,t);return}}catch(r){if(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")if(this.hasQuotaExceededError=!0,a("warn","localStorage quota exceeded, attempting cleanup",{data:{key:e,valueSize:t.length}}),this.cleanupOldData())try{if(this.storage){this.storage.setItem(e,t);return}}catch(o){a("error","localStorage quota exceeded even after cleanup - data will not persist",{error:o,data:{key:e,valueSize:t.length}})}else a("error","localStorage quota exceeded and no data to cleanup - data will not persist",{error:r,data:{key:e,valueSize:t.length}})}}removeItem(e){try{this.storage&&this.storage.removeItem(e)}catch{}this.fallbackStorage.delete(e)}clear(){if(!this.storage){this.fallbackStorage.clear();return}try{const e=[];for(let t=0;t<this.storage.length;t++){const r=this.storage.key(t);r?.startsWith("tracelog_")&&e.push(r)}e.forEach(t=>{this.storage.removeItem(t)}),this.fallbackStorage.clear()}catch(e){a("error","Failed to clear storage",{error:e}),this.fallbackStorage.clear()}}isAvailable(){return this.storage!==null}hasQuotaError(){return this.hasQuotaExceededError}cleanupOldData(){if(!this.storage)return!1;try{const e=[],t=[];for(let i=0;i<this.storage.length;i++){const o=this.storage.key(i);o?.startsWith("tracelog_")&&(e.push(o),o.startsWith("tracelog_persisted_events_")&&t.push(o))}if(t.length>0)return t.forEach(i=>{try{this.storage.removeItem(i)}catch{}}),!0;const r=["tracelog_session_","tracelog_user_id","tracelog_device_id","tracelog_config"],n=e.filter(i=>!r.some(o=>i.startsWith(o)));return n.length>0?(n.slice(0,5).forEach(o=>{try{this.storage.removeItem(o)}catch{}}),!0):!1}catch(e){return a("error","Failed to cleanup old data",{error:e}),!1}}initializeStorage(e){if(typeof window>"u")return null;try{const t=e==="localStorage"?window.localStorage:window.sessionStorage,r="__tracelog_test__";return t.setItem(r,"test"),t.removeItem(r),t}catch{return null}}getSessionItem(e){try{return this.sessionStorageRef?this.sessionStorageRef.getItem(e):this.fallbackSessionStorage.get(e)??null}catch{return this.fallbackSessionStorage.get(e)??null}}setSessionItem(e,t){this.fallbackSessionStorage.set(e,t);try{if(this.sessionStorageRef){this.sessionStorageRef.setItem(e,t);return}}catch(r){(r instanceof DOMException&&r.name==="QuotaExceededError"||r instanceof Error&&r.name==="QuotaExceededError")&&a("error","sessionStorage quota exceeded - data will not persist",{error:r,data:{key:e,valueSize:t.length}})}}removeSessionItem(e){try{this.sessionStorageRef&&this.sessionStorageRef.removeItem(e)}catch{}this.fallbackSessionStorage.delete(e)}}class gr extends I{eventManager;reportedByNav=new Map;navigationHistory=[];observers=[];vitalThresholds;lastLongTaskSentAt=0;navigationCounter=0;constructor(e){super(),this.eventManager=e,this.vitalThresholds=ce(j)}async startTracking(){const e=this.get("config"),t=e?.webVitalsMode??j;this.vitalThresholds=ce(t),e?.webVitalsThresholds&&(this.vitalThresholds={...this.vitalThresholds,...e.webVitalsThresholds}),await this.initWebVitals(),this.observeLongTasks()}stopTracking(){this.observers.forEach((e,t)=>{try{e.disconnect()}catch(r){a("debug","Failed to disconnect performance observer",{error:r,data:{observerIndex:t}})}}),this.observers.length=0,this.reportedByNav.clear(),this.navigationHistory.length=0}observeWebVitalsFallback(){this.reportTTFB(),this.safeObserve("largest-contentful-paint",r=>{const n=r.getEntries(),i=n[n.length-1];i&&this.sendVital({type:"LCP",value:Number(i.startTime.toFixed(2))})},{type:"largest-contentful-paint",buffered:!0},!0);let e=0,t=this.getNavigationId();this.safeObserve("layout-shift",r=>{const n=this.getNavigationId();n!==t&&(e=0,t=n);const i=r.getEntries();for(const o of i){if(o.hadRecentInput===!0)continue;const l=typeof o.value=="number"?o.value:0;e+=l}this.sendVital({type:"CLS",value:Number(e.toFixed(2))})},{type:"layout-shift",buffered:!0}),this.safeObserve("paint",r=>{for(const n of r.getEntries())n.name==="first-contentful-paint"&&this.sendVital({type:"FCP",value:Number(n.startTime.toFixed(2))})},{type:"paint",buffered:!0},!0),this.safeObserve("event",r=>{let n=0;const i=r.getEntries();for(const o of i){const l=(o.processingEnd??0)-(o.startTime??0);n=Math.max(n,l)}n>0&&this.sendVital({type:"INP",value:Number(n.toFixed(2))})},{type:"event",buffered:!0})}async initWebVitals(){try{const{onLCP:e,onCLS:t,onFCP:r,onTTFB:n,onINP:i}=await Promise.resolve().then(()=>Vr),o=l=>c=>{const u=Number(c.value.toFixed(2));this.sendVital({type:l,value:u})};e(o("LCP"),{reportAllChanges:!1}),t(o("CLS"),{reportAllChanges:!1}),r(o("FCP"),{reportAllChanges:!1}),n(o("TTFB"),{reportAllChanges:!1}),i(o("INP"),{reportAllChanges:!1})}catch(e){a("debug","Failed to load web-vitals library, using fallback",{error:e}),this.observeWebVitalsFallback()}}reportTTFB(){try{const e=performance.getEntriesByType("navigation")[0];if(!e)return;const t=e.responseStart;typeof t=="number"&&Number.isFinite(t)&&this.sendVital({type:"TTFB",value:Number(t.toFixed(2))})}catch(e){a("debug","Failed to report TTFB",{error:e})}}observeLongTasks(){this.safeObserve("longtask",e=>{const t=e.getEntries();for(const r of t){const n=Number(r.duration.toFixed(2)),i=Date.now();i-this.lastLongTaskSentAt>=kt&&(this.shouldSendVital("LONG_TASK",n)&&this.trackWebVital("LONG_TASK",n),this.lastLongTaskSentAt=i)}},{type:"longtask",buffered:!0})}sendVital(e){if(!this.shouldSendVital(e.type,e.value))return;const t=this.getNavigationId();if(t){const r=this.reportedByNav.get(t);if(r?.has(e.type))return;if(r)r.add(e.type);else if(this.reportedByNav.set(t,new Set([e.type])),this.navigationHistory.push(t),this.navigationHistory.length>Ut){const i=this.navigationHistory.shift();i&&this.reportedByNav.delete(i)}}this.trackWebVital(e.type,e.value)}trackWebVital(e,t){if(!Number.isFinite(t)){a("debug","Invalid web vital value",{data:{type:e,value:t}});return}this.eventManager.track({type:d.WEB_VITALS,web_vitals:{type:e,value:t}})}getNavigationId(){try{const e=performance.getEntriesByType("navigation")[0];if(!e)return null;const t=e.startTime||performance.now(),r=++this.navigationCounter,n=`${t.toFixed(2)}_${window.location.pathname}`;return r>1?`${n}_${r}`:n}catch(e){return a("debug","Failed to get navigation ID",{error:e}),null}}isObserverSupported(e){if(typeof PerformanceObserver>"u")return!1;const t=PerformanceObserver.supportedEntryTypes;return!t||t.includes(e)}safeObserve(e,t,r,n=!1){try{if(!this.isObserverSupported(e))return!1;const i=new PerformanceObserver((o,l)=>{try{t(o,l)}catch(c){a("debug","Observer callback failed",{error:c,data:{type:e}})}if(n)try{l.disconnect()}catch{}});return i.observe(r??{type:e,buffered:!0}),n||this.observers.push(i),!0}catch(i){return a("debug","Failed to create performance observer",{error:i,data:{type:e}}),!1}}shouldSendVital(e,t){if(typeof t!="number"||!Number.isFinite(t))return a("debug","Invalid web vital value",{data:{type:e,value:t}}),!1;const r=this.vitalThresholds[e];return!(typeof r=="number"&&t<=r)}}class Er extends I{eventManager;recentErrors=new Map;errorBurstCounter=0;burstWindowStart=0;burstBackoffUntil=0;constructor(e){super(),this.eventManager=e}startTracking(){window.addEventListener("error",this.handleError),window.addEventListener("unhandledrejection",this.handleRejection)}stopTracking(){window.removeEventListener("error",this.handleError),window.removeEventListener("unhandledrejection",this.handleRejection),this.recentErrors.clear(),this.errorBurstCounter=0,this.burstWindowStart=0,this.burstBackoffUntil=0}shouldSample(){const e=Date.now();if(e<this.burstBackoffUntil)return!1;if(e-this.burstWindowStart>Ot&&(this.errorBurstCounter=0,this.burstWindowStart=e),this.errorBurstCounter++,this.errorBurstCounter>Pt)return this.burstBackoffUntil=e+We,a("debug","Error burst detected - entering cooldown",{data:{errorsInWindow:this.errorBurstCounter,cooldownMs:We}}),!1;const r=this.get("config")?.errorSampling??Be;return Math.random()<r}handleError=e=>{if(!this.shouldSample())return;const t=this.sanitize(e.message||"Unknown error");this.shouldSuppressError(V.JS_ERROR,t)||this.eventManager.track({type:d.ERROR,error_data:{type:V.JS_ERROR,message:t,...e.filename&&{filename:e.filename},...e.lineno&&{line:e.lineno},...e.colno&&{column:e.colno}}})};handleRejection=e=>{if(!this.shouldSample())return;const t=this.extractRejectionMessage(e.reason),r=this.sanitize(t);this.shouldSuppressError(V.PROMISE_REJECTION,r)||this.eventManager.track({type:d.ERROR,error_data:{type:V.PROMISE_REJECTION,message:r}})};extractRejectionMessage(e){if(!e)return"Unknown rejection";if(typeof e=="string")return e;if(e instanceof Error)return e.stack??e.message??e.toString();if(typeof e=="object"&&"message"in e)return String(e.message);try{return JSON.stringify(e)}catch{return String(e)}}sanitize(e){let t=e.length>Fe?e.slice(0,Fe)+"...":e;for(const r of ae){const n=new RegExp(r.source,r.flags);t=t.replace(n,"[REDACTED]")}return t}shouldSuppressError(e,t){const r=Date.now(),n=`${e}:${t}`,i=this.recentErrors.get(n);return i&&r-i<$e?(this.recentErrors.set(n,r),!0):(this.recentErrors.set(n,r),this.recentErrors.size>Nt?(this.recentErrors.clear(),this.recentErrors.set(n,r),!1):(this.recentErrors.size>z&&this.pruneOldErrors(),!1))}pruneOldErrors(){const e=Date.now();for(const[n,i]of this.recentErrors.entries())e-i>$e&&this.recentErrors.delete(n);if(this.recentErrors.size<=z)return;const t=Array.from(this.recentErrors.entries()).sort((n,i)=>n[1]-i[1]),r=this.recentErrors.size-z;for(let n=0;n<r;n+=1){const i=t[n];i&&this.recentErrors.delete(i[0])}}}class Sr extends I{isInitialized=!1;suppressNextScrollTimer=null;emitter=new rr;transformers={};customHeadersProvider;managers={};handlers={};get initialized(){return this.isInitialized}async init(e={}){if(!this.isInitialized){this.managers.storage=new mr;try{this.setupState(e);const t=e.integrations?.custom?.headers??{};this.managers.event=new ir(this.managers.storage,this.emitter,this.transformers,t,this.customHeadersProvider),this.initializeHandlers(),await this.managers.event.recoverPersistedEvents().catch(r=>{a("warn","Failed to recover persisted events",{error:r})}),this.isInitialized=!0}catch(t){this.destroy(!0);const r=t instanceof Error?t.message:String(t);throw new Error(`[TraceLog] TraceLog initialization failed: ${r}`)}}}sendCustomEvent(e,t){if(!this.managers.event){a("warn","Cannot send custom event: TraceLog not initialized",{data:{name:e}});return}let r=t;t&&typeof t=="object"&&!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&(r=Object.assign({},t));const{valid:n,error:i,sanitizedMetadata:o}=tr(e,r);if(!n){if(this.get("mode")===B.QA)throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${i}`);return}this.managers.event.track({type:d.CUSTOM,custom_event:{name:e,...o&&{metadata:o}}})}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setTransformer(e,t){if(typeof t!="function")throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof t}`);this.transformers[e]=t}removeTransformer(e){delete this.transformers[e]}getTransformer(e){return this.transformers[e]}setCustomHeaders(e){if(typeof e!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof e}`);this.customHeadersProvider=e,this.managers.event&&this.managers.event.setCustomHeadersProvider(e)}removeCustomHeaders(){this.customHeadersProvider=void 0,this.managers.event&&this.managers.event.removeCustomHeadersProvider()}destroy(e=!1){!this.isInitialized&&!e||(Object.values(this.handlers).filter(Boolean).forEach(t=>{try{t.stopTracking()}catch(r){a("warn","Failed to stop tracking",{error:r})}}),this.suppressNextScrollTimer&&(clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=null),this.managers.event?.stop(),this.emitter.removeAllListeners(),this.transformers.beforeSend=void 0,this.transformers.beforeBatch=void 0,this.customHeadersProvider=void 0,this.set("suppressNextScroll",!1),this.set("sessionId",null),this.isInitialized=!1,this.handlers={},this.managers={})}setupState(e={}){this.set("config",e);const t=or.getId(this.managers.storage);this.set("userId",t);const r=zt(e);this.set("collectApiUrls",r);const n=Rt();this.set("device",n);const i=he(window.location.href,e.sensitiveQueryParams);this.set("pageUrl",i),Ft()&&this.set("mode",B.QA)}getConfig(){return this.get("config")}getCollectApiUrls(){return this.get("collectApiUrls")}getEventManager(){return this.managers.event}validateGlobalMetadata(e){if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,error:"Global metadata must be a plain object"};const t=Ye("Global",e,"globalMetadata");return t.valid?{valid:!0}:{valid:!1,error:t.error}}updateGlobalMetadata(e){const t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);const n={...this.get("config"),globalMetadata:e};this.set("config",n),a("debug","Global metadata updated (replaced)",{data:{keys:Object.keys(e)}})}mergeGlobalMetadata(e){const t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);const r=this.get("config"),i={...r.globalMetadata??{},...e},o={...r,globalMetadata:i};this.set("config",o),a("debug","Global metadata updated (merged)",{data:{keys:Object.keys(e)}})}initializeHandlers(){const e=this.get("config");this.handlers.session=new cr(this.managers.storage,this.managers.event),this.handlers.session.startTracking();const t=()=>{this.set("suppressNextScroll",!0),this.suppressNextScrollTimer&&clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=window.setTimeout(()=>{this.set("suppressNextScroll",!1)},500)};this.handlers.pageView=new ur(this.managers.event,t),this.handlers.pageView.startTracking(),this.handlers.click=new dr(this.managers.event),this.handlers.click.startTracking(),this.handlers.scroll=new hr(this.managers.event),this.handlers.scroll.startTracking(),this.handlers.performance=new gr(this.managers.event),this.handlers.performance.startTracking().catch(r=>{a("warn","Failed to start performance tracking",{error:r})}),this.handlers.error=new Er(this.managers.event),this.handlers.error.startTracking(),e.viewport&&(this.handlers.viewport=new fr(this.managers.event),this.handlers.viewport.startTracking())}}const O=[],C=[];let P=null,f=null,R=!1,_=!1;const Tr=async s=>{if(!(typeof window>"u"||typeof document>"u")&&(_=!1,window.__traceLogDisabled!==!0&&!f&&!R)){R=!0;try{const e=Jt(s??{}),t=new Sr;try{O.forEach(({event:i,callback:o})=>{t.on(i,o)}),O.length=0,C.forEach(({hook:i,fn:o})=>{i==="beforeSend"?t.setTransformer("beforeSend",o):t.setTransformer("beforeBatch",o)}),C.length=0,P&&(t.setCustomHeaders(P),P=null);const r=t.init(e),n=new Promise((i,o)=>{setTimeout(()=>{o(new Error("[TraceLog] Initialization timeout after 10000ms"))},1e4)});await Promise.race([r,n]),f=t}catch(r){try{t.destroy(!0)}catch(n){a("error","Failed to cleanup partially initialized app",{error:n})}throw r}}catch(e){throw f=null,e}finally{R=!1}}},pr=(s,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!f)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(_)throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");f.sendCustomEvent(s,e)}},_r=(s,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!f||R){O.push({event:s,callback:e});return}f.on(s,e)}},vr=(s,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!f){const t=O.findIndex(r=>r.event===s&&r.callback===e);t!==-1&&O.splice(t,1);return}f.off(s,e)}};function Ir(s,e){if(!(typeof window>"u"||typeof document>"u")){if(typeof e!="function")throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof e}`);if(!f||R){const t=C.findIndex(r=>r.hook===s);t!==-1&&C.splice(t,1),C.push({hook:s,fn:e});return}if(_)throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");s==="beforeSend"?f.setTransformer("beforeSend",e):f.setTransformer("beforeBatch",e)}}const wr={init:Tr,event:pr,on:_r,off:vr,setTransformer:Ir,removeTransformer:s=>{if(!(typeof window>"u"||typeof document>"u")){if(!f){const e=C.findIndex(t=>t.hook===s);e!==-1&&C.splice(e,1);return}if(_)throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");f.removeTransformer(s)}},setCustomHeaders:s=>{if(!(typeof window>"u"||typeof document>"u")){if(typeof s!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof s}`);if(!f||R){P=s;return}if(_)throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");f.setCustomHeaders(s)}},removeCustomHeaders:()=>{if(!(typeof window>"u"||typeof document>"u")){if(!f){P=null;return}if(_)throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");f.removeCustomHeaders()}},isInitialized:()=>typeof window>"u"||typeof document>"u"?!1:f!==null,destroy:()=>{if(!(typeof window>"u"||typeof document>"u")){if(_)throw new Error("[TraceLog] Destroy operation already in progress");if(!f){_=!1;return}_=!0;try{f.destroy(),f=null,R=!1,O.length=0,C.length=0,P=null,_=!1}catch(s){f=null,R=!1,O.length=0,C.length=0,P=null,_=!1,a("warn","Error during destroy, forced cleanup completed",{error:s})}}},setQaMode:s=>{typeof window>"u"||typeof document>"u"||$t(s)},updateGlobalMetadata:s=>{if(!(typeof window>"u"||typeof document>"u")){if(!f)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(_)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");f.updateGlobalMetadata(s)}},mergeGlobalMetadata:s=>{if(!(typeof window>"u"||typeof document>"u")){if(!f)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(_)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");f.mergeGlobalMetadata(s)}}};var Ee,et=-1,H=function(s){addEventListener("pageshow",(function(e){e.persisted&&(et=e.timeStamp,s(e))}),!0)},Se=function(){var s=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(s&&s.responseStart>0&&s.responseStart<performance.now())return s},q=function(){var s=Se();return s&&s.activationStart||0},A=function(s,e){var t=Se(),r="navigate";return et>=0?r="back-forward-cache":t&&(document.prerendering||q()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:s,value:e===void 0?-1:e,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},W=function(s,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(s)){var r=new PerformanceObserver((function(n){Promise.resolve().then((function(){e(n.getEntries())}))}));return r.observe(Object.assign({type:s,buffered:!0},t||{})),r}}catch{}},M=function(s,e,t,r){var n,i;return function(o){e.value>=0&&(o||r)&&((i=e.value-(n||0))||n===void 0)&&(n=e.value,e.delta=i,e.rating=(function(l,c){return l>c[1]?"poor":l>c[0]?"needs-improvement":"good"})(e.value,t),s(e))}},Te=function(s){requestAnimationFrame((function(){return requestAnimationFrame((function(){return s()}))}))},J=function(s){document.addEventListener("visibilitychange",(function(){document.visibilityState==="hidden"&&s()}))},pe=function(s){var e=!1;return function(){e||(s(),e=!0)}},x=-1,tt=function(){return document.visibilityState!=="hidden"||document.prerendering?1/0:0},Z=function(s){document.visibilityState==="hidden"&&x>-1&&(x=s.type==="visibilitychange"?s.timeStamp:0,yr())},rt=function(){addEventListener("visibilitychange",Z,!0),addEventListener("prerenderingchange",Z,!0)},yr=function(){removeEventListener("visibilitychange",Z,!0),removeEventListener("prerenderingchange",Z,!0)},st=function(){return x<0&&(x=tt(),rt(),H((function(){setTimeout((function(){x=tt(),rt()}),0)}))),{get firstHiddenTime(){return x}}},ee=function(s){document.prerendering?addEventListener("prerenderingchange",(function(){return s()}),!0):s()},_e=[1800,3e3],nt=function(s,e){e=e||{},ee((function(){var t,r=st(),n=A("FCP"),i=W("paint",(function(o){o.forEach((function(l){l.name==="first-contentful-paint"&&(i.disconnect(),l.startTime<r.firstHiddenTime&&(n.value=Math.max(l.startTime-q(),0),n.entries.push(l),t(!0)))}))}));i&&(t=M(s,n,_e,e.reportAllChanges),H((function(o){n=A("FCP"),t=M(s,n,_e,e.reportAllChanges),Te((function(){n.value=performance.now()-o.timeStamp,t(!0)}))})))}))},ve=[.1,.25],br=function(s,e){e=e||{},nt(pe((function(){var t,r=A("CLS",0),n=0,i=[],o=function(c){c.forEach((function(u){if(!u.hadRecentInput){var T=i[0],E=i[i.length-1];n&&u.startTime-E.startTime<1e3&&u.startTime-T.startTime<5e3?(n+=u.value,i.push(u)):(n=u.value,i=[u])}})),n>r.value&&(r.value=n,r.entries=i,t())},l=W("layout-shift",o);l&&(t=M(s,r,ve,e.reportAllChanges),J((function(){o(l.takeRecords()),t(!0)})),H((function(){n=0,r=A("CLS",0),t=M(s,r,ve,e.reportAllChanges),Te((function(){return t()}))})),setTimeout(t,0))})))},it=0,Ie=1/0,te=0,Ar=function(s){s.forEach((function(e){e.interactionId&&(Ie=Math.min(Ie,e.interactionId),te=Math.max(te,e.interactionId),it=te?(te-Ie)/7+1:0)}))},ot=function(){return Ee?it:performance.interactionCount||0},Mr=function(){"interactionCount"in performance||Ee||(Ee=W("event",Ar,{type:"event",buffered:!0,durationThreshold:0}))},L=[],re=new Map,at=0,Lr=function(){var s=Math.min(L.length-1,Math.floor((ot()-at)/50));return L[s]},Cr=[],Rr=function(s){if(Cr.forEach((function(n){return n(s)})),s.interactionId||s.entryType==="first-input"){var e=L[L.length-1],t=re.get(s.interactionId);if(t||L.length<10||s.duration>e.latency){if(t)s.duration>t.latency?(t.entries=[s],t.latency=s.duration):s.duration===t.latency&&s.startTime===t.entries[0].startTime&&t.entries.push(s);else{var r={id:s.interactionId,latency:s.duration,entries:[s]};re.set(r.id,r),L.push(r)}L.sort((function(n,i){return i.latency-n.latency})),L.length>10&&L.splice(10).forEach((function(n){return re.delete(n.id)}))}}},lt=function(s){var e=self.requestIdleCallback||self.setTimeout,t=-1;return s=pe(s),document.visibilityState==="hidden"?s():(t=e(s),J(s)),t},we=[200,500],Nr=function(s,e){"PerformanceEventTiming"in self&&"interactionId"in PerformanceEventTiming.prototype&&(e=e||{},ee((function(){var t;Mr();var r,n=A("INP"),i=function(l){lt((function(){l.forEach(Rr);var c=Lr();c&&c.latency!==n.value&&(n.value=c.latency,n.entries=c.entries,r())}))},o=W("event",i,{durationThreshold:(t=e.durationThreshold)!==null&&t!==void 0?t:40});r=M(s,n,we,e.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),J((function(){i(o.takeRecords()),r(!0)})),H((function(){at=ot(),L.length=0,re.clear(),n=A("INP"),r=M(s,n,we,e.reportAllChanges)})))})))},ye=[2500,4e3],be={},Or=function(s,e){e=e||{},ee((function(){var t,r=st(),n=A("LCP"),i=function(c){e.reportAllChanges||(c=c.slice(-1)),c.forEach((function(u){u.startTime<r.firstHiddenTime&&(n.value=Math.max(u.startTime-q(),0),n.entries=[u],t())}))},o=W("largest-contentful-paint",i);if(o){t=M(s,n,ye,e.reportAllChanges);var l=pe((function(){be[n.id]||(i(o.takeRecords()),o.disconnect(),be[n.id]=!0,t(!0))}));["keydown","click"].forEach((function(c){addEventListener(c,(function(){return lt(l)}),{once:!0,capture:!0})})),J(l),H((function(c){n=A("LCP"),t=M(s,n,ye,e.reportAllChanges),Te((function(){n.value=performance.now()-c.timeStamp,be[n.id]=!0,t(!0)}))}))}}))},Ae=[800,1800],Pr=function s(e){document.prerendering?ee((function(){return s(e)})):document.readyState!=="complete"?addEventListener("load",(function(){return s(e)}),!0):setTimeout(e,0)},Dr=function(s,e){e=e||{};var t=A("TTFB"),r=M(s,t,Ae,e.reportAllChanges);Pr((function(){var n=Se();n&&(t.value=Math.max(n.responseStart-q(),0),t.entries=[n],r(!0),H((function(){t=A("TTFB",0),(r=M(s,t,Ae,e.reportAllChanges))(!0)})))}))};const Vr=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:ve,FCPThresholds:_e,INPThresholds:we,LCPThresholds:ye,TTFBThresholds:Ae,onCLS:br,onFCP:nt,onINP:Nr,onLCP:Or,onTTFB:Dr},Symbol.toStringTag,{value:"Module"}));h.AppConfigValidationError=m,h.DEFAULT_SESSION_TIMEOUT=9e5,h.DEFAULT_WEB_VITALS_MODE=j,h.DeviceType=b,h.EmitterEvent=X,h.ErrorType=V,h.EventType=d,h.InitializationTimeoutError=pt,h.IntegrationValidationError=U,h.MAX_ARRAY_LENGTH=100,h.MAX_CUSTOM_EVENT_ARRAY_SIZE=10,h.MAX_CUSTOM_EVENT_KEYS=10,h.MAX_CUSTOM_EVENT_NAME_LENGTH=120,h.MAX_CUSTOM_EVENT_STRING_SIZE=8192,h.MAX_NESTED_OBJECT_KEYS=20,h.MAX_STRING_LENGTH=1e3,h.MAX_STRING_LENGTH_IN_ARRAY=500,h.Mode=B,h.PII_PATTERNS=ae,h.PermanentError=N,h.SamplingRateValidationError=ne,h.ScrollDirection=$,h.SessionTimeoutValidationError=ke,h.SpecialApiUrl=D,h.TraceLogValidationError=k,h.WEB_VITALS_GOOD_THRESHOLDS=Vt,h.WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS=le,h.WEB_VITALS_POOR_THRESHOLDS=Ge,h.getWebVitalsThresholds=ce,h.isPrimaryScrollEvent=St,h.isSecondaryScrollEvent=Tt,h.tracelog=wr,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})})(this.TraceLog=this.TraceLog||{});typeof window<"u"&&window.TraceLog?.tracelog&&(window.tracelog=window.TraceLog.tracelog);
|