@tracelog/lib 2.7.3 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- 'use strict';var C=9e5;var K=120,X=49152,z=100,Y=500,Re=200;var N=1e3,q=500,Ae=1e3;var I="data-tlog",it=["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"]'],st=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],ot=["token","auth","key","session","reset","password","api_key","apikey","secret","access_token","refresh_token","verification","code","otp"];var p={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",INVALID_SEND_INTERVAL:"Send interval must be between 1000ms (1 second) and 60000ms (60 seconds)"},at=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/on\w+\s*=/gi,/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,/<embed\b[^>]*>/gi,/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi];var v="tlog",O=`${v}:qa_mode`,H=`${v}:uid`,Le="tlog_mode",Ce="qa",Ne="qa_off",lt=n=>n?`${v}:${n}:queue`:`${v}:queue`,ct=n=>n?`${v}:${n}:session`:`${v}:session`;var dt=n=>n?`${v}:${n}:broadcast`:`${v}:broadcast`,Oe=(n,e)=>`${v}:${n}:session_counts:${e}`,Pe=10080*60*1e3,xe=`${v}:session_counts_last_cleanup`,De=3600*1e3,J=n=>n?`${v}:${n}:identity`:`${v}:identity`,M=`${v}:pending_identity`;var ut=(t=>(t.Localhost="localhost:8080",t.Fail="localhost:9999",t))(ut||{});var mt=(i=>(i.Mobile="mobile",i.Tablet="tablet",i.Desktop="desktop",i.Unknown="unknown",i))(mt||{});var ft=(t=>(t.EVENT="event",t.QUEUE="queue",t))(ft||{});var R=class n extends Error{constructor(t,r){super(t);this.statusCode=r;this.name="PermanentError",Error.captureStackTrace&&Error.captureStackTrace(this,n);}},B=class n extends Error{constructor(e){super(e),this.name="RateLimitError",Error.captureStackTrace&&Error.captureStackTrace(this,n);}},A=class n extends Error{constructor(e){super(e),this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,n);}};var y=(c=>(c.PAGE_VIEW="page_view",c.CLICK="click",c.SCROLL="scroll",c.SESSION_START="session_start",c.CUSTOM="custom",c.WEB_VITALS="web_vitals",c.ERROR="error",c.VIEWPORT_VISIBLE="viewport_visible",c))(y||{}),pt=(t=>(t.UP="up",t.DOWN="down",t))(pt||{}),gt=(t=>(t.JS_ERROR="js_error",t.PROMISE_REJECTION="promise_rejection",t))(gt||{});var ke=(e=>(e.QA="qa",e))(ke||{});var Ln=n=>n.type==="scroll"&&"scroll_data"in n&&n.scroll_data.is_primary===true,Cn=n=>n.type==="scroll"&&"scroll_data"in n&&n.scroll_data.is_primary===false;var P=class extends Error{constructor(t,r,i){super(t);this.errorCode=r;this.layer=i;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}},m=class extends P{constructor(e,t="config"){super(e,"APP_CONFIG_INVALID",t);}},Z=class extends P{constructor(e,t="config"){super(e,"SESSION_TIMEOUT_INVALID",t);}},F=class extends P{constructor(e,t="config"){super(e,"SAMPLING_RATE_INVALID",t);}},b=class extends P{constructor(e,t="config"){super(e,"INTEGRATION_INVALID",t);}},ht=class extends P{constructor(t,r,i="runtime"){super(t,"INITIALIZATION_TIMEOUT",i);this.timeoutMs=r;}};var Ve="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;",Et="background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;";var Tr=(n,e)=>{if(e){if(e instanceof Error){let t=e.message.replace(/\s+at\s+.*$/gm,"").replace(/\s*\([^()]+:\d+:\d+\)/g,"");return `[TraceLog] ${n}: ${t}`}if(e instanceof Error)return `[TraceLog] ${n}: ${e.message}`;if(typeof e=="string")return `[TraceLog] ${n}: ${e}`;if(typeof e=="object")try{return `[TraceLog] ${n}: ${JSON.stringify(e)}`}catch{return `[TraceLog] ${n}: [Unable to serialize error]`}return `[TraceLog] ${n}: ${String(e)}`}return `[TraceLog] ${n}`},_r=()=>{if(typeof window>"u"||typeof sessionStorage>"u")return false;try{return sessionStorage.getItem(O)==="true"}catch{return false}},o=(n,e,t)=>{let{error:r,data:i,showToClient:s=false,style:a,visibility:l}=t??{},c=r?Tr(e,r):`[TraceLog] ${e}`,d=n==="error"?"error":n==="warn"?"warn":"log";if(!Ir(l,s))return;let T=yr(l,a),h=i!==void 0?He(i):void 0;vt(d,c,T,h);},Ir=(n,e)=>n==="critical"?true:n==="qa"||e?_r():false,yr=(n,e)=>e!==void 0&&e!==""?e:n==="critical"?Et:"",vt=(n,e,t,r)=>{let i=t!==void 0&&t!=="",s=i?`%c${e}`:e;r!==void 0?i?console[n](s,t,r):console[n](s,r):i?console[n](s,t):console[n](s);},He=n=>{let e={},t=["token","password","secret","key","apikey","api_key","sessionid","session_id"];for(let[r,i]of Object.entries(n)){let s=r.toLowerCase();if(t.some(a=>s.includes(a))){e[r]="[REDACTED]";continue}i!==null&&typeof i=="object"&&!Array.isArray(i)?e[r]=He(i):Array.isArray(i)?e[r]=i.map(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?He(a):a):e[r]=i;}return e};var Be,St,br=()=>{typeof window<"u"&&!Be&&(Be=window.matchMedia("(pointer: coarse)"),St=window.matchMedia("(hover: none)"));},ee="Unknown",wr=n=>{let e=n.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"}let 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":ee},Mr=n=>{let e=n.userAgentData?.brands;if(e!=null&&e.length>0){let i=e.filter(s=>!/not.?a.?brand|chromium/i.test(s.brand))[0];if(i!=null){let s=i.brand;return /google chrome/i.test(s)?"Chrome":/microsoft edge/i.test(s)?"Edge":/opera/i.test(s)?"Opera":s}}let 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":ee},Rr=()=>{try{let n=navigator;if(n.userAgentData!=null&&typeof n.userAgentData.mobile=="boolean"){let c=n.userAgentData.platform;return c!=null&&c!==""&&/ipad|tablet/i.test(c)?"tablet":n.userAgentData.mobile?"mobile":"desktop"}br();let e=window.innerWidth,t=Be?.matches??!1,r=St?.matches??!1,i="ontouchstart"in window||navigator.maxTouchPoints>0,s=navigator.userAgent.toLowerCase(),a=/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(s),l=/tablet|ipad|android(?!.*mobile)/.test(s);return e<=767||a&&i?"mobile":e>=768&&e<=1024||l||t&&r&&i?"tablet":"desktop"}catch(n){return o("debug","Device detection failed, defaulting to desktop",{error:n}),"desktop"}},Tt=()=>{try{let n=navigator;return {type:Rr(),os:wr(n),browser:Mr(n)}}catch(n){return o("debug","Device info detection failed, using defaults",{error:n}),{type:"desktop",os:ee,browser:ee}}};var $=[/\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,/[?&](token|password|passwd|auth|secret|secret_key|private_key|auth_key|api_key|apikey|access_token)=[^&\s]+/gi];var Ar={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},Fe={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},_t={LCP:4e3,FCP:3e3,CLS:.25,INP:500,TTFB:1800,LONG_TASK:50},W="needs-improvement",te=(n=W)=>{switch(n){case "all":return {LCP:0,FCP:0,CLS:0,INP:0,TTFB:0,LONG_TASK:0};case "needs-improvement":return Fe;case "poor":return _t;default:return Fe}},It=1e3,yt=50;var bt="2.7.2";var wt=bt;var Mt=()=>typeof window<"u"&&typeof sessionStorage<"u",Cr=()=>{try{let n=new URLSearchParams(window.location.search);n.delete(Le);let e=n.toString(),t=window.location.pathname+(e?"?"+e:"")+window.location.hash;window.history.replaceState({},"",t);}catch{}},Rt=()=>{if(!Mt())return false;try{let e=new URLSearchParams(window.location.search).get(Le),t=sessionStorage.getItem(O),r=null;return e===Ce?(r=!0,sessionStorage.setItem(O,"true"),o("info","QA Mode ACTIVE",{visibility:"qa",style:Ve})):e===Ne&&(r=!1,sessionStorage.setItem(O,"false"),o("info","QA Mode DISABLED",{visibility:"qa",style:Ue})),(e===Ce||e===Ne)&&Cr(),r??t==="true"}catch{return false}},At=n=>{if(Mt())try{sessionStorage.setItem(O,n?"true":"false"),o("info",n?"QA Mode ACTIVE":"QA Mode DISABLED",{visibility:"qa",style:n?Ve:Ue});}catch{o("debug","Cannot set QA mode: sessionStorage unavailable");}};var Nr=["co.uk","org.uk","com.au","net.au","com.br","co.nz","co.jp","com.mx","co.in","com.cn","co.za"],Lt=n=>{let e=n.toLowerCase().split(".");if(e.length<=2)return n.toLowerCase();let t=e.slice(-2).join(".");return Nr.includes(t)?e.slice(-3).join("."):e.slice(-2).join(".")},Or=(n,e)=>n===e?true:Lt(n)===Lt(e),re=()=>{let n=document.referrer;if(!n)return "Direct";try{let e=new URL(n).hostname.toLowerCase(),t=window.location.hostname.toLowerCase();return Or(e,t)?"Direct":n}catch(e){return o("debug","Failed to parse referrer URL, using raw value",{error:e,data:{referrer:n}}),n}};var ne=()=>{let n=new URLSearchParams(window.location.search),e={};return st.forEach(r=>{let i=n.get(r);if(i){let s=r.split("utm_")[1];e[s]=i;}}),Object.keys(e).length?e:void 0};var oe=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return (n==="x"?e:e&3|8).toString(16)}),ie=0,se=0,Ct=()=>{let n=Date.now();n<se&&(n=se),n===se?ie=(ie+1)%1e3:ie=0,se=n;let e=ie.toString().padStart(3,"0"),t="";try{if(typeof crypto<"u"&&crypto.getRandomValues){let r=crypto.getRandomValues(new Uint8Array(3));r&&(t=Array.from(r,i=>i.toString(16).padStart(2,"0")).join(""));}}catch{}return t||(t=Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")),`${n}-${e}-${t}`};var Nt=(n,e=false)=>{try{let t=new URL(n),r=t.protocol==="https:",i=t.protocol==="http:";return r||e&&i}catch{return false}},Pr=n=>{try{let 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.");let 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 i;if(r.length===2?i=r.join("."):i=r.slice(-2).join("."),!i||i.split(".").length<2)throw new Error("Invalid domain structure for SaaS");let s=`https://${n}.${i}/collect`;if(!Nt(s))throw new Error("Generated URL failed validation");return s}catch(e){throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error?e.message:String(e)}`)}},Ot=n=>{let e={};n.integrations?.tracelog?.projectId&&(e.saas=Pr(n.integrations.tracelog.projectId));let t=n.integrations?.custom?.collectApiUrl;if(t){let r=n.integrations?.custom?.allowHttp??false;if(!Nt(t,r))throw new Error("Invalid custom API URL");e.custom=t;}return e},j=(n,e=[])=>{if(!n||typeof n!="string")return o("warn","Invalid URL provided to normalizeUrl",{data:{type:typeof n}}),n||"";try{let t=new URL(n),r=t.searchParams,i=[...new Set([...ot,...e])],s=!1,a=[];return i.forEach(c=>{r.has(c)&&(r.delete(c),s=!0,a.push(c));}),!s&&n.includes("?")?n:(t.search=r.toString(),t.toString())}catch(t){return o("warn","URL normalization failed, returning original",{error:t,data:{urlLength:n?.length}}),n}};var Pt=n=>{if(!n||typeof n!="string"||n.trim().length===0)return "";let e=n;n.length>1e3&&(e=n.slice(0,Math.max(0,1e3)));let t=0;for(let i of at){let s=e;e=e.replace(i,""),s!==e&&t++;}return t>0&&o("warn","XSS patterns detected and removed",{data:{patternMatches:t,valueLength:n.length}}),e.trim()},$e=(n,e=0)=>{if(n==null)return null;if(typeof n=="string")return Pt(n);if(typeof n=="number")return !Number.isFinite(n)||n<-Number.MAX_SAFE_INTEGER||n>Number.MAX_SAFE_INTEGER?0:n;if(typeof n=="boolean")return n;if(e>10)return null;if(Array.isArray(n))return n.slice(0,1e3).map(i=>$e(i,e+1)).filter(i=>i!==null);if(typeof n=="object"){let t={},i=Object.entries(n).slice(0,200);for(let[s,a]of i){let l=Pt(s);if(l){let c=$e(a,e+1);c!==null&&(t[l]=c);}}return t}return null},xt=n=>{if(typeof n!="object"||n===null)return {};try{let e=$e(n);return typeof e=="object"&&e!==null?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`[TraceLog] Metadata sanitization failed: ${t}`)}};var Fr=n=>{if(n!==void 0&&(n===null||typeof n!="object"))throw new m("Configuration must be an object","config");if(n){if(n.sessionTimeout!==void 0&&(typeof n.sessionTimeout!="number"||n.sessionTimeout<3e4||n.sessionTimeout>864e5))throw new Z(p.INVALID_SESSION_TIMEOUT,"config");if(n.globalMetadata!==void 0&&(typeof n.globalMetadata!="object"||n.globalMetadata===null))throw new m(p.INVALID_GLOBAL_METADATA,"config");if(n.integrations&&Wr(n.integrations),n.sensitiveQueryParams!==void 0){if(!Array.isArray(n.sensitiveQueryParams))throw new m(p.INVALID_SENSITIVE_QUERY_PARAMS,"config");for(let e of n.sensitiveQueryParams)if(typeof e!="string")throw new m("All sensitive query params must be strings","config")}if(n.errorSampling!==void 0&&(typeof n.errorSampling!="number"||n.errorSampling<0||n.errorSampling>1))throw new F(p.INVALID_ERROR_SAMPLING_RATE,"config");if(n.samplingRate!==void 0&&(typeof n.samplingRate!="number"||n.samplingRate<0||n.samplingRate>1))throw new F(p.INVALID_SAMPLING_RATE,"config");if(n.primaryScrollSelector!==void 0){if(typeof n.primaryScrollSelector!="string"||!n.primaryScrollSelector.trim())throw new m(p.INVALID_PRIMARY_SCROLL_SELECTOR,"config");if(n.primaryScrollSelector!=="window")try{document.querySelector(n.primaryScrollSelector);}catch{throw new m(`${p.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${n.primaryScrollSelector}"`,"config")}}if(n.pageViewThrottleMs!==void 0&&(typeof n.pageViewThrottleMs!="number"||n.pageViewThrottleMs<0))throw new m(p.INVALID_PAGE_VIEW_THROTTLE,"config");if(n.clickThrottleMs!==void 0&&(typeof n.clickThrottleMs!="number"||n.clickThrottleMs<0))throw new m(p.INVALID_CLICK_THROTTLE,"config");if(n.maxSameEventPerMinute!==void 0&&(typeof n.maxSameEventPerMinute!="number"||n.maxSameEventPerMinute<=0))throw new m(p.INVALID_MAX_SAME_EVENT_PER_MINUTE,"config");if(n.sendIntervalMs!==void 0&&(!Number.isFinite(n.sendIntervalMs)||n.sendIntervalMs<1e3||n.sendIntervalMs>6e4))throw new m(p.INVALID_SEND_INTERVAL,"config");if(n.viewport!==void 0&&$r(n.viewport),n.webVitalsMode!==void 0){if(typeof n.webVitalsMode!="string")throw new m(`Invalid webVitalsMode type: ${typeof n.webVitalsMode}. Must be a string`,"config");let e=["all","needs-improvement","poor"];if(!e.includes(n.webVitalsMode))throw new m(`Invalid webVitalsMode: "${n.webVitalsMode}". Must be one of: ${e.join(", ")}`,"config")}if(n.webVitalsThresholds!==void 0){if(typeof n.webVitalsThresholds!="object"||n.webVitalsThresholds===null||Array.isArray(n.webVitalsThresholds))throw new m("webVitalsThresholds must be an object","config");let e=["LCP","FCP","CLS","INP","TTFB","LONG_TASK"];for(let[t,r]of Object.entries(n.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")}}}},$r=n=>{if(typeof n!="object"||n===null)throw new m(p.INVALID_VIEWPORT_CONFIG,"config");if(!n.elements||!Array.isArray(n.elements))throw new m(p.INVALID_VIEWPORT_ELEMENTS,"config");if(n.elements.length===0)throw new m(p.INVALID_VIEWPORT_ELEMENTS,"config");let e=new Set;for(let t of n.elements){if(!t.selector||typeof t.selector!="string"||!t.selector.trim())throw new m(p.INVALID_VIEWPORT_ELEMENT,"config");let 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(p.INVALID_VIEWPORT_ELEMENT_ID,"config");if(t.name!==void 0&&(typeof t.name!="string"||!t.name.trim()))throw new m(p.INVALID_VIEWPORT_ELEMENT_NAME,"config")}if(n.threshold!==void 0&&(typeof n.threshold!="number"||n.threshold<0||n.threshold>1))throw new m(p.INVALID_VIEWPORT_THRESHOLD,"config");if(n.minDwellTime!==void 0&&(typeof n.minDwellTime!="number"||n.minDwellTime<0))throw new m(p.INVALID_VIEWPORT_MIN_DWELL_TIME,"config");if(n.cooldownPeriod!==void 0&&(typeof n.cooldownPeriod!="number"||n.cooldownPeriod<0))throw new m(p.INVALID_VIEWPORT_COOLDOWN_PERIOD,"config");if(n.maxTrackedElements!==void 0&&(typeof n.maxTrackedElements!="number"||n.maxTrackedElements<=0))throw new m(p.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS,"config")},Wr=n=>{if(n){if(n.tracelog&&(!n.tracelog.projectId||typeof n.tracelog.projectId!="string"||n.tracelog.projectId.trim()===""))throw new b(p.INVALID_TRACELOG_PROJECT_ID,"config");if(n.custom){if(!n.custom.collectApiUrl||typeof n.custom.collectApiUrl!="string"||n.custom.collectApiUrl.trim()==="")throw new b(p.INVALID_CUSTOM_API_URL,"config");if(n.custom.allowHttp!==void 0&&typeof n.custom.allowHttp!="boolean")throw new b("allowHttp must be a boolean","config");let e=n.custom.collectApiUrl.trim();if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new b('Custom API URL must start with "http://" or "https://"',"config");if(!(n.custom.allowHttp??false)&&e.startsWith("http://"))throw new b("Custom API URL must use HTTPS in production. Set allowHttp: true in integration config to allow HTTP (not recommended)","config");if(n.custom.fetchCredentials!==void 0&&!["include","same-origin","omit"].includes(n.custom.fetchCredentials))throw new b('fetchCredentials must be "include", "same-origin", or "omit"',"config")}}},Dt=n=>{Fr(n);let e={...n??{},sessionTimeout:n?.sessionTimeout??9e5,globalMetadata:n?.globalMetadata??{},sensitiveQueryParams:n?.sensitiveQueryParams??[],errorSampling:n?.errorSampling??1,samplingRate:n?.samplingRate??1,pageViewThrottleMs:n?.pageViewThrottleMs??1e3,clickThrottleMs:n?.clickThrottleMs??300,maxSameEventPerMinute:n?.maxSameEventPerMinute??60,sendIntervalMs:n?.sendIntervalMs??1e4};return e.integrations?.custom&&(e.integrations.custom={...e.integrations.custom,allowHttp:e.integrations.custom.allowHttp??false}),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};var Ye=(n,e=new Set)=>{if(n==null)return true;let t=typeof n;return t==="string"||t==="number"||t==="boolean"?true:t==="function"||t==="symbol"||t==="bigint"||e.has(n)?false:(e.add(n),Array.isArray(n)?n.every(r=>Ye(r,e)):t==="object"?Object.values(n).every(r=>Ye(r,e)):false)},kt=n=>typeof n!="object"||n===null?false:Ye(n),ae=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e={};for(let[t,r]of Object.entries(n))typeof r=="string"&&(e[t]=r);return Object.keys(e).length>0?e:void 0};var Ut=n=>typeof n!="string"?{valid:false,error:"Event name must be a string"}:n.length===0?{valid:false,error:"Event name cannot be empty"}:n.length>120?{valid:false,error:`Event name is too long (max ${120} characters)`}:n.includes("<")||n.includes(">")||n.includes("&")?{valid:false,error:"Event name contains invalid characters"}:["constructor","prototype","__proto__","eval","function","var","let","const"].includes(n.toLowerCase())?{valid:false,error:"Event name cannot be a reserved word"}:{valid:true},Vt=(n,e,t)=>{let r=xt(e),i=t&&t==="customEvent"?`${t} "${n}" metadata error`:`${n} metadata error`;if(!kt(r))return {valid:false,error:`${i}: object has invalid types. Valid types are string, number, boolean or string arrays.`};let s;try{s=JSON.stringify(r);}catch{return {valid:false,error:`${i}: object contains circular references or cannot be serialized.`}}if(new TextEncoder().encode(s).byteLength>49152)return {valid:false,error:`${i}: object is too large (max ${49152/1024} KB).`};if(Object.keys(r).length>100)return {valid:false,error:`${i}: object has too many keys (max ${100} keys).`};for(let[c,d]of Object.entries(r)){if(Array.isArray(d)){if(d.length>500)return {valid:false,error:`${i}: array property "${c}" is too large (max ${500} items).`};for(let g of d)if(typeof g=="string"&&g.length>500)return {valid:false,error:`${i}: array property "${c}" contains strings that are too long (max ${500} characters).`}}if(typeof d=="string"&&d.length>1e3)return {valid:false,error:`${i}: property "${c}" is too long (max ${1e3} characters).`}}return {valid:true,sanitizedMetadata:r}},le=(n,e,t)=>{if(Array.isArray(e)){let r=[],i=t&&t==="customEvent"?`${t} "${n}" metadata error`:`${n} metadata error`;for(let s=0;s<e.length;s++){let a=e[s];if(typeof a!="object"||a===null||Array.isArray(a))return {valid:false,error:`${i}: array item at index ${s} must be an object.`};let l=Vt(n,a,t);if(!l.valid)return {valid:false,error:`${i}: array item at index ${s} is invalid: ${l.error}`};l.sanitizedMetadata&&r.push(l.sanitizedMetadata);}return {valid:true,sanitizedMetadata:r}}return Vt(n,e,t)};var Ht=(n,e)=>{let t=Ut(n);if(!t.valid)return o("error","Event name validation failed",{data:{eventName:n,error:t.error}}),t;if(!e)return {valid:true};let r=le(n,e,"customEvent");return r.valid||o("error","Event metadata validation failed",{data:{eventName:n,error:r.error}}),r};var ce=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);}off(e,t){let r=this.listeners.get(e);if(r){let i=r.indexOf(t);i>-1&&r.splice(i,1);}}emit(e,t){let r=this.listeners.get(e);r&&r.forEach(i=>{i(t);});}removeAllListeners(){this.listeners.clear();}};function qe(n,e,t){try{let r=e(n);return r===null?null:typeof r=="object"&&r!==null&&"type"in r?r:(o("warn",`beforeSend transformer returned invalid data, using original [${t}]`),n)}catch(r){return o("error",`beforeSend transformer threw error, using original event [${t}]`,{error:r,visibility:"critical"}),n}}function Bt(n,e,t){return n.map(r=>qe(r,e,t)).filter(r=>r!==null)}function de(n,e,t){try{let r=e(n);return r===null?(o("debug",`Batch filtered by beforeBatch transformer [${t}]`,{data:{eventCount:n.events.length}}),null):typeof r=="object"&&r!==null&&Array.isArray(r.events)?r:(o("warn",`beforeBatch transformer returned invalid data, using original [${t}]`,{data:{eventCount:n.events.length}}),n)}catch(r){return o("error",`beforeBatch transformer threw error, using original batch [${t}]`,{error:r,data:{eventCount:n.events.length},visibility:"critical"}),n}}var Je={config:{}};var f=class{get(e){return Je[e]}set(e,t){Je[e]=t;}getState(){return {...Je}}};var Q=class extends f{storeManager;integrationId;apiUrl;transformers;staticHeaders;customHeadersProvider;lastPermanentErrorLog=null;recoveryInProgress=false;lastMetadataTimestamp=0;fetchCredentials;pendingControllers=new Set;consecutiveNetworkFailures=0;circuitOpenedAt=0;constructor(e,t,r,i={},s={},a,l="include"){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=i,this.staticHeaders=s,this.customHeadersProvider=a,this.fetchCredentials=l;}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{let t=this.customHeadersProvider();typeof t=="object"&&t!==null&&!Array.isArray(t)?e=t:o("warn","Custom headers provider returned invalid value, expected object",{data:{received:typeof t}});}catch(t){o("warn","Custom headers provider threw an error, using static headers only",{error:t});}return {...this.staticHeaders,...e}}getQueueStorageKey(){let e=this.get("userId")||"anonymous",t=lt(e);return this.integrationId?`${t}:${this.integrationId}`:t}sendEventsQueueSync(e){return this.shouldSkipSend()?true:this.apiUrl?.includes("localhost:9999")?(o("warn",`Fail mode: simulating network failure (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),false):this.apiUrl?.includes("localhost:8080")?(o("debug",`Success mode: simulating successful send (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),true):this.sendQueueSyncInternal(e)}async sendEventsQueue(e,t){try{let 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 R?(this.logPermanentError("Permanent error, not retrying",r),this.clearPersistedEvents(),t?.onFailure?.(),false):r instanceof A?(o("debug",`All attempts timed out, skipping persistence (server likely received events)${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),t?.onFailure?.(),false):(this.persistEvents(e),t?.onFailure?.(),false)}}async recoverPersistedEvents(e){if(this.recoveryInProgress){o("debug","Recovery already in progress, skipping duplicate attempt");return}this.recoveryInProgress=true;try{let t=this.getPersistedData();if(!t||!this.isDataRecent(t)||t.events.length===0){this.clearPersistedEvents();return}let r=t.recoveryFailures,i=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;if(i>=3){o("debug",`Discarding persisted events after ${i} failed recovery attempts${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),e?.onFailure?.();return}let s=this.createRecoveryBody(t);await this.send(s)?(this.clearPersistedEvents(),e?.onSuccess?.(t.events.length,t.events,s)):(this.persistEventsWithFailureCount(s,i+1,!0),e?.onFailure?.());}catch(t){if(t instanceof R){this.logPermanentError("Permanent error during recovery, clearing persisted events",t),this.clearPersistedEvents(),e?.onFailure?.();return}if(t instanceof A){o("debug",`Recovery timed out, clearing persisted events (server likely received them)${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),e?.onFailure?.();return}o("error","Failed to recover persisted events",{error:t});}finally{this.recoveryInProgress=false;}}stop(){}applyBeforeSendTransformer(e){if(this.integrationId==="saas")return e;let t=this.transformers.beforeSend;if(!t)return e;let r=Bt(e.events,t,this.integrationId||"SenderManager");return r.length===0?null:{...e,events:r}}applyBeforeBatchTransformer(e){if(this.integrationId==="saas")return e;let t=this.transformers.beforeBatch;return t?de(e,t,this.integrationId||"SenderManager"):e}async backoffDelay(e){let t=100*Math.pow(2,e),r=Math.random()*100,i=t+r;return new Promise(s=>setTimeout(s,i))}async send(e){if(this.shouldSkipSend())return this.simulateSuccessfulSend();let t=this.applyBeforeSendTransformer(e);if(!t)return true;let r=this.applyBeforeBatchTransformer(t);if(!r)return true;if(this.apiUrl?.includes("localhost:9999"))return o("debug",`Fail mode: simulating network failure${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),false;if(this.apiUrl?.includes("localhost:8080"))return o("debug",`Success mode: simulating successful send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),true;if(this.consecutiveNetworkFailures>=3){let c=Date.now()-this.circuitOpenedAt;if(c<12e4)return o("debug",`Network circuit open, skipping send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{consecutiveNetworkFailures:this.consecutiveNetworkFailures,cooldownRemainingMs:12e4-c}}),false}let{url:i,payload:s}=this.prepareRequest(r),a=true,l=false;for(let c=1;c<=3;c++)try{return (await this.sendWithTimeout(i,s)).ok?(c>1&&o("info",`Send succeeded after ${c-1} retry attempt(s)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length,attempt:c}}),this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,!0):!1}catch(d){let g=c===3;if(d instanceof R)throw this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,d;if(d instanceof B){this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,a=false,l=true,o("warn",`Rate limited, skipping retries${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length,attempt:c}});break}if(d instanceof A||(a=false),d instanceof TypeError||(l=true),o(g?"error":"warn",`Send attempt ${c} failed${this.integrationId?` [${this.integrationId}]`:""}${g?" (all retries exhausted)":", will retry"}`,{error:d,data:{events:e.events.length,url:i.replace(/\/\/[^/]+/,"//[DOMAIN]"),attempt:c,maxAttempts:3}}),!g){await this.backoffDelay(c);continue}if(a)throw new A("All retry attempts timed out (server likely received the request)");return l?(this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0):(this.consecutiveNetworkFailures=Math.min(this.consecutiveNetworkFailures+1,3),this.consecutiveNetworkFailures>=3&&(this.circuitOpenedAt=Date.now())),false}return false}async sendWithTimeout(e,t){let r=new AbortController;this.pendingControllers.add(r);let i=false,s=setTimeout(()=>{i=true,r.abort();},15e3);try{let a=this.getCustomHeaders(),l=await fetch(e,{method:"POST",body:t,keepalive:!0,credentials:this.fetchCredentials,signal:r.signal,headers:{...a,"Content-Type":"application/json"}});if(!l.ok)throw l.status>=400&&l.status<500&&l.status!==408&&l.status!==429?new R(`HTTP ${l.status}: ${l.statusText}`,l.status):l.status===429?new B(`HTTP 429: ${l.statusText}`):new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(a){throw a instanceof R?a:i?new A("Request timed out (server likely received the request)"):a}finally{clearTimeout(s),this.pendingControllers.delete(r);}}sendQueueSyncInternal(e){let t=this.applyBeforeSendTransformer(e);if(!t)return true;let r=this.applyBeforeBatchTransformer(t);if(!r)return true;let{url:i,payload:s}=this.prepareRequest(r);if(s.length>65536)return o("warn",`Payload exceeds sendBeacon limit, persisting for recovery${this.integrationId?` [${this.integrationId}]`:""}`,{data:{size:s.length,limit:65536,events:r.events.length}}),this.persistEvents(r),false;let a=new Blob([s],{type:"application/json"});if(!this.isSendBeaconAvailable())return o("warn",`sendBeacon not available, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(r),false;let l=navigator.sendBeacon(i,a);return l||(o("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;let r={...e,_metadata:{referer:typeof window<"u"?window.location.href:void 0,timestamp:t,client_version:wt}};return {url:this.apiUrl||"",payload:JSON.stringify(r)}}getPersistedData(){try{let e=this.getQueueStorageKey(),t=this.storeManager.getItem(e);if(t)return JSON.parse(t)}catch(e){o("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"?false:(Date.now()-e.timestamp)/(1e3*60*60)<2}createRecoveryBody(e){let{timestamp:t,recoveryFailures:r,...i}=e;return i}persistEvents(e){return this.persistEventsWithFailureCount(e,0)}persistEventsWithFailureCount(e,t,r=false){try{let i=this.getPersistedData();if(!r&&i&&i.timestamp){let l=Date.now()-i.timestamp;if(l<1e3)return o("debug",`Skipping persistence, another tab recently persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{data:{timeSinceExisting:l}}),!0}let s={...e,timestamp:Date.now(),...t>0&&{recoveryFailures:t}},a=this.getQueueStorageKey();return this.storeManager.setItem(a,JSON.stringify(s)),!!this.storeManager.getItem(a)}catch(i){return o("debug",`Failed to persist events${this.integrationId?` [${this.integrationId}]`:""}`,{error:i}),false}}clearPersistedEvents(){try{let e=this.getQueueStorageKey();this.storeManager.removeItem(e);}catch(e){o("debug",`Failed to clear persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{error:e});}}shouldSkipSend(){return !this.apiUrl}async simulateSuccessfulSend(){let e=Math.random()*400+100;return await new Promise(t=>setTimeout(t,e)),true}isSendBeaconAvailable(){return typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}logPermanentError(e,t){let r=Date.now();(!this.lastPermanentErrorLog||this.lastPermanentErrorLog.statusCode!==t.statusCode||r-this.lastPermanentErrorLog.timestamp>=6e4)&&(o("error",`${e}${this.integrationId?` [${this.integrationId}]`:""}`,{data:{status:t.statusCode,message:t.message}}),this.lastPermanentErrorLog={statusCode:t.statusCode,timestamp:r});}};var ue=class extends f{bootTime;bootTimestamp;hasPerformanceNow;lastClockSkewCheck=0;detectedSkew=0;constructor(){if(super(),typeof window>"u"){this.hasPerformanceNow=false,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(),o("debug","TimeManager initialized with monotonic clock",{data:{bootTime:this.bootTime.toFixed(3),bootTimestamp:this.bootTimestamp}})):(this.bootTime=0,this.bootTimestamp=Date.now(),o("debug","performance.now() not available, falling back to Date.now()"));}now(){if(!this.hasPerformanceNow)return Date.now();let e=performance.now()-this.bootTime;return Math.round(this.bootTimestamp+e)}getClockSkew(){if(!this.hasPerformanceNow)return 0;let e=Date.now();if(e-this.lastClockSkewCheck<5e3)return this.detectedSkew;this.lastClockSkewCheck=e;let t=this.now(),r=Date.now();return this.detectedSkew=r-t,Math.abs(this.detectedSkew)>3e4&&o("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){let r=this.now(),i=e-r;return i>12e4?{valid:false,error:`Timestamp is ${(i/1e3/60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`}:{valid:true}}getBootInfo(){return {bootTime:this.bootTime,bootTimestamp:this.bootTimestamp,hasPerformanceNow:this.hasPerformanceNow,clockSkew:this.getClockSkew()}}};var ln=new Set(Object.values(y)),me=class extends f{dataSenders;emitter;transformers;timeManager;recentEventFingerprints=new Map;perEventRateLimits=new Map;eventsQueue=[];pendingEventsBuffer=[];sendTimeoutId=null;sendInProgress=false;consecutiveSendFailures=0;rateLimitCounter=0;rateLimitWindowStart=0;lastSessionId=null;sessionEventCounts={total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0};saveSessionCountsDebounced=null;constructor(e,t=null,r={},i={},s,a="include"){super(),this.emitter=t,this.transformers=r,this.timeManager=new ue,this.dataSenders=[];let l=this.get("collectApiUrls");l?.saas&&this.dataSenders.push(new Q(e,"saas",l.saas,r)),l?.custom&&this.dataSenders.push(new Q(e,"custom",l.custom,r,i,s,a)),this.saveSessionCountsDebounced=this.debounce(c=>{this.saveSessionCounts(c);},500),this.cleanupExpiredSessionCounts();}async recoverPersistedEvents(){let e=this.dataSenders.map(async t=>t.recoverPersistedEvents({onSuccess:(r,i,s)=>{if(i&&i.length>0){let a=i.map(l=>l.id);this.removeProcessedEvents(a),s&&this.emitEventsQueue(s);}},onFailure:()=>{o("debug","Failed to recover persisted events");}}));await Promise.allSettled(e);}track({type:e,page_url:t,from_page_url:r,scroll_data:i,click_data:s,custom_event:a,web_vitals:l,error_data:c,viewport_data:d,page_view:g}){if(!e){o("error","Event type is required - event will be ignored");return}if(!ln.has(e)){o("error","Invalid event type - event will be ignored",{data:{type:e}});return}let E=this.get("sessionId");if(!E){this.pendingEventsBuffer.length>=100&&(this.pendingEventsBuffer.shift(),o("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:i,click_data:s,custom_event:a,web_vitals:l,error_data:c,viewport_data:d,page_view:g});return}this.lastSessionId!==E&&(this.lastSessionId=E,this.sessionEventCounts=this.loadSessionCounts(E));let T=e==="session_start";if(T&&o("debug","Processing SESSION_START event",{data:{sessionId:E}}),!T&&!this.checkRateLimit())return;let h=e;if(!T){if(this.sessionEventCounts.total>=1e3){o("warn","Session event limit reached",{data:{type:h,total:this.sessionEventCounts.total,limit:1e3}});return}let _=this.getTypeLimitForEvent(h);if(_){let Me=this.sessionEventCounts[h];if(Me!==void 0&&Me>=_){o("warn","Session event type limit reached",{data:{type:h,count:Me,limit:_}});return}}}if(h==="custom"&&a?.name){let _=this.get("config")?.maxSameEventPerMinute??60;if(!this.checkPerEventRateLimit(a.name,_))return}let nt=h==="session_start",G=t||this.get("pageUrl"),U=this.buildEventPayload({type:h,page_url:G,from_page_url:r,scroll_data:i,click_data:s,custom_event:a,web_vitals:l,error_data:c,viewport_data:d,page_view:g});if(U&&!(!T&&!this.shouldSample())){if(nt){let _=this.get("sessionId");if(!_){o("error","Session start event requires sessionId - event will be ignored");return}if(this.get("hasStartSession")){o("debug","Duplicate session_start detected",{data:{sessionId:_}});return}this.set("hasStartSession",true);}if(!this.isDuplicateEvent(U)){if(this.get("mode")==="qa"){if(h==="custom"&&a){o("info",`Custom Event: ${a.name}`,{visibility:"qa",data:{name:a.name,...a.metadata&&{metadata:a.metadata}}}),this.emitEvent(U);return}if(h==="viewport_visible"&&d){let _=d.name||d.id||d.selector;o("info",`Viewport Visible: ${_}`,{visibility:"qa",data:{selector:d.selector,...d.name&&{name:d.name},...d.id&&{id:d.id},visibilityRatio:d.visibilityRatio,dwellTime:d.dwellTime}}),this.emitEvent(U);return}}if(this.addToQueue(U),!T){this.sessionEventCounts.total++,this.sessionEventCounts[h]!==void 0&&this.sessionEventCounts[h]++;let _=this.get("sessionId");_&&this.saveSessionCountsDebounced&&this.saveSessionCountsDebounced(_);}}}}stop(){this.clearSendTimeout(),this.sendInProgress=false,this.consecutiveSendFailures=0;let 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,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0},this.lastSessionId=null,this.set("hasStartSession",false),this.dataSenders.forEach(t=>{t.stop();});}async flushImmediately(){return this.flushEvents(false)}flushImmediatelySync(){return this.flushEvents(true)}setCustomHeadersProvider(e){for(let t of this.dataSenders)t.getIntegrationId()==="custom"&&t.setCustomHeadersProvider(e);}removeCustomHeadersProvider(){for(let 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")){o("debug","Cannot flush pending events: session not initialized - keeping in buffer",{data:{bufferedEventCount:this.pendingEventsBuffer.length}});return}let t=[...this.pendingEventsBuffer];this.pendingEventsBuffer=[],t.forEach(r=>{this.track(r);});}clearSendTimeout(){this.sendTimeoutId!==null&&(clearTimeout(this.sendTimeoutId),this.sendTimeoutId=null);}isSuccessfulResult(e){return e.status==="fulfilled"&&e.value===true}flushEvents(e){if(this.eventsQueue.length===0)return e?true:Promise.resolve(true);if(!e&&this.sendInProgress)return o("debug","Async flush skipped: send already in progress"),Promise.resolve(false);let t=this.buildEventsPayload(),r=[...this.eventsQueue],i=r.map(s=>s.id);if(this.dataSenders.length===0)return this.removeProcessedEvents(i),this.clearSendTimeout(),this.emitEventsQueue(t),e?true:Promise.resolve(true);if(e){let a=this.dataSenders.map(l=>l.sendEventsQueueSync(t)).some(l=>l);return a?(this.removeProcessedEvents(i),this.clearSendTimeout(),this.emitEventsQueue(t)):(this.clearSendTimeout(),o("debug","Sync flush complete failure, events kept in queue for retry",{data:{eventCount:i.length}})),a}else {let s=this.dataSenders.map(async a=>a.sendEventsQueue(t,{onSuccess:()=>{},onFailure:()=>{}}));return Promise.allSettled(s).then(a=>{let l=a.some(c=>this.isSuccessfulResult(c));return l?(this.removeProcessedEvents(i),this.clearSendTimeout(),this.emitEventsQueue(t)):o("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||this.sendInProgress)){this.sendInProgress=true;try{let e=this.buildEventsPayload();if(this.dataSenders.length===0){this.emitEventsQueue(e);return}let t=[...this.eventsQueue],r=t.map(l=>l.id),i=this.dataSenders.map(async l=>l.sendEventsQueue(e,{onSuccess:()=>{},onFailure:()=>{}})),s=await Promise.allSettled(i);if(s.some(l=>this.isSuccessfulResult(l))){this.consecutiveSendFailures=0,this.removeProcessedEvents(r),this.emitEventsQueue(e);let l=s.filter(c=>!this.isSuccessfulResult(c)).length;l>0&&o("debug","Periodic send completed with some failures, removed from queue and persisted per-integration",{data:{eventCount:t.length,failedCount:l}});}else this.consecutiveSendFailures=Math.min(this.consecutiveSendFailures+1,5),o("debug","Periodic send complete failure, events kept in queue for retry",{data:{eventCount:t.length}});this.eventsQueue.length===0?this.clearSendTimeout():this.scheduleSendTimeout();}finally{this.sendInProgress=false;}}}buildEventsPayload(){let e=new Map,t=[];for(let c of this.eventsQueue){let d=this.createEventSignature(c);e.has(d)||t.push(d),e.set(d,c);}let r=t.map(c=>e.get(c)).filter(c=>!!c).sort((c,d)=>c.type==="session_start"&&d.type!=="session_start"?-1:d.type==="session_start"&&c.type!=="session_start"?1:c.timestamp-d.timestamp),i={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},...this.get("identity")&&{identify:this.get("identity")}},s=this.get("collectApiUrls"),a=!!(s?.custom||s?.saas),l=this.transformers.beforeBatch;if(!a&&l){let c=de(i,l,"EventManager");c!==null&&(i=c);}return i}buildEventPayload(e){let t=e.page_url??this.get("pageUrl"),r=this.timeManager.now(),i=this.timeManager.validateTimestamp(r);i.valid||o("warn","Event timestamp validation failed",{data:{type:e.type,error:i.error}});let s=this.get("sessionReferrer"),a=this.get("sessionUtm"),l={id:Ct(),type:e.type,page_url:t,timestamp:r,...s&&{referrer:s},...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},...a&&{utm:a}},c=this.get("collectApiUrls"),d=!!c?.custom,g=!!c?.saas,E=d||g,T=d&&g,h=this.transformers.beforeSend;if(h&&(!E||d&&!T)){let G=qe(l,h,"EventManager");if(G===null)return null;l=G;}return l}isDuplicateEvent(e){let t=Date.now(),r=this.createEventFingerprint(e),i=this.recentEventFingerprints.get(r);return i&&t-i<1e3?(this.recentEventFingerprints.set(r,t),true):(this.recentEventFingerprints.set(r,t),this.recentEventFingerprints.size>1500&&this.pruneOldFingerprints(),this.recentEventFingerprints.size>3e3&&(this.recentEventFingerprints.clear(),this.recentEventFingerprints.set(r,t),o("debug","Event fingerprint cache exceeded hard limit, cleared",{data:{hardLimit:3e3}})),false)}pruneOldFingerprints(){let e=Date.now(),t=1e3*10;for(let[r,i]of this.recentEventFingerprints.entries())e-i>t&&this.recentEventFingerprints.delete(r);o("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){let r=Math.round((e.click_data.x||0)/10)*10,i=Math.round((e.click_data.y||0)/10)*10;t+=`_click_${r}_${i}`;}return e.scroll_data&&(t+=`_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`),e.custom_event&&(t+=`_custom_${e.custom_event.name}`,e.custom_event.metadata&&(t+=`_${this.stableStringify(e.custom_event.metadata)}`)),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)}stableStringify(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((i,s)=>(i[s]=r[s],i),{}):r)}addToQueue(e){if(this.emitEvent(e),this.eventsQueue.push(e),this.eventsQueue.length>100){let t=this.eventsQueue.findIndex(i=>i.type!=="session_start"),r=t>=0?this.eventsQueue.splice(t,1)[0]:this.eventsQueue.shift();o("warn","Event queue overflow, oldest non-critical event removed",{data:{maxLength:100,currentLength:this.eventsQueue.length,removedEventType:r?.type,wasCritical:r?.type==="session_start"}});}this.scheduleSendTimeout(),this.eventsQueue.length>=50&&this.consecutiveSendFailures<5&&this.sendEventsQueue();}scheduleSendTimeout(){if(this.sendTimeoutId!==null)return;let e=this.calculateSendDelay();this.sendTimeoutId=window.setTimeout(()=>{this.sendTimeoutId=null,this.eventsQueue.length>0&&this.sendEventsQueue();},e);}calculateSendDelay(){let e=this.get("config")?.sendIntervalMs??1e4;if(this.consecutiveSendFailures===0)return e;let t=e*Math.pow(2,this.consecutiveSendFailures);return Math.min(t,12e4)}shouldSample(){let e=this.get("config")?.samplingRate??1;return Math.random()<e}checkRateLimit(){let e=Date.now();return e-this.rateLimitWindowStart>1e3&&(this.rateLimitCounter=0,this.rateLimitWindowStart=e),this.rateLimitCounter>=50?false:(this.rateLimitCounter++,true)}checkPerEventRateLimit(e,t){let r=Date.now(),s=(this.perEventRateLimits.get(e)??[]).filter(a=>r-a<6e4);return s.length>=t?(o("warn","Per-event rate limit exceeded for custom event",{data:{eventName:e,limit:t,window:`${6e4/1e3}s`}}),false):(s.push(r),this.perEventRateLimits.set(e,s),true)}getTypeLimitForEvent(e){return {click:500,page_view:100,custom:500,viewport_visible:200,scroll:120}[e]??null}removeProcessedEvents(e){let t=new Set(e);this.eventsQueue=this.eventsQueue.filter(r=>!t.has(r.id));}emitEvent(e){this.emitter&&this.emitter.emit("event",e);}emitEventsQueue(e){this.emitter&&this.emitter.emit("queue",e);}debounce(e,t){let r=null;return((...i)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...i),r=null;},t);})}getInitialCounts(){return {total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0}}loadSessionCounts(e){if(typeof window>"u"||typeof localStorage>"u")return this.getInitialCounts();let t=this.get("userId")||"anonymous",r=Oe(t,e);try{let i=localStorage.getItem(r);if(!i)return this.getInitialCounts();let s=JSON.parse(i);return s._timestamp&&Date.now()-s._timestamp>Pe?(o("debug","Session counts expired, clearing",{data:{sessionId:e,age:Date.now()-s._timestamp}}),localStorage.removeItem(r),this.getInitialCounts()):typeof s.total=="number"&&typeof s.click=="number"&&typeof s.page_view=="number"&&typeof s.custom=="number"&&typeof s.viewport_visible=="number"&&typeof s.scroll=="number"?{total:s.total,click:s.click,page_view:s.page_view,custom:s.custom,viewport_visible:s.viewport_visible,scroll:s.scroll}:(o("warn","Invalid session counts structure in localStorage, resetting",{data:{sessionId:e,parsed:s}}),localStorage.removeItem(r),o("debug","Session counts removed due to invalid/corrupted data",{data:{sessionId:e,parsed:s}}),this.getInitialCounts())}catch(i){return o("warn","Failed to load session counts from localStorage",{error:i,data:{sessionId:e}}),this.getInitialCounts()}}cleanupExpiredSessionCounts(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(xe);if(e){let s=Date.now()-parseInt(e,10);if(s<De){o("debug","Skipping session counts cleanup (throttled)",{data:{timeSinceLastCleanup:s,throttleMs:De}});return}}let t=this.get("userId")||"anonymous",r=`${v}:${t}:session_counts:`,i=[];for(let s=0;s<localStorage.length;s++){let a=localStorage.key(s);if(a?.startsWith(r))try{let l=localStorage.getItem(a);if(l){let c=JSON.parse(l);c._timestamp&&Date.now()-c._timestamp>Pe&&i.push(a);}}catch{}}i.forEach(s=>{localStorage.removeItem(s),o("debug","Cleaned up expired session counts",{data:{key:s}});}),i.length>0&&o("info",`Cleaned up ${i.length} expired session counts entries`),localStorage.setItem(xe,Date.now().toString());}catch(e){o("warn","Failed to cleanup expired session counts",{error:e});}}saveSessionCounts(e){let t=this.get("userId")||"anonymous",r=Oe(t,e);try{let i={...this.sessionEventCounts,_timestamp:Date.now(),_version:1};localStorage.setItem(r,JSON.stringify(i));}catch(i){o("warn","Failed to persist session counts to localStorage",{error:i,data:{sessionId:e}});}}};var pe=class{static getId(e){let t=e.getItem(H);if(t)return t;let r=oe();return e.setItem(H,r),r}};var cn=/^\d{13}-[a-z0-9]{9}$/,ge=class extends f{storageManager;eventManager;projectId;activityHandler=null;visibilityChangeHandler=null;sessionTimeoutId=null;broadcastChannel=null;isTracking=false;needsRenewal=false;constructor(e,t,r){super(),this.storageManager=e,this.eventManager=t,this.projectId=r;}initCrossTabSync(){if(typeof BroadcastChannel>"u"){o("debug","BroadcastChannel not supported");return}let e=this.getProjectId();this.broadcastChannel=new BroadcastChannel(dt(e)),this.broadcastChannel.onmessage=t=>{let{action:r,sessionId:i,timestamp:s,projectId:a}=t.data??{};a===e&&(r==="session_start"&&i&&typeof s=="number"&&s>Date.now()-5e3?(this.set("sessionId",i),this.persistSession(i,s),this.isTracking&&this.setupSessionTimeout()):r&&r!=="session_start"&&o("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(){let e=this.loadStoredSession();if(!e)return null;if(!cn.test(e.id))return o("warn","Invalid session ID format recovered from storage, clearing",{data:{sessionId:e.id}}),this.clearStoredSession(),null;let t=this.get("config")?.sessionTimeout??9e5;return Date.now()-e.lastActivity>t?(this.clearStoredSession(),null):e.id}persistSession(e,t=Date.now(),r,i){this.saveStoredSession({id:e,lastActivity:t,...r&&{referrer:r},...i&&{utm:i}});}clearStoredSession(){let e=this.getSessionStorageKey();this.storageManager.removeItem(e);}loadStoredSession(){let e=this.getSessionStorageKey(),t=this.storageManager.getItem(e);if(t!==null)try{let i=JSON.parse(t);if(i.id&&typeof i.lastActivity=="number")return i}catch{this.storageManager.removeItem(e);}let r=this.storageManager.getSessionItem(e);if(r!==null)try{let i=JSON.parse(r);if(i.id&&typeof i.lastActivity=="number")return i}catch{this.storageManager.removeSessionItem(e);}return null}saveStoredSession(e){let t=this.getSessionStorageKey(),r=JSON.stringify(e);this.storageManager.setItem(t,r),this.storageManager.setSessionItem(t,r);}getSessionStorageKey(){return ct(this.getProjectId())}getProjectId(){return this.projectId}startTracking(){if(this.isTracking){o("debug","Session tracking already active");return}let e=this.recoverSession(),t=e??this.generateSessionId(),r,i;if(e){let s=this.loadStoredSession();r=s?.referrer??re(),i=s?.utm??ne();}else r=re(),i=ne();o("debug","Session tracking initialized",{data:{sessionId:t,wasRecovered:!!e,willEmitSessionStart:!e,sessionReferrer:r,hasUtm:!!i}}),this.isTracking=true;try{this.set("sessionId",t),this.set("sessionReferrer",r),this.set("sessionUtm",i),this.persistSession(t,Date.now(),r,i),this.initCrossTabSync(),this.shareSession(t),e?o("debug","Session recovered, skipping SESSION_START",{data:{sessionId:t}}):(o("debug","Emitting SESSION_START event",{data:{sessionId:t}}),this.eventManager.track({type:"session_start"})),this.setupSessionTimeout(),this.setupActivityListeners(),this.setupLifecycleListeners();}catch(s){throw this.isTracking=false,this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.set("sessionId",null),s}}generateSessionId(){return `${Date.now()}-${Math.random().toString(36).substring(2,11)}`}setupSessionTimeout(){this.clearSessionTimeout();let e=this.get("config")?.sessionTimeout??9e5;this.sessionTimeoutId=setTimeout(()=>{this.enterRenewalMode();},e);}resetSessionTimeout(){this.setupSessionTimeout();let 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:true}),document.addEventListener("keydown",this.activityHandler,{passive:true}),document.addEventListener("scroll",this.activityHandler,{passive:true});}renewSession(){this.needsRenewal=false;let e=this.generateSessionId(),t=re(),r=ne();o("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:"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()){o("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 false;let t=this.loadStoredSession();if(!t)return false;let 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",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=true,o("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",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=false,this.isTracking=false;}stopTracking(){this.resetSessionState();}destroy(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupCrossTabSync(),this.cleanupLifecycleListeners(),this.isTracking=false,this.needsRenewal=false,this.set("hasStartSession",false);}};var he=class extends f{eventManager;storageManager;sessionManager=null;destroyed=false;constructor(e,t){super(),this.eventManager=t,this.storageManager=e;}startTracking(){if(this.isActive())return;if(this.destroyed){o("debug","Cannot start tracking on destroyed handler");return}let t=this.get("config")?.integrations?.tracelog?.projectId??"custom";try{this.sessionManager=new ge(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 o("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=true);}};var Ee=class extends f{eventManager;onTrack;originalPushState;originalReplaceState;lastPageViewTime=0;constructor(e,t){super(),this.eventManager=e,this.onTrack=t;}startTracking(){this.trackInitialPageView(),window.addEventListener("popstate",this.trackCurrentPage,true),window.addEventListener("hashchange",this.trackCurrentPage,true),this.patchHistory("pushState"),this.patchHistory("replaceState");}stopTracking(){window.removeEventListener("popstate",this.trackCurrentPage,true),window.removeEventListener("hashchange",this.trackCurrentPage,true),this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.lastPageViewTime=0;}patchHistory(e){let 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=()=>{let e=window.location.href,t=j(e,this.get("config").sensitiveQueryParams);if(this.get("pageUrl")===t)return;let r=Date.now(),i=this.get("config").pageViewThrottleMs??1e3;if(r-this.lastPageViewTime<i)return;this.lastPageViewTime=r,this.onTrack();let s=this.get("pageUrl");this.set("pageUrl",t);let a=this.extractPageViewData();this.eventManager.track({type:"page_view",page_url:this.get("pageUrl"),from_page_url:s,...a&&{page_view:a}});};trackInitialPageView(){let e=j(window.location.href,this.get("config").sensitiveQueryParams),t=this.extractPageViewData();this.lastPageViewTime=Date.now(),this.eventManager.track({type:"page_view",page_url:e,...t&&{page_view:t}}),this.onTrack();}extractPageViewData(){let{pathname:e,search:t,hash:r}=window.location,{referrer:i}=document,{title:s}=document;return !i&&!s&&!e&&!t&&!r?void 0:{...i&&{referrer:i},...s&&{title:s},...e&&{pathname:e},...t&&{search:t},...r&&{hash:r}}}};var ve=class extends f{eventManager;lastClickTimes=new Map;clickHandler;lastPruneTime=0;constructor(e){super(),this.eventManager=e;}startTracking(){this.clickHandler||(this.clickHandler=e=>{let t=e,r=t.target,i=typeof HTMLElement<"u"&&r instanceof HTMLElement?r:typeof HTMLElement<"u"&&r instanceof Node&&r.parentElement instanceof HTMLElement?r.parentElement:null;if(!i){o("debug","Click target not found or not an element");return}if(this.shouldIgnoreElement(i))return;let s=this.get("config")?.clickThrottleMs??300;if(s>0&&!this.checkClickThrottle(i,s))return;let a=this.findTrackingElement(i),l=this.getRelevantClickElement(i),c=this.calculateClickCoordinates(t,i);if(a){let g=this.extractTrackingData(a);if(g){let E=this.createCustomEventData(g);this.eventManager.track({type:"custom",custom_event:{name:E.name,...E.value&&{metadata:{value:E.value}}}});}}let d=this.generateClickData(i,l,c);this.eventManager.track({type:"click",click_data:d});},window.addEventListener("click",this.clickHandler,true));}stopTracking(){this.clickHandler&&(window.removeEventListener("click",this.clickHandler,true),this.clickHandler=void 0),this.lastClickTimes.clear(),this.lastPruneTime=0;}shouldIgnoreElement(e){return e.hasAttribute(`${I}-ignore`)?true:e.closest(`[${I}-ignore]`)!==null}checkClickThrottle(e,t){let r=this.getElementSignature(e),i=Date.now();this.pruneThrottleCache(i);let s=this.lastClickTimes.get(r);return s!==void 0&&i-s<t?(o("debug","ClickHandler: Click suppressed by throttle",{data:{signature:r,throttleRemaining:t-(i-s)}}),false):(this.lastClickTimes.set(r,i),true)}pruneThrottleCache(e){if(e-this.lastPruneTime<3e4)return;this.lastPruneTime=e;let t=e-3e5;for(let[r,i]of this.lastClickTimes.entries())i<t&&this.lastClickTimes.delete(r);if(this.lastClickTimes.size>1e3){let r=Array.from(this.lastClickTimes.entries()).sort((a,l)=>a[1]-l[1]),i=this.lastClickTimes.size-1e3,s=r.slice(0,i);for(let[a]of s)this.lastClickTimes.delete(a);o("debug","ClickHandler: Pruned throttle cache",{data:{removed:s.length,remaining:this.lastClickTimes.size}});}}getElementSignature(e){if(e.id)return `#${e.id}`;let t=e.getAttribute("data-testid");if(t)return `[data-testid="${t}"]`;let r=e.getAttribute(`${I}-name`);return r?`[${I}-name="${r}"]`:this.getElementPath(e)}getElementPath(e){let t=[],r=e;for(;r&&r!==document.body;){let i=r.tagName.toLowerCase();if(r.className){let s=r.className.split(" ")[0];s&&(i+=`.${s}`);}t.unshift(i),r=r.parentElement;}return t.join(">")||"unknown"}findTrackingElement(e){return e.hasAttribute(`${I}-name`)?e:e.closest(`[${I}-name]`)}getRelevantClickElement(e){for(let t of it)try{if(e.matches(t))return e;let r=e.closest(t);if(r)return r}catch(r){o("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){let r=t.getBoundingClientRect(),i=e.clientX,s=e.clientY,a=r.width>0?this.clamp((i-r.left)/r.width):0,l=r.height>0?this.clamp((s-r.top)/r.height):0;return {x:i,y:s,relativeX:a,relativeY:l}}extractTrackingData(e){let t=e.getAttribute(`${I}-name`),r=e.getAttribute(`${I}-value`);if(t)return {element:e,name:t,...r&&{value:r}}}generateClickData(e,t,r){let{x:i,y:s,relativeX:a,relativeY:l}=r,c=this.getRelevantText(e,t),d=this.extractElementAttributes(t);return {x:i,y:s,relativeX:a,relativeY:l,tag:t.tagName.toLowerCase(),...t.id&&{id:t.id},...t.className&&{class:t.className},...c&&{text:c},...d.href&&{href:d.href},...d.title&&{title:d.title},...d.alt&&{alt:d.alt},...d.role&&{role:d.role},...d["aria-label"]&&{ariaLabel:d["aria-label"]},...Object.keys(d).length>0&&{dataAttributes:d}}}sanitizeText(e){let t=e;for(let r of $){let i=new RegExp(r.source,r.flags);t=t.replace(i,"[REDACTED]");}return t}getRelevantText(e,t){let r=e.textContent?.trim()??"",i=t.textContent?.trim()??"";if(!r&&!i)return "";let s="";return r&&r.length<=255?s=r:i.length<=255?s=i:s=i.slice(0,252)+"...",this.sanitizeText(s)}extractElementAttributes(e){let t=["id","class","data-testid","aria-label","title","href","type","name","alt","role"],r={};for(let i of t){let s=e.getAttribute(i);s&&(r[i]=s);}return r}createCustomEventData(e){return {name:e.name,...e.value&&{value:e.value}}}};var Te=class extends f{eventManager;containers=[];limitWarningLogged=false;minDepthChange=5;minIntervalMs=500;maxEventsPerSession=120;containerDiscoveryTimeoutId=null;constructor(e){super(),this.eventManager=e;}startTracking(){this.limitWarningLogged=false,this.applyConfigOverrides(),this.set("scrollEventCount",0),this.tryDetectScrollContainers(0);}stopTracking(){this.containerDiscoveryTimeoutId!==null&&(clearTimeout(this.containerDiscoveryTimeoutId),this.containerDiscoveryTimeoutId=null);for(let 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=false;}tryDetectScrollContainers(e){let t=this.findScrollableElements();if(this.isWindowScrollable()&&this.setupScrollContainer(window,"window"),t.length>0){for(let r of t){let i=this.getElementSelector(r);this.setupScrollContainer(r,i);}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(){let e=this.get("config");e?.primaryScrollSelector&&this.applyPrimaryScrollSelector(e.primaryScrollSelector);}findScrollableElements(){if(!document.body)return [];let e=[],t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{let s=i;if(!s.isConnected||!s.offsetParent)return NodeFilter.FILTER_SKIP;let a=getComputedStyle(s);return a.overflowY==="auto"||a.overflowY==="scroll"||a.overflow==="auto"||a.overflow==="scroll"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),r;for(;(r=t.nextNode())&&e.length<10;){let i=r;this.isElementScrollable(i)&&e.push(i);}return e}getElementSelector(e){if(e===window)return "window";let t=e;if(t.id)return `#${t.id}`;if(t.className&&typeof t.className=="string"){let r=t.className.split(" ").filter(i=>i.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(d=>d.element===e)||e!==window&&!this.isElementScrollable(e))return;let i=this.getScrollTop(e),s=this.calculateScrollDepth(i,this.getScrollHeight(e),this.getViewportHeight(e)),a=this.determineIfPrimary(e),l={element:e,selector:t,isPrimary:a,lastScrollPos:i,lastDepth:s,lastDirection:"down",lastEventTime:0,firstScrollEventTime:null,maxDepthReached:s,debounceTimer:null,listener:null},c=()=>{this.get("suppressNextScroll")||(l.firstScrollEventTime===null&&(l.firstScrollEventTime=Date.now()),this.clearContainerTimer(l),l.debounceTimer=window.setTimeout(()=>{let d=this.calculateScrollData(l);if(d){let g=Date.now();this.processScrollEvent(l,d,g);}l.debounceTimer=null;},250));};l.listener=c,this.containers.push(l),e===window?window.addEventListener("scroll",c,{passive:true}):e.addEventListener("scroll",c,{passive:true});}processScrollEvent(e,t,r){if(!this.shouldEmitScrollEvent(e,t,r))return;e.lastEventTime=r,e.lastDepth=t.depth,e.lastDirection=t.direction;let i=this.get("scrollEventCount")??0;this.set("scrollEventCount",i+1),this.eventManager.track({type:"scroll",scroll_data:{...t,container_selector:e.selector,is_primary:e.isPrimary}});}shouldEmitScrollEvent(e,t,r){return this.hasReachedSessionLimit()?(this.logLimitOnce(),false):!(!this.hasElapsedMinimumInterval(e,r)||!this.hasSignificantDepthChange(e,t.depth))}hasReachedSessionLimit(){return (this.get("scrollEventCount")??0)>=this.maxEventsPerSession}hasElapsedMinimumInterval(e,t){return e.lastEventTime===0?true:t-e.lastEventTime>=this.minIntervalMs}hasSignificantDepthChange(e,t){return Math.abs(t-e.lastDepth)>=this.minDepthChange}logLimitOnce(){this.limitWarningLogged||(this.limitWarningLogged=true,o("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;let i=t-r;return Math.min(100,Math.max(0,Math.floor(e/i*100)))}calculateScrollData(e){let{element:t,lastScrollPos:r,lastEventTime:i}=e,s=this.getScrollTop(t),a=Date.now(),l=Math.abs(s-r);if(l<10||t===window&&!this.isWindowScrollable())return null;let c=this.getViewportHeight(t),d=this.getScrollHeight(t),g=this.getScrollDirection(s,r),E=this.calculateScrollDepth(s,d,c),T;i>0?T=a-i:e.firstScrollEventTime!==null?T=a-e.firstScrollEventTime:T=250;let h=Math.round(l/T*1e3);return E>e.maxDepthReached&&(e.maxDepthReached=E),e.lastScrollPos=s,{depth:E,direction:g,velocity:h,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){let t=getComputedStyle(e),r=t.overflowY==="auto"||t.overflowY==="scroll"||t.overflow==="auto"||t.overflow==="scroll",i=e.scrollHeight>e.clientHeight;return r&&i}applyPrimaryScrollSelector(e){let t;if(e==="window")t=window;else {let i=document.querySelector(e);if(!(i instanceof HTMLElement)){o("debug",`Selector "${e}" did not match an HTMLElement`);return}t=i;}this.containers.forEach(i=>{this.updateContainerPrimary(i,i.element===t);}),!this.containers.some(i=>i.element===t)&&t instanceof HTMLElement&&this.isElementScrollable(t)&&this.setupScrollContainer(t,e);}updateContainerPrimary(e,t){e.isPrimary=t;}};var _e=class extends f{eventManager;trackedElements=new Map;observer=null;mutationObserver=null;mutationDebounceTimer=null;config=null;constructor(e){super(),this.eventManager=e;}startTracking(){let e=this.get("config");if(this.config=e.viewport??null,!this.config?.elements||this.config.elements.length===0)return;let t=this.config.threshold??.5,r=this.config.minDwellTime??1e3;if(t<0||t>1){o("debug","ViewportHandler: Invalid threshold, must be between 0 and 1");return}if(r<0){o("debug","ViewportHandler: Invalid minDwellTime, must be non-negative");return}if(typeof IntersectionObserver>"u"){o("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(let e of this.trackedElements.values())e.timeoutId!==null&&window.clearTimeout(e.timeoutId);this.trackedElements.clear();}observeElements(){if(!this.config||!this.observer)return;let e=this.config.maxTrackedElements??100,t=this.trackedElements.size;for(let r of this.config.elements)try{let i=document.querySelectorAll(r.selector);for(let s of Array.from(i)){if(t>=e){o("debug","ViewportHandler: Maximum tracked elements reached",{data:{limit:e,selector:r.selector,message:"Some elements will not be tracked. Consider more specific selectors."}});return}s.hasAttribute(`${I}-ignore`)||this.trackedElements.has(s)||(this.trackedElements.set(s,{element:s,selector:r.selector,id:r.id,name:r.name,startTime:null,timeoutId:null,lastFiredTime:null}),this.observer?.observe(s),t++);}}catch(i){o("debug",`ViewportHandler: Invalid selector "${r.selector}"`,{error:i});}o("debug","ViewportHandler: Elements tracked",{data:{count:t,limit:e}});}handleIntersection=e=>{if(!this.config)return;let t=this.config.minDwellTime??1e3;for(let r of e){let i=this.trackedElements.get(r.target);i&&(r.isIntersecting?i.startTime===null&&(i.startTime=performance.now(),i.timeoutId=window.setTimeout(()=>{let s=Math.round(r.intersectionRatio*100)/100;this.fireViewportEvent(i,s);},t)):i.startTime!==null&&(i.timeoutId!==null&&(window.clearTimeout(i.timeoutId),i.timeoutId=null),i.startTime=null));}};fireViewportEvent(e,t){if(e.startTime===null)return;let r=Math.round(performance.now()-e.startTime);if(e.element.hasAttribute(`${I}-ignore`))return;let i=this.config?.cooldownPeriod??6e4,s=Date.now();if(e.lastFiredTime!==null&&s-e.lastFiredTime<i){o("debug","ViewportHandler: Event suppressed by cooldown period",{data:{selector:e.selector,cooldownRemaining:i-(s-e.lastFiredTime)}}),e.startTime=null,e.timeoutId=null;return}let a={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:"viewport_visible",viewport_data:a}),e.startTime=null,e.timeoutId=null,e.lastFiredTime=s;}setupMutationObserver(){if(!(!this.config||typeof MutationObserver>"u")){if(!document.body){o("debug","ViewportHandler: document.body not available, skipping MutationObserver setup");return}this.mutationObserver=new MutationObserver(e=>{let t=false;for(let r of e)r.type==="childList"&&(r.addedNodes.length>0&&(t=true),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:true,subtree:true});}}cleanupRemovedNodes(e){e.forEach(t=>{if(t.nodeType!==1)return;let r=t,i=this.trackedElements.get(r);i&&(i.timeoutId!==null&&window.clearTimeout(i.timeoutId),this.observer?.unobserve(r),this.trackedElements.delete(r)),Array.from(this.trackedElements.keys()).filter(a=>r.contains(a)).forEach(a=>{let l=this.trackedElements.get(a);l&&l.timeoutId!==null&&window.clearTimeout(l.timeoutId),this.observer?.unobserve(a),this.trackedElements.delete(a);});});}};var Ie=class{storage;sessionStorageRef;fallbackStorage=new Map;fallbackSessionStorage=new Map;hasQuotaExceededError=false;constructor(){this.storage=this.initializeStorage("localStorage"),this.sessionStorageRef=this.initializeStorage("sessionStorage"),this.storage||o("debug","localStorage not available, using memory fallback"),this.sessionStorageRef||o("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=true,o("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(a){o("error","localStorage quota exceeded even after cleanup - data will not persist",{error:a,data:{key:e,valueSize:t.length}});}else o("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{let e=[];for(let t=0;t<this.storage.length;t++){let r=this.storage.key(t);r?.startsWith("tracelog_")&&e.push(r);}e.forEach(t=>{this.storage.removeItem(t);}),this.fallbackStorage.clear();}catch(e){o("error","Failed to clear storage",{error:e}),this.fallbackStorage.clear();}}isAvailable(){return this.storage!==null}hasQuotaError(){return this.hasQuotaExceededError}cleanupOldData(){if(!this.storage)return false;try{let e=[],t=[];for(let s=0;s<this.storage.length;s++){let a=this.storage.key(s);a?.startsWith("tracelog_")&&(e.push(a),a.startsWith("tracelog_persisted_events_")&&t.push(a));}if(t.length>0)return t.forEach(s=>{try{this.storage.removeItem(s);}catch{}}),!0;let r=["tracelog_session_","tracelog_user_id","tracelog_device_id","tracelog_config"],i=e.filter(s=>!r.some(a=>s.startsWith(a)));return i.length>0?(i.slice(0,5).forEach(a=>{try{this.storage.removeItem(a);}catch{}}),!0):!1}catch(e){return o("error","Failed to cleanup old data",{error:e}),false}}initializeStorage(e){if(typeof window>"u")return null;try{let 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")&&o("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);}};var ye=class extends f{eventManager;reportedByNav=new Map;navigationHistory=[];observers=[];vitalThresholds;lastLongTaskSentAt=0;navigationCounter=0;constructor(e){super(),this.eventManager=e,this.vitalThresholds=te(W);}async startTracking(){let e=this.get("config"),t=e?.webVitalsMode??W;this.vitalThresholds=te(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){o("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=>{let i=r.getEntries(),s=i[i.length-1];s&&this.sendVital({type:"LCP",value:Number(s.startTime.toFixed(2))});},{type:"largest-contentful-paint",buffered:true},true);let e=0,t=this.getNavigationId();this.safeObserve("layout-shift",r=>{let i=this.getNavigationId();i!==t&&(e=0,t=i);let s=r.getEntries();for(let a of s){if(a.hadRecentInput===true)continue;let l=typeof a.value=="number"?a.value:0;e+=l;}this.sendVital({type:"CLS",value:Number(e.toFixed(2))});},{type:"layout-shift",buffered:true}),this.safeObserve("paint",r=>{for(let i of r.getEntries())i.name==="first-contentful-paint"&&this.sendVital({type:"FCP",value:Number(i.startTime.toFixed(2))});},{type:"paint",buffered:true},true),this.safeObserve("event",r=>{let i=0,s=r.getEntries();for(let a of s){let l=(a.processingEnd??0)-(a.startTime??0);i=Math.max(i,l);}i>0&&this.sendVital({type:"INP",value:Number(i.toFixed(2))});},{type:"event",buffered:true});}async initWebVitals(){try{let{onLCP:e,onCLS:t,onFCP:r,onTTFB:i,onINP:s}=await import('web-vitals'),a=l=>c=>{let d=Number(c.value.toFixed(2));this.sendVital({type:l,value:d});};e(a("LCP"),{reportAllChanges:!1}),t(a("CLS"),{reportAllChanges:!1}),r(a("FCP"),{reportAllChanges:!1}),i(a("TTFB"),{reportAllChanges:!1}),s(a("INP"),{reportAllChanges:!1});}catch(e){o("debug","Failed to load web-vitals library, using fallback",{error:e}),this.observeWebVitalsFallback();}}reportTTFB(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return;let t=e.responseStart;typeof t=="number"&&Number.isFinite(t)&&this.sendVital({type:"TTFB",value:Number(t.toFixed(2))});}catch(e){o("debug","Failed to report TTFB",{error:e});}}observeLongTasks(){this.safeObserve("longtask",e=>{let t=e.getEntries();for(let r of t){let i=Number(r.duration.toFixed(2)),s=Date.now();s-this.lastLongTaskSentAt>=It&&(this.shouldSendVital("LONG_TASK",i)&&this.trackWebVital("LONG_TASK",i),this.lastLongTaskSentAt=s);}},{type:"longtask",buffered:true});}sendVital(e){if(!this.shouldSendVital(e.type,e.value))return;let t=this.getNavigationId();if(t){let 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>yt){let s=this.navigationHistory.shift();s&&this.reportedByNav.delete(s);}}this.trackWebVital(e.type,e.value);}trackWebVital(e,t){if(!Number.isFinite(t)){o("debug","Invalid web vital value",{data:{type:e,value:t}});return}this.eventManager.track({type:"web_vitals",web_vitals:{type:e,value:t}});}getNavigationId(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return null;let t=e.startTime||performance.now(),r=++this.navigationCounter,i=`${t.toFixed(2)}_${window.location.pathname}`;return r>1?`${i}_${r}`:i}catch(e){return o("debug","Failed to get navigation ID",{error:e}),null}}isObserverSupported(e){if(typeof PerformanceObserver>"u")return false;let t=PerformanceObserver.supportedEntryTypes;return !t||t.includes(e)}safeObserve(e,t,r,i=false){try{if(!this.isObserverSupported(e))return !1;let s=new PerformanceObserver((a,l)=>{try{t(a,l);}catch(c){o("debug","Observer callback failed",{error:c,data:{type:e}});}if(i)try{l.disconnect();}catch{}});return s.observe(r??{type:e,buffered:!0}),i||this.observers.push(s),!0}catch(s){return o("debug","Failed to create performance observer",{error:s,data:{type:e}}),false}}shouldSendVital(e,t){if(typeof t!="number"||!Number.isFinite(t))return o("debug","Invalid web vital value",{data:{type:e,value:t}}),false;let r=this.vitalThresholds[e];return !(typeof r=="number"&&t<=r)}};var be=class n extends f{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(){let e=Date.now();if(e<this.burstBackoffUntil)return false;if(e-this.burstWindowStart>1e3&&(this.errorBurstCounter=0,this.burstWindowStart=e),this.errorBurstCounter++,this.errorBurstCounter>10)return this.burstBackoffUntil=e+5e3,o("debug","Error burst detected - entering cooldown",{data:{errorsInWindow:this.errorBurstCounter,cooldownMs:5e3}}),false;let r=this.get("config").errorSampling??1;return Math.random()<r}handleError=e=>{if(!this.shouldSample())return;let t=this.sanitize(e.message||"Unknown error");if(this.shouldSuppressError("js_error",t))return;let r=typeof e.error?.stack=="string"?this.truncateStack(e.error.stack):void 0;this.eventManager.track({type:"error",error_data:{type:"js_error",message:t,...e.filename!==""&&{filename:e.filename},...e.lineno!==0&&{line:e.lineno},...e.colno!==0&&{column:e.colno},...r!==void 0&&{stack:r}}});};handleRejection=e=>{if(!this.shouldSample())return;let t=this.extractRejectionMessage(e.reason),r=this.sanitize(t);if(this.shouldSuppressError("promise_rejection",r))return;let i=e.reason instanceof Error&&typeof e.reason.stack=="string"?this.truncateStack(e.reason.stack):void 0;this.eventManager.track({type:"error",error_data:{type:"promise_rejection",message:r,...i!==void 0&&{stack:i}}});};extractRejectionMessage(e){if(e==null)return "Unknown rejection";if(typeof e=="string")return e;if(e instanceof Error)return e.message;if(typeof e=="object"&&"message"in e)return String(e.message);try{return JSON.stringify(e)}catch{return "Unserializable rejection"}}sanitize(e){let t=e.length>500?e.slice(0,500)+"...":e;return this.sanitizePii(t)}sanitizePii(e){let t=e;for(let r of $){let i=new RegExp(r.source,r.flags);t=t.replace(i,"[REDACTED]");}return t}shouldSuppressError(e,t){let r=Date.now(),i=`${e}:${t}`,s=this.recentErrors.get(i);return s!==void 0&&r-s<5e3?(this.recentErrors.set(i,r),true):(this.recentErrors.set(i,r),this.recentErrors.size>100?(this.recentErrors.clear(),this.recentErrors.set(i,r),false):(this.recentErrors.size>50&&this.pruneOldErrors(),false))}static TRUNCATION_SUFFIX=`
2
- ...truncated`;truncateStack(e){if(e.length<=2e3)return this.sanitizePii(e);let t=2e3-n.TRUNCATION_SUFFIX.length,r=e.slice(0,t)+n.TRUNCATION_SUFFIX;return this.sanitizePii(r)}pruneOldErrors(){let e=Date.now();for(let[i,s]of this.recentErrors.entries())e-s>5e3&&this.recentErrors.delete(i);if(this.recentErrors.size<=50)return;let t=Array.from(this.recentErrors.entries()).sort((i,s)=>i[1]-s[1]),r=this.recentErrors.size-50;for(let i=0;i<r;i+=1){let s=t[i];s&&this.recentErrors.delete(s[0]);}}};var we=class extends f{isInitialized=false;suppressNextScrollTimer=null;pageUnloadHandler=null;emitter=new ce;transformers={};customHeadersProvider;managers={};handlers={};get initialized(){return this.isInitialized}async init(e={}){if(this.isInitialized)return {sessionId:this.get("sessionId")??""};this.managers.storage=new Ie;try{this.setupState(e);let t=e.integrations?.custom?.headers??{},r=e.integrations?.custom?.fetchCredentials??"include";return this.managers.event=new me(this.managers.storage,this.emitter,this.transformers,t,this.customHeadersProvider,r),this.loadPersistedIdentity(),this.initializeHandlers(),this.setupPageLifecycleListeners(),await this.managers.event.recoverPersistedEvents().catch(i=>{o("warn","Failed to recover persisted events",{error:i});}),this.isInitialized=!0,{sessionId:this.get("sessionId")??""}}catch(t){this.destroy(true);let r=t instanceof Error?t.message:String(t);throw new Error(`[TraceLog] TraceLog initialization failed: ${r}`)}}sendCustomEvent(e,t){if(!this.managers.event){o("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));let{valid:i,error:s,sanitizedMetadata:a}=Ht(e,r);if(!i){if(this.get("mode")==="qa")throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${s}`);o("warn",`Custom event "${e}" dropped: ${s}`);return}this.managers.event.track({type:"custom",custom_event:{name:e,...a&&{metadata:a}}});}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=false){!this.isInitialized&&!e||(Object.values(this.handlers).filter(Boolean).forEach(t=>{try{t.stopTracking();}catch(r){o("warn","Failed to stop tracking",{error:r});}}),this.suppressNextScrollTimer&&(clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=null),this.pageUnloadHandler&&(window.removeEventListener("pagehide",this.pageUnloadHandler),window.removeEventListener("beforeunload",this.pageUnloadHandler),this.pageUnloadHandler=null),this.managers.event?.flushImmediatelySync(),this.managers.event?.stop(),this.emitter.removeAllListeners(),this.transformers.beforeSend=void 0,this.transformers.beforeBatch=void 0,this.customHeadersProvider=void 0,this.set("suppressNextScroll",false),this.set("sessionId",null),this.set("identity",void 0),this.clearPersistedIdentity(),this.isInitialized=false,this.handlers={},this.managers={});}setupState(e={}){this.set("config",e);let t=pe.getId(this.managers.storage);this.set("userId",t);let r=Ot(e);this.set("collectApiUrls",r);let i=Tt();this.set("device",i);let s=j(window.location.href,e.sensitiveQueryParams);this.set("pageUrl",s),Rt()&&this.set("mode","qa");}getConfig(){return this.get("config")}getCollectApiUrls(){return this.get("collectApiUrls")}getEventManager(){return this.managers.event}getSessionId(){return this.get("sessionId")}validateGlobalMetadata(e){if(typeof e!="object"||e===null||Array.isArray(e))return {valid:false,error:"Global metadata must be a plain object"};let t=le("Global",e,"globalMetadata");return t.valid?{valid:true}:{valid:false,error:t.error}}updateGlobalMetadata(e){let t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);let i={...this.get("config"),globalMetadata:e};this.set("config",i),o("debug","Global metadata updated (replaced)",{data:{keys:Object.keys(e)}});}mergeGlobalMetadata(e){let t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);let r=this.get("config"),s={...r.globalMetadata??{},...e},a={...r,globalMetadata:s};this.set("config",a),o("debug","Global metadata updated (merged)",{data:{keys:Object.keys(e)}});}identify(e,t){if(!e||typeof e!="string"||e.trim().length===0){o("warn","identify() called with invalid userId",{data:{type:typeof e,length:typeof e=="string"?e.trim().length:0}});return}if(e.trim().length>256){o("warn","identify() userId exceeds 256 characters",{data:{length:e.trim().length}});return}let r=e.trim(),i=ae(t),s={userId:r,...i?{traits:i}:{}};this.set("identity",s),this.persistIdentity(s),o("debug","Visitor identified",{data:{userIdLength:r.length,traitKeys:i?Object.keys(i):[]}});}async resetIdentity(){await this.managers.event?.flushImmediately(),this.set("identity",void 0),this.clearPersistedIdentity();let e=oe();this.managers.storage.setItem(H,e),this.set("userId",e),this.set("hasStartSession",false),this.set("sessionId",null),this.handlers.session?.stopTracking(),this.handlers.session?.startTracking(),o("debug","Identity reset, new UUID generated");}getProjectId(){return this.get("config")?.integrations?.tracelog?.projectId??"custom"}persistIdentity(e){try{let t=this.getProjectId(),r=J(t);this.managers.storage.setItem(r,JSON.stringify(e));}catch{o("debug","Failed to persist identity to localStorage");}}loadPersistedIdentity(){let e=this.managers.storage,t=this.getProjectId(),r=J(t);try{let i=e.getItem(M);if(i){let s=JSON.parse(i);if(e.removeItem(M),!this.isValidIdentityData(s)){o("debug","Invalid pending identity in localStorage, discarded");return}let a={...s,userId:s.userId.trim()};e.setItem(r,JSON.stringify(a)),this.set("identity",a),o("debug","Migrated pending identity to project-scoped key");return}}catch{e.removeItem(M);}try{let i=e.getItem(r);if(i){let s=JSON.parse(i);if(!this.isValidIdentityData(s)){e.removeItem(r),o("debug","Invalid persisted identity in localStorage, discarded");return}let a={...s,userId:s.userId.trim()};this.set("identity",a),o("debug","Loaded persisted identity");}}catch{o("debug","Failed to load persisted identity");}}isValidIdentityData(e){if(!e||typeof e!="object")return false;let{userId:t,traits:r}=e;if(typeof t!="string"||t.trim().length===0||t.trim().length>256)return false;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r))return false;for(let i of Object.values(r))if(typeof i!="string")return false}return true}clearPersistedIdentity(){try{let e=this.managers.storage,t=this.getProjectId();e.removeItem(J(t)),e.removeItem(M);}catch{o("debug","Failed to clear persisted identity");}}setupPageLifecycleListeners(){this.pageUnloadHandler=()=>{this.managers.event?.flushImmediatelySync();},window.addEventListener("pagehide",this.pageUnloadHandler),window.addEventListener("beforeunload",this.pageUnloadHandler);}initializeHandlers(){let e=this.get("config");this.handlers.session=new he(this.managers.storage,this.managers.event),this.handlers.session.startTracking();let t=()=>{this.set("suppressNextScroll",true),this.suppressNextScrollTimer&&clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=window.setTimeout(()=>{this.set("suppressNextScroll",false);},500);};this.handlers.pageView=new Ee(this.managers.event,t),this.handlers.pageView.startTracking(),this.handlers.click=new ve(this.managers.event),this.handlers.click.startTracking(),this.handlers.scroll=new Te(this.managers.event),this.handlers.scroll.startTracking(),this.handlers.performance=new ye(this.managers.event),this.handlers.performance.startTracking().catch(r=>{o("warn","Failed to start performance tracking",{error:r});}),this.handlers.error=new be(this.managers.event),this.handlers.error.startTracking(),e.viewport&&(this.handlers.viewport=new _e(this.managers.event),this.handlers.viewport.startTracking());}};var V=[],w=[],k=null,u=null,L=false,S=false,D=null,ir=async n=>typeof window>"u"||typeof document>"u"?{sessionId:""}:(S=false,window.__traceLogDisabled===true?{sessionId:""}:u?{sessionId:u.getSessionId()??""}:(L&&D||(L=true,D=(async()=>{try{let e=Dt(n??{}),t=new we;try{V.forEach(({event:a,callback:l})=>{t.on(a,l);}),V.length=0,w.forEach(({hook:a,fn:l})=>{a==="beforeSend"?t.setTransformer("beforeSend",l):t.setTransformer("beforeBatch",l);}),w.length=0,k&&(t.setCustomHeaders(k),k=null);let r=t.init(e),i=new Promise((a,l)=>{setTimeout(()=>{l(new Error(`[TraceLog] Initialization timeout after ${1e4}ms`));},1e4);}),s=await Promise.race([r,i]);return u=t,s}catch(r){try{t.destroy(!0);}catch(i){o("error","Failed to cleanup partially initialized app",{error:i});}throw r}}catch(e){throw u=null,e}finally{L=false,D=null;}})()),D)),sr=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(S)throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");u.sendCustomEvent(n,e);}},or=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u||L){V.push({event:n,callback:e});return}u.on(n,e);}},ar=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){let t=V.findIndex(r=>r.event===n&&r.callback===e);t!==-1&&V.splice(t,1);return}u.off(n,e);}};function lr(n,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(!u||L){let t=w.findIndex(r=>r.hook===n);t!==-1&&w.splice(t,1),w.push({hook:n,fn:e});return}if(S)throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");n==="beforeSend"?u.setTransformer("beforeSend",e):u.setTransformer("beforeBatch",e);}}var cr=n=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){let e=w.findIndex(t=>t.hook===n);e!==-1&&w.splice(e,1);return}if(S)throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");u.removeTransformer(n);}},dr=n=>{if(!(typeof window>"u"||typeof document>"u")){if(typeof n!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof n}`);if(!u||L){k=n;return}if(S)throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");u.setCustomHeaders(n);}},ur=()=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){k=null;return}if(S)throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");u.removeCustomHeaders();}},mr=()=>typeof window>"u"||typeof document>"u"?false:u!==null,fr=()=>typeof window>"u"||typeof document>"u"||!u?null:u.getSessionId(),pr=()=>{if(!(typeof window>"u"||typeof document>"u")){if(S)throw new Error("[TraceLog] Destroy operation already in progress");if(!u){S=false;return}S=true;try{u.destroy(),u=null,L=!1,D=null,V.length=0,w.length=0,k=null,S=!1;}catch(n){u=null,L=false,D=null,V.length=0,w.length=0,k=null,S=false,o("warn","Error during destroy, forced cleanup completed",{error:n});}}},gr=n=>{typeof window>"u"||typeof document>"u"||At(n);},hr=n=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(S)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");u.updateGlobalMetadata(n);}},Er=n=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(S)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");u.mergeGlobalMetadata(n);}},vr=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!n||typeof n!="string"||n.trim().length===0){o("warn","identify() called with invalid userId");return}if(n.trim().length>256){o("warn","identify() userId exceeds 256 characters");return}if(S){o("warn","Cannot identify while TraceLog is being destroyed");return}if(u){u.identify(n,e);return}try{let t=ae(e),r={userId:n.trim(),...t?{traits:t}:{}};localStorage.setItem(M,JSON.stringify(r)),o("debug","Identity persisted pre-init (will be applied on init)");}catch{o("debug","Failed to persist pre-init identity");}}},Sr=async()=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){try{localStorage.removeItem(M);}catch{}return}if(S)throw new Error("[TraceLog] Cannot reset identity while TraceLog is being destroyed");await u.resetIdentity();}};var ya={init:ir,event:sr,on:or,off:ar,setTransformer:lr,removeTransformer:cr,setCustomHeaders:dr,removeCustomHeaders:ur,isInitialized:mr,getSessionId:fr,destroy:pr,setQaMode:gr,updateGlobalMetadata:hr,mergeGlobalMetadata:Er,identify:vr,resetIdentity:Sr};exports.AppConfigValidationError=m;exports.DEFAULT_SESSION_TIMEOUT=C;exports.DEFAULT_WEB_VITALS_MODE=W;exports.DeviceType=mt;exports.EmitterEvent=ft;exports.ErrorType=gt;exports.EventType=y;exports.InitializationTimeoutError=ht;exports.IntegrationValidationError=b;exports.MAX_ARRAY_LENGTH=Ae;exports.MAX_CUSTOM_EVENT_ARRAY_SIZE=Y;exports.MAX_CUSTOM_EVENT_KEYS=z;exports.MAX_CUSTOM_EVENT_NAME_LENGTH=K;exports.MAX_CUSTOM_EVENT_STRING_SIZE=X;exports.MAX_NESTED_OBJECT_KEYS=Re;exports.MAX_STRING_LENGTH=N;exports.MAX_STRING_LENGTH_IN_ARRAY=q;exports.Mode=ke;exports.PII_PATTERNS=$;exports.PermanentError=R;exports.RateLimitError=B;exports.SamplingRateValidationError=F;exports.ScrollDirection=pt;exports.SessionTimeoutValidationError=Z;exports.SpecialApiUrl=ut;exports.TimeoutError=A;exports.TraceLogValidationError=P;exports.WEB_VITALS_GOOD_THRESHOLDS=Ar;exports.WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS=Fe;exports.WEB_VITALS_POOR_THRESHOLDS=_t;exports.getWebVitalsThresholds=te;exports.isPrimaryScrollEvent=Ln;exports.isSecondaryScrollEvent=Cn;exports.tracelog=ya;//# sourceMappingURL=public-api.cjs.map
1
+ 'use strict';var C=9e5;var X=120,z=49152,Y=100,q=500,Ae=200;var N=1e3,J=500,Le=1e3;var y="data-tlog",ot=["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"]'],at=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],lt=["token","auth","key","session","reset","password","api_key","apikey","secret","access_token","refresh_token","verification","code","otp"];var p={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",INVALID_SEND_INTERVAL:"Send interval must be between 1000ms (1 second) and 60000ms (60 seconds)"},ct=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/on\w+\s*=/gi,/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,/<embed\b[^>]*>/gi,/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi];var v="tlog",O=`${v}:qa_mode`,H=`${v}:uid`,Ce="tlog_mode",Ne="qa",Oe="qa_off",dt=n=>n?`${v}:${n}:queue`:`${v}:queue`,ut=n=>n?`${v}:${n}:session`:`${v}:session`;var mt=n=>n?`${v}:${n}:broadcast`:`${v}:broadcast`,Pe=(n,e)=>`${v}:${n}:session_counts:${e}`,xe=10080*60*1e3,De=`${v}:session_counts_last_cleanup`,ke=3600*1e3,Z=n=>n?`${v}:${n}:identity`:`${v}:identity`,M=`${v}:pending_identity`;var ft=(t=>(t.Localhost="localhost:8080",t.Fail="localhost:9999",t))(ft||{});var pt=(i=>(i.Mobile="mobile",i.Tablet="tablet",i.Desktop="desktop",i.Unknown="unknown",i))(pt||{});var Ve=(t=>(t.EVENT="event",t.QUEUE="queue",t))(Ve||{});var R=class n extends Error{constructor(t,r){super(t);this.statusCode=r;this.name="PermanentError",Error.captureStackTrace&&Error.captureStackTrace(this,n);}},B=class n extends Error{constructor(e){super(e),this.name="RateLimitError",Error.captureStackTrace&&Error.captureStackTrace(this,n);}},A=class n extends Error{constructor(e){super(e),this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,n);}};var I=(c=>(c.PAGE_VIEW="page_view",c.CLICK="click",c.SCROLL="scroll",c.SESSION_START="session_start",c.CUSTOM="custom",c.WEB_VITALS="web_vitals",c.ERROR="error",c.VIEWPORT_VISIBLE="viewport_visible",c))(I||{}),ht=(t=>(t.UP="up",t.DOWN="down",t))(ht||{}),gt=(t=>(t.JS_ERROR="js_error",t.PROMISE_REJECTION="promise_rejection",t))(gt||{});var Ue=(e=>(e.QA="qa",e))(Ue||{});var Nn=n=>n.type==="scroll"&&"scroll_data"in n&&n.scroll_data.is_primary===true,On=n=>n.type==="scroll"&&"scroll_data"in n&&n.scroll_data.is_primary===false;var P=class extends Error{constructor(t,r,i){super(t);this.errorCode=r;this.layer=i;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}},m=class extends P{constructor(e,t="config"){super(e,"APP_CONFIG_INVALID",t);}},ee=class extends P{constructor(e,t="config"){super(e,"SESSION_TIMEOUT_INVALID",t);}},F=class extends P{constructor(e,t="config"){super(e,"SAMPLING_RATE_INVALID",t);}},b=class extends P{constructor(e,t="config"){super(e,"INTEGRATION_INVALID",t);}},Et=class extends P{constructor(t,r,i="runtime"){super(t,"INITIALIZATION_TIMEOUT",i);this.timeoutMs=r;}};var He="background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",Be="background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;",vt="background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;";var _r=(n,e)=>{if(e){if(e instanceof Error){let t=e.message.replace(/\s+at\s+.*$/gm,"").replace(/\s*\([^()]+:\d+:\d+\)/g,"");return `[TraceLog] ${n}: ${t}`}if(e instanceof Error)return `[TraceLog] ${n}: ${e.message}`;if(typeof e=="string")return `[TraceLog] ${n}: ${e}`;if(typeof e=="object")try{return `[TraceLog] ${n}: ${JSON.stringify(e)}`}catch{return `[TraceLog] ${n}: [Unable to serialize error]`}return `[TraceLog] ${n}: ${String(e)}`}return `[TraceLog] ${n}`},yr=()=>{if(typeof window>"u"||typeof sessionStorage>"u")return false;try{return sessionStorage.getItem(O)==="true"}catch{return false}},o=(n,e,t)=>{let{error:r,data:i,showToClient:s=false,style:a,visibility:l}=t??{},c=r?_r(e,r):`[TraceLog] ${e}`,d=n==="error"?"error":n==="warn"?"warn":"log";if(!Ir(l,s))return;let T=br(l,a),g=i!==void 0?Fe(i):void 0;St(d,c,T,g);},Ir=(n,e)=>n==="critical"?true:n==="qa"||e?yr():false,br=(n,e)=>e!==void 0&&e!==""?e:n==="critical"?vt:"",St=(n,e,t,r)=>{let i=t!==void 0&&t!=="",s=i?`%c${e}`:e;r!==void 0?i?console[n](s,t,r):console[n](s,r):i?console[n](s,t):console[n](s);},Fe=n=>{let e={},t=["token","password","secret","key","apikey","api_key","sessionid","session_id"];for(let[r,i]of Object.entries(n)){let s=r.toLowerCase();if(t.some(a=>s.includes(a))){e[r]="[REDACTED]";continue}i!==null&&typeof i=="object"&&!Array.isArray(i)?e[r]=Fe(i):Array.isArray(i)?e[r]=i.map(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?Fe(a):a):e[r]=i;}return e};var $e,Tt,wr=()=>{typeof window<"u"&&!$e&&($e=window.matchMedia("(pointer: coarse)"),Tt=window.matchMedia("(hover: none)"));},te="Unknown",Mr=n=>{let e=n.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"}let 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":te},Rr=n=>{let e=n.userAgentData?.brands;if(e!=null&&e.length>0){let i=e.filter(s=>!/not.?a.?brand|chromium/i.test(s.brand))[0];if(i!=null){let s=i.brand;return /google chrome/i.test(s)?"Chrome":/microsoft edge/i.test(s)?"Edge":/opera/i.test(s)?"Opera":s}}let 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":te},Ar=()=>{try{let n=navigator;if(n.userAgentData!=null&&typeof n.userAgentData.mobile=="boolean"){let c=n.userAgentData.platform;return c!=null&&c!==""&&/ipad|tablet/i.test(c)?"tablet":n.userAgentData.mobile?"mobile":"desktop"}wr();let e=window.innerWidth,t=$e?.matches??!1,r=Tt?.matches??!1,i="ontouchstart"in window||navigator.maxTouchPoints>0,s=navigator.userAgent.toLowerCase(),a=/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(s),l=/tablet|ipad|android(?!.*mobile)/.test(s);return e<=767||a&&i?"mobile":e>=768&&e<=1024||l||t&&r&&i?"tablet":"desktop"}catch(n){return o("debug","Device detection failed, defaulting to desktop",{error:n}),"desktop"}},_t=()=>{try{let n=navigator;return {type:Ar(),os:Mr(n),browser:Rr(n)}}catch(n){return o("debug","Device info detection failed, using defaults",{error:n}),{type:"desktop",os:te,browser:te}}};var $=[/\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,/[?&](token|password|passwd|auth|secret|secret_key|private_key|auth_key|api_key|apikey|access_token)=[^&\s]+/gi];var Lr={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},We={LCP:2500,FCP:1800,CLS:.1,INP:200,TTFB:800,LONG_TASK:50},yt={LCP:4e3,FCP:3e3,CLS:.25,INP:500,TTFB:1800,LONG_TASK:50},W="needs-improvement",re=(n=W)=>{switch(n){case "all":return {LCP:0,FCP:0,CLS:0,INP:0,TTFB:0,LONG_TASK:0};case "needs-improvement":return We;case "poor":return yt;default:return We}},It=1e3,bt=50;var wt="2.7.3";var Mt=wt;var Rt=()=>typeof window<"u"&&typeof sessionStorage<"u",Nr=()=>{try{let n=new URLSearchParams(window.location.search);n.delete(Ce);let e=n.toString(),t=window.location.pathname+(e?"?"+e:"")+window.location.hash;window.history.replaceState({},"",t);}catch{}},At=()=>{if(!Rt())return false;try{let e=new URLSearchParams(window.location.search).get(Ce),t=sessionStorage.getItem(O),r=null;return e===Ne?(r=!0,sessionStorage.setItem(O,"true"),o("info","QA Mode ACTIVE",{visibility:"qa",style:He})):e===Oe&&(r=!1,sessionStorage.setItem(O,"false"),o("info","QA Mode DISABLED",{visibility:"qa",style:Be})),(e===Ne||e===Oe)&&Nr(),r??t==="true"}catch{return false}},Lt=n=>{if(Rt())try{sessionStorage.setItem(O,n?"true":"false"),o("info",n?"QA Mode ACTIVE":"QA Mode DISABLED",{visibility:"qa",style:n?He:Be});}catch{o("debug","Cannot set QA mode: sessionStorage unavailable");}};var Or=["co.uk","org.uk","com.au","net.au","com.br","co.nz","co.jp","com.mx","co.in","com.cn","co.za"],Ct=n=>{let e=n.toLowerCase().split(".");if(e.length<=2)return n.toLowerCase();let t=e.slice(-2).join(".");return Or.includes(t)?e.slice(-3).join("."):e.slice(-2).join(".")},Pr=(n,e)=>n===e?true:Ct(n)===Ct(e),ne=()=>{let n=document.referrer;if(!n)return "Direct";try{let e=new URL(n).hostname.toLowerCase(),t=window.location.hostname.toLowerCase();return Pr(e,t)?"Direct":n}catch(e){return o("debug","Failed to parse referrer URL, using raw value",{error:e,data:{referrer:n}}),n}};var ie=()=>{let n=new URLSearchParams(window.location.search),e={};return at.forEach(r=>{let i=n.get(r);if(i){let s=r.split("utm_")[1];e[s]=i;}}),Object.keys(e).length?e:void 0};var ae=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return (n==="x"?e:e&3|8).toString(16)}),se=0,oe=0,Nt=()=>{let n=Date.now();n<oe&&(n=oe),n===oe?se=(se+1)%1e3:se=0,oe=n;let e=se.toString().padStart(3,"0"),t="";try{if(typeof crypto<"u"&&crypto.getRandomValues){let r=crypto.getRandomValues(new Uint8Array(3));r&&(t=Array.from(r,i=>i.toString(16).padStart(2,"0")).join(""));}}catch{}return t||(t=Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")),`${n}-${e}-${t}`};var Ot=(n,e=false)=>{try{let t=new URL(n),r=t.protocol==="https:",i=t.protocol==="http:";return r||e&&i}catch{return false}},xr=n=>{try{let 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.");let 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 i;if(r.length===2?i=r.join("."):i=r.slice(-2).join("."),!i||i.split(".").length<2)throw new Error("Invalid domain structure for SaaS");let s=`https://${n}.${i}/collect`;if(!Ot(s))throw new Error("Generated URL failed validation");return s}catch(e){throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error?e.message:String(e)}`)}},Pt=n=>{let e={};n.integrations?.tracelog?.projectId&&(e.saas=xr(n.integrations.tracelog.projectId));let t=n.integrations?.custom?.collectApiUrl;if(t){let r=n.integrations?.custom?.allowHttp??false;if(!Ot(t,r))throw new Error("Invalid custom API URL");e.custom=t;}return e},j=(n,e=[])=>{if(!n||typeof n!="string")return o("warn","Invalid URL provided to normalizeUrl",{data:{type:typeof n}}),n||"";try{let t=new URL(n),r=t.searchParams,i=[...new Set([...lt,...e])],s=!1,a=[];return i.forEach(c=>{r.has(c)&&(r.delete(c),s=!0,a.push(c));}),!s&&n.includes("?")?n:(t.search=r.toString(),t.toString())}catch(t){return o("warn","URL normalization failed, returning original",{error:t,data:{urlLength:n?.length}}),n}};var xt=n=>{if(!n||typeof n!="string"||n.trim().length===0)return "";let e=n;n.length>1e3&&(e=n.slice(0,Math.max(0,1e3)));let t=0;for(let i of ct){let s=e;e=e.replace(i,""),s!==e&&t++;}return t>0&&o("warn","XSS patterns detected and removed",{data:{patternMatches:t,valueLength:n.length}}),e.trim()},je=(n,e=0)=>{if(n==null)return null;if(typeof n=="string")return xt(n);if(typeof n=="number")return !Number.isFinite(n)||n<-Number.MAX_SAFE_INTEGER||n>Number.MAX_SAFE_INTEGER?0:n;if(typeof n=="boolean")return n;if(e>10)return null;if(Array.isArray(n))return n.slice(0,1e3).map(i=>je(i,e+1)).filter(i=>i!==null);if(typeof n=="object"){let t={},i=Object.entries(n).slice(0,200);for(let[s,a]of i){let l=xt(s);if(l){let c=je(a,e+1);c!==null&&(t[l]=c);}}return t}return null},Dt=n=>{if(typeof n!="object"||n===null)return {};try{let e=je(n);return typeof e=="object"&&e!==null?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`[TraceLog] Metadata sanitization failed: ${t}`)}};var $r=n=>{if(n!==void 0&&(n===null||typeof n!="object"))throw new m("Configuration must be an object","config");if(n){if(n.sessionTimeout!==void 0&&(typeof n.sessionTimeout!="number"||n.sessionTimeout<3e4||n.sessionTimeout>864e5))throw new ee(p.INVALID_SESSION_TIMEOUT,"config");if(n.globalMetadata!==void 0&&(typeof n.globalMetadata!="object"||n.globalMetadata===null))throw new m(p.INVALID_GLOBAL_METADATA,"config");if(n.integrations&&jr(n.integrations),n.sensitiveQueryParams!==void 0){if(!Array.isArray(n.sensitiveQueryParams))throw new m(p.INVALID_SENSITIVE_QUERY_PARAMS,"config");for(let e of n.sensitiveQueryParams)if(typeof e!="string")throw new m("All sensitive query params must be strings","config")}if(n.errorSampling!==void 0&&(typeof n.errorSampling!="number"||n.errorSampling<0||n.errorSampling>1))throw new F(p.INVALID_ERROR_SAMPLING_RATE,"config");if(n.samplingRate!==void 0&&(typeof n.samplingRate!="number"||n.samplingRate<0||n.samplingRate>1))throw new F(p.INVALID_SAMPLING_RATE,"config");if(n.primaryScrollSelector!==void 0){if(typeof n.primaryScrollSelector!="string"||!n.primaryScrollSelector.trim())throw new m(p.INVALID_PRIMARY_SCROLL_SELECTOR,"config");if(n.primaryScrollSelector!=="window")try{document.querySelector(n.primaryScrollSelector);}catch{throw new m(`${p.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${n.primaryScrollSelector}"`,"config")}}if(n.pageViewThrottleMs!==void 0&&(typeof n.pageViewThrottleMs!="number"||n.pageViewThrottleMs<0))throw new m(p.INVALID_PAGE_VIEW_THROTTLE,"config");if(n.clickThrottleMs!==void 0&&(typeof n.clickThrottleMs!="number"||n.clickThrottleMs<0))throw new m(p.INVALID_CLICK_THROTTLE,"config");if(n.maxSameEventPerMinute!==void 0&&(typeof n.maxSameEventPerMinute!="number"||n.maxSameEventPerMinute<=0))throw new m(p.INVALID_MAX_SAME_EVENT_PER_MINUTE,"config");if(n.sendIntervalMs!==void 0&&(!Number.isFinite(n.sendIntervalMs)||n.sendIntervalMs<1e3||n.sendIntervalMs>6e4))throw new m(p.INVALID_SEND_INTERVAL,"config");if(n.viewport!==void 0&&Wr(n.viewport),n.webVitalsMode!==void 0){if(typeof n.webVitalsMode!="string")throw new m(`Invalid webVitalsMode type: ${typeof n.webVitalsMode}. Must be a string`,"config");let e=["all","needs-improvement","poor"];if(!e.includes(n.webVitalsMode))throw new m(`Invalid webVitalsMode: "${n.webVitalsMode}". Must be one of: ${e.join(", ")}`,"config")}if(n.webVitalsThresholds!==void 0){if(typeof n.webVitalsThresholds!="object"||n.webVitalsThresholds===null||Array.isArray(n.webVitalsThresholds))throw new m("webVitalsThresholds must be an object","config");let e=["LCP","FCP","CLS","INP","TTFB","LONG_TASK"];for(let[t,r]of Object.entries(n.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")}}}},Wr=n=>{if(typeof n!="object"||n===null)throw new m(p.INVALID_VIEWPORT_CONFIG,"config");if(!n.elements||!Array.isArray(n.elements))throw new m(p.INVALID_VIEWPORT_ELEMENTS,"config");if(n.elements.length===0)throw new m(p.INVALID_VIEWPORT_ELEMENTS,"config");let e=new Set;for(let t of n.elements){if(!t.selector||typeof t.selector!="string"||!t.selector.trim())throw new m(p.INVALID_VIEWPORT_ELEMENT,"config");let 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(p.INVALID_VIEWPORT_ELEMENT_ID,"config");if(t.name!==void 0&&(typeof t.name!="string"||!t.name.trim()))throw new m(p.INVALID_VIEWPORT_ELEMENT_NAME,"config")}if(n.threshold!==void 0&&(typeof n.threshold!="number"||n.threshold<0||n.threshold>1))throw new m(p.INVALID_VIEWPORT_THRESHOLD,"config");if(n.minDwellTime!==void 0&&(typeof n.minDwellTime!="number"||n.minDwellTime<0))throw new m(p.INVALID_VIEWPORT_MIN_DWELL_TIME,"config");if(n.cooldownPeriod!==void 0&&(typeof n.cooldownPeriod!="number"||n.cooldownPeriod<0))throw new m(p.INVALID_VIEWPORT_COOLDOWN_PERIOD,"config");if(n.maxTrackedElements!==void 0&&(typeof n.maxTrackedElements!="number"||n.maxTrackedElements<=0))throw new m(p.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS,"config")},jr=n=>{if(n){if(n.tracelog&&(!n.tracelog.projectId||typeof n.tracelog.projectId!="string"||n.tracelog.projectId.trim()===""))throw new b(p.INVALID_TRACELOG_PROJECT_ID,"config");if(n.custom){if(!n.custom.collectApiUrl||typeof n.custom.collectApiUrl!="string"||n.custom.collectApiUrl.trim()==="")throw new b(p.INVALID_CUSTOM_API_URL,"config");if(n.custom.allowHttp!==void 0&&typeof n.custom.allowHttp!="boolean")throw new b("allowHttp must be a boolean","config");let e=n.custom.collectApiUrl.trim();if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new b('Custom API URL must start with "http://" or "https://"',"config");if(!(n.custom.allowHttp??false)&&e.startsWith("http://"))throw new b("Custom API URL must use HTTPS in production. Set allowHttp: true in integration config to allow HTTP (not recommended)","config");if(n.custom.fetchCredentials!==void 0&&!["include","same-origin","omit"].includes(n.custom.fetchCredentials))throw new b('fetchCredentials must be "include", "same-origin", or "omit"',"config")}if(n.tracelog?.shopify!==void 0&&typeof n.tracelog.shopify!="boolean")throw new b("tracelog.shopify must be a boolean","config")}},kt=n=>{$r(n);let e={...n??{},sessionTimeout:n?.sessionTimeout??9e5,globalMetadata:n?.globalMetadata??{},sensitiveQueryParams:n?.sensitiveQueryParams??[],errorSampling:n?.errorSampling??1,samplingRate:n?.samplingRate??1,pageViewThrottleMs:n?.pageViewThrottleMs??1e3,clickThrottleMs:n?.clickThrottleMs??300,maxSameEventPerMinute:n?.maxSameEventPerMinute??60,sendIntervalMs:n?.sendIntervalMs??1e4};return e.integrations?.custom&&(e.integrations.custom={...e.integrations.custom,allowHttp:e.integrations.custom.allowHttp??false}),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};var Je=(n,e=new Set)=>{if(n==null)return true;let t=typeof n;return t==="string"||t==="number"||t==="boolean"?true:t==="function"||t==="symbol"||t==="bigint"||e.has(n)?false:(e.add(n),Array.isArray(n)?n.every(r=>Je(r,e)):t==="object"?Object.values(n).every(r=>Je(r,e)):false)},Vt=n=>typeof n!="object"||n===null?false:Je(n),le=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e={};for(let[t,r]of Object.entries(n))typeof r=="string"&&(e[t]=r);return Object.keys(e).length>0?e:void 0};var Ht=n=>typeof n!="string"?{valid:false,error:"Event name must be a string"}:n.length===0?{valid:false,error:"Event name cannot be empty"}:n.length>120?{valid:false,error:`Event name is too long (max ${120} characters)`}:n.includes("<")||n.includes(">")||n.includes("&")?{valid:false,error:"Event name contains invalid characters"}:["constructor","prototype","__proto__","eval","function","var","let","const"].includes(n.toLowerCase())?{valid:false,error:"Event name cannot be a reserved word"}:{valid:true},Ut=(n,e,t)=>{let r=Dt(e),i=t&&t==="customEvent"?`${t} "${n}" metadata error`:`${n} metadata error`;if(!Vt(r))return {valid:false,error:`${i}: object has invalid types. Valid types are string, number, boolean or string arrays.`};let s;try{s=JSON.stringify(r);}catch{return {valid:false,error:`${i}: object contains circular references or cannot be serialized.`}}if(new TextEncoder().encode(s).byteLength>49152)return {valid:false,error:`${i}: object is too large (max ${49152/1024} KB).`};if(Object.keys(r).length>100)return {valid:false,error:`${i}: object has too many keys (max ${100} keys).`};for(let[c,d]of Object.entries(r)){if(Array.isArray(d)){if(d.length>500)return {valid:false,error:`${i}: array property "${c}" is too large (max ${500} items).`};for(let h of d)if(typeof h=="string"&&h.length>500)return {valid:false,error:`${i}: array property "${c}" contains strings that are too long (max ${500} characters).`}}if(typeof d=="string"&&d.length>1e3)return {valid:false,error:`${i}: property "${c}" is too long (max ${1e3} characters).`}}return {valid:true,sanitizedMetadata:r}},ce=(n,e,t)=>{if(Array.isArray(e)){let r=[],i=t&&t==="customEvent"?`${t} "${n}" metadata error`:`${n} metadata error`;for(let s=0;s<e.length;s++){let a=e[s];if(typeof a!="object"||a===null||Array.isArray(a))return {valid:false,error:`${i}: array item at index ${s} must be an object.`};let l=Ut(n,a,t);if(!l.valid)return {valid:false,error:`${i}: array item at index ${s} is invalid: ${l.error}`};l.sanitizedMetadata&&r.push(l.sanitizedMetadata);}return {valid:true,sanitizedMetadata:r}}return Ut(n,e,t)};var Bt=(n,e)=>{let t=Ht(n);if(!t.valid)return o("error","Event name validation failed",{data:{eventName:n,error:t.error}}),t;if(!e)return {valid:true};let r=ce(n,e,"customEvent");return r.valid||o("error","Event metadata validation failed",{data:{eventName:n,error:r.error}}),r};var de=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);}off(e,t){let r=this.listeners.get(e);if(r){let i=r.indexOf(t);i>-1&&r.splice(i,1);}}emit(e,t){let r=this.listeners.get(e);r&&r.forEach(i=>{i(t);});}removeAllListeners(){this.listeners.clear();}};function Ze(n,e,t){try{let r=e(n);return r===null?null:typeof r=="object"&&r!==null&&"type"in r?r:(o("warn",`beforeSend transformer returned invalid data, using original [${t}]`),n)}catch(r){return o("error",`beforeSend transformer threw error, using original event [${t}]`,{error:r,visibility:"critical"}),n}}function Ft(n,e,t){return n.map(r=>Ze(r,e,t)).filter(r=>r!==null)}function ue(n,e,t){try{let r=e(n);return r===null?(o("debug",`Batch filtered by beforeBatch transformer [${t}]`,{data:{eventCount:n.events.length}}),null):typeof r=="object"&&r!==null&&Array.isArray(r.events)?r:(o("warn",`beforeBatch transformer returned invalid data, using original [${t}]`,{data:{eventCount:n.events.length}}),n)}catch(r){return o("error",`beforeBatch transformer threw error, using original batch [${t}]`,{error:r,data:{eventCount:n.events.length},visibility:"critical"}),n}}var et={config:{}};var f=class{get(e){return et[e]}set(e,t){et[e]=t;}getState(){return {...et}}};var Q=class extends f{storeManager;integrationId;apiUrl;transformers;staticHeaders;customHeadersProvider;lastPermanentErrorLog=null;recoveryInProgress=false;lastMetadataTimestamp=0;fetchCredentials;pendingControllers=new Set;consecutiveNetworkFailures=0;circuitOpenedAt=0;constructor(e,t,r,i={},s={},a,l="include"){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=i,this.staticHeaders=s,this.customHeadersProvider=a,this.fetchCredentials=l;}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{let t=this.customHeadersProvider();typeof t=="object"&&t!==null&&!Array.isArray(t)?e=t:o("warn","Custom headers provider returned invalid value, expected object",{data:{received:typeof t}});}catch(t){o("warn","Custom headers provider threw an error, using static headers only",{error:t});}return {...this.staticHeaders,...e}}getQueueStorageKey(){let e=this.get("userId")||"anonymous",t=dt(e);return this.integrationId?`${t}:${this.integrationId}`:t}sendEventsQueueSync(e){return this.shouldSkipSend()?true:this.apiUrl?.includes("localhost:9999")?(o("warn",`Fail mode: simulating network failure (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),false):this.apiUrl?.includes("localhost:8080")?(o("debug",`Success mode: simulating successful send (sync)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length}}),true):this.sendQueueSyncInternal(e)}async sendEventsQueue(e,t){try{let 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 R?(this.logPermanentError("Permanent error, not retrying",r),this.clearPersistedEvents(),t?.onFailure?.(),false):r instanceof A?(o("debug",`All attempts timed out, skipping persistence (server likely received events)${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),t?.onFailure?.(),false):(this.persistEvents(e),t?.onFailure?.(),false)}}async recoverPersistedEvents(e){if(this.recoveryInProgress){o("debug","Recovery already in progress, skipping duplicate attempt");return}this.recoveryInProgress=true;try{let t=this.getPersistedData();if(!t||!this.isDataRecent(t)||t.events.length===0){this.clearPersistedEvents();return}let r=t.recoveryFailures,i=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:0;if(i>=3){o("debug",`Discarding persisted events after ${i} failed recovery attempts${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),e?.onFailure?.();return}let s=this.createRecoveryBody(t);await this.send(s)?(this.clearPersistedEvents(),e?.onSuccess?.(t.events.length,t.events,s)):(this.persistEventsWithFailureCount(s,i+1,!0),e?.onFailure?.());}catch(t){if(t instanceof R){this.logPermanentError("Permanent error during recovery, clearing persisted events",t),this.clearPersistedEvents(),e?.onFailure?.();return}if(t instanceof A){o("debug",`Recovery timed out, clearing persisted events (server likely received them)${this.integrationId?` [${this.integrationId}]`:""}`),this.clearPersistedEvents(),e?.onFailure?.();return}o("error","Failed to recover persisted events",{error:t});}finally{this.recoveryInProgress=false;}}stop(){}applyBeforeSendTransformer(e){if(this.integrationId==="saas")return e;let t=this.transformers.beforeSend;if(!t)return e;let r=Ft(e.events,t,this.integrationId||"SenderManager");return r.length===0?null:{...e,events:r}}applyBeforeBatchTransformer(e){if(this.integrationId==="saas")return e;let t=this.transformers.beforeBatch;return t?ue(e,t,this.integrationId||"SenderManager"):e}async backoffDelay(e){let t=100*Math.pow(2,e),r=Math.random()*100,i=t+r;return new Promise(s=>setTimeout(s,i))}async send(e){if(this.shouldSkipSend())return this.simulateSuccessfulSend();let t=this.applyBeforeSendTransformer(e);if(!t)return true;let r=this.applyBeforeBatchTransformer(t);if(!r)return true;if(this.apiUrl?.includes("localhost:9999"))return o("debug",`Fail mode: simulating network failure${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),false;if(this.apiUrl?.includes("localhost:8080"))return o("debug",`Success mode: simulating successful send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length}}),true;if(this.consecutiveNetworkFailures>=3){let c=Date.now()-this.circuitOpenedAt;if(c<12e4)return o("debug",`Network circuit open, skipping send${this.integrationId?` [${this.integrationId}]`:""}`,{data:{consecutiveNetworkFailures:this.consecutiveNetworkFailures,cooldownRemainingMs:12e4-c}}),false}let{url:i,payload:s}=this.prepareRequest(r),a=true,l=false;for(let c=1;c<=3;c++)try{return (await this.sendWithTimeout(i,s)).ok?(c>1&&o("info",`Send succeeded after ${c-1} retry attempt(s)${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:r.events.length,attempt:c}}),this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,!0):!1}catch(d){let h=c===3;if(d instanceof R)throw this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,d;if(d instanceof B){this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0,a=false,l=true,o("warn",`Rate limited, skipping retries${this.integrationId?` [${this.integrationId}]`:""}`,{data:{events:e.events.length,attempt:c}});break}if(d instanceof A||(a=false),d instanceof TypeError||(l=true),o(h?"error":"warn",`Send attempt ${c} failed${this.integrationId?` [${this.integrationId}]`:""}${h?" (all retries exhausted)":", will retry"}`,{error:d,data:{events:e.events.length,url:i.replace(/\/\/[^/]+/,"//[DOMAIN]"),attempt:c,maxAttempts:3}}),!h){await this.backoffDelay(c);continue}if(a)throw new A("All retry attempts timed out (server likely received the request)");return l?(this.consecutiveNetworkFailures=0,this.circuitOpenedAt=0):(this.consecutiveNetworkFailures=Math.min(this.consecutiveNetworkFailures+1,3),this.consecutiveNetworkFailures>=3&&(this.circuitOpenedAt=Date.now())),false}return false}async sendWithTimeout(e,t){let r=new AbortController;this.pendingControllers.add(r);let i=false,s=setTimeout(()=>{i=true,r.abort();},15e3);try{let a=this.getCustomHeaders(),l=await fetch(e,{method:"POST",body:t,keepalive:!0,credentials:this.fetchCredentials,signal:r.signal,headers:{...a,"Content-Type":"application/json"}});if(!l.ok)throw l.status>=400&&l.status<500&&l.status!==408&&l.status!==429?new R(`HTTP ${l.status}: ${l.statusText}`,l.status):l.status===429?new B(`HTTP 429: ${l.statusText}`):new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(a){throw a instanceof R?a:i?new A("Request timed out (server likely received the request)"):a}finally{clearTimeout(s),this.pendingControllers.delete(r);}}sendQueueSyncInternal(e){let t=this.applyBeforeSendTransformer(e);if(!t)return true;let r=this.applyBeforeBatchTransformer(t);if(!r)return true;let{url:i,payload:s}=this.prepareRequest(r);if(s.length>65536)return o("warn",`Payload exceeds sendBeacon limit, persisting for recovery${this.integrationId?` [${this.integrationId}]`:""}`,{data:{size:s.length,limit:65536,events:r.events.length}}),this.persistEvents(r),false;let a=new Blob([s],{type:"application/json"});if(!this.isSendBeaconAvailable())return o("warn",`sendBeacon not available, persisting events for recovery${this.integrationId?` [${this.integrationId}]`:""}`),this.persistEvents(r),false;let l=navigator.sendBeacon(i,a);return l||(o("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;let r={...e,_metadata:{referer:typeof window<"u"?window.location.href:void 0,timestamp:t,client_version:Mt}};return {url:this.apiUrl||"",payload:JSON.stringify(r)}}getPersistedData(){try{let e=this.getQueueStorageKey(),t=this.storeManager.getItem(e);if(t)return JSON.parse(t)}catch(e){o("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"?false:(Date.now()-e.timestamp)/(1e3*60*60)<2}createRecoveryBody(e){let{timestamp:t,recoveryFailures:r,...i}=e;return i}persistEvents(e){return this.persistEventsWithFailureCount(e,0)}persistEventsWithFailureCount(e,t,r=false){try{let i=this.getPersistedData();if(!r&&i&&i.timestamp){let l=Date.now()-i.timestamp;if(l<1e3)return o("debug",`Skipping persistence, another tab recently persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{data:{timeSinceExisting:l}}),!0}let s={...e,timestamp:Date.now(),...t>0&&{recoveryFailures:t}},a=this.getQueueStorageKey();return this.storeManager.setItem(a,JSON.stringify(s)),!!this.storeManager.getItem(a)}catch(i){return o("debug",`Failed to persist events${this.integrationId?` [${this.integrationId}]`:""}`,{error:i}),false}}clearPersistedEvents(){try{let e=this.getQueueStorageKey();this.storeManager.removeItem(e);}catch(e){o("debug",`Failed to clear persisted events${this.integrationId?` [${this.integrationId}]`:""}`,{error:e});}}shouldSkipSend(){return !this.apiUrl}async simulateSuccessfulSend(){let e=Math.random()*400+100;return await new Promise(t=>setTimeout(t,e)),true}isSendBeaconAvailable(){return typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}logPermanentError(e,t){let r=Date.now();(!this.lastPermanentErrorLog||this.lastPermanentErrorLog.statusCode!==t.statusCode||r-this.lastPermanentErrorLog.timestamp>=6e4)&&(o("error",`${e}${this.integrationId?` [${this.integrationId}]`:""}`,{data:{status:t.statusCode,message:t.message}}),this.lastPermanentErrorLog={statusCode:t.statusCode,timestamp:r});}};var me=class extends f{bootTime;bootTimestamp;hasPerformanceNow;lastClockSkewCheck=0;detectedSkew=0;constructor(){if(super(),typeof window>"u"){this.hasPerformanceNow=false,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(),o("debug","TimeManager initialized with monotonic clock",{data:{bootTime:this.bootTime.toFixed(3),bootTimestamp:this.bootTimestamp}})):(this.bootTime=0,this.bootTimestamp=Date.now(),o("debug","performance.now() not available, falling back to Date.now()"));}now(){if(!this.hasPerformanceNow)return Date.now();let e=performance.now()-this.bootTime;return Math.round(this.bootTimestamp+e)}getClockSkew(){if(!this.hasPerformanceNow)return 0;let e=Date.now();if(e-this.lastClockSkewCheck<5e3)return this.detectedSkew;this.lastClockSkewCheck=e;let t=this.now(),r=Date.now();return this.detectedSkew=r-t,Math.abs(this.detectedSkew)>3e4&&o("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){let r=this.now(),i=e-r;return i>12e4?{valid:false,error:`Timestamp is ${(i/1e3/60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`}:{valid:true}}getBootInfo(){return {bootTime:this.bootTime,bootTimestamp:this.bootTimestamp,hasPerformanceNow:this.hasPerformanceNow,clockSkew:this.getClockSkew()}}};var cn=new Set(Object.values(I)),fe=class extends f{dataSenders;emitter;transformers;timeManager;recentEventFingerprints=new Map;perEventRateLimits=new Map;eventsQueue=[];pendingEventsBuffer=[];sendTimeoutId=null;sendInProgress=false;consecutiveSendFailures=0;rateLimitCounter=0;rateLimitWindowStart=0;lastSessionId=null;sessionEventCounts={total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0};saveSessionCountsDebounced=null;constructor(e,t=null,r={},i={},s,a="include"){super(),this.emitter=t,this.transformers=r,this.timeManager=new me,this.dataSenders=[];let l=this.get("collectApiUrls");l?.saas&&this.dataSenders.push(new Q(e,"saas",l.saas,r)),l?.custom&&this.dataSenders.push(new Q(e,"custom",l.custom,r,i,s,a)),this.saveSessionCountsDebounced=this.debounce(c=>{this.saveSessionCounts(c);},500),this.cleanupExpiredSessionCounts();}async recoverPersistedEvents(){let e=this.dataSenders.map(async t=>t.recoverPersistedEvents({onSuccess:(r,i,s)=>{if(i&&i.length>0){let a=i.map(l=>l.id);this.removeProcessedEvents(a),s&&this.emitEventsQueue(s);}},onFailure:()=>{o("debug","Failed to recover persisted events");}}));await Promise.allSettled(e);}track({type:e,page_url:t,from_page_url:r,scroll_data:i,click_data:s,custom_event:a,web_vitals:l,error_data:c,viewport_data:d,page_view:h}){if(!e){o("error","Event type is required - event will be ignored");return}if(!cn.has(e)){o("error","Invalid event type - event will be ignored",{data:{type:e}});return}let E=this.get("sessionId");if(!E){this.pendingEventsBuffer.length>=100&&(this.pendingEventsBuffer.shift(),o("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:i,click_data:s,custom_event:a,web_vitals:l,error_data:c,viewport_data:d,page_view:h});return}this.lastSessionId!==E&&(this.lastSessionId=E,this.sessionEventCounts=this.loadSessionCounts(E));let T=e==="session_start";if(T&&o("debug","Processing SESSION_START event",{data:{sessionId:E}}),!T&&!this.checkRateLimit())return;let g=e;if(!T){if(this.sessionEventCounts.total>=1e3){o("warn","Session event limit reached",{data:{type:g,total:this.sessionEventCounts.total,limit:1e3}});return}let _=this.getTypeLimitForEvent(g);if(_){let Re=this.sessionEventCounts[g];if(Re!==void 0&&Re>=_){o("warn","Session event type limit reached",{data:{type:g,count:Re,limit:_}});return}}}if(g==="custom"&&a?.name){let _=this.get("config")?.maxSameEventPerMinute??60;if(!this.checkPerEventRateLimit(a.name,_))return}let st=g==="session_start",K=t||this.get("pageUrl"),U=this.buildEventPayload({type:g,page_url:K,from_page_url:r,scroll_data:i,click_data:s,custom_event:a,web_vitals:l,error_data:c,viewport_data:d,page_view:h});if(U&&!(!T&&!this.shouldSample())){if(st){let _=this.get("sessionId");if(!_){o("error","Session start event requires sessionId - event will be ignored");return}if(this.get("hasStartSession")){o("debug","Duplicate session_start detected",{data:{sessionId:_}});return}this.set("hasStartSession",true);}if(!this.isDuplicateEvent(U)){if(this.get("mode")==="qa"){if(g==="custom"&&a){o("info",`Custom Event: ${a.name}`,{visibility:"qa",data:{name:a.name,...a.metadata&&{metadata:a.metadata}}}),this.emitEvent(U);return}if(g==="viewport_visible"&&d){let _=d.name||d.id||d.selector;o("info",`Viewport Visible: ${_}`,{visibility:"qa",data:{selector:d.selector,...d.name&&{name:d.name},...d.id&&{id:d.id},visibilityRatio:d.visibilityRatio,dwellTime:d.dwellTime}}),this.emitEvent(U);return}}if(this.addToQueue(U),!T){this.sessionEventCounts.total++,this.sessionEventCounts[g]!==void 0&&this.sessionEventCounts[g]++;let _=this.get("sessionId");_&&this.saveSessionCountsDebounced&&this.saveSessionCountsDebounced(_);}}}}stop(){this.clearSendTimeout(),this.sendInProgress=false,this.consecutiveSendFailures=0;let 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,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0},this.lastSessionId=null,this.set("hasStartSession",false),this.dataSenders.forEach(t=>{t.stop();});}async flushImmediately(){return this.flushEvents(false)}flushImmediatelySync(){return this.flushEvents(true)}setCustomHeadersProvider(e){for(let t of this.dataSenders)t.getIntegrationId()==="custom"&&t.setCustomHeadersProvider(e);}removeCustomHeadersProvider(){for(let 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")){o("debug","Cannot flush pending events: session not initialized - keeping in buffer",{data:{bufferedEventCount:this.pendingEventsBuffer.length}});return}let t=[...this.pendingEventsBuffer];this.pendingEventsBuffer=[],t.forEach(r=>{this.track(r);});}clearSendTimeout(){this.sendTimeoutId!==null&&(clearTimeout(this.sendTimeoutId),this.sendTimeoutId=null);}isSuccessfulResult(e){return e.status==="fulfilled"&&e.value===true}flushEvents(e){if(this.eventsQueue.length===0)return e?true:Promise.resolve(true);if(!e&&this.sendInProgress)return o("debug","Async flush skipped: send already in progress"),Promise.resolve(false);let t=this.buildEventsPayload(),r=[...this.eventsQueue],i=r.map(s=>s.id);if(this.dataSenders.length===0)return this.removeProcessedEvents(i),this.clearSendTimeout(),this.emitEventsQueue(t),e?true:Promise.resolve(true);if(e){let a=this.dataSenders.map(l=>l.sendEventsQueueSync(t)).some(l=>l);return a?(this.removeProcessedEvents(i),this.clearSendTimeout(),this.emitEventsQueue(t)):(this.clearSendTimeout(),o("debug","Sync flush complete failure, events kept in queue for retry",{data:{eventCount:i.length}})),a}else {let s=this.dataSenders.map(async a=>a.sendEventsQueue(t,{onSuccess:()=>{},onFailure:()=>{}}));return Promise.allSettled(s).then(a=>{let l=a.some(c=>this.isSuccessfulResult(c));return l?(this.removeProcessedEvents(i),this.clearSendTimeout(),this.emitEventsQueue(t)):o("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||this.sendInProgress)){this.sendInProgress=true;try{let e=this.buildEventsPayload();if(this.dataSenders.length===0){this.emitEventsQueue(e);return}let t=[...this.eventsQueue],r=t.map(l=>l.id),i=this.dataSenders.map(async l=>l.sendEventsQueue(e,{onSuccess:()=>{},onFailure:()=>{}})),s=await Promise.allSettled(i);if(s.some(l=>this.isSuccessfulResult(l))){this.consecutiveSendFailures=0,this.removeProcessedEvents(r),this.emitEventsQueue(e);let l=s.filter(c=>!this.isSuccessfulResult(c)).length;l>0&&o("debug","Periodic send completed with some failures, removed from queue and persisted per-integration",{data:{eventCount:t.length,failedCount:l}});}else this.consecutiveSendFailures=Math.min(this.consecutiveSendFailures+1,5),o("debug","Periodic send complete failure, events kept in queue for retry",{data:{eventCount:t.length}});this.eventsQueue.length===0?this.clearSendTimeout():this.scheduleSendTimeout();}finally{this.sendInProgress=false;}}}buildEventsPayload(){let e=new Map,t=[];for(let c of this.eventsQueue){let d=this.createEventSignature(c);e.has(d)||t.push(d),e.set(d,c);}let r=t.map(c=>e.get(c)).filter(c=>!!c).sort((c,d)=>c.type==="session_start"&&d.type!=="session_start"?-1:d.type==="session_start"&&c.type!=="session_start"?1:c.timestamp-d.timestamp),i={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},...this.get("identity")&&{identify:this.get("identity")}},s=this.get("collectApiUrls"),a=!!(s?.custom||s?.saas),l=this.transformers.beforeBatch;if(!a&&l){let c=ue(i,l,"EventManager");c!==null&&(i=c);}return i}buildEventPayload(e){let t=e.page_url??this.get("pageUrl"),r=this.timeManager.now(),i=this.timeManager.validateTimestamp(r);i.valid||o("warn","Event timestamp validation failed",{data:{type:e.type,error:i.error}});let s=this.get("sessionReferrer"),a=this.get("sessionUtm"),l={id:Nt(),type:e.type,page_url:t,timestamp:r,...s&&{referrer:s},...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},...a&&{utm:a}},c=this.get("collectApiUrls"),d=!!c?.custom,h=!!c?.saas,E=d||h,T=d&&h,g=this.transformers.beforeSend;if(g&&(!E||d&&!T)){let K=Ze(l,g,"EventManager");if(K===null)return null;l=K;}return l}isDuplicateEvent(e){let t=Date.now(),r=this.createEventFingerprint(e),i=this.recentEventFingerprints.get(r);return i&&t-i<1e3?(this.recentEventFingerprints.set(r,t),true):(this.recentEventFingerprints.set(r,t),this.recentEventFingerprints.size>1500&&this.pruneOldFingerprints(),this.recentEventFingerprints.size>3e3&&(this.recentEventFingerprints.clear(),this.recentEventFingerprints.set(r,t),o("debug","Event fingerprint cache exceeded hard limit, cleared",{data:{hardLimit:3e3}})),false)}pruneOldFingerprints(){let e=Date.now(),t=1e3*10;for(let[r,i]of this.recentEventFingerprints.entries())e-i>t&&this.recentEventFingerprints.delete(r);o("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){let r=Math.round((e.click_data.x||0)/10)*10,i=Math.round((e.click_data.y||0)/10)*10;t+=`_click_${r}_${i}`;}return e.scroll_data&&(t+=`_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`),e.custom_event&&(t+=`_custom_${e.custom_event.name}`,e.custom_event.metadata&&(t+=`_${this.stableStringify(e.custom_event.metadata)}`)),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)}stableStringify(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((i,s)=>(i[s]=r[s],i),{}):r)}addToQueue(e){if(this.emitEvent(e),this.eventsQueue.push(e),this.eventsQueue.length>100){let t=this.eventsQueue.findIndex(i=>i.type!=="session_start"),r=t>=0?this.eventsQueue.splice(t,1)[0]:this.eventsQueue.shift();o("warn","Event queue overflow, oldest non-critical event removed",{data:{maxLength:100,currentLength:this.eventsQueue.length,removedEventType:r?.type,wasCritical:r?.type==="session_start"}});}this.scheduleSendTimeout(),this.eventsQueue.length>=50&&this.consecutiveSendFailures<5&&this.sendEventsQueue();}scheduleSendTimeout(){if(this.sendTimeoutId!==null)return;let e=this.calculateSendDelay();this.sendTimeoutId=window.setTimeout(()=>{this.sendTimeoutId=null,this.eventsQueue.length>0&&this.sendEventsQueue();},e);}calculateSendDelay(){let e=this.get("config")?.sendIntervalMs??1e4;if(this.consecutiveSendFailures===0)return e;let t=e*Math.pow(2,this.consecutiveSendFailures);return Math.min(t,12e4)}shouldSample(){let e=this.get("config")?.samplingRate??1;return Math.random()<e}checkRateLimit(){let e=Date.now();return e-this.rateLimitWindowStart>1e3&&(this.rateLimitCounter=0,this.rateLimitWindowStart=e),this.rateLimitCounter>=50?false:(this.rateLimitCounter++,true)}checkPerEventRateLimit(e,t){let r=Date.now(),s=(this.perEventRateLimits.get(e)??[]).filter(a=>r-a<6e4);return s.length>=t?(o("warn","Per-event rate limit exceeded for custom event",{data:{eventName:e,limit:t,window:`${6e4/1e3}s`}}),false):(s.push(r),this.perEventRateLimits.set(e,s),true)}getTypeLimitForEvent(e){return {click:500,page_view:100,custom:500,viewport_visible:200,scroll:120}[e]??null}removeProcessedEvents(e){let t=new Set(e);this.eventsQueue=this.eventsQueue.filter(r=>!t.has(r.id));}emitEvent(e){this.emitter&&this.emitter.emit("event",e);}emitEventsQueue(e){this.emitter&&this.emitter.emit("queue",e);}debounce(e,t){let r=null;return((...i)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{e(...i),r=null;},t);})}getInitialCounts(){return {total:0,click:0,page_view:0,custom:0,viewport_visible:0,scroll:0}}loadSessionCounts(e){if(typeof window>"u"||typeof localStorage>"u")return this.getInitialCounts();let t=this.get("userId")||"anonymous",r=Pe(t,e);try{let i=localStorage.getItem(r);if(!i)return this.getInitialCounts();let s=JSON.parse(i);return s._timestamp&&Date.now()-s._timestamp>xe?(o("debug","Session counts expired, clearing",{data:{sessionId:e,age:Date.now()-s._timestamp}}),localStorage.removeItem(r),this.getInitialCounts()):typeof s.total=="number"&&typeof s.click=="number"&&typeof s.page_view=="number"&&typeof s.custom=="number"&&typeof s.viewport_visible=="number"&&typeof s.scroll=="number"?{total:s.total,click:s.click,page_view:s.page_view,custom:s.custom,viewport_visible:s.viewport_visible,scroll:s.scroll}:(o("warn","Invalid session counts structure in localStorage, resetting",{data:{sessionId:e,parsed:s}}),localStorage.removeItem(r),o("debug","Session counts removed due to invalid/corrupted data",{data:{sessionId:e,parsed:s}}),this.getInitialCounts())}catch(i){return o("warn","Failed to load session counts from localStorage",{error:i,data:{sessionId:e}}),this.getInitialCounts()}}cleanupExpiredSessionCounts(){if(!(typeof window>"u"||typeof localStorage>"u"))try{let e=localStorage.getItem(De);if(e){let s=Date.now()-parseInt(e,10);if(s<ke){o("debug","Skipping session counts cleanup (throttled)",{data:{timeSinceLastCleanup:s,throttleMs:ke}});return}}let t=this.get("userId")||"anonymous",r=`${v}:${t}:session_counts:`,i=[];for(let s=0;s<localStorage.length;s++){let a=localStorage.key(s);if(a?.startsWith(r))try{let l=localStorage.getItem(a);if(l){let c=JSON.parse(l);c._timestamp&&Date.now()-c._timestamp>xe&&i.push(a);}}catch{}}i.forEach(s=>{localStorage.removeItem(s),o("debug","Cleaned up expired session counts",{data:{key:s}});}),i.length>0&&o("info",`Cleaned up ${i.length} expired session counts entries`),localStorage.setItem(De,Date.now().toString());}catch(e){o("warn","Failed to cleanup expired session counts",{error:e});}}saveSessionCounts(e){let t=this.get("userId")||"anonymous",r=Pe(t,e);try{let i={...this.sessionEventCounts,_timestamp:Date.now(),_version:1};localStorage.setItem(r,JSON.stringify(i));}catch(i){o("warn","Failed to persist session counts to localStorage",{error:i,data:{sessionId:e}});}}};var he=class{static getId(e){let t=e.getItem(H);if(t)return t;let r=ae();return e.setItem(H,r),r}};var dn=/^\d{13}-[a-z0-9]{9}$/,ge=class extends f{storageManager;eventManager;projectId;activityHandler=null;visibilityChangeHandler=null;sessionTimeoutId=null;broadcastChannel=null;isTracking=false;needsRenewal=false;constructor(e,t,r){super(),this.storageManager=e,this.eventManager=t,this.projectId=r;}initCrossTabSync(){if(typeof BroadcastChannel>"u"){o("debug","BroadcastChannel not supported");return}let e=this.getProjectId();this.broadcastChannel=new BroadcastChannel(mt(e)),this.broadcastChannel.onmessage=t=>{let{action:r,sessionId:i,timestamp:s,projectId:a}=t.data??{};a===e&&(r==="session_start"&&i&&typeof s=="number"&&s>Date.now()-5e3?(this.set("sessionId",i),this.persistSession(i,s),this.isTracking&&this.setupSessionTimeout()):r&&r!=="session_start"&&o("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(){let e=this.loadStoredSession();if(!e)return null;if(!dn.test(e.id))return o("warn","Invalid session ID format recovered from storage, clearing",{data:{sessionId:e.id}}),this.clearStoredSession(),null;let t=this.get("config")?.sessionTimeout??9e5;return Date.now()-e.lastActivity>t?(this.clearStoredSession(),null):e.id}persistSession(e,t=Date.now(),r,i){this.saveStoredSession({id:e,lastActivity:t,...r&&{referrer:r},...i&&{utm:i}});}clearStoredSession(){let e=this.getSessionStorageKey();this.storageManager.removeItem(e);}loadStoredSession(){let e=this.getSessionStorageKey(),t=this.storageManager.getItem(e);if(t!==null)try{let i=JSON.parse(t);if(i.id&&typeof i.lastActivity=="number")return i}catch{this.storageManager.removeItem(e);}let r=this.storageManager.getSessionItem(e);if(r!==null)try{let i=JSON.parse(r);if(i.id&&typeof i.lastActivity=="number")return i}catch{this.storageManager.removeSessionItem(e);}return null}saveStoredSession(e){let t=this.getSessionStorageKey(),r=JSON.stringify(e);this.storageManager.setItem(t,r),this.storageManager.setSessionItem(t,r);}getSessionStorageKey(){return ut(this.getProjectId())}getProjectId(){return this.projectId}startTracking(){if(this.isTracking){o("debug","Session tracking already active");return}let e=this.recoverSession(),t=e??this.generateSessionId(),r,i;if(e){let s=this.loadStoredSession();r=s?.referrer??ne(),i=s?.utm??ie();}else r=ne(),i=ie();o("debug","Session tracking initialized",{data:{sessionId:t,wasRecovered:!!e,willEmitSessionStart:!e,sessionReferrer:r,hasUtm:!!i}}),this.isTracking=true;try{this.set("sessionId",t),this.set("sessionReferrer",r),this.set("sessionUtm",i),this.persistSession(t,Date.now(),r,i),this.initCrossTabSync(),this.shareSession(t),e?o("debug","Session recovered, skipping SESSION_START",{data:{sessionId:t}}):(o("debug","Emitting SESSION_START event",{data:{sessionId:t}}),this.eventManager.track({type:"session_start"})),this.setupSessionTimeout(),this.setupActivityListeners(),this.setupLifecycleListeners();}catch(s){throw this.isTracking=false,this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupLifecycleListeners(),this.cleanupCrossTabSync(),this.set("sessionId",null),s}}generateSessionId(){return `${Date.now()}-${Math.random().toString(36).substring(2,11)}`}setupSessionTimeout(){this.clearSessionTimeout();let e=this.get("config")?.sessionTimeout??9e5;this.sessionTimeoutId=setTimeout(()=>{this.enterRenewalMode();},e);}resetSessionTimeout(){this.setupSessionTimeout();let 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:true}),document.addEventListener("keydown",this.activityHandler,{passive:true}),document.addEventListener("scroll",this.activityHandler,{passive:true});}renewSession(){this.needsRenewal=false;let e=this.generateSessionId(),t=ne(),r=ie();o("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:"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()){o("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 false;let t=this.loadStoredSession();if(!t)return false;let 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",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=true,o("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",false),this.set("sessionReferrer",void 0),this.set("sessionUtm",void 0),this.needsRenewal=false,this.isTracking=false;}stopTracking(){this.resetSessionState();}destroy(){this.clearSessionTimeout(),this.cleanupActivityListeners(),this.cleanupCrossTabSync(),this.cleanupLifecycleListeners(),this.isTracking=false,this.needsRenewal=false,this.set("hasStartSession",false);}};var Ee=class extends f{eventManager;storageManager;sessionManager=null;destroyed=false;constructor(e,t){super(),this.eventManager=t,this.storageManager=e;}startTracking(){if(this.isActive())return;if(this.destroyed){o("debug","Cannot start tracking on destroyed handler");return}let t=this.get("config")?.integrations?.tracelog?.projectId??"custom";try{this.sessionManager=new ge(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 o("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=true);}};var ve=class extends f{eventManager;onTrack;originalPushState;originalReplaceState;lastPageViewTime=0;constructor(e,t){super(),this.eventManager=e,this.onTrack=t;}startTracking(){this.trackInitialPageView(),window.addEventListener("popstate",this.trackCurrentPage,true),window.addEventListener("hashchange",this.trackCurrentPage,true),this.patchHistory("pushState"),this.patchHistory("replaceState");}stopTracking(){window.removeEventListener("popstate",this.trackCurrentPage,true),window.removeEventListener("hashchange",this.trackCurrentPage,true),this.originalPushState&&(window.history.pushState=this.originalPushState),this.originalReplaceState&&(window.history.replaceState=this.originalReplaceState),this.lastPageViewTime=0;}patchHistory(e){let 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=()=>{let e=window.location.href,t=j(e,this.get("config").sensitiveQueryParams);if(this.get("pageUrl")===t)return;let r=Date.now(),i=this.get("config").pageViewThrottleMs??1e3;if(r-this.lastPageViewTime<i)return;this.lastPageViewTime=r,this.onTrack();let s=this.get("pageUrl");this.set("pageUrl",t);let a=this.extractPageViewData();this.eventManager.track({type:"page_view",page_url:this.get("pageUrl"),from_page_url:s,...a&&{page_view:a}});};trackInitialPageView(){let e=j(window.location.href,this.get("config").sensitiveQueryParams),t=this.extractPageViewData();this.lastPageViewTime=Date.now(),this.eventManager.track({type:"page_view",page_url:e,...t&&{page_view:t}}),this.onTrack();}extractPageViewData(){let{pathname:e,search:t,hash:r}=window.location,{referrer:i}=document,{title:s}=document;return !i&&!s&&!e&&!t&&!r?void 0:{...i&&{referrer:i},...s&&{title:s},...e&&{pathname:e},...t&&{search:t},...r&&{hash:r}}}};var Se=class extends f{eventManager;lastClickTimes=new Map;clickHandler;lastPruneTime=0;constructor(e){super(),this.eventManager=e;}startTracking(){this.clickHandler||(this.clickHandler=e=>{let t=e,r=t.target,i=typeof HTMLElement<"u"&&r instanceof HTMLElement?r:typeof HTMLElement<"u"&&r instanceof Node&&r.parentElement instanceof HTMLElement?r.parentElement:null;if(!i){o("debug","Click target not found or not an element");return}if(this.shouldIgnoreElement(i))return;let s=this.get("config")?.clickThrottleMs??300;if(s>0&&!this.checkClickThrottle(i,s))return;let a=this.findTrackingElement(i),l=this.getRelevantClickElement(i),c=this.calculateClickCoordinates(t,i);if(a){let h=this.extractTrackingData(a);if(h){let E=this.createCustomEventData(h);this.eventManager.track({type:"custom",custom_event:{name:E.name,...E.value&&{metadata:{value:E.value}}}});}}let d=this.generateClickData(i,l,c);this.eventManager.track({type:"click",click_data:d});},window.addEventListener("click",this.clickHandler,true));}stopTracking(){this.clickHandler&&(window.removeEventListener("click",this.clickHandler,true),this.clickHandler=void 0),this.lastClickTimes.clear(),this.lastPruneTime=0;}shouldIgnoreElement(e){return e.hasAttribute(`${y}-ignore`)?true:e.closest(`[${y}-ignore]`)!==null}checkClickThrottle(e,t){let r=this.getElementSignature(e),i=Date.now();this.pruneThrottleCache(i);let s=this.lastClickTimes.get(r);return s!==void 0&&i-s<t?(o("debug","ClickHandler: Click suppressed by throttle",{data:{signature:r,throttleRemaining:t-(i-s)}}),false):(this.lastClickTimes.set(r,i),true)}pruneThrottleCache(e){if(e-this.lastPruneTime<3e4)return;this.lastPruneTime=e;let t=e-3e5;for(let[r,i]of this.lastClickTimes.entries())i<t&&this.lastClickTimes.delete(r);if(this.lastClickTimes.size>1e3){let r=Array.from(this.lastClickTimes.entries()).sort((a,l)=>a[1]-l[1]),i=this.lastClickTimes.size-1e3,s=r.slice(0,i);for(let[a]of s)this.lastClickTimes.delete(a);o("debug","ClickHandler: Pruned throttle cache",{data:{removed:s.length,remaining:this.lastClickTimes.size}});}}getElementSignature(e){if(e.id)return `#${e.id}`;let t=e.getAttribute("data-testid");if(t)return `[data-testid="${t}"]`;let r=e.getAttribute(`${y}-name`);return r?`[${y}-name="${r}"]`:this.getElementPath(e)}getElementPath(e){let t=[],r=e;for(;r&&r!==document.body;){let i=r.tagName.toLowerCase();if(r.className){let s=r.className.split(" ")[0];s&&(i+=`.${s}`);}t.unshift(i),r=r.parentElement;}return t.join(">")||"unknown"}findTrackingElement(e){return e.hasAttribute(`${y}-name`)?e:e.closest(`[${y}-name]`)}getRelevantClickElement(e){for(let t of ot)try{if(e.matches(t))return e;let r=e.closest(t);if(r)return r}catch(r){o("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){let r=t.getBoundingClientRect(),i=e.clientX,s=e.clientY,a=r.width>0?this.clamp((i-r.left)/r.width):0,l=r.height>0?this.clamp((s-r.top)/r.height):0;return {x:i,y:s,relativeX:a,relativeY:l}}extractTrackingData(e){let t=e.getAttribute(`${y}-name`),r=e.getAttribute(`${y}-value`);if(t)return {element:e,name:t,...r&&{value:r}}}generateClickData(e,t,r){let{x:i,y:s,relativeX:a,relativeY:l}=r,c=this.getRelevantText(e,t),d=this.extractElementAttributes(t);return {x:i,y:s,relativeX:a,relativeY:l,tag:t.tagName.toLowerCase(),...t.id&&{id:t.id},...t.className&&{class:t.className},...c&&{text:c},...d.href&&{href:d.href},...d.title&&{title:d.title},...d.alt&&{alt:d.alt},...d.role&&{role:d.role},...d["aria-label"]&&{ariaLabel:d["aria-label"]},...Object.keys(d).length>0&&{dataAttributes:d}}}sanitizeText(e){let t=e;for(let r of $){let i=new RegExp(r.source,r.flags);t=t.replace(i,"[REDACTED]");}return t}getRelevantText(e,t){let r=e.textContent?.trim()??"",i=t.textContent?.trim()??"";if(!r&&!i)return "";let s="";return r&&r.length<=255?s=r:i.length<=255?s=i:s=i.slice(0,252)+"...",this.sanitizeText(s)}extractElementAttributes(e){let t=["id","class","data-testid","aria-label","title","href","type","name","alt","role"],r={};for(let i of t){let s=e.getAttribute(i);s&&(r[i]=s);}return r}createCustomEventData(e){return {name:e.name,...e.value&&{value:e.value}}}};var _e=class extends f{eventManager;containers=[];limitWarningLogged=false;minDepthChange=5;minIntervalMs=500;maxEventsPerSession=120;containerDiscoveryTimeoutId=null;constructor(e){super(),this.eventManager=e;}startTracking(){this.limitWarningLogged=false,this.applyConfigOverrides(),this.set("scrollEventCount",0),this.tryDetectScrollContainers(0);}stopTracking(){this.containerDiscoveryTimeoutId!==null&&(clearTimeout(this.containerDiscoveryTimeoutId),this.containerDiscoveryTimeoutId=null);for(let 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=false;}tryDetectScrollContainers(e){let t=this.findScrollableElements();if(this.isWindowScrollable()&&this.setupScrollContainer(window,"window"),t.length>0){for(let r of t){let i=this.getElementSelector(r);this.setupScrollContainer(r,i);}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(){let e=this.get("config");e?.primaryScrollSelector&&this.applyPrimaryScrollSelector(e.primaryScrollSelector);}findScrollableElements(){if(!document.body)return [];let e=[],t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{let s=i;if(!s.isConnected||!s.offsetParent)return NodeFilter.FILTER_SKIP;let a=getComputedStyle(s);return a.overflowY==="auto"||a.overflowY==="scroll"||a.overflow==="auto"||a.overflow==="scroll"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),r;for(;(r=t.nextNode())&&e.length<10;){let i=r;this.isElementScrollable(i)&&e.push(i);}return e}getElementSelector(e){if(e===window)return "window";let t=e;if(t.id)return `#${t.id}`;if(t.className&&typeof t.className=="string"){let r=t.className.split(" ").filter(i=>i.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(d=>d.element===e)||e!==window&&!this.isElementScrollable(e))return;let i=this.getScrollTop(e),s=this.calculateScrollDepth(i,this.getScrollHeight(e),this.getViewportHeight(e)),a=this.determineIfPrimary(e),l={element:e,selector:t,isPrimary:a,lastScrollPos:i,lastDepth:s,lastDirection:"down",lastEventTime:0,firstScrollEventTime:null,maxDepthReached:s,debounceTimer:null,listener:null},c=()=>{this.get("suppressNextScroll")||(l.firstScrollEventTime===null&&(l.firstScrollEventTime=Date.now()),this.clearContainerTimer(l),l.debounceTimer=window.setTimeout(()=>{let d=this.calculateScrollData(l);if(d){let h=Date.now();this.processScrollEvent(l,d,h);}l.debounceTimer=null;},250));};l.listener=c,this.containers.push(l),e===window?window.addEventListener("scroll",c,{passive:true}):e.addEventListener("scroll",c,{passive:true});}processScrollEvent(e,t,r){if(!this.shouldEmitScrollEvent(e,t,r))return;e.lastEventTime=r,e.lastDepth=t.depth,e.lastDirection=t.direction;let i=this.get("scrollEventCount")??0;this.set("scrollEventCount",i+1),this.eventManager.track({type:"scroll",scroll_data:{...t,container_selector:e.selector,is_primary:e.isPrimary}});}shouldEmitScrollEvent(e,t,r){return this.hasReachedSessionLimit()?(this.logLimitOnce(),false):!(!this.hasElapsedMinimumInterval(e,r)||!this.hasSignificantDepthChange(e,t.depth))}hasReachedSessionLimit(){return (this.get("scrollEventCount")??0)>=this.maxEventsPerSession}hasElapsedMinimumInterval(e,t){return e.lastEventTime===0?true:t-e.lastEventTime>=this.minIntervalMs}hasSignificantDepthChange(e,t){return Math.abs(t-e.lastDepth)>=this.minDepthChange}logLimitOnce(){this.limitWarningLogged||(this.limitWarningLogged=true,o("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;let i=t-r;return Math.min(100,Math.max(0,Math.floor(e/i*100)))}calculateScrollData(e){let{element:t,lastScrollPos:r,lastEventTime:i}=e,s=this.getScrollTop(t),a=Date.now(),l=Math.abs(s-r);if(l<10||t===window&&!this.isWindowScrollable())return null;let c=this.getViewportHeight(t),d=this.getScrollHeight(t),h=this.getScrollDirection(s,r),E=this.calculateScrollDepth(s,d,c),T;i>0?T=a-i:e.firstScrollEventTime!==null?T=a-e.firstScrollEventTime:T=250;let g=Math.round(l/T*1e3);return E>e.maxDepthReached&&(e.maxDepthReached=E),e.lastScrollPos=s,{depth:E,direction:h,velocity:g,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){let t=getComputedStyle(e),r=t.overflowY==="auto"||t.overflowY==="scroll"||t.overflow==="auto"||t.overflow==="scroll",i=e.scrollHeight>e.clientHeight;return r&&i}applyPrimaryScrollSelector(e){let t;if(e==="window")t=window;else {let i=document.querySelector(e);if(!(i instanceof HTMLElement)){o("debug",`Selector "${e}" did not match an HTMLElement`);return}t=i;}this.containers.forEach(i=>{this.updateContainerPrimary(i,i.element===t);}),!this.containers.some(i=>i.element===t)&&t instanceof HTMLElement&&this.isElementScrollable(t)&&this.setupScrollContainer(t,e);}updateContainerPrimary(e,t){e.isPrimary=t;}};var ye=class extends f{eventManager;trackedElements=new Map;observer=null;mutationObserver=null;mutationDebounceTimer=null;config=null;constructor(e){super(),this.eventManager=e;}startTracking(){let e=this.get("config");if(this.config=e.viewport??null,!this.config?.elements||this.config.elements.length===0)return;let t=this.config.threshold??.5,r=this.config.minDwellTime??1e3;if(t<0||t>1){o("debug","ViewportHandler: Invalid threshold, must be between 0 and 1");return}if(r<0){o("debug","ViewportHandler: Invalid minDwellTime, must be non-negative");return}if(typeof IntersectionObserver>"u"){o("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(let e of this.trackedElements.values())e.timeoutId!==null&&window.clearTimeout(e.timeoutId);this.trackedElements.clear();}observeElements(){if(!this.config||!this.observer)return;let e=this.config.maxTrackedElements??100,t=this.trackedElements.size;for(let r of this.config.elements)try{let i=document.querySelectorAll(r.selector);for(let s of Array.from(i)){if(t>=e){o("debug","ViewportHandler: Maximum tracked elements reached",{data:{limit:e,selector:r.selector,message:"Some elements will not be tracked. Consider more specific selectors."}});return}s.hasAttribute(`${y}-ignore`)||this.trackedElements.has(s)||(this.trackedElements.set(s,{element:s,selector:r.selector,id:r.id,name:r.name,startTime:null,timeoutId:null,lastFiredTime:null}),this.observer?.observe(s),t++);}}catch(i){o("debug",`ViewportHandler: Invalid selector "${r.selector}"`,{error:i});}o("debug","ViewportHandler: Elements tracked",{data:{count:t,limit:e}});}handleIntersection=e=>{if(!this.config)return;let t=this.config.minDwellTime??1e3;for(let r of e){let i=this.trackedElements.get(r.target);i&&(r.isIntersecting?i.startTime===null&&(i.startTime=performance.now(),i.timeoutId=window.setTimeout(()=>{let s=Math.round(r.intersectionRatio*100)/100;this.fireViewportEvent(i,s);},t)):i.startTime!==null&&(i.timeoutId!==null&&(window.clearTimeout(i.timeoutId),i.timeoutId=null),i.startTime=null));}};fireViewportEvent(e,t){if(e.startTime===null)return;let r=Math.round(performance.now()-e.startTime);if(e.element.hasAttribute(`${y}-ignore`))return;let i=this.config?.cooldownPeriod??6e4,s=Date.now();if(e.lastFiredTime!==null&&s-e.lastFiredTime<i){o("debug","ViewportHandler: Event suppressed by cooldown period",{data:{selector:e.selector,cooldownRemaining:i-(s-e.lastFiredTime)}}),e.startTime=null,e.timeoutId=null;return}let a={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:"viewport_visible",viewport_data:a}),e.startTime=null,e.timeoutId=null,e.lastFiredTime=s;}setupMutationObserver(){if(!(!this.config||typeof MutationObserver>"u")){if(!document.body){o("debug","ViewportHandler: document.body not available, skipping MutationObserver setup");return}this.mutationObserver=new MutationObserver(e=>{let t=false;for(let r of e)r.type==="childList"&&(r.addedNodes.length>0&&(t=true),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:true,subtree:true});}}cleanupRemovedNodes(e){e.forEach(t=>{if(t.nodeType!==1)return;let r=t,i=this.trackedElements.get(r);i&&(i.timeoutId!==null&&window.clearTimeout(i.timeoutId),this.observer?.unobserve(r),this.trackedElements.delete(r)),Array.from(this.trackedElements.keys()).filter(a=>r.contains(a)).forEach(a=>{let l=this.trackedElements.get(a);l&&l.timeoutId!==null&&window.clearTimeout(l.timeoutId),this.observer?.unobserve(a),this.trackedElements.delete(a);});});}};var hn="tracelog_session_id",G=class extends f{visibilityHandler=null;lastSyncedSessionId=null;activate(){this.cleanupVisibilityListener(),this.syncCartAttribute(),this.setupVisibilityListener();}deactivate(){this.cleanupVisibilityListener(),this.lastSyncedSessionId=null;}onSessionChange(){this.syncCartAttribute();}syncCartAttribute(){let e=this.get("sessionId");!e||e===this.lastSyncedSessionId||(this.lastSyncedSessionId=e,this.postCartUpdate(e));}postCartUpdate(e){try{fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:{[hn]:e}}),credentials:"same-origin"}).then(t=>{t.ok||(this.lastSyncedSessionId=null,o("debug","Shopify cart attribute update failed",{data:{status:t.status}}));}).catch(()=>{this.lastSyncedSessionId=null,o("debug","Shopify cart attribute update failed");});}catch{this.lastSyncedSessionId=null,o("debug","Shopify cart attribute update failed");}}setupVisibilityListener(){this.visibilityHandler=()=>{document.hidden||this.syncCartAttribute();},document.addEventListener("visibilitychange",this.visibilityHandler);}cleanupVisibilityListener(){this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}};var Ie=class{storage;sessionStorageRef;fallbackStorage=new Map;fallbackSessionStorage=new Map;hasQuotaExceededError=false;constructor(){this.storage=this.initializeStorage("localStorage"),this.sessionStorageRef=this.initializeStorage("sessionStorage"),this.storage||o("debug","localStorage not available, using memory fallback"),this.sessionStorageRef||o("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=true,o("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(a){o("error","localStorage quota exceeded even after cleanup - data will not persist",{error:a,data:{key:e,valueSize:t.length}});}else o("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{let e=[];for(let t=0;t<this.storage.length;t++){let r=this.storage.key(t);r?.startsWith("tracelog_")&&e.push(r);}e.forEach(t=>{this.storage.removeItem(t);}),this.fallbackStorage.clear();}catch(e){o("error","Failed to clear storage",{error:e}),this.fallbackStorage.clear();}}isAvailable(){return this.storage!==null}hasQuotaError(){return this.hasQuotaExceededError}cleanupOldData(){if(!this.storage)return false;try{let e=[],t=[];for(let s=0;s<this.storage.length;s++){let a=this.storage.key(s);a?.startsWith("tracelog_")&&(e.push(a),a.startsWith("tracelog_persisted_events_")&&t.push(a));}if(t.length>0)return t.forEach(s=>{try{this.storage.removeItem(s);}catch{}}),!0;let r=["tracelog_session_","tracelog_user_id","tracelog_device_id","tracelog_config"],i=e.filter(s=>!r.some(a=>s.startsWith(a)));return i.length>0?(i.slice(0,5).forEach(a=>{try{this.storage.removeItem(a);}catch{}}),!0):!1}catch(e){return o("error","Failed to cleanup old data",{error:e}),false}}initializeStorage(e){if(typeof window>"u")return null;try{let 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")&&o("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);}};var be=class extends f{eventManager;reportedByNav=new Map;navigationHistory=[];observers=[];vitalThresholds;lastLongTaskSentAt=0;navigationCounter=0;constructor(e){super(),this.eventManager=e,this.vitalThresholds=re(W);}async startTracking(){let e=this.get("config"),t=e?.webVitalsMode??W;this.vitalThresholds=re(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){o("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=>{let i=r.getEntries(),s=i[i.length-1];s&&this.sendVital({type:"LCP",value:Number(s.startTime.toFixed(2))});},{type:"largest-contentful-paint",buffered:true},true);let e=0,t=this.getNavigationId();this.safeObserve("layout-shift",r=>{let i=this.getNavigationId();i!==t&&(e=0,t=i);let s=r.getEntries();for(let a of s){if(a.hadRecentInput===true)continue;let l=typeof a.value=="number"?a.value:0;e+=l;}this.sendVital({type:"CLS",value:Number(e.toFixed(2))});},{type:"layout-shift",buffered:true}),this.safeObserve("paint",r=>{for(let i of r.getEntries())i.name==="first-contentful-paint"&&this.sendVital({type:"FCP",value:Number(i.startTime.toFixed(2))});},{type:"paint",buffered:true},true),this.safeObserve("event",r=>{let i=0,s=r.getEntries();for(let a of s){let l=(a.processingEnd??0)-(a.startTime??0);i=Math.max(i,l);}i>0&&this.sendVital({type:"INP",value:Number(i.toFixed(2))});},{type:"event",buffered:true});}async initWebVitals(){try{let{onLCP:e,onCLS:t,onFCP:r,onTTFB:i,onINP:s}=await import('web-vitals'),a=l=>c=>{let d=Number(c.value.toFixed(2));this.sendVital({type:l,value:d});};e(a("LCP"),{reportAllChanges:!1}),t(a("CLS"),{reportAllChanges:!1}),r(a("FCP"),{reportAllChanges:!1}),i(a("TTFB"),{reportAllChanges:!1}),s(a("INP"),{reportAllChanges:!1});}catch(e){o("debug","Failed to load web-vitals library, using fallback",{error:e}),this.observeWebVitalsFallback();}}reportTTFB(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return;let t=e.responseStart;typeof t=="number"&&Number.isFinite(t)&&this.sendVital({type:"TTFB",value:Number(t.toFixed(2))});}catch(e){o("debug","Failed to report TTFB",{error:e});}}observeLongTasks(){this.safeObserve("longtask",e=>{let t=e.getEntries();for(let r of t){let i=Number(r.duration.toFixed(2)),s=Date.now();s-this.lastLongTaskSentAt>=It&&(this.shouldSendVital("LONG_TASK",i)&&this.trackWebVital("LONG_TASK",i),this.lastLongTaskSentAt=s);}},{type:"longtask",buffered:true});}sendVital(e){if(!this.shouldSendVital(e.type,e.value))return;let t=this.getNavigationId();if(t){let 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>bt){let s=this.navigationHistory.shift();s&&this.reportedByNav.delete(s);}}this.trackWebVital(e.type,e.value);}trackWebVital(e,t){if(!Number.isFinite(t)){o("debug","Invalid web vital value",{data:{type:e,value:t}});return}this.eventManager.track({type:"web_vitals",web_vitals:{type:e,value:t}});}getNavigationId(){try{let e=performance.getEntriesByType("navigation")[0];if(!e)return null;let t=e.startTime||performance.now(),r=++this.navigationCounter,i=`${t.toFixed(2)}_${window.location.pathname}`;return r>1?`${i}_${r}`:i}catch(e){return o("debug","Failed to get navigation ID",{error:e}),null}}isObserverSupported(e){if(typeof PerformanceObserver>"u")return false;let t=PerformanceObserver.supportedEntryTypes;return !t||t.includes(e)}safeObserve(e,t,r,i=false){try{if(!this.isObserverSupported(e))return !1;let s=new PerformanceObserver((a,l)=>{try{t(a,l);}catch(c){o("debug","Observer callback failed",{error:c,data:{type:e}});}if(i)try{l.disconnect();}catch{}});return s.observe(r??{type:e,buffered:!0}),i||this.observers.push(s),!0}catch(s){return o("debug","Failed to create performance observer",{error:s,data:{type:e}}),false}}shouldSendVital(e,t){if(typeof t!="number"||!Number.isFinite(t))return o("debug","Invalid web vital value",{data:{type:e,value:t}}),false;let r=this.vitalThresholds[e];return !(typeof r=="number"&&t<=r)}};var we=class n extends f{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(){let e=Date.now();if(e<this.burstBackoffUntil)return false;if(e-this.burstWindowStart>1e3&&(this.errorBurstCounter=0,this.burstWindowStart=e),this.errorBurstCounter++,this.errorBurstCounter>10)return this.burstBackoffUntil=e+5e3,o("debug","Error burst detected - entering cooldown",{data:{errorsInWindow:this.errorBurstCounter,cooldownMs:5e3}}),false;let r=this.get("config").errorSampling??1;return Math.random()<r}handleError=e=>{if(!this.shouldSample())return;let t=this.sanitize(e.message||"Unknown error");if(this.shouldSuppressError("js_error",t))return;let r=typeof e.error?.stack=="string"?this.truncateStack(e.error.stack):void 0;this.eventManager.track({type:"error",error_data:{type:"js_error",message:t,...e.filename!==""&&{filename:e.filename},...e.lineno!==0&&{line:e.lineno},...e.colno!==0&&{column:e.colno},...r!==void 0&&{stack:r}}});};handleRejection=e=>{if(!this.shouldSample())return;let t=this.extractRejectionMessage(e.reason),r=this.sanitize(t);if(this.shouldSuppressError("promise_rejection",r))return;let i=e.reason instanceof Error&&typeof e.reason.stack=="string"?this.truncateStack(e.reason.stack):void 0;this.eventManager.track({type:"error",error_data:{type:"promise_rejection",message:r,...i!==void 0&&{stack:i}}});};extractRejectionMessage(e){if(e==null)return "Unknown rejection";if(typeof e=="string")return e;if(e instanceof Error)return e.message;if(typeof e=="object"&&"message"in e)return String(e.message);try{return JSON.stringify(e)}catch{return "Unserializable rejection"}}sanitize(e){let t=e.length>500?e.slice(0,500)+"...":e;return this.sanitizePii(t)}sanitizePii(e){let t=e;for(let r of $){let i=new RegExp(r.source,r.flags);t=t.replace(i,"[REDACTED]");}return t}shouldSuppressError(e,t){let r=Date.now(),i=`${e}:${t}`,s=this.recentErrors.get(i);return s!==void 0&&r-s<5e3?(this.recentErrors.set(i,r),true):(this.recentErrors.set(i,r),this.recentErrors.size>100?(this.recentErrors.clear(),this.recentErrors.set(i,r),false):(this.recentErrors.size>50&&this.pruneOldErrors(),false))}static TRUNCATION_SUFFIX=`
2
+ ...truncated`;truncateStack(e){if(e.length<=2e3)return this.sanitizePii(e);let t=2e3-n.TRUNCATION_SUFFIX.length,r=e.slice(0,t)+n.TRUNCATION_SUFFIX;return this.sanitizePii(r)}pruneOldErrors(){let e=Date.now();for(let[i,s]of this.recentErrors.entries())e-s>5e3&&this.recentErrors.delete(i);if(this.recentErrors.size<=50)return;let t=Array.from(this.recentErrors.entries()).sort((i,s)=>i[1]-s[1]),r=this.recentErrors.size-50;for(let i=0;i<r;i+=1){let s=t[i];s&&this.recentErrors.delete(s[0]);}}};var Me=class extends f{isInitialized=false;suppressNextScrollTimer=null;pageUnloadHandler=null;emitter=new de;transformers={};customHeadersProvider;managers={};handlers={};integrationInstances={};get initialized(){return this.isInitialized}async init(e={}){if(this.isInitialized)return {sessionId:this.get("sessionId")??""};this.managers.storage=new Ie;try{this.setupState(e);let t=e.integrations?.custom?.headers??{},r=e.integrations?.custom?.fetchCredentials??"include";return this.managers.event=new fe(this.managers.storage,this.emitter,this.transformers,t,this.customHeadersProvider,r),this.loadPersistedIdentity(),this.initializeHandlers(),this.setupPageLifecycleListeners(),await this.managers.event.recoverPersistedEvents().catch(i=>{o("warn","Failed to recover persisted events",{error:i});}),this.isInitialized=!0,{sessionId:this.get("sessionId")??""}}catch(t){this.destroy(true);let r=t instanceof Error?t.message:String(t);throw new Error(`[TraceLog] TraceLog initialization failed: ${r}`)}}sendCustomEvent(e,t){if(!this.managers.event){o("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));let{valid:i,error:s,sanitizedMetadata:a}=Bt(e,r);if(!i){if(this.get("mode")==="qa")throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${s}`);o("warn",`Custom event "${e}" dropped: ${s}`);return}this.managers.event.track({type:"custom",custom_event:{name:e,...a&&{metadata:a}}});}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=false){!this.isInitialized&&!e||(Object.values(this.handlers).filter(Boolean).forEach(t=>{try{t.stopTracking();}catch(r){o("warn","Failed to stop tracking",{error:r});}}),this.suppressNextScrollTimer&&(clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=null),this.pageUnloadHandler&&(window.removeEventListener("pagehide",this.pageUnloadHandler),window.removeEventListener("beforeunload",this.pageUnloadHandler),this.pageUnloadHandler=null),this.managers.event?.flushImmediatelySync(),this.managers.event?.stop(),this.emitter.removeAllListeners(),this.transformers.beforeSend=void 0,this.transformers.beforeBatch=void 0,this.customHeadersProvider=void 0,this.set("suppressNextScroll",false),this.set("sessionId",null),this.set("identity",void 0),this.clearPersistedIdentity(),this.integrationInstances.shopifyCartLinker?.deactivate(),this.integrationInstances={},this.isInitialized=false,this.handlers={},this.managers={});}setupState(e={}){this.set("config",e);let t=he.getId(this.managers.storage);this.set("userId",t);let r=Pt(e);this.set("collectApiUrls",r);let i=_t();this.set("device",i);let s=j(window.location.href,e.sensitiveQueryParams);this.set("pageUrl",s),At()&&this.set("mode","qa");}getConfig(){return this.get("config")}getCollectApiUrls(){return this.get("collectApiUrls")}getEventManager(){return this.managers.event}getSessionId(){return this.get("sessionId")}validateGlobalMetadata(e){if(typeof e!="object"||e===null||Array.isArray(e))return {valid:false,error:"Global metadata must be a plain object"};let t=ce("Global",e,"globalMetadata");return t.valid?{valid:true}:{valid:false,error:t.error}}updateGlobalMetadata(e){let t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);let i={...this.get("config"),globalMetadata:e};this.set("config",i),o("debug","Global metadata updated (replaced)",{data:{keys:Object.keys(e)}});}mergeGlobalMetadata(e){let t=this.validateGlobalMetadata(e);if(!t.valid)throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);let r=this.get("config"),s={...r.globalMetadata??{},...e},a={...r,globalMetadata:s};this.set("config",a),o("debug","Global metadata updated (merged)",{data:{keys:Object.keys(e)}});}identify(e,t){if(!e||typeof e!="string"||e.trim().length===0){o("warn","identify() called with invalid userId",{data:{type:typeof e,length:typeof e=="string"?e.trim().length:0}});return}if(e.trim().length>256){o("warn","identify() userId exceeds 256 characters",{data:{length:e.trim().length}});return}let r=e.trim(),i=le(t),s={userId:r,...i?{traits:i}:{}};this.set("identity",s),this.persistIdentity(s),o("debug","Visitor identified",{data:{userIdLength:r.length,traitKeys:i?Object.keys(i):[]}});}async resetIdentity(){await this.managers.event?.flushImmediately(),this.set("identity",void 0),this.clearPersistedIdentity();let e=ae();this.managers.storage.setItem(H,e),this.set("userId",e),this.set("hasStartSession",false),this.set("sessionId",null),this.handlers.session?.stopTracking(),this.handlers.session?.startTracking(),o("debug","Identity reset, new UUID generated");}getProjectId(){return this.get("config")?.integrations?.tracelog?.projectId??"custom"}persistIdentity(e){try{let t=this.getProjectId(),r=Z(t);this.managers.storage.setItem(r,JSON.stringify(e));}catch{o("debug","Failed to persist identity to localStorage");}}loadPersistedIdentity(){let e=this.managers.storage,t=this.getProjectId(),r=Z(t);try{let i=e.getItem(M);if(i){let s=JSON.parse(i);if(e.removeItem(M),!this.isValidIdentityData(s)){o("debug","Invalid pending identity in localStorage, discarded");return}let a={...s,userId:s.userId.trim()};e.setItem(r,JSON.stringify(a)),this.set("identity",a),o("debug","Migrated pending identity to project-scoped key");return}}catch{e.removeItem(M);}try{let i=e.getItem(r);if(i){let s=JSON.parse(i);if(!this.isValidIdentityData(s)){e.removeItem(r),o("debug","Invalid persisted identity in localStorage, discarded");return}let a={...s,userId:s.userId.trim()};this.set("identity",a),o("debug","Loaded persisted identity");}}catch{o("debug","Failed to load persisted identity");}}isValidIdentityData(e){if(!e||typeof e!="object")return false;let{userId:t,traits:r}=e;if(typeof t!="string"||t.trim().length===0||t.trim().length>256)return false;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r))return false;for(let i of Object.values(r))if(typeof i!="string")return false}return true}clearPersistedIdentity(){try{let e=this.managers.storage,t=this.getProjectId();e.removeItem(Z(t)),e.removeItem(M);}catch{o("debug","Failed to clear persisted identity");}}setupPageLifecycleListeners(){this.pageUnloadHandler=()=>{this.managers.event?.flushImmediatelySync();},window.addEventListener("pagehide",this.pageUnloadHandler),window.addEventListener("beforeunload",this.pageUnloadHandler);}initializeHandlers(){let e=this.get("config");this.handlers.session=new Ee(this.managers.storage,this.managers.event),this.handlers.session.startTracking();let t=()=>{this.set("suppressNextScroll",true),this.suppressNextScrollTimer&&clearTimeout(this.suppressNextScrollTimer),this.suppressNextScrollTimer=window.setTimeout(()=>{this.set("suppressNextScroll",false);},500);};if(this.handlers.pageView=new ve(this.managers.event,t),this.handlers.pageView.startTracking(),this.handlers.click=new Se(this.managers.event),this.handlers.click.startTracking(),this.handlers.scroll=new _e(this.managers.event),this.handlers.scroll.startTracking(),this.handlers.performance=new be(this.managers.event),this.handlers.performance.startTracking().catch(r=>{o("warn","Failed to start performance tracking",{error:r});}),this.handlers.error=new we(this.managers.event),this.handlers.error.startTracking(),e.viewport&&(this.handlers.viewport=new ye(this.managers.event),this.handlers.viewport.startTracking()),e.integrations?.tracelog?.shopify){let r=new G;r.activate(),this.integrationInstances.shopifyCartLinker=r,this.emitter.on("event",i=>{i.type==="session_start"&&r.onSessionChange();});}}};var V=[],w=[],k=null,u=null,L=false,S=false,D=null,sr=async n=>typeof window>"u"||typeof document>"u"?{sessionId:""}:(S=false,window.__traceLogDisabled===true?{sessionId:""}:u?{sessionId:u.getSessionId()??""}:(L&&D||(L=true,D=(async()=>{try{let e=kt(n??{}),t=new Me;try{V.forEach(({event:a,callback:l})=>{t.on(a,l);}),V.length=0,w.forEach(({hook:a,fn:l})=>{a==="beforeSend"?t.setTransformer("beforeSend",l):t.setTransformer("beforeBatch",l);}),w.length=0,k&&(t.setCustomHeaders(k),k=null);let r=t.init(e),i=new Promise((a,l)=>{setTimeout(()=>{l(new Error(`[TraceLog] Initialization timeout after ${1e4}ms`));},1e4);}),s=await Promise.race([r,i]);return u=t,s}catch(r){try{t.destroy(!0);}catch(i){o("error","Failed to cleanup partially initialized app",{error:i});}throw r}}catch(e){throw u=null,e}finally{L=false,D=null;}})()),D)),or=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(S)throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");u.sendCustomEvent(n,e);}},ar=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u||L){V.push({event:n,callback:e});return}u.on(n,e);}},lr=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){let t=V.findIndex(r=>r.event===n&&r.callback===e);t!==-1&&V.splice(t,1);return}u.off(n,e);}};function cr(n,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(!u||L){let t=w.findIndex(r=>r.hook===n);t!==-1&&w.splice(t,1),w.push({hook:n,fn:e});return}if(S)throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");n==="beforeSend"?u.setTransformer("beforeSend",e):u.setTransformer("beforeBatch",e);}}var dr=n=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){let e=w.findIndex(t=>t.hook===n);e!==-1&&w.splice(e,1);return}if(S)throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");u.removeTransformer(n);}},ur=n=>{if(!(typeof window>"u"||typeof document>"u")){if(typeof n!="function")throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof n}`);if(!u||L){k=n;return}if(S)throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");u.setCustomHeaders(n);}},mr=()=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){k=null;return}if(S)throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");u.removeCustomHeaders();}},fr=()=>typeof window>"u"||typeof document>"u"?false:u!==null,pr=()=>typeof window>"u"||typeof document>"u"||!u?null:u.getSessionId(),hr=()=>{if(!(typeof window>"u"||typeof document>"u")){if(S)throw new Error("[TraceLog] Destroy operation already in progress");if(!u){S=false;return}S=true;try{u.destroy(),u=null,L=!1,D=null,V.length=0,w.length=0,k=null,S=!1;}catch(n){u=null,L=false,D=null,V.length=0,w.length=0,k=null,S=false,o("warn","Error during destroy, forced cleanup completed",{error:n});}}},gr=n=>{typeof window>"u"||typeof document>"u"||Lt(n);},Er=n=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(S)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");u.updateGlobalMetadata(n);}},vr=n=>{if(!(typeof window>"u"||typeof document>"u")){if(!u)throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");if(S)throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");u.mergeGlobalMetadata(n);}},Sr=(n,e)=>{if(!(typeof window>"u"||typeof document>"u")){if(!n||typeof n!="string"||n.trim().length===0){o("warn","identify() called with invalid userId");return}if(n.trim().length>256){o("warn","identify() userId exceeds 256 characters");return}if(S){o("warn","Cannot identify while TraceLog is being destroyed");return}if(u){u.identify(n,e);return}try{let t=le(e),r={userId:n.trim(),...t?{traits:t}:{}};localStorage.setItem(M,JSON.stringify(r)),o("debug","Identity persisted pre-init (will be applied on init)");}catch{o("debug","Failed to persist pre-init identity");}}},Tr=async()=>{if(!(typeof window>"u"||typeof document>"u")){if(!u){try{localStorage.removeItem(M);}catch{}return}if(S)throw new Error("[TraceLog] Cannot reset identity while TraceLog is being destroyed");await u.resetIdentity();}};var Na={init:sr,event:or,on:ar,off:lr,setTransformer:cr,removeTransformer:dr,setCustomHeaders:ur,removeCustomHeaders:mr,isInitialized:fr,getSessionId:pr,destroy:hr,setQaMode:gr,updateGlobalMetadata:Er,mergeGlobalMetadata:vr,identify:Sr,resetIdentity:Tr};exports.AppConfigValidationError=m;exports.DEFAULT_SESSION_TIMEOUT=C;exports.DEFAULT_WEB_VITALS_MODE=W;exports.DeviceType=pt;exports.EmitterEvent=Ve;exports.ErrorType=gt;exports.EventType=I;exports.InitializationTimeoutError=Et;exports.IntegrationValidationError=b;exports.MAX_ARRAY_LENGTH=Le;exports.MAX_CUSTOM_EVENT_ARRAY_SIZE=q;exports.MAX_CUSTOM_EVENT_KEYS=Y;exports.MAX_CUSTOM_EVENT_NAME_LENGTH=X;exports.MAX_CUSTOM_EVENT_STRING_SIZE=z;exports.MAX_NESTED_OBJECT_KEYS=Ae;exports.MAX_STRING_LENGTH=N;exports.MAX_STRING_LENGTH_IN_ARRAY=J;exports.Mode=Ue;exports.PII_PATTERNS=$;exports.PermanentError=R;exports.RateLimitError=B;exports.SamplingRateValidationError=F;exports.ScrollDirection=ht;exports.SessionTimeoutValidationError=ee;exports.SpecialApiUrl=ft;exports.TimeoutError=A;exports.TraceLogValidationError=P;exports.WEB_VITALS_GOOD_THRESHOLDS=Lr;exports.WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS=We;exports.WEB_VITALS_POOR_THRESHOLDS=yt;exports.getWebVitalsThresholds=re;exports.isPrimaryScrollEvent=Nn;exports.isSecondaryScrollEvent=On;exports.tracelog=Na;//# sourceMappingURL=public-api.cjs.map
3
3
  //# sourceMappingURL=public-api.cjs.map