@tracescout/browser 2.7.1 → 2.9.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 +1 @@
1
- function generateId(){return Math.random().toString(36).substr(2,9)+Date.now().toString(36)}function parseUrl(S,b=("undefined"!=typeof location?location.origin:void 0)){try{const I=new URL(S,b);return{hostname:I.hostname,pathname:I.pathname,search:I.search,protocol:I.protocol,origin:I.origin,hash:I.hash}}catch(S){return{hostname:"",pathname:"",search:"",protocol:"",origin:"",hash:""}}}const S={get(S){try{const b=localStorage.getItem(S);return b?JSON.parse(b):null}catch(S){return null}},set(S,b){try{return localStorage.setItem(S,JSON.stringify(b)),!0}catch(S){return!1}},remove(S){try{return localStorage.removeItem(S),!0}catch(S){return!1}},getItem(S){return this.get(S)},setItem(S,b){return this.set(S,b)},removeItem(S){return this.remove(S)}},b={getItem(S){try{return sessionStorage.getItem(S)}catch(S){return null}},setItem(S,b){try{return sessionStorage.setItem(S,b),!0}catch(S){return!1}},removeItem(S){try{return sessionStorage.removeItem(S),!0}catch(S){return!1}}},I={isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isString:S=>"string"==typeof S,isFunction:S=>"function"==typeof S,isEmpty:S=>null==S||""===S||Array.isArray(S)&&0===S.length,get:(S,b,I)=>{if(!S)return I;const x=b.split(".");let R=S;for(const S of x){if(!R||"object"!=typeof R||!(S in R))return I;R=R[S]}return R}};function debounce(S,b){let I;return function executedFunction(...x){clearTimeout(I),I=setTimeout(()=>{clearTimeout(I),S(...x)},b)}}function throttle$1(S,b){let I;return function(...x){I||(S.apply(this,x),I=!0,setTimeout(()=>I=!1,b))}}function deepClone(S){if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>deepClone(S));if(S instanceof Object){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=deepClone(S[I]));return b}}function safeJsonParse(S,b=null){try{return JSON.parse(S)}catch(S){return b}}function safeJsonStringify(S,b="{}"){try{return JSON.stringify(S)}catch(S){return b}}function safeStringify(S,b=10,I=1e4){const x=new WeakSet;let R=0;const A=JSON.stringify(S,function(S,I){if("object"==typeof I&&null!==I&&(R++,R>b))return"[Max Depth Exceeded]";if("object"==typeof I&&null!==I){if(x.has(I))return"[Circular Reference]";x.add(I)}return"function"==typeof I?`[Function: ${I.name||"anonymous"}]`:I instanceof Error?{__type:"Error",name:I.name,message:I.message,stack:I.stack}:I instanceof RegExp?`[RegExp: ${I.toString()}]`:I instanceof Date?`[Date: ${I.toISOString()}]`:"symbol"==typeof I?`[Symbol: ${I.toString()}]`:"bigint"==typeof I?`[BigInt: ${I.toString()}]`:"undefined"!=typeof HTMLElement&&I instanceof HTMLElement?`[HTMLElement: <${I.tagName.toLowerCase()}${I.id?' id="'+I.id+'"':""}>]`:"undefined"!=typeof Window&&I instanceof Window?"[Window]":"undefined"!=typeof Document&&I instanceof Document?"[Document]":I});return A&&A.length>I?A.substring(0,I)+"... [truncated]":A}function safeParseConsoleArgs(S,b=5e3,I=1e4){if(!Array.isArray(S))return[];const x=[];let R=0;for(let A=0;A<S.length;A++){if(R>=I){x.push(`[${S.length-A} more arguments truncated]`);break}const _=S[A];let D;try{D=null===_?"null":void 0===_?"undefined":"string"==typeof _?_.length>b?_.substring(0,b)+"... [truncated]":_:"number"==typeof _||"boolean"==typeof _?String(_):"object"==typeof _?safeStringify(_,5,b):String(_)}catch(S){D=`[Unserializable: ${typeof _}]`}const L="string"==typeof D?D.length:0;if(R+L>I){const S=I-R;if(!(S>50&&"string"==typeof D)){x.push("[Remaining arguments truncated]");break}D=D.substring(0,S)+"... [truncated]"}x.push(D),R+=L}return x}const isResourceUrl=(S,b="")=>{const I=S.split("?")[0].toLowerCase();return[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".woff",".woff2",".ttf",".eot",".otf",".pdf",".mp4",".mp3",".wav",".zip",".tar",".gz",".xml",".txt",".csv"].some(S=>I.endsWith(S))},x={get:(S,b,I)=>{const x=b.split(".");let R=S;for(const S of x){if(null==R)return I;R=R[S]}return void 0!==R?R:I},set:(S,b,I)=>{const x=b.split("."),R=x.pop();let A=S;for(const S of x)S in A&&"object"==typeof A[S]||(A[S]={}),A=A[S];return A[R]=I,S},has:(S,b)=>{const I=b.split(".");let x=S;for(const S of I){if(null==x||!(S in x))return!1;x=x[S]}return!0},isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isArray:S=>Array.isArray(S),isString:S=>"string"==typeof S,isNumber:S=>"number"==typeof S&&!isNaN(S),isBoolean:S=>"boolean"==typeof S,isFunction:S=>"function"==typeof S,isNull:S=>null===S,isUndefined:S=>void 0===S,isEmpty:S=>null==S||("string"==typeof S||Array.isArray(S)?0===S.length:"object"==typeof S&&0===Object.keys(S).length),toLower:S=>String(S).toLowerCase(),toUpper:S=>String(S).toUpperCase(),trim:S=>String(S).trim(),startsWith:(S,b)=>String(S).startsWith(b),endsWith:(S,b)=>String(S).endsWith(b),includes:(S,b)=>String(S).includes(b),filter:(S,b)=>Array.isArray(S)?S.filter(b):[],map:(S,b)=>Array.isArray(S)?S.map(b):[],find:(S,b)=>{if(Array.isArray(S))return S.find(b)},sortBy:(S,b)=>Array.isArray(S)?[...S].sort((S,I)=>{const x="function"==typeof b?b(S):S[b],R="function"==typeof b?b(I):I[b];return x<R?-1:x>R?1:0}):[],keys:S=>Object.keys(S||{}),values:S=>Object.values(S||{}),entries:S=>Object.entries(S||{}),assign:(S,...b)=>Object.assign({},S,...b),cloneDeep:S=>{if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>x.cloneDeep(S));if("object"==typeof S){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=x.cloneDeep(S[I]));return b}return S},merge:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&(x.isObject(S[b])&&x.isObject(I[b])?I[b]=x.merge(I[b],S[b]):I[b]=S[b]);return I},defaults:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&void 0===I[b]&&(I[b]=S[b]);return I},min:(...S)=>Math.min(...S),max:(...S)=>Math.max(...S),round:(S,b=0)=>{const I=Math.pow(10,b);return Math.round(S*I)/I},noop:()=>{},identity:S=>S,isEqual:(S,b)=>{if(S===b)return!0;if(null===S||null===b)return!1;if(typeof S!=typeof b)return!1;if("object"!=typeof S)return!1;const I=Object.keys(S),R=Object.keys(b);if(I.length!==R.length)return!1;for(const A of I){if(!R.includes(A))return!1;if(!x.isEqual(S[A],b[A]))return!1}return!0}},R={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},A={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]},_="[TraceScoutMonitoringCore]",D={FETCH_HTTP_ERROR:"fetch_http_error",FETCH_NETWORK_ERROR:"fetch_network_error",FETCH_SILENT_LOGIN_FAILURE:"fetch_silent_login_failure",XHR_HTTP_ERROR:"xhr_http_error",XHR_NETWORK_ERROR:"xhr_network_error",XHR_TIMEOUT_ERROR:"xhr_timeout_error",XHR_ABORTED_ERROR:"xhr_aborted_error",XHR_SILENT_LOGIN_FAILURE:"xhr_silent_login_failure",RESOURCE_LOAD_ERROR:"resource_load_error",CUSTOM_API_ERROR:"custom_api_error",UNKNOWN_ERROR:"unknown_error",POSTMESSAGE_COMMUNICATION:"postmessage_communication",POSTMESSAGE_CROSS_ORIGIN:"postmessage_cross_origin",POSTMESSAGE_LARGE_PAYLOAD:"postmessage_large_payload",POSTMESSAGE_SUSPICIOUS_ORIGIN:"postmessage_suspicious_origin",POSTMESSAGE_ERROR:"postmessage_error",FETCH_SLOW_REQUEST:"fetch_slow_request",XHR_SLOW_REQUEST:"xhr_slow_request",PERFORMANCE_DEGRADATION_ALERT:"performance_degradation_alert",P1_INCIDENT_EVENT:"p1_incident_event",CORE_WEB_VITAL:"core_web_vital"},L={EMAIL_REGEX:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,PHONE_REGEX:/^[\+]?[1-9][\d]{0,15}$/,UUID_REGEX:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i},B={THRESHOLDS:{lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3}},COLLECT_METRICS:{lcp:!0,fid:!0,cls:!0,inp:!0,ttfb:!0,fcp:!0},USE_WEB_VITALS_LIBRARY:!0,REPORTING_ENABLED:!0,REPORT_THRESHOLD:"needsImprovement"};class LoggingManager{constructor(){this.globalConfig={enabled:!1,level:"info",showTimestamps:!0,showServiceIcons:!0},this.serviceConfig={TraceScoutMonitoringCore:{enabled:!1,level:"info"},ConfigManager:{enabled:!1,level:"info"},EventManager:{enabled:!1,level:"info"},ServiceManager:{enabled:!1,level:"info"},UserProfileManager:{enabled:!1,level:"info"},PerformanceMonitor:{enabled:!1,level:"info"},FetchInterceptor:{enabled:!1,level:"info"},XHRInterceptor:{enabled:!1,level:"info"},ResourceInterceptor:{enabled:!1,level:"info"},PostMessageInterceptor:{enabled:!1,level:"info"},CoreWebVitalsMonitor:{enabled:!1,level:"info"},Recorder:{enabled:!1,level:"info"},SessionStorage:{enabled:!1,level:"info"},UploadQueue:{enabled:!1,level:"info"},"CDN-Loader":{enabled:!1,level:"info"},Replayer:{enabled:!1,level:"info"},Validation:{enabled:!1,level:"info"},BaseService:{enabled:!1,level:"info"}},this.logLevels={error:0,warn:1,info:2,debug:3},this.serviceStyles={TraceScoutMonitoringCore:{icon:"🎯",color:"#009688"},ConfigManager:{icon:"⚙️",color:"#607D8B"},EventManager:{icon:"📝",color:"#4CAF50"},ServiceManager:{icon:"🌐",color:"#9C27B0"},UserProfileManager:{icon:"👤",color:"#FF9800"},PerformanceMonitor:{icon:"⚡",color:"#795548"},FetchInterceptor:{icon:"🔌",color:"#8BC34A"},XHRInterceptor:{icon:"📡",color:"#FFC107"},ResourceInterceptor:{icon:"📦",color:"#E91E63"},PostMessageInterceptor:{icon:"💬",color:"#3F51B5"},CoreWebVitalsMonitor:{icon:"📊",color:"#2196F3"},Recorder:{icon:"🎬",color:"#FF5722"},SessionStorage:{icon:"💾",color:"#673AB7"},UploadQueue:{icon:"📤",color:"#FF9800"},"CDN-Loader":{icon:"📥",color:"#4CAF50"},Replayer:{icon:"▶️",color:"#9C27B0"},Validation:{icon:"✅",color:"#4CAF50"},BaseService:{icon:"🔧",color:"#607D8B"},default:{icon:"🔍",color:"#666"}}}configure(S={}){this.globalConfig={...this.globalConfig,...S},S.services&&Object.keys(S.services).forEach(b=>{this.serviceConfig[b]&&(this.serviceConfig[b]={...this.serviceConfig[b],...S.services[b]})})}enableServices(S,b="info"){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!0,this.serviceConfig[S].level=b)}),this.globalConfig.enabled=!0}disableServices(S){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!1)})}enableAll(S="info"){Object.keys(this.serviceConfig).forEach(b=>{this.serviceConfig[b].enabled=!0,this.serviceConfig[b].level=S}),this.globalConfig.enabled=!0}disableAll(){Object.keys(this.serviceConfig).forEach(S=>{this.serviceConfig[S].enabled=!1}),this.globalConfig.enabled=!1}getConfig(){return{global:{...this.globalConfig},services:{...this.serviceConfig}}}getEnabledServices(){return Object.keys(this.serviceConfig).filter(S=>this.serviceConfig[S].enabled)}isEnabled(S,b="info"){if(!this.globalConfig.enabled)return!1;const I=this.serviceConfig[S];if(!I||!I.enabled)return!1;const x=this.logLevels[I.level]||this.logLevels.info;return(this.logLevels[b]||this.logLevels.info)<=x}createLogger(S){return new ServiceLogger(S,this)}formatMessage(S,b,I){const x=this.serviceStyles[S]||this.serviceStyles.default;return{prefix:`%c${`${this.globalConfig.showTimestamps?`[${(new Date).toLocaleTimeString()}]`:""}[TraceScout][${S}]${this.globalConfig.showServiceIcons?x.icon:""}`}`,style:`color: ${x.color}; font-weight: bold;`,args:I}}}class ServiceLogger{constructor(S,b){this.serviceName=S,this.loggingManager=b}log(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.log(b.prefix,b.style,...b.args)}}info(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.info(b.prefix,b.style,...b.args)}}warn(...S){if(this.loggingManager.isEnabled(this.serviceName,"warn")){const b=this.loggingManager.formatMessage(this.serviceName,"warn",S);console.warn(b.prefix,"color: #FF5722; font-weight: bold;",...b.args)}}error(...S){const b=this.loggingManager.formatMessage(this.serviceName,"error",S);console.error(b.prefix,"color: #F44336; font-weight: bold;",...b.args)}debug(...S){if(this.loggingManager.isEnabled(this.serviceName,"debug")){const b=this.loggingManager.formatMessage(this.serviceName,"debug",S);console.debug(b.prefix,"color: #9E9E9E; font-weight: bold;",...b.args)}}session(...S){this.log("🎬",...S)}performance(...S){this.log("⚡",...S)}network(...S){this.log("🌐",...S)}storage(...S){this.log("💾",...S)}updateDebugMode(S){S?this.loggingManager.enableServices(this.serviceName):this.loggingManager.disableServices(this.serviceName)}}const U=new LoggingManager;function createLogger(S){return U.createLogger(S)}class Logger{constructor(S="",b=!1){this.serviceName=S.replace(/^\[|\]$/g,""),this.serviceLogger=U.createLogger(this.serviceName),b&&U.enableServices(this.serviceName),this.prefix=S,this.debug=Boolean(b)}updateDebugMode(S){this.debug=Boolean(S),this.serviceLogger.updateDebugMode(S)}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.serviceLogger.debug(...S)}success(...S){this.serviceLogger.log("✅",...S)}important(...S){this.serviceLogger.log("⚠️",...S)}session(...S){this.serviceLogger.session(...S)}performance(...S){this.serviceLogger.performance(...S)}interceptor(...S){this.serviceLogger.network(...S)}service(...S){this.serviceLogger.network(...S)}monitor(...S){this.serviceLogger.log("📊",...S)}}function validateEndpoints(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateDomains(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateService(S){return S&&"object"==typeof S&&"function"==typeof S.send}class ConfigManager{constructor(S={}){this.defaultConfig=S,this.config={},this.logger=new Logger("[ConfigManager]",S.debug)}validate(S={}){const b=[];try{const I=validateEndpoints(S.endpoints),x=validateDomains(S.domainsToTrack);I||x||b.push("Either endpoints or domainsToTrack must be provided"),S.service&&!validateService(S.service)&&b.push("Invalid service: must be an object with send() method");const R={retryIntervalMs:{min:1e3,max:3e5},deduplicationWindowMs:{min:100,max:36e5},maxQueueSize:{min:10,max:1e4},maxRetries:{min:1,max:10},batchSize:{min:1,max:100}};if(Object.entries(R).forEach(([I,{min:x,max:R}])=>{const A=S[I];void 0!==A&&("number"!=typeof A||A<x||A>R)&&b.push(`${I} must be a number between ${x} and ${R}`)}),void 0!==S.monitorPostMessages)if("object"!=typeof S.monitorPostMessages||null===S.monitorPostMessages)b.push("monitorPostMessages must be an object");else{const I=S.monitorPostMessages;void 0!==I.postMessageOriginWhitelist&&(Array.isArray(I.postMessageOriginWhitelist)?I.postMessageOriginWhitelist.every(S=>"string"==typeof S)||b.push("postMessageOriginWhitelist must contain only strings"):b.push("postMessageOriginWhitelist must be an array")),void 0===I.excludePostMessagesEvents||Array.isArray(I.excludePostMessagesEvents)||b.push("excludePostMessagesEvents must be an array"),void 0===I.monitorSpecificPostMessagesEvents||Array.isArray(I.monitorSpecificPostMessagesEvents)||b.push("monitorSpecificPostMessagesEvents must be an array")}if(void 0!==S.monitorPerformance&&"boolean"!=typeof S.monitorPerformance&&b.push("monitorPerformance must be a boolean"),void 0!==S.slowRequestThreshold&&("number"!=typeof S.slowRequestThreshold||S.slowRequestThreshold<100||S.slowRequestThreshold>3e4)&&b.push("slowRequestThreshold must be a number between 100 and 30000 milliseconds"),void 0!==S.averageAlertThreshold&&("number"!=typeof S.averageAlertThreshold||S.averageAlertThreshold<100||S.averageAlertThreshold>3e4)&&b.push("averageAlertThreshold must be a number between 100 and 30000 milliseconds"),b.length>0)throw new Error(`Configuration validation failed: ${b.join(", ")}`);return!0}catch(S){throw S}}apply(S={}){this.logger.log("Applying configuration options"),this.validate(S);try{this.config=x.merge({},this.defaultConfig,S,{debug:"boolean"==typeof x.get(S,"debug")?x.get(S,"debug"):Boolean(x.get(S,"debug")),retryIntervalMs:Math.max(1e3,x.get(S,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,x.get(S,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs)),maxQueueSize:Math.max(10,x.get(S,"maxQueueSize",this.defaultConfig.maxQueueSize)),maxRetries:Math.max(1,Math.min(10,x.get(S,"maxRetries",this.defaultConfig.maxRetries))),batchSize:Math.max(1,Math.min(100,x.get(S,"batchSize",this.defaultConfig.batchSize)))}),S.service&&(this.config.service=S.service),S.endpoints&&(this.config.endpoints=S.endpoints),S.domainsToTrack&&(this.config.domainsToTrack=S.domainsToTrack),S.monitorPostMessages&&(this.config.monitorPostMessages={postMessageOriginWhitelist:S.monitorPostMessages.postMessageOriginWhitelist||[],excludePostMessagesEvents:S.monitorPostMessages.excludePostMessagesEvents||[],monitorSpecificPostMessagesEvents:S.monitorPostMessages.monitorSpecificPostMessagesEvents||[]}),void 0!==S.monitorPerformance&&(this.config.monitorPerformance=S.monitorPerformance),void 0!==S.slowRequestThreshold&&(this.config.slowRequestThreshold=Math.max(100,Math.min(3e4,S.slowRequestThreshold))),void 0!==S.averageAlertThreshold&&(this.config.averageAlertThreshold=Math.max(100,Math.min(3e4,S.averageAlertThreshold)));return["appName","appVersion","environment","userId","sessionId","logPreflight","logResourceErrors","enableSessionRecording","sessionRecordingOptions","coreWebVitalsConfig"].forEach(b=>{void 0!==S[b]&&(this.config[b]=S[b])}),this.logger.log("Configuration applied successfully"),this.config}catch(S){throw this.logger.error("Failed to apply configuration:",S),S}}get(S,b=void 0){return x.get(this.config,S,b)}getAll(){return{...this.config}}update(S,b){return"string"==typeof S?this.config[S]=b:"object"==typeof S&&(this.config={...this.config,...S}),this.config}reset(){return this.config={...this.defaultConfig},this.config}}var $,j,W,H,V,Q=-1,o=function(S){addEventListener("pageshow",function(b){b.persisted&&(Q=b.timeStamp,S(b))},!0)},c=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},u=function(){var S=c();return S&&S.activationStart||0},f=function(S,b){var I=c(),x="navigate";return Q>=0?x="back-forward-cache":I&&(document.prerendering||u()>0?x="prerender":document.wasDiscarded?x="restore":I.type&&(x=I.type.replace(/_/g,"-"))),{name:S,value:void 0===b?-1:b,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:x}},s=function(S,b,I){try{if(PerformanceObserver.supportedEntryTypes.includes(S)){var x=new PerformanceObserver(function(S){Promise.resolve().then(function(){b(S.getEntries())})});return x.observe(Object.assign({type:S,buffered:!0},I||{})),x}}catch(S){}},d=function(S,b,I,x){var R,A;return function(_){b.value>=0&&(_||x)&&((A=b.value-(R||0))||void 0===R)&&(R=b.value,b.delta=A,b.rating=function(S,b){return S>b[1]?"poor":S>b[0]?"needs-improvement":"good"}(b.value,I),S(b))}},l=function(S){requestAnimationFrame(function(){return requestAnimationFrame(function(){return S()})})},p=function(S){var n=function(b){"pagehide"!==b.type&&"hidden"!==document.visibilityState||S(b)};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},v=function(S){var b=!1;return function(I){b||(S(I),b=!0)}},G=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(S){"hidden"===document.visibilityState&&G>-1&&(G="visibilitychange"===S.type?S.timeStamp:0,T())},y=function(){addEventListener("visibilitychange",g,!0),addEventListener("prerenderingchange",g,!0)},T=function(){removeEventListener("visibilitychange",g,!0),removeEventListener("prerenderingchange",g,!0)},E=function(){return G<0&&(G=h(),y(),o(function(){setTimeout(function(){G=h(),y()},0)})),{get firstHiddenTime(){return G}}},C=function(S){document.prerendering?addEventListener("prerenderingchange",function(){return S()},!0):S()},J=[1800,3e3],w=function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FCP"),A=s("paint",function(S){S.forEach(function(S){"first-contentful-paint"===S.name&&(A.disconnect(),S.startTime<x.firstHiddenTime&&(R.value=Math.max(S.startTime-u(),0),R.entries.push(S),I(!0)))})});A&&(I=d(S,R,J,b.reportAllChanges),o(function(x){R=f("FCP"),I=d(S,R,J,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,I(!0)})}))})},X=[.1,.25],Y={passive:!0,capture:!0},ee=new Date,P=function(S,b){$||($=b,j=S,W=new Date,k(removeEventListener),F())},F=function(){if(j>=0&&j<W-ee){var S={entryType:"first-input",name:$.type,target:$.target,cancelable:$.cancelable,startTime:$.timeStamp,processingStart:$.timeStamp+j};H.forEach(function(b){b(S)}),H=[]}},M=function(S){if(S.cancelable){var b=(S.timeStamp>1e12?new Date:performance.now())-S.timeStamp;"pointerdown"==S.type?function(S,b){var t=function(){P(S,b),r()},i=function(){r()},r=function(){removeEventListener("pointerup",t,Y),removeEventListener("pointercancel",i,Y)};addEventListener("pointerup",t,Y),addEventListener("pointercancel",i,Y)}(b,S):P(b,S)}},k=function(S){["mousedown","keydown","touchstart","pointerdown"].forEach(function(b){return S(b,M,Y)})},te=[100,300],se=0,re=1/0,ne=0,N=function(S){S.forEach(function(S){S.interactionId&&(re=Math.min(re,S.interactionId),ne=Math.max(ne,S.interactionId),se=ne?(ne-re)/7+1:0)})},O=function(){return V?se:performance.interactionCount||0},q=function(){"interactionCount"in performance||V||(V=s("event",N,{type:"event",buffered:!0,durationThreshold:0}))},ie=[200,500],oe=0,z=function(){return O()-oe},ae=[],le={},K=function(S){var b=ae[ae.length-1],I=le[S.interactionId];if(I||ae.length<10||S.duration>b.latency){if(I)I.entries.push(S),I.latency=Math.max(I.latency,S.duration);else{var x={id:S.interactionId,latency:S.duration,entries:[S]};le[x.id]=x,ae.push(x)}ae.sort(function(S,b){return b.latency-S.latency}),ae.splice(10).forEach(function(S){delete le[S.id]})}},ce=[2500,4e3],ue={},he=[800,1800],de=function e(S){document.prerendering?C(function(){return e(S)}):"complete"!==document.readyState?addEventListener("load",function(){return e(S)},!0):setTimeout(S,0)},Z=function(S,b){b=b||{};var I=f("TTFB"),x=d(S,I,he,b.reportAllChanges);de(function(){var R=c();if(R){var A=R.responseStart;if(A<=0||A>performance.now())return;I.value=Math.max(A-u(),0),I.entries=[R],x(!0),o(function(){I=f("TTFB",0),(x=d(S,I,he,b.reportAllChanges))(!0)})}})};class CoreWebVitalsMonitor{constructor(S={}){this.config=S,this.logger=new Logger("[CoreWebVitalsMonitor]",S.debug),this.enabled=!1!==S.enabled,this.metrics=new Map,this.observers=[],this.callbacks=[],this.useWebVitalsLibrary=!1!==S.useWebVitalsLibrary,this.thresholds={lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3},...S.thresholds},this.collectMetrics={lcp:!1!==S.collectLCP,fid:!1!==S.collectFID,cls:!1!==S.collectCLS,inp:!1!==S.collectINP,ttfb:!1!==S.collectTTFB,fcp:!1!==S.collectFCP},this.reportingEnabled=!1!==S.reportingEnabled,this.reportThreshold=S.reportThreshold||"needsImprovement",this.enabled&&"undefined"!=typeof window&&this.init()}init(){if(this.logger.log("Initializing Core Web Vitals monitoring..."),this.useWebVitalsLibrary)try{return this.initWithWebVitalsLibrary(),void this.logger.log("Core Web Vitals monitoring initialized with web-vitals library")}catch(S){this.logger.warn("web-vitals library subscription failed, falling back to custom implementation:",S)}this.initCustomImplementation(),this.logger.log("Core Web Vitals monitoring initialized with custom implementation")}initWithWebVitalsLibrary(){this.collectMetrics.lcp&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("LCP"),a=function(S){var b=S[S.length-1];b&&b.startTime<x.firstHiddenTime&&(R.value=Math.max(b.startTime-u(),0),R.entries=[b],I())},A=s("largest-contentful-paint",a);if(A){I=d(S,R,ce,b.reportAllChanges);var _=v(function(){ue[R.id]||(a(A.takeRecords()),A.disconnect(),ue[R.id]=!0,I(!0))});["keydown","click"].forEach(function(S){addEventListener(S,function(){return setTimeout(_,0)},!0)}),p(_),o(function(x){R=f("LCP"),I=d(S,R,ce,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,ue[R.id]=!0,I(!0)})})}})}(S=>this.handleWebVitalsMetric("lcp",S)),this.collectMetrics.fid&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FID"),l=function(S){S.startTime<x.firstHiddenTime&&(R.value=S.processingStart-S.startTime,R.entries.push(S),I(!0))},m=function(S){S.forEach(l)},A=s("first-input",m);I=d(S,R,te,b.reportAllChanges),A&&p(v(function(){m(A.takeRecords()),A.disconnect()})),A&&o(function(){var x;R=f("FID"),I=d(S,R,te,b.reportAllChanges),H=[],j=-1,$=null,k(addEventListener),x=l,H.push(x),F()})})}(S=>this.handleWebVitalsMetric("fid",S)),this.collectMetrics.cls&&function(S,b){b=b||{},w(v(function(){var I,x=f("CLS",0),R=0,A=[],c=function(S){S.forEach(function(S){if(!S.hadRecentInput){var b=A[0],I=A[A.length-1];R&&S.startTime-I.startTime<1e3&&S.startTime-b.startTime<5e3?(R+=S.value,A.push(S)):(R=S.value,A=[S])}}),R>x.value&&(x.value=R,x.entries=A,I())},_=s("layout-shift",c);_&&(I=d(S,x,X,b.reportAllChanges),p(function(){c(_.takeRecords()),I(!0)}),o(function(){R=0,x=f("CLS",0),I=d(S,x,X,b.reportAllChanges),l(function(){return I()})}),setTimeout(I,0))}))}(S=>this.handleWebVitalsMetric("cls",S)),this.collectMetrics.inp&&function(S,b){b=b||{},C(function(){var I;q();var x,R=f("INP"),a=function(S){S.forEach(function(S){S.interactionId&&K(S),"first-input"===S.entryType&&!ae.some(function(b){return b.entries.some(function(b){return S.duration===b.duration&&S.startTime===b.startTime})})&&K(S)});var b,I=(b=Math.min(ae.length-1,Math.floor(z()/50)),ae[b]);I&&I.latency!==R.value&&(R.value=I.latency,R.entries=I.entries,x())},A=s("event",a,{durationThreshold:null!==(I=b.durationThreshold)&&void 0!==I?I:40});x=d(S,R,ie,b.reportAllChanges),A&&("PerformanceEventTiming"in window&&"interactionId"in PerformanceEventTiming.prototype&&A.observe({type:"first-input",buffered:!0}),p(function(){a(A.takeRecords()),R.value<0&&z()>0&&(R.value=0,R.entries=[]),x(!0)}),o(function(){ae=[],oe=O(),R=f("INP"),x=d(S,R,ie,b.reportAllChanges)}))})}(S=>this.handleWebVitalsMetric("inp",S)),this.collectMetrics.ttfb&&Z(S=>this.handleWebVitalsMetric("ttfb",S)),this.collectMetrics.fcp&&w(S=>this.handleWebVitalsMetric("fcp",S)),this.setupVisibilityChangeHandler()}handleWebVitalsMetric(S,b){const I={type:S,value:b.value,id:b.id,timestamp:Date.now(),rating:this.getRating(S,b.value),threshold:this.thresholds[S],libRating:"string"==typeof b.rating?b.rating:null,navigationType:"string"==typeof b.navigationType?b.navigationType:null};this.metrics.set(S,I),this.logger.log(`Web Vital metric captured: ${S} = ${b.value}ms (${I.rating})`),this.reportingEnabled&&this.shouldReport(I)&&this.reportMetric(I),this.triggerCallbacks(S,I)}initCustomImplementation(){this.logger.log("Initializing custom Core Web Vitals implementation..."),this.collectMetrics.fcp&&this.trackFCP(),this.collectMetrics.lcp&&this.trackLCP(),this.collectMetrics.fid&&this.trackFID(),this.collectMetrics.cls&&this.trackCLS(),this.collectMetrics.ttfb&&this.trackTTFB(),this.setupVisibilityChangeHandler()}trackFCP(){try{const S=new PerformanceObserver(b=>{for(const I of b.getEntries())"first-contentful-paint"===I.name&&(this.handleWebVitalsMetric("fcp",{value:I.startTime,id:`fcp-${Date.now()}`,name:"FCP"}),S.disconnect())});S.observe({type:"paint",buffered:!0})}catch(S){this.logger.warn("Failed to track FCP:",S)}}trackLCP(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.size>S&&(S=I.size,this.handleWebVitalsMetric("lcp",{value:I.startTime,id:`lcp-${Date.now()}`,name:"LCP"}))});b.observe({type:"largest-contentful-paint",buffered:!0})}catch(S){this.logger.warn("Failed to track LCP:",S)}}trackFID(){let S=!1;const handleInput=b=>{if(S)return;S=!0;const I=b.timeStamp-b.timeStamp;this.handleWebVitalsMetric("fid",{value:I,id:`fid-${Date.now()}`,name:"FID"}),["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.removeEventListener(S,handleInput)})};["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.addEventListener(S,handleInput,{once:!0,passive:!0})})}trackCLS(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.hadRecentInput||(S+=I.value,this.handleWebVitalsMetric("cls",{value:S,id:`cls-${Date.now()}`,name:"CLS"}))});b.observe({type:"layout-shift",buffered:!0})}catch(S){this.logger.warn("Failed to track CLS:",S)}}trackTTFB(){try{if(window.performance&&window.performance.timing){const S=window.performance.timing,b=S.responseStart-S.navigationStart;b>0&&this.handleWebVitalsMetric("ttfb",{value:b,id:`ttfb-${Date.now()}`,name:"TTFB"})}}catch(S){this.logger.warn("Failed to track TTFB:",S)}}getRating(S,b){const I=this.thresholds[S];return I?b<=I.good?"good":b<=I.needsImprovement?"needsImprovement":"poor":"unknown"}shouldReport(S){return"good"===this.reportThreshold?"good"===S.rating:"needsImprovement"!==this.reportThreshold||("good"===S.rating||"needsImprovement"===S.rating)}reportMetric(S){const b={type:"core_web_vital",context:{forceLog:!0,isMonitored:!0,metricType:S.type,metricValue:S.value,metricRating:S.rating,threshold:S.threshold},data:S};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}triggerCallbacks(S,b){this.callbacks.forEach(I=>{try{I(S,b)}catch(S){this.logger.error("Error in metric callback:",S)}})}setupVisibilityChangeHandler(){document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.reportFinalMetrics()})}reportFinalMetrics(){if(!this.reportingEnabled)return;const S=Array.from(this.metrics.values());if(0===S.length)return;this.logger.log("Reporting final Core Web Vitals metrics:",S);const b={type:"core_web_vitals_final_report",context:{forceLog:!0,isMonitored:!0,timestamp:Date.now(),pageUrl:window.location.href},data:{metrics:S,summary:this.generateSummary(S)}};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}generateSummary(S){const b={total:S.length,byRating:{good:0,needsImprovement:0,poor:0},average:0,worst:null};let I=0,x=null;return S.forEach(S=>{b.byRating[S.rating]++,I+=S.value,(!x||"poor"===S.rating||"needsImprovement"===S.rating&&"poor"!==x.rating)&&(x=S)}),b.average=I/S.length,b.worst=x,b}addCallback(S){"function"==typeof S&&this.callbacks.push(S)}removeCallback(S){const b=this.callbacks.indexOf(S);b>-1&&this.callbacks.splice(b,1)}getMetrics(){return Array.from(this.metrics.values())}getMetric(S){return this.metrics.get(S)}updateThresholds(S){this.thresholds={...this.thresholds,...S},this.logger.log("Core Web Vitals thresholds updated:",this.thresholds)}destroy(){this.observers.forEach(S=>{S&&"function"==typeof S.disconnect&&S.disconnect()}),this.observers=[],this.callbacks=[],this.metrics.clear(),this.logger=null}}let ge=class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=createLogger("PerformanceMonitor"),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}};const pe="0123456789abcdef";function generateSessionId(){return`ts_${Date.now()}_${function randomHexSuffix(S=12){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const b=new Uint8Array(Math.ceil(S/2));crypto.getRandomValues(b);let I="";for(let S=0;S<b.length;S++)I+=pe[b[S]>>4]+pe[15&b[S]];return I.slice(0,S)}let b="";for(let I=0;I<S;I++)b+=pe[Math.floor(16*Math.random())];return b}(12)}`}const fe=new Set(["confirmed","partial","disabled"]),me="2.7.1",ye=`@tracescout/browser/${me}`;class SDKContext{static#e=null;static initialize(S){return this.#e?(console.warn("[SDKContext] Already initialized, returning existing instance"),this.#e):(this.#e=new SDKContext(S),this.#e)}static updateSessionId(S){this.#e&&(this.#e.sessionId=S,this.#e.sessionStartTime=Date.now(),console.log("[SDKContext] ✅ Session ID updated:",S))}static getInstance(){return this.#e}static resetForTests(){if("undefined"!=typeof process)throw new Error("resetForTests() only allowed in test environment");this.#e=null}constructor({projectId:S,workspaceId:b,environment:I,userId:x,sessionId:R,sessionManager:A}){this.#t({projectId:S}),this.projectId=S,this.workspaceId=null,this.environment=I||"production",this.userId=x||null,this.userEmail=null,this.userAttributes={},this.sessionManager=A||null,this.pageviewManager=null,this.sessionId=R||this.#s(),this.sessionStartTime=Date.now(),this.device={userAgent:navigator.userAgent,viewport:this.#r(),platform:navigator.platform,language:navigator.language,timezone:this.#n(),screen:{width:window.screen.width,height:window.screen.height,colorDepth:window.screen.colorDepth}},this.uaInfo=function parseUserAgent(S){const b={browserName:null,browserVersion:null,osName:null,osVersion:null,deviceType:null};if(!S||"string"!=typeof S)return b;let I;return/iPad|Tablet|PlayBook|Silk/i.test(S)||/Android/i.test(S)&&!/Mobile/i.test(S)?b.deviceType="tablet":/Mobi|iPhone|iPod|Android.*Mobile|Windows Phone|BlackBerry/i.test(S)?b.deviceType="mobile":/Mozilla|Chrome|Safari|Firefox|Edg|Opera|OPR/i.test(S)&&(b.deviceType="desktop"),(I=S.match(/Edg(?:e|A|iOS)?\/([\d.]+)/))?(b.browserName="Edge",b.browserVersion=I[1]):(I=S.match(/(?:OPR|Opera)\/([\d.]+)/))?(b.browserName="Opera",b.browserVersion=I[1]):(I=S.match(/SamsungBrowser\/([\d.]+)/))?(b.browserName="Samsung Internet",b.browserVersion=I[1]):(I=S.match(/(?:FxiOS|Firefox)\/([\d.]+)/))?(b.browserName="Firefox",b.browserVersion=I[1]):(I=S.match(/(?:CriOS|Chrome)\/([\d.]+)/))?(b.browserName="Chrome",b.browserVersion=I[1]):/Safari\//.test(S)&&(I=S.match(/Version\/([\d.]+)/))&&(b.browserName="Safari",b.browserVersion=I[1]),(I=S.match(/Windows NT ([\d.]+)/))?(b.osName="Windows",b.osVersion={"10.0":"10/11",6.3:"8.1",6.2:"8",6.1:"7"}[I[1]]||I[1]):(I=S.match(/iPhone OS ([\d_]+)|iPad; CPU OS ([\d_]+)/))?(b.osName="iOS",b.osVersion=(I[1]||I[2]||"").replace(/_/g,".")||null):(I=S.match(/Mac OS X ([\d_.]+)/))?(b.osName="macOS",b.osVersion=I[1].replace(/_/g,".")):(I=S.match(/Android ([\d.]+)/))?(b.osName="Android",b.osVersion=I[1]):/Android/i.test(S)?b.osName="Android":/CrOS/.test(S)?b.osName="ChromeOS":/Linux/.test(S)&&(b.osName="Linux"),b}(navigator.userAgent),this.domPrivacy=null,this.topFrameIdentity=null,this.errorCount=0,this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] ✅ Initialized successfully"),console.log(` Project ID: ${S}`),console.log(` Session ID: ${this.sessionId}`),console.log(` Environment: ${this.environment}`)}setWorkspaceId(S){this.workspaceId=S,console.log("[SDKContext] ✅ Workspace ID updated:",S)}#t(S){const b=[];if(S.projectId?this.#i(S.projectId)||b.push("projectId must be a valid UUID"):b.push("projectId is required"),b.length>0){const S=new Error(`TraceScout.init() validation failed:\n - ${b.join("\n - ")}`);throw S.name="ValidationError",S.validationErrors=b,S}}#i(S){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(S)}#s(){return generateSessionId()}#r(){return{width:window.innerWidth,height:window.innerHeight}}#n(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}enrichEvent(S){return{...S,sessionId:this.sessionId,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,relativeTime:S.timestamp?S.timestamp-this.sessionStartTime:0,browser:{...this.device,url:window.location.href,referrer:document.referrer,title:document.title},userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0}}enrichChunk(S){return{...S,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,metadata:{...S.metadata,metaSchema:2,sdkVersion:me,projectId:this.projectId,workspaceId:this.workspaceId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,userName:this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??void 0:void 0,userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0,userTraits:this.userAttributes,browser:this.uaInfo.browserName?{name:this.uaInfo.browserName,version:this.uaInfo.browserVersion||void 0}:void 0,os:this.uaInfo.osName?{name:this.uaInfo.osName,version:this.uaInfo.osVersion||void 0}:void 0,deviceType:this.uaInfo.deviceType||void 0,userAgent:this.device.userAgent,viewport:this.device.viewport,platform:this.device.platform,language:this.device.language,timezone:this.device.timezone,screen:this.device.screen,errorCount:this.errorCount,domPrivacy:this.domPrivacy||void 0,url:window.location.href,referrer:document.referrer,title:document.title}}}recordError(){this.errorCount++}setDomPrivacy(S){"string"==typeof S&&fe.has(S)&&(this.domPrivacy=S)}setTopFrameIdentity(S){this.topFrameIdentity=S&&"object"==typeof S?S:null}setUser(S,b={}){this.userId=S,this.userEmail=b.email||this.userEmail,this.userAttributes=b,console.log("[SDKContext] User updated:",S)}clearUser(){this.userId=null,this.userEmail=null,this.userAttributes={},console.log("[SDKContext] User cleared")}updatePageContext(){this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] Page context updated:",this.page.url)}getContext(){return{workspace:{id:this.workspaceId},project:{id:this.projectId,environment:this.environment},session:{id:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime},user:{id:this.userId,email:this.userEmail,attributes:this.userAttributes},device:this.device,page:{url:window.location.href,referrer:document.referrer,title:document.title}}}getEventContext(S={}){const b=this.sessionManager?.currentSession?.anonymousId??null,I=this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??null:null,x="function"==typeof this.pageviewManager?.getCurrentPageviewId?this.pageviewManager.getCurrentPageviewId():null,R={projectId:this.projectId,sessionId:this.sessionId,anonymousId:b,environment:this.environment,sdkVersion:S.sdkVersion??"1.0.0",workspaceId:this.workspaceId,userId:this.userId,userEmail:this.userEmail,userName:I,release:S.release??null,dist:S.dist??null,debugId:S.debugId??null,sourceName:S.sourceName??null,url:"undefined"!=typeof window?window.location.href:null,pageviewId:x},A=this.topFrameIdentity;return A&&"object"==typeof A&&("string"==typeof A.frameId&&A.frameId&&(R.frameId=A.frameId),"string"==typeof A.topFrameId&&A.topFrameId&&(R.topFrameId=A.topFrameId),"string"==typeof A.frameInstanceId&&A.frameInstanceId&&(R.frameInstanceId=A.frameInstanceId),R.frameDepth=0,R.captureRealm="top","string"==typeof A.frameOrigin&&A.frameOrigin&&(R.frameOrigin=A.frameOrigin),"string"==typeof A.frameUrl&&A.frameUrl&&(R.frameUrl=A.frameUrl),"string"==typeof A.frameLifecycle&&A.frameLifecycle&&(R.frameLifecycle=A.frameLifecycle),"string"==typeof A.privacyStatus&&A.privacyStatus&&(R.privacyStatus=A.privacyStatus)),R}setPageviewManager(S){this.pageviewManager=S||null}getSessionInfo(){return{sessionId:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId}}}const ve={CHANNEL_NAME:"ts_session",HEARTBEAT_INTERVAL:5e3,TAB_TIMEOUT:1e4,AWAY_THRESHOLD:12e4};class TabCoordinator{constructor(S={}){this.tabId=`tab_${Date.now()}_${Math.random().toString(36).substr(2,6)}`,this.awayAt=null,this.lastHeartbeat=Date.now(),this.knownTabs=new Map,this.channel=null,this.heartbeatTimer=null,this.channelName=S.channelName||ve.CHANNEL_NAME,this.heartbeatInterval=S.heartbeatInterval||ve.HEARTBEAT_INTERVAL,this.tabTimeout=S.tabTimeout||ve.TAB_TIMEOUT,this.awayThreshold=S.awayThreshold||ve.AWAY_THRESHOLD,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onActivity=S.onActivity||(()=>{}),this.debug=S.debug||!1,this._initBroadcastChannel(),this._initVisibilityTracking(),this._startHeartbeat(),this.debug&&console.log(`[TabCoordinator] Initialized tab: ${this.tabId}`)}_initBroadcastChannel(){if("undefined"!=typeof BroadcastChannel)try{this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=S=>this._handleMessage(S.data),this._broadcast({type:"hb",tabId:this.tabId,timestamp:Date.now()}),this.debug&&console.log("[TabCoordinator] BroadcastChannel connected")}catch(S){console.warn("[TabCoordinator] Failed to create BroadcastChannel:",S)}else console.warn("[TabCoordinator] BroadcastChannel not supported - single-tab mode")}_initVisibilityTracking(){document.addEventListener("visibilitychange",()=>{document.hidden?this._markAway():this._markVisible()}),window.addEventListener("pagehide",()=>{this._markAway(),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt})}),window.addEventListener("beforeunload",()=>{this._markAway()})}_startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.lastHeartbeat=Date.now(),this._broadcast({type:"hb",tabId:this.tabId,timestamp:this.lastHeartbeat,awayAt:this.awayAt}),this._pruneDeadTabs(),this._checkAwayRule()},this.heartbeatInterval)}_broadcast(S){if(this.channel)try{this.channel.postMessage(S)}catch(S){this.debug&&console.warn("[TabCoordinator] Broadcast failed:",S)}}_handleMessage(S){if(S.tabId!==this.tabId)switch(S.type){case"hb":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt}),this.debug&&console.log(`[TabCoordinator] Heartbeat from ${S.tabId}, away: ${S.awayAt?"yes":"no"}`);break;case"activity":this.onActivity(S.timestamp);break;case"away":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt});break;case"visible":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:null});break;case"new_session":this.debug&&console.log("[TabCoordinator] New session broadcast received")}}_markAway(){this.awayAt||(this.awayAt=Date.now(),this.debug&&console.log("[TabCoordinator] Tab marked AWAY"),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt}))}_markVisible(){if(this.awayAt){const S=Date.now()-this.awayAt;this.debug&&console.log(`[TabCoordinator] Tab back VISIBLE after ${Math.round(S/1e3)}s`),this.awayAt=null,this._broadcast({type:"visible",tabId:this.tabId,timestamp:Date.now()})}}_pruneDeadTabs(){const S=Date.now();for(const[b,I]of this.knownTabs.entries())S-I.lastSeen>this.tabTimeout&&(this.debug&&console.log(`[TabCoordinator] Pruning dead tab: ${b}`),this.knownTabs.delete(b))}_checkAwayRule(){const S=Date.now(),b=this.awayAt&&S-this.awayAt>this.awayThreshold;if(this.awayAt){for(const[b,I]of this.knownTabs.entries())if(!I.awayAt||S-I.awayAt<this.awayThreshold)return;b&&(console.log("[TabCoordinator] ALL tabs away >2min - session should end"),this.onSessionEnd("away_rule"))}}reportActivity(){const S=Date.now();this._broadcast({type:"activity",tabId:this.tabId,timestamp:S})}broadcastNewSession(S){this._broadcast({type:"new_session",tabId:this.tabId,sessionId:S,timestamp:Date.now()})}hasActiveTab(){if(!this.awayAt)return!0;for(const[S,b]of this.knownTabs.entries())if(!b.awayAt)return!0;return!1}getTabCount(){return this.knownTabs.size+1}getTabId(){return this.tabId}isAway(){return null!==this.awayAt}getAwayDuration(){return this.awayAt?Date.now()-this.awayAt:0}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.channel&&(this.channel.close(),this.channel=null),this.knownTabs.clear(),this.debug&&console.log(`[TabCoordinator] Destroyed tab: ${this.tabId}`)}}function uuidv4(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID()}catch{}const S=new Uint8Array(16);let b=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(S),b=!0)}catch{}if(!b)for(let b=0;b<16;b++)S[b]=Math.floor(256*Math.random());S[6]=15&S[6]|64,S[8]=63&S[8]|128;const I=Array.from(S,S=>S.toString(16).padStart(2,"0")).join("");return I.slice(0,8)+"-"+I.slice(8,12)+"-"+I.slice(12,16)+"-"+I.slice(16,20)+"-"+I.slice(20)}const Se="__ts_aid";let we=null;function readCookie(S){if("undefined"==typeof document||"string"!=typeof document.cookie)return null;const b=document.cookie.split("; ");for(const I of b){const b=I.indexOf("=");if(!(b<0)&&I.slice(0,b)===S)try{return decodeURIComponent(I.slice(b+1))}catch{return I.slice(b+1)}}return null}function peekAnonymousId(){const S=readCookie(Se);return S||we}function getOrCreateAnonymousId(){const S=peekAnonymousId();if(S)return S;const b=uuidv4();return function writeCookie(S,b,I){if("undefined"==typeof document)return!1;let x=`${S}=${encodeURIComponent(b)}; max-age=${I}; path=/; SameSite=Lax`;"undefined"!=typeof window&&window.location&&"https:"===window.location.protocol&&(x+="; Secure");try{document.cookie=x}catch{return!1}return readCookie(S)===b}(Se,b,63072e3)||(we=b),b}const be={INACTIVITY_TIMEOUT:18e5,ACTIVITY_THROTTLE:1e3,MAX_SESSION_DURATION:144e5};class SessionManager{constructor(S={}){this.sessionIdCookie=S.sessionIdCookie||"__ts_sid",this.lastActivityCookie=S.lastActivityCookie||"__ts_ts",this.sessionStartCookie=S.sessionStartCookie||"__ts_start",this.storageKey=S.storageKey||"__tracescout_session_stats__",this.inactivityTimeout=S.inactivityTimeout||be.INACTIVITY_TIMEOUT,this.maxSessionDuration=S.maxSessionDuration||be.MAX_SESSION_DURATION,this.activityThrottle=S.activityThrottle||be.ACTIVITY_THROTTLE,this.cookieDomain=S.cookieDomain||window.location.hostname,this.cookiePath=S.cookiePath||"/",this.cookieSameSite=S.cookieSameSite||"Lax",this.debug=S.debug||!1,this.onLifecycleEnd="function"==typeof S.onLifecycleEnd?S.onLifecycleEnd:null,this.currentSession=null,this._lastActivityUpdate=0,this._boundActivityHandler=this._handleActivity.bind(this),this._trackingStarted=!1,this.tabCoordinator=new TabCoordinator({onSessionEnd:S=>this._handleSessionEnd(S),onActivity:S=>this._handleRemoteActivity(S),debug:this.debug,awayThreshold:S.awayThreshold,heartbeatInterval:S.heartbeatInterval,tabTimeout:S.tabTimeout})}getOrCreateSession(S={}){const b=this._getStoredSession();if(b&&this._isSessionValid(b))return console.log("[SessionManager] ✅ Continuing session:",b.sessionId),console.log(" Duration:",Math.round((Date.now()-b.startTime)/1e3/60),"min"),console.log(" Pages so far:",b.pageCount),this.currentSession=b,this.currentSession.pageCount++,this._updateActivity(),this._startActivityTracking(),b.sessionId;const I=generateSessionId(),x=getOrCreateAnonymousId();this.currentSession={sessionId:I,anonymousId:x,startTime:Date.now(),lastActivityTime:Date.now(),pageCount:1,eventCount:0,chunkCount:0,lastChunkSequence:0,projectId:S.projectId,workspaceId:S.workspaceId,environment:S.environment,userId:S.userId||null,userEmail:null,userAttributes:{},lifecycle:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}},this._saveSession(),this._startActivityTracking();const R=b?.expiredReason||(b?"Previous session invalid":"No previous session found");return console.log("[SessionManager] 🆕 Created new session:",I),console.log(" Reason:",R),this.tabCoordinator.broadcastNewSession(I),I}_isSessionValid(S){if(!S?.sessionId)return!1;const b=Date.now(),I=b-(S.lastActivityTime||0),x=b-(S.startTime||0),R=this.tabCoordinator?.awayThreshold||12e4;return I>R?(console.log("[SessionManager] ⏰ Session expired: away rule (all tabs closed)"),console.log(" Away for:",Math.round(I/1e3),"seconds"),console.log(" Threshold:",Math.round(R/1e3),"seconds"),S.expiredReason="away_rule",!1):I>this.inactivityTimeout?(console.log("[SessionManager] ⏰ Session expired: inactivity"),console.log(" Inactive for:",Math.round(I/1e3/60),"min"),S.expiredReason="inactivity",!1):!(x>this.maxSessionDuration)||(console.log("[SessionManager] ⏰ Session expired: max duration"),console.log(" Duration:",Math.round(x/1e3/60),"min"),S.expiredReason="max_duration",!1)}_getStoredSession(){try{const S=this._getCookie(this.sessionIdCookie);if(!S)return null;const b=getOrCreateAnonymousId(),I=parseInt(this._getCookie(this.sessionStartCookie))||Date.now(),x=parseInt(this._getCookie(this.lastActivityCookie))||Date.now();let R={};try{const S=localStorage.getItem(this.storageKey);S&&(R=JSON.parse(S))}catch(S){console.warn("[SessionManager] Failed to load stats from localStorage:",S)}if(R.anonymousId&&R.anonymousId!==b)return console.log("[SessionManager] 🔄 Storage cleared detected (anonymousId mismatch)"),console.log(" Cookie anonymousId:",b),console.log(" localStorage anonymousId:",R.anonymousId),this._clearSession(),null;if("number"==typeof R.schemaVersion&&5!==R.schemaVersion)return console.log("[SessionManager] 🔄 Stats schemaVersion mismatch — dropping cached session"),console.log(" cached schemaVersion:",R.schemaVersion),console.log(" required schemaVersion: 5"),this._clearSession(),null;return{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x,pageCount:R.pageCount||1,eventCount:R.eventCount||0,chunkCount:R.chunkCount||0,lastChunkSequence:R.lastChunkSequence||0,projectId:R.projectId,workspaceId:R.workspaceId,environment:R.environment,userId:R.userId,userEmail:R.userEmail,userAttributes:R.userAttributes||{},lifecycle:R.lifecycle&&"object"==typeof R.lifecycle?{sessionStartEmitted:!0===R.lifecycle.sessionStartEmitted,sessionEndEmitted:!0===R.lifecycle.sessionEndEmitted,startedAt:"number"==typeof R.lifecycle.startedAt?R.lifecycle.startedAt:null,endedAt:"number"==typeof R.lifecycle.endedAt?R.lifecycle.endedAt:null,endReason:"string"==typeof R.lifecycle.endReason?R.lifecycle.endReason:null}:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}}}catch(S){return console.warn("[SessionManager] Failed to load stored session:",S),this._clearSession(),null}}_saveSession(){if(this.currentSession)try{const{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x}=this.currentSession,R=this.maxSessionDuration;this._setCookie(this.sessionIdCookie,S,R),this._setCookie(this.sessionStartCookie,I.toString(),R),this._setCookie(this.lastActivityCookie,x.toString(),R);const A={schemaVersion:5,anonymousId:b,pageCount:this.currentSession.pageCount,eventCount:this.currentSession.eventCount,chunkCount:this.currentSession.chunkCount,lastChunkSequence:this.currentSession.lastChunkSequence,projectId:this.currentSession.projectId,workspaceId:this.currentSession.workspaceId,environment:this.currentSession.environment,userId:this.currentSession.userId,userEmail:this.currentSession.userEmail,userAttributes:this.currentSession.userAttributes||{},lifecycle:this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}};localStorage.setItem(this.storageKey,JSON.stringify(A))}catch(S){console.warn("[SessionManager] Failed to save session:",S)}}_handleActivity(){const S=Date.now();S-this._lastActivityUpdate<this.activityThrottle||(this._lastActivityUpdate=S,this._updateActivity(),this.tabCoordinator.reportActivity())}_handleRemoteActivity(S){this.currentSession&&(this.currentSession.lastActivityTime=S,this._setCookie(this.lastActivityCookie,S.toString(),this.maxSessionDuration))}_updateActivity(){this.currentSession&&(this.currentSession.lastActivityTime=Date.now(),this._saveSession())}_startActivityTracking(){if(this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.addEventListener(S,this._boundActivityHandler,{passive:!0})}),this._trackingStarted=!0,this.debug&&console.log("[SessionManager] ✅ Activity tracking started (mousemove/click/scroll)")}_stopActivityTracking(){if(!this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.removeEventListener(S,this._boundActivityHandler)}),this._trackingStarted=!1}_handleSessionEnd(S){if(console.log("[SessionManager] 🛑 Session ended by TabCoordinator:",S),"away_rule"===S&&"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"allTabsClosed"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}}getLifecycleGuard(){if(!this.currentSession)return null;const S=this.currentSession.lifecycle;return S&&"object"==typeof S?{sessionStartEmitted:!0===S.sessionStartEmitted,sessionEndEmitted:!0===S.sessionEndEmitted,startedAt:"number"==typeof S.startedAt?S.startedAt:null,endedAt:"number"==typeof S.endedAt?S.endedAt:null,endReason:"string"==typeof S.endReason?S.endReason:null}:null}setLifecycleGuard(S){if(!this.currentSession)return;if(!S||"object"!=typeof S)return;const b=this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null};!0===S.sessionStartEmitted&&(b.sessionStartEmitted=!0),!0===S.sessionEndEmitted&&(b.sessionEndEmitted=!0),"number"==typeof S.startedAt&&(b.startedAt=S.startedAt),"number"==typeof S.endedAt&&(b.endedAt=S.endedAt),"string"==typeof S.endReason&&(b.endReason=S.endReason),this.currentSession.lifecycle=b,this._saveSession()}_getCookie(S){return document.cookie.split("; ").reduce((S,b)=>{const[I,x]=b.split("=");return I&&(S[I]=decodeURIComponent(x||"")),S},{})[S]||null}_setCookie(S,b,I){const x=Math.floor(I/1e3);let R=`${S}=${encodeURIComponent(b)}`;R+=`; max-age=${x}`,R+=`; path=${this.cookiePath}`,R+=`; SameSite=${this.cookieSameSite}`,"undefined"!=typeof window&&"https:"===window.location.protocol&&(R+="; Secure"),this.cookieDomain&&!this.cookieDomain.includes("localhost")&&(R+=`; domain=${this.cookieDomain}`),document.cookie=R}_deleteCookie(S){document.cookie=`${S}=; max-age=0; path=${this.cookiePath}`}_clearSession(){this._deleteCookie(this.sessionIdCookie),this._deleteCookie(this.lastActivityCookie),this._deleteCookie(this.sessionStartCookie);try{localStorage.removeItem(this.storageKey)}catch(S){console.warn("[SessionManager] Failed to clear localStorage:",S)}}getSessionInfo(){if(!this.currentSession)return null;const S=Date.now(),b=S-this.currentSession.startTime,I=S-this.currentSession.lastActivityTime;return{...this.currentSession,duration:b,durationMinutes:Math.round(b/1e3/60),timeSinceActivity:I,timeSinceActivityMinutes:Math.round(I/1e3/60),isValid:this._isSessionValid(this.currentSession),willExpireIn:this.inactivityTimeout-I,willExpireInMinutes:Math.round((this.inactivityTimeout-I)/1e3/60),tabCount:this.tabCoordinator.getTabCount(),tabId:this.tabCoordinator.getTabId(),isAway:this.tabCoordinator.isAway()}}incrementEventCount(S=1){this.currentSession&&(this.currentSession.eventCount+=S,this._updateActivity())}incrementPageCount(){this.currentSession&&(this.currentSession.pageCount++,this._updateActivity(),this.debug&&console.log("[SessionManager] 📄 Page navigation, count:",this.currentSession.pageCount))}incrementChunkCount(){this.currentSession&&(this.currentSession.chunkCount++,this._saveSession())}updateLastChunkSequence(S){this.currentSession&&(this.currentSession.lastChunkSequence=S,this._saveSession(),this.debug&&console.log(`[SessionManager] Updated lastChunkSequence to ${S}`))}getLastChunkSequence(){return this.currentSession?.lastChunkSequence||0}getResumeInfo(){const S=this._getStoredSession();return S&&this._isSessionValid(S)&&(S.pageCount||1)>1?{sessionId:S.sessionId,lastChunkSequence:S.lastChunkSequence||0,lastActivityTime:S.lastActivityTime,isResumed:!0,pageCount:S.pageCount||1,eventCount:S.eventCount||0,chunkCount:S.chunkCount||0}:{sessionId:null,lastChunkSequence:0,lastActivityTime:null,isResumed:!1,pageCount:0,eventCount:0,chunkCount:0}}isResumedSession(){return!!this.currentSession&&(this.currentSession.pageCount||1)>1}updateUser(S,b){this.updateUserMetadata(S,{email:b})}updateUserMetadata(S,b={}){this.currentSession&&(this.currentSession.userId=S,this.currentSession.userEmail=b.email||this.currentSession.userEmail,this.currentSession.userAttributes=b,this._saveSession(),console.log("[SessionManager] 👤 User metadata updated"))}clearUserMetadata(){this.currentSession&&(this.currentSession.userId=null,this.currentSession.userEmail=null,this.currentSession.userAttributes={},this._saveSession(),console.log("[SessionManager] 👤 User metadata cleared"))}endSession(){if(!this.currentSession)return;const S=Date.now()-this.currentSession.startTime;if(console.log("[SessionManager] 🛑 Ending session:",this.currentSession.sessionId),console.log(" Duration:",Math.round(S/1e3),"s"),console.log(" Events:",this.currentSession.eventCount),console.log(" Pages:",this.currentSession.pageCount),console.log(" Chunks:",this.currentSession.chunkCount),"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"manual"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}this._stopActivityTracking(),this._clearSession(),this.currentSession=null}forceNewSession(S="manual"){console.log("[SessionManager] 🔄 Force new session, reason:",S),this.currentSession&&console.log(" Ending:",this.currentSession.sessionId),this.endSession()}destroy(){this._stopActivityTracking(),this.tabCoordinator.destroy()}}class EventManager{constructor(S={},b={}){this.config=S,this.storageKeys=b,this.logger=new Logger("[EventManager]",S.debug),this.eventQueue=[],this.eventOccurrenceTracker=new Map,this.debouncedSave=debounce(this.saveToLocal.bind(this),100),this._cleanupInterval=null,this._startCleanupTimer()}_startCleanupTimer(){const S=this.config.memoryCleanupIntervalMs||6e4;this._cleanupInterval=setInterval(()=>{this._cleanupOccurrenceTracker()},S)}_stopCleanupTimer(){this._cleanupInterval&&(clearInterval(this._cleanupInterval),this._cleanupInterval=null)}_cleanupOccurrenceTracker(){const S=Date.now(),b=this.config.deduplicationWindowMs||6e4,I=this.config.maxOccurrenceTrackerSize||5e3;let x=0;for(const[I,R]of this.eventOccurrenceTracker.entries())S-R>b&&(this.eventOccurrenceTracker.delete(I),x++);if(this.eventOccurrenceTracker.size>I){const S=Array.from(this.eventOccurrenceTracker.entries()).sort((S,b)=>b[1]-S[1]);this.eventOccurrenceTracker.clear();const b=S.slice(0,I);for(const[S,I]of b)this.eventOccurrenceTracker.set(S,I);const R=S.length-I;this.config.debug&&this.logger.log(`[Memory] Force-cleaned ${R} entries (exceeded max size ${I})`),x+=R}x>0&&this.config.debug&&this.logger.log(`[Memory] Cleaned up ${x} stale entries from occurrence tracker (size: ${this.eventOccurrenceTracker.size})`)}destroy(){this._stopCleanupTimer(),this.eventOccurrenceTracker.clear(),this.eventQueue=[]}addEvent(S){try{return!!this.shouldLogEvent(S)&&(!!this.deduplicateEvent(S)&&(this.eventQueue.length>=this.config.maxQueueSize&&(this.eventQueue.shift(),this.logger.warn("Queue size limit reached, removing oldest event")),this.eventQueue.push(S),this.debouncedSave(),this.logger.log("Event added:",S.type),!0))}catch(S){return this.logger.error("Failed to add event:",S),!1}}getEvents(){try{return x.sortBy(x.cloneDeep(this.eventQueue),"timestamp")}catch(S){return this.logger.error("Failed to get events:",S),[]}}removeEvents(S){try{const b=new Set(S);this.eventQueue=x.filter(this.eventQueue,S=>!b.has(S.id)),this.debouncedSave()}catch(S){this.logger.error("Failed to remove events:",S)}}clearEvents(){try{this.eventQueue.length=0,this.eventOccurrenceTracker.clear(),this.clearLocal(),this.logger.log("All events cleared")}catch(S){this.logger.error("Failed to clear events:",S)}}getQueueSize(){return this.eventQueue.length}shouldLogEvent(S){try{const b=S.context?.isMonitored,I=S.context?.forceLog;if(!(b||I))return!1;return!(this.config.ignoreEventTypes||[]).includes(S.type)}catch(S){return this.logger.error("Error in shouldLogEvent:",S),!1}}deduplicateEvent(S){try{const b=this.generateDedupeKey(S),I=Date.now(),x=this.eventOccurrenceTracker.get(b);return!(x&&I-x<this.config.deduplicationWindowMs)&&(this.eventOccurrenceTracker.set(b,I),!0)}catch(S){return this.logger.error("Error in deduplicateEvent:",S),!0}}generateDedupeKey(S){try{return`${S.type}_${S.context?.url||"unknown"}_${S.context?.method||"unknown"}`}catch(b){return this.logger.error("Error generating dedupe key:",b),`${S.type}_${Date.now()}`}}saveToLocal(){try{const b={events:this.eventQueue,timestamp:Date.now()};S.set(this.storageKeys.EVENTS||"__api_reporter_events__",b)}catch(S){this.logger.error("Failed to save events to local storage:",S)}}loadFromLocal(){try{const b=S.get(this.storageKeys.EVENTS||"__api_reporter_events__");b&&b.events&&(this.eventQueue=b.events,this.logger.log(`Loaded ${this.eventQueue.length} events from local storage`))}catch(S){this.logger.error("Failed to load events from local storage:",S)}}clearLocal(){try{S.remove(this.storageKeys.EVENTS||"__api_reporter_events__")}catch(S){this.logger.error("Failed to clear local storage:",S)}}getEventById(S){try{return this.eventQueue.find(b=>b.id===S)}catch(S){return this.logger.error("Failed to get event by ID:",S),null}}getEventsByType(S){try{return this.eventQueue.filter(b=>b.type===S)}catch(S){return this.logger.error("Failed to get events by type:",S),[]}}getEventsByTimeRange(S,b){try{return this.eventQueue.filter(I=>{const x=I.timestamp;return x>=S&&x<=b})}catch(S){return this.logger.error("Failed to get events by time range:",S),[]}}getEventStats(){try{const S={total:this.eventQueue.length,byType:{},byStatus:{}};return this.eventQueue.forEach(b=>{S.byType[b.type]=(S.byType[b.type]||0)+1;const I=b.context?.status||"unknown";S.byStatus[I]=(S.byStatus[I]||0)+1}),S}catch(S){return this.logger.error("Failed to get event stats:",S),{total:0,byType:{},byStatus:{}}}}cleanupOldEvents(S=864e5){try{const b=Date.now()-S,I=this.eventQueue.length;this.eventQueue=this.eventQueue.filter(S=>S.timestamp>b);const x=I-this.eventQueue.length;x>0&&(this.logger.log(`Cleaned up ${x} old events`),this.debouncedSave())}catch(S){this.logger.error("Failed to cleanup old events:",S)}}}class ServiceManager{constructor(S={},b=null){this.config=S,this.logger=b||new Logger("[ServiceManager]",S.debug),this.service=null,this.isSending=!1,this.retryCount=0,this.maxRetries=x.get(S,"maxRetries",3),this.initializeService()}initializeService(){if(!x.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(x.get(this.config,"service"),x.get(this.config,"serviceOptions",{}))}setService(S,b={}){if(!x.isObject(S)||!x.isFunction(x.get(S,"send")))throw new Error("Invalid service: must be an object with send() method");this.service=S,this.logger.log(`Service initialized: ${this.getServiceName()}`)}async sendEvents(S){if(this.isSending||x.isEmpty(S)||!this.service)return this.logger.warn("Cannot send events:",{isSending:this.isSending,isEmpty:x.isEmpty(S),noService:!this.service}),x.map(S||[],S=>({event:S,success:!1,error:new Error("Service unavailable")}));this.isSending=!0;try{const b=[];for(const I of S)try{await this.sendSingleEvent(I),b.push({event:I,success:!0}),this.logger.log(`Event sent successfully: ${I.type}`)}catch(S){this.logger.error(`Event failed: ${I.type}`,S),b.push({event:I,success:!1,error:S})}return this.retryCount=0,b}catch(b){return this.logger.error("Failed to send events:",b),this.retryCount++,x.map(S,S=>({event:S,success:!1,error:b}))}finally{this.isSending=!1}}async sendSingleEvent(S){let b;for(let I=1;I<=this.maxRetries;I++)try{return void await this.service.send(S)}catch(x){b=x,this.logger.warn(`Attempt ${I}/${this.maxRetries} failed for event ${S.id}:`,x.message),I<this.maxRetries&&await this.delay(this.getRetryDelay(I))}throw b}getRetryDelay(S){return Math.min(1e3*Math.pow(2,S-1),3e4)}async delay(S){return new Promise(b=>setTimeout(b,S))}getServiceName(){return x.isString(this.config.service)?this.config.service:this.service.constructor.name}isServiceAvailable(){return null!==this.service}getServiceStatus(){return{available:this.isServiceAvailable(),name:this.getServiceName(),isSending:this.isSending,retryCount:this.retryCount}}resetRetryCount(){this.retryCount=0}destroy(){this.service=null,this.isSending=!1,this.retryCount=0}}class UserProfileManager{constructor(S,b=[],I=!1){this.storageKey=S,this.fieldsToExtract=b,this.logger=new Logger("[UserProfileManager]",I)}getProfile(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.warn("Failed to read user profile:",S),{}}}setProfile(S={}){if(!x.isObject(S))return this.logger.warn("Invalid profile object provided"),!1;try{const b=this.getProfile(),I=x.merge(b,S);return localStorage.setItem(this.storageKey,JSON.stringify(I)),this.logger.log("User profile updated:",I),!0}catch(S){return"QuotaExceededError"===S.name?this.logger.warn("Storage quota exceeded for user profile"):this.logger.error("Failed to save user profile:",S),!1}}ensureProfile(){try{const S=this.getProfile();if(x.isEmpty(x.get(S,"uniqId"))){const b=x.merge(S,{uniqId:generateId(),createdAt:(new Date).toISOString()});this.setProfile(b),this.logger.log("Generated new user profile:",x.get(b,"uniqId"))}}catch(S){this.logger.error("Failed to ensure user profile:",S)}}extractContextFromData({data:S,source:b="response",url:I=""}){const R={};try{if(!x.isObject(S)||!x.isArray(this.fieldsToExtract))return R;const A=x.toLower(I);return this.fieldsToExtract.forEach(_=>{try{const D=x.toLower(x.get(_,"api","")),L=x.get(_,"source",""),B="*"===D||A.includes(D);if(!B||!("*"===L||L===b))return;const U=x.get(_,"fields",[]);x.isArray(U)?U.forEach(x=>{try{this.recursiveFieldMatch({context:R,matchRule:x,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with pattern "${x}":`,S)}}):x.isObject(U)&&x.entries(U).forEach(([x,A])=>{try{this.recursiveFieldMatchWithMapping({context:R,newKey:x,matchRule:A,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with mapping "${x}": "${A}":`,S)}})}catch(S){this.logger.warn("Failed to process extraction rule:",S)}}),R}catch(S){return this.logger.error("Failed to extract context from data:",S),R}}updateFromContext({url:S,source:b,data:I}){try{const x=this.extractContextFromData({url:S,source:b,data:I});if(Object.keys(x).length>0){const S=this.getProfile(),b={...S,...x};if(JSON.stringify(S)!==JSON.stringify(b))return this.setProfile(b),!0}return!1}catch(S){return this.logger.warn("Failed to update user profile context:",S),!1}}recursiveFieldMatch({context:S,matchRule:b,data:I,source:R,url:A}){try{if(!x.isObject(I))return;if(x.isString(b)){const R=x.get(I,b);if(void 0!==R)return S[b]=R,void this.logger.log(`Found field by path: ${b} = ${JSON.stringify(R)}`);const A=x.find(x.entries(I),([S])=>x.toLower(S)===x.toLower(b));if(A){const[b,I]=A;return S[b]=I,void this.logger.log(`Found field by name: ${b} = ${JSON.stringify(I)}`)}}if(b instanceof RegExp){const R=x.find(x.entries(I),([S,I])=>x.isString(I)&&b.test(I));if(R){const[b,I]=R;return S[b]=I,void this.logger.log(`Found field by value pattern: ${b} = ${I}`)}}x.values(I).forEach(I=>{x.isObject(I)&&!x.isNull(I)&&this.recursiveFieldMatch({context:S,matchRule:b,data:I,source:R,url:A})})}catch(S){this.logger.warn("Error in recursive field matching:",S)}}recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:R,source:A,url:_}){try{if(!x.isObject(R))return;if(x.isString(I)){const A=x.get(R,I);if(void 0!==A)return S[b]=A,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(A)}`);const _=x.find(x.entries(R),([S])=>x.toLower(S)===x.toLower(I));if(_){const[I,x]=_;return S[b]=x,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(x)}`)}}if(I instanceof RegExp){const A=x.find(x.entries(R),([S,b])=>x.isString(b)&&I.test(b));if(A){const[I,x]=A;return S[b]=x,void this.logger.log(`Found field by pattern with mapping: ${I} -> ${b} = ${x}`)}}x.values(R).forEach(R=>{x.isObject(R)&&!x.isNull(R)&&this.recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:R,source:A,url:_})})}catch(S){this.logger.warn("Error in recursive field matching with mapping:",S)}}validateFieldValue(S,b){try{if(x.isString(b)){const I=x.get(DEFAULT_FIELD_PATTERNS,b);return I&&I.test(S)}if(x.isFunction(b))return b(S);if(x.isObject(b)){const{type:I,min:x,max:R,pattern:A}=b;return(!I||typeof S===I)&&(!(void 0!==x&&S<x)&&(!(void 0!==R&&S>R)&&!(A&&!A.test(S))))}return!0}catch(S){return this.logger.warn("Validation error:",S),!1}}transformFieldValue(S,b){try{if(x.isFunction(b))return b(S);if(x.isString(b))switch(b){case"toLowerCase":return x.toLower(S);case"toUpperCase":return x.toUpper(S);case"trim":return x.trim(S);case"toString":return String(S);case"toNumber":return Number(S);default:return S}return S}catch(b){return this.logger.warn("Transform error:",b),S}}clearProfile(){try{return localStorage.removeItem(this.storageKey),this.logger.log("User profile cleared"),!0}catch(S){return this.logger.error("Failed to clear user profile:",S),!1}}getProfileField(S){try{const b=this.getProfile();return x.get(b,S)}catch(S){return void this.logger.error("Failed to get profile field:",S)}}setProfileField(S,b){try{const I=this.getProfile();return I[S]=b,this.setProfile(I)}catch(S){return this.logger.error("Failed to set profile field:",S),!1}}hasProfile(){try{const S=this.getProfile();return!x.isEmpty(S)}catch(S){return this.logger.error("Failed to check profile existence:",S),!1}}getProfileSize(){try{const S=this.getProfile();return Object.keys(S).length}catch(S){return this.logger.error("Failed to get profile size:",S),0}}}class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=new Logger("[PerformanceMonitor]",this.debug),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function resolveApiBaseUrl(S={}){if(S&&"string"==typeof S.apiBaseUrl&&S.apiBaseUrl)return S.apiBaseUrl;if(S&&"string"==typeof S.backendUrl&&S.backendUrl)return S.backendUrl;if("undefined"!=typeof window&&window.location&&window.location.hostname){const S=window.location.hostname;if("localhost"===S||"127.0.0.1"===S)return"http://localhost:3001"}return"https://api.tracescout.com"}const Ce=["/chunks","/logs/batch","/telemetry","/sdk-config"];function isInternalSdkEndpoint(S){if("string"!=typeof S||!S)return!1;if(!S.includes("/api/"))return!1;for(const b of Ce)if(S.includes(b)){if(S.includes("/api/projects/")||S.includes("/api/sdk-config"))return!0;if("/sdk-config"===b&&S.includes("/sdk-config"))return!0}return!1}class InitializationPipeline{#o=null;#a=null;constructor(S){this.#o=S}async run(S){this.#a=S;try{this.#l();const S=this.#c(),b=this.#u(S),I=this.#h(b),x=this.#d(I,b);x&&(I.service=x);const R=this.#g(I);return{success:!0,sessionManager:S,sdkContext:b,remoteConfigService:null,serverConfig:this.#p(),config:I,managers:R}}catch(S){throw this.#o?.error("Initialization pipeline failed:",S),S}}#l(){const S=this.#a;if(!x.isObject(S))throw new Error("InitializationPipeline.run(options): options must be an object");if(!S.projectId)throw new Error("InitializationPipeline.run(options): projectId missing");S.debug&&console.log("[TraceScout] ✓ Required fields validated")}#c(){const S=this.#a;S.debug&&console.log("[TraceScout] 📅 Initializing session manager...");const b=new SessionManager({inactivityTimeout:18e5,maxSessionDuration:144e5,activityThrottle:1e3,awayThreshold:12e4,heartbeatInterval:5e3,tabTimeout:1e4,debug:S.debug||!1}),I=b.getOrCreateSession({projectId:S.projectId,environment:S.environment});return S.debug&&console.log("[TraceScout] ✓ Session manager initialized"),{sessionManager:b,sessionId:I}}#u(S){const b=this.#a,{sessionManager:I,sessionId:x}=S;try{const S=SDKContext.initialize({projectId:b.projectId,environment:b.environment||"production",userId:void 0,sessionId:x,sessionManager:I});if(I&&I.currentSession){const x=I.currentSession;x.userId&&x.userAttributes&&(S.setUser(x.userId,x.userAttributes),b.debug&&console.log("[TraceScout] ✓ Restored user metadata from session"))}return b.debug&&(console.log("[TraceScout] ✓ SDK Context initialized"),console.log(` Session ID: ${S.sessionId}`),console.log(` Project: ${S.projectId}`),console.log(` Environment: ${S.environment}`)),S}catch(S){throw console.error("[TraceScout] ❌ Failed to initialize SDKContext:",S),S}}#h(S){const b=this.#a,I={projectId:S.projectId,environment:S.environment,release:b.release,dist:b.dist,debugId:b.debugId,sourceName:b.sourceName,debug:b.debug||!1,apiBaseUrl:resolveApiBaseUrl(b),sampleRate:1,sessionChunkDuration:3e4,sessionMaxChunkSize:5e5,privacy:{maskAllInputs:!1,maskTextClass:"ts-mask",blockClass:"ts-block",ignoreClass:"ts-ignore",blockSelectors:[],maskImages:!1},network:(x=b.network,{isEnabled:!0,captureRequestHeaders:!0,captureResponseHeaders:!0,captureRequestBody:!0,captureResponseBody:!0,excludeEndpoints:[],maxBodyBytes:10240,requestSanitizer:null,responseSanitizer:null,sensitiveFields:[],...x&&"object"==typeof x&&!Array.isArray(x)?x:{}})};var x;return b.debug&&console.log("[TraceScout] ✓ Configuration built (SDK defaults)"),I}#p(){return{workspace:{name:"Unknown",id:null},project:{name:"Unknown"},configVersion:"sdk-defaults",features:{sessionRecording:{enabled:!0,sampleRate:1,captureNetwork:!0,captureConsole:!0,captureErrors:!0,networkSettings:{captureHeaders:!0,captureRequestBody:!0,captureResponseBody:!0},chunkDuration:3e4,maxChunkSize:5e5,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},performanceMonitoring:{enabled:!0,coreWebVitals:!0},logging:{enabled:!0,captureConsole:!0,minLevel:"debug",maxBufferSize:1e3,flushInterval:5e3,sampleRate:1}},telemetry:{}}}#d(S,b){const I=`${resolveApiBaseUrl(S)}/api/projects/${b.projectId}/telemetry`;return{send:async S=>{const x=Array.isArray(S)?S:[S];try{const S=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:x,context:{projectId:b.projectId,sessionId:b.sessionId,environment:b.environment}})});if(!S.ok)throw new Error(`Telemetry send failed: ${S.status}`);return await S.json()}catch(S){throw console.error("[TraceScout][TelemetryService] Send failed:",S),S}}}}#g(S){const b=new EventManager(S),I=new ServiceManager(S,this.#o),x=new UserProfileManager(S),R=new PerformanceMonitor(S);return S.debug&&console.log("[TraceScout] ✓ Core managers initialized"),{eventManager:b,serviceManager:I,userProfileManager:x,performanceMonitor:R}}}var ke={environment:{type:"string",minLength:1,maxLength:64,default:"production"},release:{type:"string",minLength:1,maxLength:255},debug:{type:"boolean",default:!1},sourceName:{type:"string",minLength:1,maxLength:100,pattern:"^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$",default:"web-client",description:"S-2d.2 (step B): optional browser-source attribution. Defaults to 'web-client' when omitted. Emitted on every SDK v1 common envelope as `sourceName`. Pattern matches the API's envelope.schema.json SOURCE_NAME_PATTERN union. NOT named `source` to avoid collision with the existing js_error leaf `source` field (stack-frame URL, up to 2048 chars)."},dist:{type:"string",minLength:1,maxLength:64,description:"B2 source maps: optional build variant (e.g. 'web', 'ios-webview'). Emitted on every v1 envelope as `dist`; used with `release` to match uploaded source-map artifacts."},debugId:{type:"string",minLength:8,maxLength:64,pattern:"^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$",description:"B2 source maps: optional build-pinned debug ID (hex/UUID form). Strongest source-map match identity. May also be supplied by an injected build-time global (globalThis.__TRACESCOUT_DEBUG_ID__) read synchronously at init — never fetched over the network."}};const Ie=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ee=new Set(["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody","maxBodyBytes","excludeEndpoints","requestSanitizer","responseSanitizer","sensitiveFields"]),xe=["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody"];const Me=/^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$/,Re=new Set(Object.keys(ke));function validateConfig(S,b){if(null!==S&&"object"==typeof S&&!Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_FIRST_ARG"};if(null==S||""===S||"string"!=typeof S)return{ok:!1,code:"CONFIG_PROJECT_ID_REQUIRED"};if(!Ie.test(S))return{ok:!1,code:"CONFIG_PROJECT_ID_INVALID"};const I=b??{};if("object"!=typeof I||Array.isArray(I)||null===I)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:["(options must be a plain object)"]};const x=[];for(const S of Object.keys(I))"network"!==S&&"iframe"!==S&&(Re.has(S)||x.push(S));if(x.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:x};if(void 0!==I.debugId){const S=/^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$/;if("string"!=typeof I.debugId||!S.test(I.debugId))return{ok:!1,code:"CONFIG_INVALID_DEBUG_ID",keys:["debugId"]}}if(void 0!==I.dist&&("string"!=typeof I.dist||I.dist.length<1||I.dist.length>64))return{ok:!1,code:"CONFIG_INVALID_DIST",keys:["dist"]};if(void 0!==I.network){const S=function validateNetworkOptions(S){if("object"!=typeof S||null===S||Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["(network must be a plain object)"]};const b=[];for(const I of Object.keys(S))Ee.has(I)||b.push(`network.${I}`);if(b.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:b};for(const b of xe)if(void 0!==S[b]&&"boolean"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};if(void 0!==S.maxBodyBytes){const b=S.maxBodyBytes;if("number"!=typeof b||!Number.isFinite(b)||b<0)return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.maxBodyBytes"]}}if(void 0!==S.excludeEndpoints){if(!Array.isArray(S.excludeEndpoints))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]};for(const b of S.excludeEndpoints)if("string"!=typeof b&&!(b instanceof RegExp))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]}}if(void 0!==S.sensitiveFields&&(!Array.isArray(S.sensitiveFields)||S.sensitiveFields.some(S=>"string"!=typeof S)))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.sensitiveFields"]};for(const b of["requestSanitizer","responseSanitizer"])if(void 0!==S[b]&&"function"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};return{ok:!0}}(I.network);if(!S.ok)return S}return void 0!==I.sourceName&&("string"!=typeof I.sourceName||I.sourceName.length<1||I.sourceName.length>100||!Me.test(I.sourceName))?{ok:!1,code:"CONFIG_INVALID_SOURCE_NAME"}:{ok:!0,projectId:S,options:I}}function shouldSampleSession(S,b={}){const I=b.anonymousId??null,x=b.randomFn??Math.random;return null==S||"number"!=typeof S||(!!Number.isNaN(S)||(S>=1||!(S<=0)&&("string"==typeof I&&I.length>0?function hashToUnitInterval(S){let b=2166136261;for(let I=0;I<S.length;I++)b^=S.charCodeAt(I),b=Math.imul(b,16777619);return(b>>>0)/4294967296}(I)<S:x()<S)))}const Te="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ulid(S=Date.now()){return function encodeTimestamp(S){let b="",I=S;for(let S=9;S>=0;S--)b=Te[I%32]+b,I=Math.floor(I/32);return b}(S)+function encodeRandom(){let S="";const b=new Uint8Array(10);let I=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(b),I=!0)}catch{}if(!I)for(let S=0;S<b.length;S++)b[S]=Math.floor(256*Math.random());let x=0,R=0;for(let I=0;I<b.length;I++)for(x=x<<8|b[I],R+=8;R>=5;)R-=5,S+=Te[x>>R&31];return S}()}const Ae=Object.freeze(["session_start","session_end","replay_chunk","page_view","route_change","network_request","console_event","js_error","performance_metric","custom_event","user_identified"]),_e=new Set(Ae);function wrapInEnvelope(S,b,I){if(!_e.has(S))throw new Error(`wrapInEnvelope: unknown eventType "${S}"`);if(null===I||"object"!=typeof I)throw new Error("wrapInEnvelope: context is required");const x={eventId:ulid(),eventType:S,timestamp:Date.now(),contractVersion:"1.0.0",projectId:I.projectId,sessionId:I.sessionId,anonymousId:I.anonymousId,environment:I.environment,sdkVersion:I.sdkVersion};return isNonEmptyString$3(I.workspaceId)&&(x.workspaceId=I.workspaceId),isNonEmptyString$3(I.userId)&&(x.userId=I.userId),isNonEmptyString$3(I.userEmail)&&(x.userEmail=I.userEmail),isNonEmptyString$3(I.userName)&&(x.userName=I.userName),isNonEmptyString$3(I.release)&&(x.release=I.release),isNonEmptyString$3(I.dist)&&(x.dist=I.dist),isNonEmptyString$3(I.debugId)&&(x.debugId=I.debugId),isNonEmptyString$3(I.sourceName)&&(x.sourceName=I.sourceName),isNonEmptyString$3(I.pageviewId)&&(x.pageviewId=I.pageviewId),isNonEmptyString$3(I.url)&&(x.url=I.url),isNonEmptyString$3(I.traceId)&&(x.traceId=I.traceId),isNonEmptyString$3(I.spanId)&&(x.spanId=I.spanId),isNonEmptyString$3(I.frameId)&&(x.frameId=I.frameId),isNonEmptyString$3(I.parentFrameId)&&(x.parentFrameId=I.parentFrameId),isNonEmptyString$3(I.topFrameId)&&(x.topFrameId=I.topFrameId),isNonEmptyString$3(I.frameInstanceId)&&(x.frameInstanceId=I.frameInstanceId),isNonNegativeInt(I.frameDepth)&&(x.frameDepth=I.frameDepth),isNonEmptyString$3(I.frameOrigin)&&(x.frameOrigin=I.frameOrigin),isNonEmptyString$3(I.frameUrl)&&(x.frameUrl=I.frameUrl),isNonEmptyString$3(I.frameLifecycle)&&(x.frameLifecycle=I.frameLifecycle),isNonEmptyString$3(I.captureRealm)&&(x.captureRealm=I.captureRealm),isNonEmptyString$3(I.privacyStatus)&&(x.privacyStatus=I.privacyStatus),isNonNegativeInt(I.bridgeProtocolVersion)&&(x.bridgeProtocolVersion=I.bridgeProtocolVersion),isNonNegativeInt(I.localSequence)&&(x.localSequence=I.localSequence),Number.isFinite(I.tsLocal)&&(x.tsLocal=I.tsLocal),Number.isFinite(I.tsNormalized)&&(x.tsNormalized=I.tsNormalized),Number.isFinite(I.clockOffsetMs)&&(x.clockOffsetMs=I.clockOffsetMs),Number.isFinite(I.clockUncertaintyMs)&&(x.clockUncertaintyMs=I.clockUncertaintyMs),{...x,...b}}function isNonEmptyString$3(S){return"string"==typeof S&&S.length>0}function isNonNegativeInt(S){return Number.isInteger(S)&&S>=0}const Oe=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/i;function normalizeOrigin(S){if("string"!=typeof S)return null;const b=S.trim();if(!b||"*"===b||"null"===b)return null;if(!Oe.test(b))return null;if(/^http:\/\//i.test(b)&&!function isLocalhostOrigin(S){return/^https?:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/i.test(S)}(b))return null;try{const S=new URL(b);return S.pathname&&"/"!==S.pathname||(S.search||S.hash)?null:(S.protocol+"//"+S.host).toLowerCase()}catch(S){return null}}function parseIframeConfig(S){const disabled=S=>({enabled:!1,role:null,parentOrigin:null,childOrigins:[],reason:S});if(null==S)return disabled("absent");if("object"!=typeof S||Array.isArray(S))return disabled("not_an_object");if(!0!==S.merge)return disabled("merge_not_enabled");const b="childOrigins"in S&&void 0!==S.childOrigins,I="parentOrigin"in S&&void 0!==S.parentOrigin;if(!b&&!I)return disabled("no_origins_declared");let x=[];if(b){const b=function normalizeChildOrigins(S){if(!Array.isArray(S))return null;const b=[],I=new Set;for(const x of S){const S=normalizeOrigin(x);if(!S)return null;I.has(S)||(I.add(S),b.push(S))}return b.length>0?b:null}(S.childOrigins);if(!b)return disabled("invalid_child_origins");x=b}let R=null;if(I){const b=normalizeOrigin(S.parentOrigin);if(!b)return disabled("invalid_parent_origin");R=b}let A=null;if(x.length>0&&R)A="both";else if(x.length>0)A="parent";else{if(!R)return disabled("no_origins_declared");A="child"}return{enabled:!0,role:A,parentOrigin:R,childOrigins:x,reason:null}}const De="undefined"!=typeof TextEncoder?new TextEncoder:null;function getSubtle(){const S="undefined"!=typeof globalThis?globalThis.crypto:void 0;return S&&S.subtle?S.subtle:null}function hex(S){return Array.from(new Uint8Array(S)).map(S=>S.toString(16).padStart(2,"0")).join("")}function fromHex(S){const b=new Uint8Array(S.length/2);for(let I=0;I<b.length;I++)b[I]=parseInt(S.substr(2*I,2),16);return b}async function sha256Hex(S){const b=getSubtle();return hex(await b.digest("SHA-256",De.encode(S)))}async function hmacHex(S,b){const I=getSubtle();return hex(await I.sign("HMAC",S,De.encode(b)))}function macInput(S){return[S.v,S.frameId,S.frameInstanceId,S.navigationGeneration,S.counter,S.projectId,S.sessionId,S.payloadType,S.payloadHash].join("|")}function safeEq(S,b){if("string"!=typeof S||"string"!=typeof b||S.length!==b.length)return!1;let I=0;for(let x=0;x<S.length;x++)I|=S.charCodeAt(x)^b.charCodeAt(x);return 0===I}const Fe=new Set(["rrweb-dom","telemetry"]);const Ne={PROTOCOL_VERSION:1,ALLOWED_PAYLOAD_TYPES:Fe,hex:hex,fromHex:fromHex,sha256Hex:sha256Hex,randHex:function randHex(S){const b=new Uint8Array(S);return globalThis.crypto.getRandomValues(b),hex(b)},importKey:async function importKey(S){return getSubtle().importKey("raw",fromHex(S),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])},hmacHex:hmacHex,macInput:macInput,safeEq:safeEq,sealData:async function sealData(S,b,I){const x=void 0===I.payload?"":JSON.stringify(I.payload),R=await sha256Hex(x),A={v:1,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:I.payloadType,payloadHash:R},_=await hmacHex(S,macInput(A));return{v:1,kind:"data",frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,payloadType:I.payloadType,tag:I.tag,tsLocal:I.tsLocal,tsNormalized:I.tsNormalized,payloadHash:R,hmac:_,payload:I.payload}},validateData:async function validateData(S,b){try{if(!b||b.closed)return{ok:!1,reason:"stale_port"};if(!b.admitted||!b.key)return{ok:!1,reason:"not_admitted"};if(!S||"data"!==S.kind||"number"!=typeof S.counter||"string"!=typeof S.hmac||"string"!=typeof S.payloadHash)return{ok:!1,reason:"bad_shape"};if(S.v!==b.protocolVersion)return{ok:!1,reason:"protocol_mismatch",fatal:!0};if(!Fe.has(S.payloadType))return{ok:!1,reason:"bad_payload_type"};if(S.frameId!==b.frameId)return{ok:!1,reason:"wrong_frame:"+S.frameId};if(S.frameInstanceId!==b.frameInstanceId)return{ok:!1,reason:"stale_frame_instance"};if(S.navigationGeneration!==b.navigationGeneration)return{ok:!1,reason:"stale_generation"};const I=void 0===S.payload?"":JSON.stringify(S.payload);if(I.length>(b.maxBytes||65536))return{ok:!1,reason:"oversize:"+I.length};if(!safeEq(await sha256Hex(I),S.payloadHash))return{ok:!1,reason:"payload_hash_mismatch"};return safeEq(await hmacHex(b.key,macInput({v:S.v,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:S.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:S.payloadType,payloadHash:S.payloadHash})),S.hmac)?S.counter<=b.lastCounter?{ok:!1,reason:"counter_not_monotonic:"+S.counter+"<="+b.lastCounter}:{ok:!0}:{ok:!1,reason:"hmac_mismatch"}}catch(S){return{ok:!1,reason:"validator_error"}}}},Le=Ne.PROTOCOL_VERSION,Pe="__TS_IFRAME_BRIDGE",Be="__TS_IFRAME_BRIDGE_PARENT_REGISTER";class BridgeChild{#f;#m;#y;#v;#o;#S;#w=null;#b=null;#C=null;#k=!1;#I=0;#E=null;#x=[];#M=[];#R=!1;#T=0;#A=1/0;#_=new Map;#O={forwarded:0,droppedUnadmitted:0,droppedBackpressure:0,offersRejected:0};constructor({parentOrigin:S,projectId:b,selfWindow:I,parentWindow:x,logger:R,queueCap:A}={}){this.#f=S,this.#m=b,this.#y=I,this.#v=x||I&&I.parent,this.#o=R||null,this.#S=A||1e3}get isAdmitted(){return this.#k}getStats(){return{admitted:this.#k,queued:this.#x.length+this.#M.length,...this.#O}}install(){if(!this.#y)return!1;const S={forwardRrwebDom:S=>this.forwardRrwebDom(S),forwardTelemetry:(S,b)=>this.forwardTelemetry(S,b),isAdmitted:()=>this.#k,__tsRole:"child"};try{Object.defineProperty(this.#y,Pe,{value:S,configurable:!0,enumerable:!1,writable:!0})}catch(b){this.#y[Pe]=S}this.#E=S=>{try{this.#D(S)}catch(S){this.#F("offer handler failed:",S)}};try{this.#y.addEventListener("message",this.#E)}catch(S){this.#F("addEventListener failed:",S)}return!0}#D(S){const b=S&&S.data;if(!b||"offer"!==b.__tsBridge)return;if(S.origin!==this.#f)return this.#O.offersRejected++,this.#F("offer origin mismatch");if(S.source!==this.#v)return this.#O.offersRejected++,this.#F("offer source mismatch");if(b.v!==Le)return this.#O.offersRejected++,this.#F("offer protocol mismatch");if(this.#m&&b.projectId&&b.projectId!==this.#m)return this.#O.offersRejected++,this.#F("offer project mismatch");const I=S.ports&&S.ports[0];if(!I)return this.#O.offersRejected++,this.#F("offer missing port");this.#N(),this.#b={frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,projectId:b.projectId,sessionId:b.sessionId},this.#w=I,I.onmessage=S=>{try{this.#L(S.data)}catch(S){this.#F("control handler failed:",S)}};try{I.start&&I.start()}catch(S){}try{I.unref&&I.unref()}catch(S){}try{I.postMessage({c:"hello",v:Le})}catch(S){this.#F("hello failed:",S)}}async#L(S){if(S&&this.#w)if("secret"!==S.c){if("pong"===S.c){const b=this.#_.get(S.id);if(!b)return;this.#_.delete(S.id);const I=Date.now()-b.sent,x=I/2,R=S.tParent-(b.sent+x);I<this.#A&&(this.#A=I,this.#T=R)}}else{if("string"!=typeof S.secret||!S.secret)return;try{this.#C=await Ne.importKey(S.secret),this.#k=!0,this.#P(),this.#B()}catch(S){this.#F("secret import failed:",S)}}}#P(){for(let S=0;S<5;S++){const S=Ne.randHex(8),b=Date.now();this.#_.set(S,{sent:b});try{this.#w.postMessage({c:"ping",id:S,t0:b})}catch(S){}}}forwardRrwebDom(S){return this.#z("rrweb-dom",void 0,S)}forwardTelemetry(S,b){return this.#z("telemetry",S,b)}#z(S,b,I){if(!this.#k)return this.#O.droppedUnadmitted++,!1;const x=function priorityForTag(S,b){return"rrweb-dom"===S?"high":"performance_metric"===b||"network_resource"===b?"low":"high"}(S,b),R=Date.now(),A={payloadType:S,tag:b,payload:I,priority:x,tsLocal:R,tsNormalized:this.#A===1/0?R:R+this.#T};if(this.#x.length+this.#M.length>=this.#S){if("low"===x)return this.#O.droppedBackpressure++,!1;this.#M.length>0?(this.#M.shift(),this.#O.droppedBackpressure++):(this.#x.shift(),this.#O.droppedBackpressure++)}return("low"===x?this.#M:this.#x).push(A),this.#B(),!0}async#B(){if(!this.#R&&this.#k&&this.#w&&this.#C){this.#R=!0;try{for(;this.#x.length||this.#M.length;){const S=this.#x.length?this.#x.shift():this.#M.shift(),b=++this.#I;try{const I=await Ne.sealData(this.#C,this.#b,{counter:b,payloadType:S.payloadType,tag:S.tag,tsLocal:S.tsLocal,tsNormalized:S.tsNormalized,payload:S.payload});this.#w.postMessage(I),this.#O.forwarded++}catch(S){this.#F("seal/post failed:",S)}}}finally{this.#R=!1}}}#N(){if(this.#w)try{this.#w.close&&this.#w.close()}catch(S){}this.#w=null,this.#C=null,this.#k=!1,this.#I=0,this.#x.length=0,this.#M.length=0,this.#_.clear(),this.#T=0,this.#A=1/0}shutdown(){try{this.#E&&this.#y.removeEventListener("message",this.#E)}catch(S){}this.#N();try{this.#y[Pe]&&"child"===this.#y[Pe].__tsRole&&delete this.#y[Pe]}catch(S){}this.#E=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:child]",...S)}catch(S){}}}class BridgeParent{#U;#m;#$;#j;#o;#S;#q;#W;#H;#V;#Q;#G=new Map;#K=new WeakMap;#J=0;#X=0;#Y=new WeakSet;#Z=null;#ee=null;#te=!1;#O={admitted:0,closed:0,accepted:0,rejected:0,fatal:0};#se=[];constructor({childOrigins:S,projectId:b,sessionId:I,topWindow:x,logger:R,queueCap:A,maxBytes:_,parentFrameId:D,topFrameId:L,feedRrwebDom:B,feedTelemetry:U}={}){this.#U=S instanceof Set?S:new Set(S||[]),this.#m=b,this.#$=I,this.#j=x||("undefined"!=typeof window?window:void 0),this.#o=R||null,this.#S=A||1e3,this.#q=_||65536,this.#W=D||"ts-top",this.#H=L||"ts-top",this.#V="function"==typeof B?B:()=>{},this.#Q="function"==typeof U?U:()=>{}}get isStarted(){return this.#te}getStats(){return{active:this.#G.size,...this.#O}}getRejectLog(){return this.#se.slice()}start(){if(this.#te)return!0;if(!this.#j)return!1;this.#te=!0;try{this.#j[Be]=S=>this.registerRrwebManager(S)}catch(S){}try{this.#re(this.#j.document),this.#ne(this.#j.document)}catch(S){this.#F("start scan failed:",S)}return!0}registerRrwebManager(S){this.#ee=S||null}#re(S){if(!S||"function"!=typeof S.querySelectorAll)return;let b;try{b=S.querySelectorAll("iframe")}catch(S){return}b.forEach(S=>{this.#ie(S),this.#oe(S)})}#ne(S){try{const b=this.#j.MutationObserver;if(!b)return;this.#Z=new b(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation failed:",S)}}),this.#Z.observe(S.documentElement||S,{childList:!0,subtree:!0})}catch(S){this.#F("observe failed:",S)}}#ae(S){if(S&&1===S.nodeType&&("IFRAME"===S.tagName&&(this.#ie(S),this.#oe(S)),S.querySelectorAll))try{S.querySelectorAll("iframe").forEach(S=>{this.#ie(S),this.#oe(S)})}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#K.get(S);if(!b)return;if(S.isConnected)return;const I=this.#G.get(b);I&&this.#ce(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#ie(S){if(!this.#Y.has(S)){this.#Y.add(S);try{S.addEventListener("load",()=>{try{this.#oe(S)}catch(S){this.#F("load re-admit failed:",S)}})}catch(S){}}}#ue(S){let b=null;try{b=S.src||S.getAttribute&&S.getAttribute("src")}catch(S){b=null}if(!b)return null;try{const S=this.#j.location&&this.#j.location.href||void 0,I=new URL(b,S);return(I.protocol+"//"+I.host).toLowerCase()}catch(S){return null}}#he(S){let b=this.#K.get(S);return b||(b="ts-xframe-"+ ++this.#J,this.#K.set(S,b)),b}#oe(S){const b=this.#ue(S);if(!b||!this.#U.has(b))return;let I=null;try{I=S.contentWindow}catch(S){I=null}if(!I)return;const x=this.#he(S),R=++this.#X,A=this.#G.get(x);let _;A&&this.#ce(A,"superseded");try{_=new this.#j.MessageChannel}catch(S){try{_=new MessageChannel}catch(S){return void this.#F("MessageChannel unavailable:",S)}}const D={frameId:x,frameInstanceId:`${x}-g${R}`,navigationGeneration:R,projectId:this.#m,sessionId:this.#$,expectedOrigin:b,sourceWindow:I,protocolVersion:Le,lastCounter:-1,closed:!1,admitted:!1,key:null,maxBytes:this.#q,port:_.port1,secret:Ne.randHex(32),nonce:Ne.randHex(16),el:S};D.port.onmessage=S=>{this.#de(D,S&&S.data)};try{D.port.start&&D.port.start()}catch(S){}try{D.port.unref&&D.port.unref()}catch(S){}this.#G.set(x,D);const L={__tsBridge:"offer",v:Le,projectId:this.#m,sessionId:this.#$,frameId:x,parentFrameId:this.#W,topFrameId:this.#H,frameInstanceId:D.frameInstanceId,navigationGeneration:R};try{I.postMessage(L,b,[_.port2]),this.#O.admitted++}catch(S){this.#F("offer post failed:",S),this.#ce(D,"offer_failed")}}async#de(S,b){if(b&&!S.closed)if("hello"!==b.c)if("ping"!==b.c){if("data"===b.kind){const I=await Ne.validateData(b,S);return I.ok?(S.lastCounter=b.counter,this.#O.accepted++,void("rrweb-dom"===b.payloadType?this.#ge(S,b.payload):"telemetry"===b.payloadType&&this.#pe(S,b))):(this.#O.rejected++,this.#fe(S.frameId,I.reason),void(I.fatal&&(this.#O.fatal++,this.#ce(S,"protocol_mismatch"))))}this.#O.rejected++,this.#fe(S.frameId,"unknown_message")}else try{S.port.postMessage({c:"pong",id:b.id,t0:b.t0,tParent:Date.now()})}catch(S){}else try{S.key=await Ne.importKey(S.secret),S.admitted=!0,S.port.postMessage({c:"secret",secret:S.secret,nonce:S.nonce}),S.secret=null}catch(S){this.#F("secret delivery failed:",S)}}#ge(S,b){try{const I={data:b,origin:S.expectedOrigin,source:S.sourceWindow};this.#ee&&"function"==typeof this.#ee.handleMessage&&this.#ee.handleMessage(I),this.#V(S,b,I)}catch(S){this.#F("deliverDom failed:",S)}}#pe(S,b){try{this.#Q(S,b)}catch(S){this.#F("deliverTelemetry failed:",S)}}#ce(S,b){S.closed=!0;try{S.port&&S.port.close&&S.port.close()}catch(S){}S.port=null,S.key=null,S.sourceWindow=null,S.el=null,this.#G.get(S.frameId)===S&&this.#G.delete(S.frameId),this.#O.closed++}shutdown(){for(const S of Array.from(this.#G.values()))this.#ce(S,"shutdown");this.#G.clear();try{this.#Z&&this.#Z.disconnect()}catch(S){}this.#Z=null;try{this.#j[Be]&&delete this.#j[Be]}catch(S){}this.#ee=null,this.#te=!1}#fe(S,b){this.#se.push({frameId:S,reason:b,t:Date.now()}),this.#se.length>200&&this.#se.shift()}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:parent]",...S)}catch(S){}}}class CrossOriginIframeBridge{#me;#ye;#m;#$;#o;#j;#ve=null;#Se=null;constructor({config:S,core:b,projectId:I,sessionId:x,logger:R,topWindow:A}={}){this.#me=S,this.#ye=b,this.#m=I,this.#$=x,this.#o=R||null,this.#j=A||("undefined"!=typeof window?window:void 0)}get parent(){return this.#ve}get child(){return this.#Se}get isChildMode(){return!!this.#Se}start(){if(!this.#me||!this.#me.enabled)return!1;const S=this.#me.role;try{return"child"!==S&&"both"!==S||(this.#Se=new BridgeChild({parentOrigin:this.#me.parentOrigin,projectId:this.#m,selfWindow:this.#j,parentWindow:this.#j&&this.#j.parent,logger:this.#o}),this.#Se.install()),"parent"!==S&&"both"!==S||(this.#ve=new BridgeParent({childOrigins:new Set(this.#me.childOrigins),projectId:this.#m,sessionId:this.#$,topWindow:this.#j,logger:this.#o,feedTelemetry:(S,b)=>this.#Q(S,b)}),this.#ve.start()),!0}catch(S){return this.#F("bridge start failed (fail-closed):",S),!1}}#Q(S,b){const I=b.payload&&"object"==typeof b.payload?b.payload:{},x=Object.assign({},I,{frameId:S.frameId,parentFrameId:"ts-top",topFrameId:"ts-top",frameInstanceId:S.frameInstanceId,frameOrigin:S.expectedOrigin,captureRealm:"iframe",privacyStatus:"unknown",bridgeProtocolVersion:Le,localSequence:b.counter,tsLocal:b.tsLocal,tsNormalized:b.tsNormalized});try{this.#ye&&this.#ye.addSessionCustomEvent(b.tag,x)}catch(S){this.#F("writer feed failed:",S)}}shutdown(){try{this.#Se&&this.#Se.shutdown()}catch(S){}try{this.#ve&&this.#ve.shutdown()}catch(S){}this.#Se=null,this.#ve=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge]",...S)}catch(S){}}}function mapInternalEndReason(S){switch(S){case"max_inactivity":case"inactivity":return"inactivity";case"max_duration":case"maxDuration":return"maxDuration";case"away_rule":case"allTabsClosed":return"allTabsClosed";case"manual":return"manual";default:return null}}function detectDeviceType$1(S){const b=(S&&"string"==typeof S.userAgent?S.userAgent:"")||("undefined"!=typeof navigator&&navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"");return b?/iPad|Tablet|PlayBook|Silk/i.test(b)||/Android/i.test(b)&&!/Mobile/i.test(b)?"tablet":/Mobi|iPhone|iPod|Android/i.test(b)?"mobile":"desktop":"desktop"}function buildDeviceField(){const S="undefined"!=typeof navigator?navigator:{},b="undefined"!=typeof window?window:{},I=b.screen||{};let x="UTC";try{x=Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch(S){}return{type:detectDeviceType$1(S),userAgent:"string"==typeof S.userAgent?S.userAgent:"",platform:"string"==typeof S.platform?S.platform:"",language:"string"==typeof S.language?S.language:"",timezone:x,viewport:{width:"number"==typeof b.innerWidth?b.innerWidth:0,height:"number"==typeof b.innerHeight?b.innerHeight:0},screen:{width:"number"==typeof I.width?I.width:0,height:"number"==typeof I.height?I.height:0,colorDepth:"number"==typeof I.colorDepth?I.colorDepth:0}}}function isNonEmptyString$2(S){return"string"==typeof S&&S.length>0}class SessionLifecycleEmitter{#we=!1;#be=!1;#Ce;#ke;#Ie;#Ee;#xe;#Me;constructor(S){if(!S||"object"!=typeof S)throw new Error("SessionLifecycleEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("SessionLifecycleEmitter: addCustomEvent callback is required");if("function"!=typeof S.getContext)throw new Error("SessionLifecycleEmitter: getContext callback is required");if("function"!=typeof S.readGuard||"function"!=typeof S.writeGuard)throw new Error("SessionLifecycleEmitter: readGuard/writeGuard callbacks are required");this.#ke=S.addCustomEvent,this.#Me=S.getContext,this.#Ie=S.readGuard,this.#Ee=S.writeGuard,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitStart(S={}){if(this.#we)return!1;let b=null;try{b=this.#Ie()}catch(S){b=null}if(b&&!0===b.sessionStartEmitted)return this.#we=!0,!1;b||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const I=this.#Me(),x="undefined"!=typeof window?window:{},R="undefined"!=typeof document?document:{},A=isNonEmptyString$2(S.landingUrl)?S.landingUrl:"string"==typeof x.location?.href?x.location.href:"";if(!isNonEmptyString$2(A))return this.#xe("[SDK lifecycle] session_start skipped — landingUrl unavailable"),!1;const _={device:buildDeviceField(),landingUrl:A},D=void 0!==S.referrer?S.referrer:"string"==typeof R.referrer?R.referrer:"";isNonEmptyString$2(D)&&(_.referrer=D);const L=void 0!==S.landingTitle?S.landingTitle:"string"==typeof R.title?R.title:"";let B;isNonEmptyString$2(L)&&(_.landingTitle=L),function isPlainObjectWithKeys(S){if(!S||"object"!=typeof S)return!1;for(const b in S)return!0;return!1}(S.userTraits)&&(_.userTraits=S.userTraits);try{B=this.#Ce("session_start",_,I)}catch(S){return this.#xe("[SDK lifecycle] session_start envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_start",B)}catch(S){return this.#xe("[SDK lifecycle] session_start addCustomEvent failed:",S),!1}this.#we=!0;try{this.#Ee({sessionStartEmitted:!0,startedAt:"number"==typeof B.timestamp?B.timestamp:Date.now()})}catch(S){}return!0}emitEnd(S){if(!S||"object"!=typeof S)return!1;if(this.#be)return!1;const b=mapInternalEndReason(S.reason);if(!b)return this.#xe("[SDK lifecycle] session_end refused for non-logical reason:",S.reason),!1;let I=null;try{I=this.#Ie()}catch(S){I=null}if(I&&!0===I.sessionEndEmitted)return this.#be=!0,!1;I||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const x=this.#Me(),R=Date.now(),A=I&&"number"==typeof I.startedAt?I.startedAt:"number"==typeof x.sessionStartTime?x.sessionStartTime:R,_={endedAt:R,durationMs:Math.max(0,R-A),reason:b};let D;Number.isFinite(S.totalChunks)&&S.totalChunks>=0&&(_.totalChunks=Math.trunc(S.totalChunks)),Number.isFinite(S.totalEvents)&&S.totalEvents>=0&&(_.totalEvents=Math.trunc(S.totalEvents));try{D=this.#Ce("session_end",_,x)}catch(S){return this.#xe("[SDK lifecycle] session_end envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_end",D)}catch(S){return this.#xe("[SDK lifecycle] session_end addCustomEvent failed:",S),!1}this.#be=!0;try{this.#Ee({sessionEndEmitted:!0,endedAt:R,endReason:b})}catch(S){}return!0}get startEmitted(){return this.#we}get endEmitted(){return this.#be}}function isNonEmptyString$1(S){return"string"==typeof S&&S.length>0}function urlParts(S){if("string"!=typeof S||0===S.length)return{path:null,query:null,hash:null};try{const b=new URL(S);return{path:b.pathname,query:b.search||null,hash:b.hash||null}}catch(S){return{path:null,query:null,hash:null}}}class PageviewManager{#Re;#Te=!1;#Ae=null;#ke;#_e;#Ce;#xe;constructor(S){if(!S||"object"!=typeof S)throw new Error("PageviewManager: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("PageviewManager: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("PageviewManager: getBaseContext callback is required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{},this.#Re=uuidv4()}getCurrentPageviewId(){return this.#Re}emitInitialPageView(S={}){if(this.#Te)return!1;const b="undefined"!=typeof window?window:{},I="undefined"!=typeof document?document:{},x="string"==typeof b.location?.href?b.location.href:"";if(!isNonEmptyString$1(x))return this.#xe("[SDK pageview] initial page_view skipped — url unavailable"),!1;const R=urlParts(x);if(!isNonEmptyString$1(R.path))return this.#xe("[SDK pageview] initial page_view skipped — could not derive path"),!1;const A={url:x,path:R.path,isInitial:!0!==S.isResumed};isNonEmptyString$1(R.query)&&(A.query=R.query),isNonEmptyString$1(R.hash)&&(A.hash=R.hash),isNonEmptyString$1(I.title)&&(A.title=I.title),isNonEmptyString$1(I.referrer)&&(A.referrer=I.referrer);const _=this.#Oe(this.#Re);let D;try{D=this.#Ce("page_view",A,_)}catch(S){return this.#xe("[SDK pageview] initial page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",D)}catch(S){return this.#xe("[SDK pageview] initial page_view addCustomEvent failed:",S),!1}return this.#Te=!0,this.#Ae=x,!0}recordNavigation(S,b,I){if(!isNonEmptyString$1(I))return this.#xe("[SDK pageview] navigation skipped — toUrl unavailable"),!1;if(null!==this.#Ae&&this.#Ae===I)return!1;if(!["pushState","replaceState","popstate","hashchange"].includes(S))return this.#xe("[SDK pageview] navigation skipped — unknown method:",S),!1;const x=isNonEmptyString$1(b)?b:I,R=urlParts(x),A=urlParts(I);if(!isNonEmptyString$1(A.path))return this.#xe("[SDK pageview] navigation skipped — could not derive toPath"),!1;const _=this.#Re,D=uuidv4(),L={fromUrl:x,toUrl:I,method:S,nextPageviewId:D};let B;isNonEmptyString$1(R.path)&&(L.fromPath=R.path),isNonEmptyString$1(A.path)&&(L.toPath=A.path);try{B=this.#Ce("route_change",L,this.#Oe(_))}catch(S){return this.#xe("[SDK pageview] route_change envelope wrap failed:",S),!1}try{this.#ke("tracescout.route_change",B)}catch(S){return this.#xe("[SDK pageview] route_change addCustomEvent failed:",S),!1}this.#Re=D,this.#Ae=I;const U="undefined"!=typeof document?document:{},$={url:I,path:A.path,isInitial:!1};let j;isNonEmptyString$1(A.query)&&($.query=A.query),isNonEmptyString$1(A.hash)&&($.hash=A.hash),isNonEmptyString$1(U.title)&&($.title=U.title),isNonEmptyString$1(x)&&($.referrer=x);try{j=this.#Ce("page_view",$,this.#Oe(D))}catch(S){return this.#xe("[SDK pageview] post-nav page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",j)}catch(S){return this.#xe("[SDK pageview] post-nav page_view addCustomEvent failed:",S),!1}return!0}#Oe(S){const b=this.#_e()||{};return Object.assign({},b,{pageviewId:S})}get initialEmitted(){return this.#Te}get lastUrl(){return this.#Ae}}function normalizeRating(S){if("string"!=typeof S)return null;switch(S){case"good":return"good";case"needs-improvement":case"needsImprovement":return"needs-improvement";case"poor":return"poor";default:return null}}const ze=new Set(["navigate","reload","back-forward","prerender","back-forward-cache","restore"]);function isNonEmptyString(S){return"string"==typeof S&&S.length>0}class WebVitalsEmitter{#De;#Fe;#Ne=new Set;#ke;#_e;#Ce;#xe;constructor(S){if(!S||"object"!=typeof S)throw new Error("WebVitalsEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("WebVitalsEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("WebVitalsEmitter: getBaseContext callback is required");if(!isNonEmptyString(S.initialPageviewId))throw new Error("WebVitalsEmitter: initialPageviewId is required");if(!isNonEmptyString(S.initialUrl))throw new Error("WebVitalsEmitter: initialUrl is required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#De=S.initialPageviewId,this.#Fe=S.initialUrl,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emit(S,b){if(!b||"object"!=typeof b)return!1;const I=function normalizeMetricType(S){switch((S||"").toString().toLowerCase()){case"lcp":return"LCP";case"fid":return"FID";case"cls":return"CLS";case"inp":return"INP";case"ttfb":return"TTFB";case"fcp":return"FCP";default:return null}}(S);if(!I)return this.#xe("[SDK web-vitals] emit refused — unknown metric type:",S),!1;if(this.#Ne.has(I))return!1;if(!function isPositiveFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)&&S>=0}(b.value))return this.#xe("[SDK web-vitals] emit refused — invalid value for",I,b.value),!1;const x=normalizeRating(b.libRating)??normalizeRating(b.rating);if(!x)return this.#xe("[SDK web-vitals] emit refused — invalid rating for",I,b.libRating,b.rating),!1;const R={metric:I,value:b.value,unit:(A=I,"CLS"===A?"score":"ms"),rating:x};var A;"string"==typeof b.navigationType&&ze.has(b.navigationType)&&(R.navigationType=b.navigationType);const _=this.#_e()||{},D=Object.assign({},_,{pageviewId:this.#De,url:this.#Fe});let L;try{L=this.#Ce("performance_metric",R,D)}catch(S){return this.#xe("[SDK web-vitals] envelope wrap failed:",S),!1}try{this.#ke("tracescout.performance_metric",L)}catch(S){return this.#xe("[SDK web-vitals] addCustomEvent failed:",S),!1}return this.#Ne.add(I),!0}get emittedMetrics(){return new Set(this.#Ne)}get initialPageviewId(){return this.#De}get initialUrl(){return this.#Fe}}const Ue=/^[a-zA-Z][a-zA-Z0-9_.-]*$/,$e=["_ts_","internal","system"],je=["password","token","authorization","cookie","ssn","creditcard","secret","apikey"],qe=new Set(["__proto__","constructor","prototype"]);function isValidUserId(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isValidEmail(S){if("string"!=typeof S)return!1;if(0===S.length||S.length>320)return!1;if(/\s/.test(S))return!1;const b=S.indexOf("@");if(b<1||b!==S.lastIndexOf("@"))return!1;const I=S.slice(0,b),x=S.slice(b+1);if(0===I.length||x.length<3)return!1;if(I.startsWith(".")||I.endsWith("."))return!1;if(!x.includes("."))return!1;if(x.startsWith(".")||x.endsWith("."))return!1;if(x.includes("..")||I.includes(".."))return!1;const R=x.lastIndexOf("."),A=x.slice(R+1);return!(A.length<2||!/^[a-zA-Z]+$/.test(A))}function isValidUserName(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)}function sanitizeScalarBag(S,b){const I={};if(!S||"object"!=typeof S||Array.isArray(S))return I;const x="function"==typeof b?b:()=>{};let R=0;for(const b of Object.keys(S)){if(R>=50){x("too-many-keys",b);continue}if("string"!=typeof b||0===b.length){x("invalid-key",String(b));continue}if(b.length>64){x("key-too-long",b);continue}if(qe.has(b)){x("pollution-key",b);continue}if($e.some(S=>b.startsWith(S))){x("reserved-key",b);continue}const A=b.toLowerCase();if(je.some(S=>A.includes(S))){x("sensitive-key",b);continue}const _=S[b];if(null===_){I[b]=null,R++;continue}const D=typeof _;if("string"!==D)if("number"!==D)"boolean"!==D?x(`invalid-type:${Array.isArray(_)?"array":D}`,b):(I[b]=_,R++);else{if(!isFiniteNumber(_)){x("non-finite-number",b);continue}I[b]=_,R++}else{if(_.length>1024){x("string-too-long",b);continue}I[b]=_,R++}}return I}class TrackIdentifyEmitter{#ke;#_e;#Ce;#xe;constructor(S){if(!S||"object"!=typeof S)throw new Error("TrackIdentifyEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("TrackIdentifyEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("TrackIdentifyEmitter: getBaseContext callback is required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitCustomEvent(S,b){if(!function isValidEventName(S){return"string"==typeof S&&S.length>=1&&S.length<=128&&Ue.test(S)}(S))return this.#xe("[SDK track] emit refused — invalid event name:",S),!1;const I=[],x=sanitizeScalarBag(b,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#xe("[SDK track] properties keys dropped:",I);const R={name:S};Object.keys(x).length>0&&(R.properties=x);const A=this.#_e()||{};let _;try{_=this.#Ce("custom_event",R,A)}catch(S){return this.#xe("[SDK track] envelope wrap failed:",S),!1}try{this.#ke("tracescout.custom_event",_)}catch(S){return this.#xe("[SDK track] addCustomEvent failed:",S),!1}return!0}emitUserIdentified(S){if(!S||"object"!=typeof S)return!1;if(!isValidUserId(S.userId))return this.#xe("[SDK identify] emit refused — invalid userId"),!1;const b="set"===S.mode?"set":"merge",I=[],x=sanitizeScalarBag(S.traits,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#xe("[SDK identify] traits keys dropped:",I);const R={mode:b};Object.keys(x).length>0&&(R.traits=x);const A=this.#_e()||{},_=Object.assign({},A,{userId:S.userId});let D;isValidEmail(S.userEmail)&&(_.userEmail=S.userEmail),isValidUserName(S.userName)&&(_.userName=S.userName);try{D=this.#Ce("user_identified",R,_)}catch(S){return this.#xe("[SDK identify] envelope wrap failed:",S),!1}try{this.#ke("tracescout.user_identified",D)}catch(S){return this.#xe("[SDK identify] addCustomEvent failed:",S),!1}return!0}}class SessionRecordingFeature{#o=null;#Le=null;#Pe=null;#a=null;#Be=null;#ze=null;#Ue=null;#$e=null;#je=!1;#qe=!1;#We=null;#He=0;#Ve=null;#Qe=null;#Ge=null;#Ke=null;constructor({logger:S,sdkContext:b,config:I,options:x}){this.#o=S,this.#Le=b,this.#Pe=I,this.#a=x}async initialize(S,b){try{console.log("[TraceScout] Loading recording module..."),this.#Be=await Promise.resolve().then(function(){return Wc});const{SessionStorage:I,UploadQueue:x,Recorder:R}=this.#Be;return this.#Ue=new I({storageKey:"__tracescout_sessions_v2__",maxStorageSize:2097152,maxSessions:5,logger:this.#o}),console.log("[TraceScout] ✓ Session storage initialized"),!0===this.#a.childMode?(this.#$e=null,console.log("[TraceScout] ⏭️ Upload queue SUPPRESSED (cross-origin child — parent owns the session)")):(this.#$e=this.#Je(x,S,b),console.log("[TraceScout] ✓ Upload queue initialized"),console.log(` Endpoint: /api/projects/${this.#Le.projectId}/sessions/${this.#Le.sessionId}/chunks`)),this.#ze=this.#Xe(R,S),console.log("[TraceScout] ✓ Session recorder initialized"),await this.#ze.start(),console.log("[TraceScout] ✓ Session recording started"),this.#a.onSessionStart&&this.#a.onSessionStart(this.#Le.sessionId),this.#je=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize session recording:",S),!1}}#Je(S,b,I){return new S({sdkContext:this.#Le,baseUrl:I?.baseUrl,batchSize:b.telemetry?.batchSize||5,maxRetries:3,retryDelay:2e3,enableCompression:!1!==b.telemetry?.enableCompression,enableOfflineQueue:!0,logger:this.#o,onUploadSuccess:(S,b)=>{this.#o?.log(`✅ Chunk ${S.chunkIndex} uploaded successfully`),this.#a.onChunkUploaded&&this.#a.onChunkUploaded(S,b)},onUploadError:(S,b)=>{if(b&&"QUOTA_EXCEEDED"===b.code)return console.error("[TraceScout] ⛔ QUOTA EXCEEDED - Stopping recording"),void this.#Ge?.(b);this.#o?.error(`❌ Chunk ${S?.chunkIndex} upload failed:`,b?.message)},onNetworkChange:S=>{this.#o?.log("Network status: "+(S?"online":"offline"))}})}#Xe(S,b){const I=b.features.sessionRecording;return new S({sdkContext:this.#Le,serverSettings:I,emit:S=>this.#Ye(S),onChunk:S=>{this.#Ze(S),this.#$e&&this.#$e.enqueue(S,"normal")},onSessionEnd:S=>{console.log(`[TraceScout] 🛑 Session ended: ${S.reason}`),console.log(` Session ID: ${S.sessionId}`),console.log(` Duration: ${Math.round(S.duration/6e4)}min`),console.log(` Total events: ${S.totalEvents}`),this.#qe=!0,this.#We=S.reason,this.#a.onSessionEnd&&this.#a.onSessionEnd(S),this.#Qe?.(S)},chunkDuration:I.chunkDuration||3e4,maxChunkSize:I.maxChunkSize||5e5,blockClass:I.blockClass||"ts-block",ignoreClass:I.ignoreClass||"ts-ignore",maskTextClass:I.maskTextClass||"ts-mask",maskAllInputs:I.maskAllInputs||!1,recordCanvas:I.recordCanvas||!1,collectFonts:I.collectFonts||!1,inactivityTimeout:I.inactivityTimeout||3e5,maxInactivityDuration:I.maxInactivityDuration||18e5,maxSessionDuration:I.maxSessionDuration||36e5,enableInactivityDetection:!0,enableSampling:I.enableSampling||!1,enableDeduplication:I.enableDeduplication||!1,mousemoveSampling:I.mousemoveSampling||1,scrollSampling:I.scrollSampling||1,enableStorage:!0,enableCompression:!0,debug:this.#Pe.debug||!1,recordCrossOriginIframes:!0===this.#Pe.recordCrossOriginIframes,onSpaNavigation:(S,b,I)=>{"function"==typeof this.#Ke&&this.#Ke(S,b,I)}})}#Ye(S){}#Ze(S){const b=Date.now();if(b-this.#He>=1e4){const I="number"==typeof S.size?S.size:S.compressedSize||0;this.#o?.log(`Session chunk created: ${S.chunkId} (${S.eventCount} events, ${I} bytes)`),this.#He=b}this.#Ue&&this.#Ue.storeChunk(S.sessionId,S),this.#Ve?.(S)}setCallbacks({onChunkCreated:S,onSessionEnd:b,onQuotaExceeded:I,onSpaNavigation:x}){this.#Ve=S,this.#Qe=b,this.#Ge=I,this.#Ke=x||null}get isAvailable(){return this.#je&&null!=this.#ze}get isRecording(){return this.#ze?.isRecording||!1}get sessionEnded(){return this.#qe}get sessionEndReason(){return this.#We}get recorder(){return this.#ze}get uploadQueue(){return this.#$e}get sessionStorage(){return this.#Ue}async start(S={}){if(!this.#ze)return this.#o?.warn("Session recording not enabled"),null;try{const b=this.#ze.start(S),I=this.#ze.getSessionId();return this.#o?.info("Session recording started:",I),{sessionId:I,startTime:Date.now(),status:"recording",stop:b}}catch(S){return this.#o?.error("Failed to start session recording:",S),null}}stop(){if(!this.#ze)return this.#o?.warn("Session recording not enabled"),null;try{this.#ze.stop();const S=this.#ze.getEvents(),b=this.#ze.getSessionId();return this.#o?.info("Session recording stopped:",b),{sessionId:b,startTime:this.#ze.recordingStartTime,duration:Date.now()-this.#ze.recordingStartTime,totalEvents:S.length,events:S,status:"stopped"}}catch(S){return this.#o?.error("Failed to stop session recording:",S),null}}addCustomEvent(S,b){if(!this.#ze)return!1;try{return this.#ze.addCustomEvent(S,b)}catch(S){return!1}}getStatus(){return this.#ze?{available:!0,isRecording:this.#ze.isRecording,sessionId:this.#ze.getSessionId(),eventCount:this.#ze.getEvents().length,startTime:this.#ze.recordingStartTime}:{available:!1,error:"Session recording not enabled"}}getEvents(){return this.#ze?.getEvents()||[]}getChunks(){return this.#ze?.getChunks?.()||[]}getMetadata(){return this.#ze?.getMetadata?.()||{}}getSessionId(){return this.#ze?.getSessionId()}updateSessionId(S){this.#ze&&(this.#ze.sessionId=S),this.#qe=!1,this.#We=null}updateUploadEndpoint(S){this.#$e&&(this.#$e.config.endpoint=S)}destroy(){if(this.#ze){try{this.#ze.stop()}catch(S){}this.#ze=null}this.#Ue=null,this.#$e=null,this.#Be=null,this.#je=!1}}class LogManager{#o=null;#Pe=null;#Le=null;#et=[];#tt={};#st="debug";#rt=1e3;#nt=new Map;#it=5e3;#ot=null;#at=!0;static LOG_LEVELS={debug:0,info:1,warn:2,error:3,fatal:4};constructor(S={},b=null,I=null){this.#Pe=S,this.#Le=b,this.#ot=I,this.#o=new Logger("[LogManager]",S.debug),this.#at=!1!==S.logs?.enabled,this.#st=S.logs?.minLevel||"debug",this.#rt=S.logs?.maxBufferSize||1e3,this.#o.log("LogManager initialized",{enabled:this.#at,minLevel:this.#st,maxBufferSize:this.#rt})}log(S,b,I={}){if(!this.#at)return!1;if(!this.#lt(S))return!1;try{const x=this.#ct(S,b,I);return!this.#ut(x)&&(this.#et.push(x),this.#et.length>=this.#rt&&this.flush(),"error"!==S&&"fatal"!==S||setTimeout(()=>this.flush(),0),!0)}catch(S){return this.#o.error("Failed to log message:",S),!1}}debug(S,b={}){return this.log("debug",S,b)}info(S,b={}){return this.log("info",S,b)}warn(S,b={}){return this.log("warn",S,b)}error(S,b={}){return this.log("error",S,b)}fatal(S,b={}){return this.log("fatal",S,b)}attachContext(S,b){"string"==typeof S?this.#tt[S]=b:"object"==typeof S&&Object.assign(this.#tt,S),this.#o.log("Context attached:",S)}clearContext(){this.#tt={},this.#o.log("Context cleared")}setLogLevel(S){LogManager.LOG_LEVELS.hasOwnProperty(S)?(this.#st=S,this.#o.log("Log level set to:",S)):this.#o.warn("Invalid log level:",S)}getLogLevel(){return this.#st}setEnabled(S){this.#at=S,this.#o.log("Logging",S?"enabled":"disabled")}isEnabled(){return this.#at}flush(){if(0===this.#et.length)return[];const S=[...this.#et];if(this.#et=[],this.#o.log(`Flushing ${S.length} logs`),this.#ot)try{this.#ot(S)}catch(S){this.#o.error("Error in flush callback:",S)}return S}getQueueSize(){return this.#et.length}getQueue(){return[...this.#et]}clearQueue(){const S=this.#et.length;this.#et=[],this.#o.log(`Cleared ${S} logs from queue`)}getStats(){const S={queueSize:this.#et.length,byLevel:{},enabled:this.#at,minLevel:this.#st};return this.#et.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}#ct(S,b,I={}){const x=Date.now(),R=`log_${x}_${generateId()}`,A={source:"undefined"!=typeof process&&process.versions&&process.versions.node?"server":"client",timestamp:x,...this.#ht(),...this.#tt};this.#Le&&(A.sessionId=this.#Le.sessionId,A.projectId=this.#Le.projectId,A.environment=this.#Le.environment,this.#Le.userId&&(A.userId=this.#Le.userId));const _=this.#dt(I);return"error"!==S&&"fatal"!==S||!1===this.#Pe.logs?.attachStackTrace||_.stack||(_.stack=this.#gt()),{logId:R,timestamp:x,level:S,message:String(b),metadata:_,context:A}}#ht(){const S={};return"undefined"!=typeof window?(S.url=window.location?.href,S.userAgent=navigator?.userAgent,S.platform=navigator?.platform):"undefined"!=typeof process&&(S.platform=process.platform,S.nodeVersion=process.version,S.pid=process.pid),S}#dt(S){if(!S||"object"!=typeof S)return{};const b={};for(const[I,x]of Object.entries(S))if(x instanceof Error)b[I]={name:x.name,message:x.message,stack:x.stack,...x};else if("object"==typeof x&&null!==x)try{JSON.stringify(x),b[I]=x}catch(S){b[I]="[Circular Reference]"}else b[I]=x;return b}#gt(){try{const S=(new Error).stack||"";return S.split("\n").slice(3).join("\n")}catch(S){return"Stack trace unavailable"}}#lt(S){const b=LogManager.LOG_LEVELS[S],I=LogManager.LOG_LEVELS[this.#st];return void 0===b||void 0===I||b>=I}#ut(S){const b=`${S.level}:${S.message}`,I=Date.now(),x=this.#nt.get(b);return!!(x&&I-x<this.#it)||(this.#nt.set(b,I),this.#nt.size>1e3&&this.#pt(),!1)}#pt(){const S=Date.now();for(const[b,I]of this.#nt.entries())S-I>this.#it&&this.#nt.delete(b)}destroy(){this.flush(),this.#et=[],this.#tt={},this.#nt.clear(),this.#ot=null,this.#o.log("LogManager destroyed")}}function newOperationId(){return`ts-${uuidv4()}`}class LogBuffer{#o=null;#Pe=null;#Le=null;#ft=[];#mt=null;#yt=5e3;#vt=100;#St=!1;#wt=null;#bt=!0;#Ct=0;static MAX_CONSECUTIVE_FAILURES=5;#kt=null;constructor(S={},b=null,I=null){this.#Pe=S,this.#Le=b,this.#wt=I,this.#o=new Logger("[LogBuffer]",S.debug),this.#yt=S.logs?.flushInterval||5e3,this.#vt=S.logs?.maxBatchSize||100,this.#bt=!1!==S.telemetry?.enableCompression,this.#It(),this.#o.log("LogBuffer initialized",{flushInterval:this.#yt,maxBatchSize:this.#vt,compressionEnabled:this.#bt})}add(S){Array.isArray(S)||(S=[S]),this.#ft.push(...S),this.#o.log(`Added ${S.length} logs to buffer. Buffer size: ${this.#ft.length}`),this.#ft.length>=this.#vt&&(this.#o.log("Buffer size threshold reached, flushing..."),this.flush())}async flush(){if(this.#St)return this.#o.log("Already sending, skipping flush"),{success:!1,reason:"Already sending"};if(null===this.#kt&&0===this.#ft.length)return{success:!0,sent:0};if(null===this.#kt){const S=this.#ft.splice(0,this.#vt);if(0===S.length)return{success:!0,sent:0};this.#kt={operationId:newOperationId(),logs:S}}const S=this.#kt.logs;this.#o.log(`Flushing ${S.length} logs (operation ${this.#kt.operationId})`);try{this.#St=!0;const b=this.#Et(S,this.#kt.operationId);let I=b,x=!1;if(this.#bt&&"function"==typeof this.#xt)try{I=await this.#xt(b),x=!0,this.#o.log(`Compressed batch from ${JSON.stringify(b).length} to ${I.length} bytes`)}catch(S){this.#o.warn("Compression failed, sending uncompressed:",S)}return this.#wt&&await this.#wt(I,x),this.#o.log(`Successfully sent batch with ${S.length} logs`),this.#Ct=0,this.#kt=null,{success:!0,sent:S.length}}catch(b){return this.#Ct++,this.#o.error(`Failed to flush logs (consecutive failures: ${this.#Ct}):`,b),this.#Ct>LogBuffer.MAX_CONSECUTIVE_FAILURES?(this.#o.warn(`Dropping batch of ${S.length} logs after ${this.#Ct} consecutive failures`),this.#kt=null,{success:!1,dropped:S.length,error:b.message}):{success:!1,error:b.message}}finally{this.#St=!1}}getConsecutiveFailures(){return this.#Ct}async forceFlush(){this.#Mt();try{await this.flush()}finally{this.#It()}}getBufferSize(){return this.#ft.length}getStats(){const S={bufferSize:this.#ft.length,isSending:this.#St,flushInterval:this.#yt,maxBatchSize:this.#vt,byLevel:{}};return this.#ft.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}clear(){const S=this.#ft.length;this.#ft=[],this.#o.log(`Cleared ${S} logs from buffer`)}destroy(){this.#Mt(),this.flush().catch(S=>{this.#o.error("Error during final flush:",S)}),this.clear(),this.#o.log("LogBuffer destroyed")}#Et(S,b){const I=b||newOperationId(),x=Date.now();return{batchId:I,producer:ye,timestamp:x,projectId:this.#Le?.projectId,count:S.length,logs:S}}async#xt(S){const b=JSON.stringify(S);if("undefined"!=typeof CompressionStream)try{const S=new Blob([b]).stream().pipeThrough(new CompressionStream("gzip")),I=await new Response(S).blob(),x=await I.arrayBuffer();return Array.from(new Uint8Array(x))}catch(S){throw this.#o.warn("Browser compression failed:",S),S}throw new Error("Compression not available - CompressionStream not supported")}#It(){this.#mt||(this.#mt=setInterval(()=>{this.#ft.length>0&&this.flush().catch(S=>{this.#o.error("Auto-flush failed:",S)})},this.#yt),this.#o.log("Auto-flush started"))}#Mt(){this.#mt&&(clearInterval(this.#mt),this.#mt=null,this.#o.log("Auto-flush stopped"))}}class LoggingFeature{#o=null;#Le=null;#Pe=null;#Rt=null;#Tt=null;#je=!1;constructor({logger:S,sdkContext:b,config:I}){this.#o=S,this.#Le=b,this.#Pe=I}initialize(S){console.log("[TraceScout] Initializing logging system...");try{return this.#Rt=new LogManager(this.#Pe,this.#Le,S=>{this.#Tt&&this.#Tt.add(S)}),this.#Tt=new LogBuffer(this.#Pe,this.#Le,async(S,b)=>this.#At(S,b)),console.log("[TraceScout] ✓ Logging system initialized"),this.#je=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize logging:",S),!1}}configure(S){try{const b={enabled:S.debug||!1,level:S.logLevel||"info",showTimestamps:!1!==S.showLogTimestamps,showServiceIcons:!1!==S.showServiceIcons};S.logging&&"object"==typeof S.logging&&(b.services=S.logging),U.configure(b),S.enabledLogServices&&Array.isArray(S.enabledLogServices)?U.enableServices(S.enabledLogServices,S.logLevel||"info"):S.debug&&U.enableServices(["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager"],S.logLevel||"info"),this.#o?.log("Logging system configured successfully")}catch(S){this.#o?.error("Failed to configure logging system:",S)}}async#At(S,b){if(!this.#Le)throw new Error("SDK not initialized");const I=this.#Le.projectId,x=`${resolveApiBaseUrl(this.#Pe)}/api/projects/${I}/logs/batch`;try{const I={};b?(I["Content-Type"]="application/octet-stream",I["Content-Encoding"]="gzip"):I["Content-Type"]="application/json";const R=await fetch(x,{method:"POST",headers:I,body:b?new Blob([new Uint8Array(S)]):JSON.stringify(S)});if(!R.ok)throw new Error(`HTTP ${R.status}: ${R.statusText}`);const A=await R.json();return this.#o?.log("Log batch sent successfully"),A}catch(S){throw this.#o?.error("Failed to send log batch:",S),S}}get isAvailable(){return this.#je&&null!=this.#Rt}get logManager(){return this.#Rt}get logBuffer(){return this.#Tt}log(S,b,I={}){return!!this.#Rt&&this.#Rt.log(S,b,I)}debug(S,b={}){return this.#Rt?.debug(S,b)||!1}info(S,b={}){return this.#Rt?.info(S,b)||!1}warn(S,b={}){return this.#Rt?.warn(S,b)||!1}error(S,b={}){return this.#Rt?.error(S,b)||!1}fatal(S,b={}){return this.#Rt?.fatal(S,b)||!1}setContext(S,b){return!!this.#Rt&&(this.#Rt.attachContext(S,b),!0)}clearContext(){return!!this.#Rt&&(this.#Rt.clearContext(),!0)}setLogLevel(S){return!!this.#Rt&&(this.#Rt.setLogLevel(S),!0)}getStats(){return this.#Rt?{manager:this.#Rt.getStats(),buffer:this.#Tt?this.#Tt.getStats():null}:null}async flush(){if(!this.#Tt)return!1;try{return await this.#Tt.forceFlush(),!0}catch(S){return this.#o?.error("Failed to flush logs:",S),!1}}enableServices(S,b="info"){try{return U.enableServices(S,b),!0}catch(S){return this.#o?.error("Failed to enable logging:",S),!1}}disableServices(S){try{return U.disableServices(S),!0}catch(S){return this.#o?.error("Failed to disable logging:",S),!1}}enableAll(S="info"){try{return U.enableAll(S),!0}catch(S){return this.#o?.error("Failed to enable all logging:",S),!1}}disableAll(){try{return U.disableAll(),!0}catch(S){return this.#o?.error("Failed to disable all logging:",S),!1}}getConfig(){try{return U.getConfig()}catch(S){return this.#o?.error("Failed to get logging config:",S),null}}getEnabledServices(){try{return U.getEnabledServices()}catch(S){return[]}}getAvailableServices(){return["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager","UserProfileManager","PerformanceMonitor","FetchInterceptor","XHRInterceptor","ResourceInterceptor","PostMessageInterceptor","CoreWebVitalsMonitor","Recorder","SessionStorage","UploadQueue","CDN-Loader","Replayer","Validation","BaseService"]}destroy(){this.#Tt&&(this.#Tt.destroy(),this.#Tt=null),this.#Rt&&(this.#Rt.destroy(),this.#Rt=null),this.#je=!1}}class ConsoleInterceptor{constructor(S,b={},I=null,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),this.realmConsole=x&&x.console?x.console:"undefined"!=typeof console?console:void 0,this.logManager=null,this.config={captureLog:!1!==b.captureLog,captureWarn:!1!==b.captureWarn,captureError:!1!==b.captureError,captureInfo:!1!==b.captureInfo,captureDebug:!1!==b.captureDebug,captureTrace:!1!==b.captureTrace,maxMessageLength:b.maxMessageLength||5e3,maxArgSize:b.maxArgSize||2e3,maxTotalArgsSize:b.maxTotalArgsSize||1e4,...b},this.logger=createLogger("ConsoleInterceptor"),this.originalMethods={},this.installed=!1}setLogManager(S){this.logManager=S,this.logger.debug("LogManager attached to ConsoleInterceptor")}install(){if(this.installed)return;const S=[];this.config.captureLog&&S.push("log"),this.config.captureWarn&&S.push("warn"),this.config.captureError&&S.push("error"),this.config.captureInfo&&S.push("info"),this.config.captureDebug&&S.push("debug"),this.config.captureTrace&&S.push("trace");const b=this.realmConsole;S.forEach(S=>{this.originalMethods[S]=b[S],b[S]=this.createInterceptor(S)}),this.installed=!0,this.logger.debug("Console interceptor installed")}uninstall(){if(!this.installed)return;const S=this.realmConsole;Object.keys(this.originalMethods).forEach(b=>{S[b]=this.originalMethods[b]}),this.originalMethods={},this.installed=!1,this.logger.debug("Console interceptor uninstalled")}createInterceptor(S){const b=this;return function(...I){b.originalMethods[S].apply(b.realmConsole,I);const x=I[0];if("string"!=typeof x||!(x.includes("[TraceScout]")||x.includes("[Recorder]")||x.includes("[SDK]")||x.includes("[ConsoleInterceptor]")||x.includes("[NetworkInterceptor]")||x.includes("[FetchInterceptor]")||x.includes("[XHRInterceptor]")||x.includes("[SessionManager]")||x.includes("[UploadQueue]")||x.includes("[ErrorHandler]")||x.includes("TraceScoutMonitoringCore")))try{const x=b.formatMessage(I),R=Date.now(),A=b.getLevel(S),_=b.processArgs(I),D={method:S,args:_,source:"console"};if("error"!==S&&"trace"!==S||(D.stack=b.captureStackTrace()),b.logManager&&"function"==typeof b.logManager.log)try{const I=b.truncateMessage(x),R=b.mapToLogLevel(S);b.logManager.log(R,I,D)}catch(S){}const L={type:"console",category:"console",method:S,message:b.truncateMessage(x),timestamp:R,level:A,args:_};if("error"!==S&&"trace"!==S||(L.stack=b.captureStackTrace()),b.eventManager&&"function"==typeof b.eventManager.logEvent&&b.eventManager.logEvent("console",L),b.reporter&&b.reporter.addSessionCustomEvent&&"function"==typeof b.reporter.addSessionCustomEvent)try{b.reporter.addSessionCustomEvent("console",{method:S,message:L.message,args:L.args,level:L.level,stack:L.stack,timestamp:L.timestamp})}catch(S){}}catch(S){}}}formatMessage(S){return S.map(S=>{if(null===S)return"null";if(void 0===S)return"undefined";if("object"==typeof S)try{return safeStringify(S,5,this.config.maxArgSize)}catch{return"[Unserializable Object]"}return"string"==typeof S&&S.length>this.config.maxArgSize?S.substring(0,this.config.maxArgSize)+"... [truncated]":String(S)}).join(" ")}processArgs(S){if(this.config.captureArgs)return safeParseConsoleArgs(S,this.config.maxArgSize,this.config.maxTotalArgsSize)}truncateMessage(S){return S.length>this.config.maxMessageLength?S.substring(0,this.config.maxMessageLength)+"...":S}getLevel(S){return{log:"log",info:"info",warn:"warn",error:"error",debug:"debug",trace:"trace"}[S]||"log"}mapToLogLevel(S){return{log:"info",info:"info",warn:"warn",error:"error",debug:"debug",trace:"debug"}[S]||"info"}captureStackTrace(){return(new Error).stack||""}}const We=["authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-csrf-token","x-xsrf-token","api-key","apikey","x-amz-security-token","x-ms-client-principal","proxy-authorization","www-authenticate"],He="[REDACTED]";function filterSensitiveHeaders(S,b=[]){if(!S)return{};const I={},x=new Set([...We,...b.map(S=>S.toLowerCase())]);if(S instanceof Headers||S.forEach&&"function"==typeof S.forEach)S.forEach((S,b)=>{const R=b.toLowerCase();I[b]=x.has(R)?He:S});else if("object"==typeof S)for(const[b,R]of Object.entries(S)){const S=b.toLowerCase();I[b]=x.has(S)?He:R}return I}function isSensitiveHeader(S){return!!S&&We.includes(S.toLowerCase())}function getSensitiveHeadersList(){return[...We]}function createSensitiveHeaderSet(S=[]){return new Set([...We,...S.map(S=>S.toLowerCase())])}const Ve=[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".woff",".woff2",".ttf",".eot",".ico",".webp",".avif"],Qe=["text/css","text/javascript","application/javascript","image/","font/","application/font","application/x-font"],Ge=[/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|ico|webp|avif)(\?|$)/i,/\/static\//i,/\/assets\//i,/\/images\//i,/\/fonts\//i,/\/_next\/static\//i,/\/webpack\//i,/\/node_modules\//i];function isStaticResource(S,b=""){if(!S)return!1;if(Ve.some(b=>S.toLowerCase().includes(b)))return!0;const I=Qe.some(S=>b.toLowerCase().startsWith(S));return!!I||Ge.some(b=>b.test(S))}function getResourceType(S,b=""){const I=S.toLowerCase(),x=b.toLowerCase();return I.includes(".js")||x.includes("javascript")?"script":I.includes(".css")||x.includes("text/css")?"stylesheet":/\.(woff2?|ttf|eot|otf)(\?|$)/i.test(S)||x.includes("font")?"font":/\.(png|jpg|jpeg|gif|svg|ico|webp|avif)(\?|$)/i.test(S)||x.includes("image")?"image":"other"}function isApiEndpoint(S){if(!S)return!1;const b=S.toLowerCase();return!![/\/api\//i,/\/v\d+\//i,/\/graphql/i,/\/rest\//i,/\/rpc\//i,/\.json(\?|$)/i].some(S=>S.test(b))||!isStaticResource(S)}const Ke=1e4;function parseFormData(S){try{const b=new URLSearchParams(S),I={};for(const[S,x]of b)I[S]=x;return I}catch(S){return null}}function createTruncatedBody(S,b,I="body"){return{_truncated:!0,_originalSize:S.length,_message:`${I} body truncated (${S.length} bytes, limit ${b} bytes)`,_preview:S.substring(0,b)+"...",_tip:"Enable full body capture in project settings if needed"}}function handleRequestBody(S,b={}){const{maxSize:I=Ke,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Request");try{const S=JSON.parse(b),x=JSON.stringify(S);return x.length>I?createTruncatedBody(x,I,"Request"):S}catch{const S=parseFormData(b);return S||b}}else{if(b instanceof FormData){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if(b instanceof URLSearchParams){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Request"):b}}}catch(S){x("Failed to parse request data:",S)}return null}function handleResponseBody(S,b={}){const{maxSize:I=Ke,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Response");try{b=JSON.parse(b)}catch{return b}}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Response"):b}return b}catch(S){x("Failed to parse response data:",S)}return null}const Je="[REDACTED]",Xe=10240,Ye=65536,Ze=["password","passwd","pwd","secret","token","access_token","refresh_token","id_token","authorization","auth","api_key","apikey","x-api-key","cookie","session","sessionid","session_id","sid","jwt","bearer","credential","credentials","private_key","client_secret","card","cardnumber","card_number","cvv","cvc","pin","ssn","social_security","dob","date_of_birth","email","phone","address"];function utf8Bytes(S){return"string"!=typeof S||0===S.length?0:(new TextEncoder).encode(S).length}function truncateToBytes(S,b){const I=new TextEncoder,x=I.encode(S),R=x.length;if(R<=b)return{text:S,truncated:!1,capturedBytes:R,originalBytes:R};if(b<=0)return{text:"",truncated:!0,capturedBytes:0,originalBytes:R};const A=x.subarray(0,b);let _=new TextDecoder("utf-8",{fatal:!1}).decode(A);_.length&&65533===_.charCodeAt(_.length-1)&&(_=_.slice(0,-1));return{text:_,truncated:!0,capturedBytes:I.encode(_).length,originalBytes:R}}function safeMime(S){if(!S||"string"!=typeof S)return null;const b=S.split(";")[0].trim().toLowerCase();return b&&/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(b)?b.length>128?b.slice(0,128):b:null}function classifyMime(S){return S?"application/json"===S||"application/ld+json"===S||"application/graphql"===S||"application/graphql+json"===S||S.endsWith("+json")?"json":"application/x-www-form-urlencoded"===S?"form":"image/svg+xml"===S||"application/xml"===S||"text/xml"===S||"application/xhtml+xml"===S||"application/javascript"===S||"application/x-javascript"===S||"text/javascript"===S||S.startsWith("text/")?"text":S.startsWith("image/")||S.startsWith("audio/")||S.startsWith("video/")||S.startsWith("font/")||"application/octet-stream"===S||"application/zip"===S||"application/gzip"===S||"application/pdf"===S||"application/x-protobuf"===S||"application/protobuf"===S||S.startsWith("multipart/")?"binary":"unknown":"unknown"}function isTextualContentType(S){const b=classifyMime(safeMime(S));return"json"===b||"form"===b||"text"===b}function buildFieldDenylist(S=[]){const b=new Set(Ze);if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.add(I.toLowerCase());return b}function isSensitiveField(S,b){const I=String(S).toLowerCase();for(const S of b)if(I.includes(S))return!0;return!1}function redactObject(S,b){let I=!1;const walk=S=>{if(Array.isArray(S))return S.map(walk);if(S&&"object"==typeof S){const x={};for(const R of Object.keys(S))isSensitiveField(R,b)?(x[R]=Je,I=!0):x[R]=walk(S[R]);return x}return S};return{value:walk(S),redacted:I}}function redactFormUrlEncoded(S,b){let I;try{I=new URLSearchParams(S)}catch{return{text:S,redacted:!1}}let x=!1;const R=[];for(const S of I.keys())R.push(S);const A=new Set;for(const S of R){if(A.has(S))continue;if(A.add(S),!isSensitiveField(S,b))continue;const R=I.getAll(S).length;I.delete(S);for(let b=0;b<R;b++)I.append(S,Je);x=!0}return{text:I.toString(),redacted:x}}function rawBodyBinarySize(S){return"undefined"!=typeof Blob&&S instanceof Blob&&"number"==typeof S.size?S.size:"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(S)?S.byteLength:null}function makeResult({state:S,contentType:b=null,originalBytes:I=null,redacted:x=!1}){return{text:null,state:S,redacted:!!x,truncated:!1,originalBytes:"number"==typeof I&&I>=0?I:null,capturedBytes:null,contentType:b||null}}function runSanitizer(S,b){try{return{threw:!1,value:S(b)}}catch{return{threw:!0}}}function safeToString(S){try{return"string"==typeof S?S:JSON.stringify(S)}catch{return String(S)}}function finalizeText(S,{mime:b,maxBytes:I,redacted:x}){const{text:R,truncated:A,capturedBytes:_,originalBytes:D}=truncateToBytes(S,I);let L;return L=A?"truncated":x?"redacted":"captured",{text:R,state:L,redacted:!!x,truncated:A,originalBytes:D,capturedBytes:_,contentType:b||null}}function finalizeStructured(S,{redacted:b,mime:I,maxBytes:x,sanitizer:R}){let A,_=S;if(R){const x=runSanitizer(R,S);if(x.threw)return makeResult({state:"failed",contentType:I,redacted:b});if(null===x.value||void 0===x.value)return makeResult({state:"excluded",contentType:I});_=x.value}try{A=JSON.stringify(_)}catch{return makeResult({state:"failed",contentType:I,redacted:b})}return void 0===A&&(A=""),finalizeText(A,{mime:I,maxBytes:x,redacted:b})}function captureText(S,{mime:b,maxBytes:I,sanitizer:x}){let R=S;if(x){const I=runSanitizer(x,S);if(I.threw)return makeResult({state:"failed",contentType:b});if(null===I.value||void 0===I.value)return makeResult({state:"excluded",contentType:b});R="string"==typeof I.value?I.value:safeToString(I.value)}return finalizeText(R,{mime:b,maxBytes:I,redacted:!1})}function captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const{text:A,redacted:_}=redactFormUrlEncoded(S,x);let D=A;if(R){const S=runSanitizer(R,D);if(S.threw)return makeResult({state:"failed",contentType:b,redacted:_});if(null===S.value||void 0===S.value)return makeResult({state:"excluded",contentType:b});D="string"==typeof S.value?S.value:safeToString(S.value)}return finalizeText(D,{mime:b,maxBytes:I,redacted:_})}function captureStringByMime(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const A=classifyMime(b);if("binary"===A||"unknown"===A)return makeResult({state:"binary",contentType:b,originalBytes:utf8Bytes(S)});if("form"===A)return captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R});if("json"===A){let A;try{A=JSON.parse(S)}catch{return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}const{value:_,redacted:D}=redactObject(A,x);return finalizeStructured(_,{redacted:D,mime:b,maxBytes:I,sanitizer:R})}return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}function normalizeOpts(S){let b="number"==typeof S.maxBytes&&S.maxBytes>=0?S.maxBytes:Xe;return b>Ye&&(b=Ye),{maxBytes:b,denylist:S.denylist instanceof Set?S.denylist:buildFieldDenylist(S.sensitiveFields),sanitizer:"function"==typeof S.sanitizer?S.sanitizer:null,captureEnabled:!1!==S.captureEnabled,excluded:!0===S.excluded}}function captureRequestBody(S,b={}){const I=safeMime(b.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(null==S||""===S)return makeResult({state:"unavailable",contentType:I});try{if("undefined"!=typeof FormData&&S instanceof FormData){const{obj:b,redacted:_}=function sanitizeFormData(S,b){let I=!1;const x={};for(const[R,A]of S.entries()){let S;"undefined"!=typeof File&&A instanceof File||"undefined"!=typeof Blob&&A instanceof Blob?S={_type:"file",mime:safeMime(A.type)||null,bytes:"number"==typeof A.size?A.size:null}:isSensitiveField(R,b)?(S=Je,I=!0):S=String(A),Object.prototype.hasOwnProperty.call(x,R)?Array.isArray(x[R])?x[R].push(S):x[R]=[x[R],S]:x[R]=S}return{obj:x,redacted:I}}(S,R);return finalizeStructured(b,{redacted:_,mime:I||"multipart/form-data",maxBytes:x,sanitizer:A})}if("undefined"!=typeof URLSearchParams&&S instanceof URLSearchParams)return captureFormString(S.toString(),{mime:I||"application/x-www-form-urlencoded",maxBytes:x,denylist:R,sanitizer:A});if(function isBinaryRawBody(S){return"undefined"!=typeof Blob&&S instanceof Blob||"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||!("undefined"==typeof ArrayBuffer||!ArrayBuffer.isView||!ArrayBuffer.isView(S))||"undefined"!=typeof ReadableStream&&S instanceof ReadableStream}(S))return makeResult({state:"binary",contentType:I||(L=S,"undefined"!=typeof Blob&&L instanceof Blob&&L.type?safeMime(L.type):null),originalBytes:rawBodyBinarySize(S)});if("string"==typeof S)return captureStringByMime(S,{mime:I,maxBytes:x,denylist:R,sanitizer:A});if("object"==typeof S){const{value:b,redacted:_}=redactObject(S,R);return finalizeStructured(b,{redacted:_,mime:I||"application/json",maxBytes:x,sanitizer:A})}return captureStringByMime(String(S),{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}var L}function captureResponseBody(S={},b={}){const I=safeMime(S.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(S.opaque)return makeResult({state:"inaccessible",contentType:I});if(S.readError)return makeResult({state:"failed",contentType:I});if(S.binary){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}const L=classifyMime(I);if("binary"===L||"unknown"===L){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}if(S.empty||null===S.text||void 0===S.text||""===S.text)return makeResult({state:"unavailable",contentType:I});try{return captureStringByMime(S.text,{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}}const et="[REDACTED]",tt=["token","access_token","refresh_token","id_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","ssid","password","passwd","pwd","secret","jwt","bearer","credential","credentials","private_token","private_key","client_secret","pin","cvv","cvc","ssn","email"];function buildTokens(S=[]){const b=[...tt];if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.push(I.toLowerCase());return b}function isSensitiveParam(S,b){const I=String(S).toLowerCase();return b.some(S=>I.includes(S))}function scrubSearchParams(S,b,I){let x=!1;const R=[];for(const b of S.keys())R.push(b);const A=new Set;for(const _ of R)if(!A.has(_)&&(A.add(_),isSensitiveParam(_,b)))if(x=!0,"delete"===I)S.delete(_);else{const b=S.getAll(_).length;S.delete(_);for(let I=0;I<b;I++)S.append(_,et)}return x}function splitSanitizedUrl(S,b={}){const{extraParams:I=[],mode:x="redact"}=b;if(!S)return{url:"",path:"",query:""};const R=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);scrubSearchParams(I.searchParams,R,x);const A=I.searchParams.toString();return{url:I.toString(),path:I.pathname||"",query:A}}catch{const I=function sanitizeUrl$1(S,b={}){const{extraParams:I=[],mode:x="redact",stripHash:R=!1}=b;if(!S)return S||"";const A=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);return scrubSearchParams(I.searchParams,A,x),R&&(I.hash=""),I.toString()}catch{let b=S.replace(/([?&][^=&]*(?:token|key|secret|password|passwd|pwd|auth|jwt|bearer|session|sid|credential|pin|cvv|cvc|ssn|email)[^=&]*=)[^&#]*/gi,`$1${et}`);return b.length>2048&&(b=b.substring(0,2048)),b}}(S,b),x=I.indexOf("?");return-1===x?{url:I,path:I,query:""}:{url:I,path:I.substring(0,x),query:I.substring(x+1).split("#")[0]}}}class InterceptorLogger{constructor(S,b=!1){let I=S.replace(/^\[|\]$/g,"").replace(":","");I="xhrinterceptor"===I.toLowerCase()?"XHRInterceptor":I.charAt(0).toUpperCase()+I.slice(1),this.serviceLogger=createLogger(I),this.prefix=S,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class BaseInterceptor{constructor(S,b,I){this.reporter=S,this.interceptorName=b,this.realm=I||("undefined"!=typeof window?window:void 0),this.logger=new InterceptorLogger(`[${this.interceptorName}Interceptor]`,this.reporter.config?.debug||!1)}updateDebugMode(S){this.logger.updateDebugMode(S)}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!1}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isStaticResource(S,b=""){return isStaticResource(S,b)}isResourceUrl(S,b=""){return isStaticResource(S,b)}getResourceType(S,b=""){return getResourceType(S,b)}extractRequestDetails(S,b,I,x,R){const A=parseUrl(S);return{method:b.toUpperCase(),url:S,domain:A.hostname,path:A.pathname,status:I,statusText:x,response:R,interceptor:this.interceptorName}}logEvent(S){const b=S?.url||S?.request?.url;if(b&&isInternalSdkEndpoint(b))return;if(this.reporter?._sessionRecorder?.isRecording||this.reporter?.sessionRecording?.isRecording)return;const I={id:generateId(),timestamp:Date.now(),...S};this.reporter.logEvent&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(I)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("string"==typeof S&&0===S.indexOf("network")){const S=this.reporter.config&&this.reporter.config.network;if(S&&!1===S.isEnabled)return!1}const I=b?.url||b?.request?.url;if(I&&isInternalSdkEndpoint(I))return!1;if(!this.reporter.addSessionCustomEvent)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateUserProfileFromContext({url:S,source:b,data:I}){try{if(this.reporter.extractUserContextFromBody&&"function"==typeof this.reporter.extractUserContextFromBody){const x=this.reporter.extractUserContextFromBody({url:S,source:b,data:I});if(Object.keys(x).length>0){let S={};this.reporter._getUserProfile&&"function"==typeof this.reporter._getUserProfile?S=this.reporter._getUserProfile():this.reporter.getUserProfile&&"function"==typeof this.reporter.getUserProfile&&(S=this.reporter.getUserProfile());const b={...S,...x};JSON.stringify(S)!==JSON.stringify(b)&&this.reporter.setUserProfile&&"function"==typeof this.reporter.setUserProfile&&this.reporter.setUserProfile(b)}}}catch(S){this.logger.warn("Failed to update user profile context:",S)}}getNetworkConfig(){const S=this.reporter&&this.reporter.config&&this.reporter.config.network||{};let b="number"==typeof S.maxBodyBytes?S.maxBodyBytes:Xe;b>=0||(b=Xe),b>Ye&&(b=Ye);const I=Array.isArray(S.sensitiveFields)?S.sensitiveFields:[];return{isEnabled:!1!==S.isEnabled,captureRequestHeaders:!1!==S.captureRequestHeaders,captureResponseHeaders:!1!==S.captureResponseHeaders,captureRequestBody:!1!==S.captureRequestBody,captureResponseBody:!1!==S.captureResponseBody,maxBodyBytes:b,excludeEndpoints:Array.isArray(S.excludeEndpoints)?S.excludeEndpoints:[],requestSanitizer:"function"==typeof S.requestSanitizer?S.requestSanitizer:null,responseSanitizer:"function"==typeof S.responseSanitizer?S.responseSanitizer:null,sensitiveFields:I,_denylist:buildFieldDenylist(I)}}isEndpointExcluded(S,b){const I=b&&b.excludeEndpoints||[],x=String(S||"");for(const S of I)try{if(S instanceof RegExp){if(S.test(x))return!0}else if("string"==typeof S&&S&&x.includes(S))return!0}catch{}return!1}sanitizeRequestUrlFields(S,b){try{return splitSanitizedUrl(S,{extraParams:b&&b.sensitiveFields||[]})}catch{return{url:String(S||""),path:"",query:""}}}mapCaptureToFields(S,b){const I={};return I[`${b}Body`]="string"==typeof S.text?S.text:null,I[`${b}BodyState`]=S.state,I[`${b}BodyRedacted`]=!!S.redacted,I[`${b}BodyTruncated`]=!!S.truncated,"number"==typeof S.originalBytes&&(I[`${b}BodySize`]=S.originalBytes),"number"==typeof S.capturedBytes&&(I[`${b}BodyCapturedBytes`]=S.capturedBytes),S.contentType&&(I[`${b}BodyContentType`]=S.contentType),I}buildRequestBodyFields(S,b,I,x){const R=captureRequestBody(S,{contentTypeHeader:b,maxBytes:I.maxBodyBytes,denylist:I._denylist,sanitizer:I.requestSanitizer,captureEnabled:I.captureRequestBody,excluded:x});return this.mapCaptureToFields(R,"request")}buildResponseBodyFields(S,b,I){const x=captureResponseBody(S,{maxBytes:b.maxBodyBytes,denylist:b._denylist,sanitizer:b.responseSanitizer,captureEnabled:b.captureResponseBody,excluded:I});return this.mapCaptureToFields(x,"response")}handleRequestData(S,b){return handleRequestBody(b,{maxSize:Ke,onWarn:(...S)=>this.logger.warn(...S)})}handleResponseData(S,b){return handleResponseBody(b,{maxSize:Ke,onWarn:(...S)=>this.logger.warn(...S)})}createEvent(S,b,I,x,R,A=null,_=null,D={}){const L={type:S,context:{url:b,method:I.toUpperCase(),status:x,statusText:R,requestData:this.handleRequestData(b,A),responseData:this.handleResponseData(b,_),isMonitored:this.shouldMonitor(b),...D}};return this.shouldExtractFields(b,"response")&&_&&this.updateUserProfileFromContext({url:b,source:"response",data:_}),L}logErrorEvent(S,b,I,x,R=null,A=null,_={}){const D={type:_.errorType||`${this.interceptorName}_http_error`,request:this.extractRequestDetails(S,b,I,x,A),extraData:_,context:{isMonitored:this.shouldMonitor(S),forceLog:I>=400,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}handleSilentLoginFailure(S,b,I,x,R,A){S.toLowerCase().includes("/myava/login")&&(I>=200&&I<300)&&null==R?.LoginToken&&this.logEvent({type:A,request:this.extractRequestDetails(S,b,I,x,R),extraData:R})}logCustomApiError(S,b,I,x,R,A,_={}){const D={type:"custom_api_error",request:this.extractRequestDetails(S,b,I,x,R),extraData:{errorCondition:A,..._},context:{isMonitored:this.shouldMonitor(S),forceLog:!0,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}logUnknownError(S,b,I,x={}){const R={type:"unknown_error",request:{method:b||"UNKNOWN",url:S||"unknown",domain:S?this.extractDomain(S):"unknown",path:S?this.extractPath(S):"unknown",status:0,statusText:"Unknown Error",response:{error:I?.message||"Unknown error occurred",stack:I?.stack||""},interceptor:this.interceptorName},extraData:{errorType:I?.name||"UnknownError",errorMessage:I?.message||"Unknown error",...x},context:{forceLog:!0,isMonitored:!0,scriptOrigin:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logEvent(R)}extractDomain(S){try{return new URL(S,this.realm?.location?.origin).hostname}catch{return"unknown"}}extractPath(S){try{return new URL(S,this.realm?.location?.origin).pathname}catch{return"unknown"}}destroy(){this.reporter=null,this.logger=null}}function getHeader(S,b){if(!S)return null;const I=b.toLowerCase();if(S instanceof Headers)return S.get(I);for(const b in S)if(b.toLowerCase()===I)return S[b];return null}function setHeader(S,b,I){if(!S)return;if(S instanceof Headers)return void S.set(b,I);const x=b.toLowerCase();for(const b in S)b.toLowerCase()===x&&delete S[b];S[b]=I}function hasHeader(S,b){if(!S)return!1;const I=b.toLowerCase();if(S instanceof Headers)return S.has(I);for(const b in S)if(b.toLowerCase()===I)return!0;return!1}const st=/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/,rt=/^0+$/;function readTraceContextFromHeaders(S){return function parseTraceparent(S){if("string"!=typeof S)return null;const b=S.match(st);if(!b)return null;const I=b[1],x=b[2];return rt.test(I)||rt.test(x)?null:{traceId:I,spanId:x}}(function readTraceparentFromHeaders(S){if(!S)return null;if("undefined"!=typeof Headers&&S instanceof Headers){const b=S.get("traceparent");return"string"==typeof b?b:null}if("object"==typeof S)for(const b of Object.keys(S))if("traceparent"===b.toLowerCase()){const I=S[b];return"string"==typeof I?I:null}return null}(S))}function isSameOrigin(S,b,I){const x=function resolveOrigin(S,b){try{const I=b||"undefined"!=typeof window&&window.location&&window.location.href||void 0;return new URL(S,I).origin}catch{return null}}(S,I),R=function currentOrigin(S){return S||("undefined"!=typeof window&&window.location?window.location.origin:null)}(b);return null!==x&&null!==R&&x===R}function tracePropagationDecision(S,b={}){const{pageOrigin:I,pageHref:x}=b;return"string"==typeof S&&isInternalSdkEndpoint(S)?{traceparent:!1,baggage:!1,reason:"sdk_ingest_excluded"}:isSameOrigin(S,I,x)?{traceparent:!0,baggage:!0,reason:"same_origin"}:{traceparent:!1,baggage:!1,reason:"third_party"}}const nt="undefined"!=typeof window&&window.fetch?window.fetch.bind(window):void 0;class FetchInterceptor extends BaseInterceptor{constructor(S,b){super(S,"fetch",b),this.originalFetch=this.realm&&this.realm.fetch?this.realm.fetch.bind(this.realm):nt}setup(){this.logger.log("Initializing Fetch interceptor...");const S=this,b=this.realm;b._apiReporter_originalFetch||(b._apiReporter_originalFetch=this.originalFetch),b.fetch=async function(...I){I=S.injectCorrelationHeaders(I);const x=b.Request,R=b.Headers,A=x&&I[0]instanceof x?I[0].url:String(I[0]),_=I[1]||{},D=_.method||(x&&I[0]instanceof x?I[0].method:"GET"),L=_.body;let B={};x&&I[0]instanceof x?I[0].headers.forEach((S,b)=>{B[b]=S}):_.headers&&(R&&_.headers instanceof R?_.headers.forEach((S,b)=>{B[b]=S}):Object.assign(B,_.headers));const U=filterSensitiveHeaders(B),$=S.shouldMonitor(A),j=S.isStaticResource(A);let W=null;$&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&(W=S.reporter.performanceMonitor.generateRequestId(),S.reporter.performanceMonitor.startTracking(W,A,D));const H=Date.now();if(!j){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(A,b),x=S.sanitizeRequestUrlFields(A,b),R=getHeader(B,"content-type"),_=S.buildRequestBodyFields(L,R,b,I),$={interceptor:"fetch",method:D,url:x.url,requestHeaders:b.captureRequestHeaders?U:{},timestamp:H,..._};x.path&&($.requestPath=x.path),x.query&&($.requestQuery=x.query);const j=readTraceContextFromHeaders(B);j&&($.traceId=j.traceId,$.spanId=j.spanId),S.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing API request:",{url:x.url,hasHeaders:!!U&&Object.keys(U).length>0,bodyState:_.requestBodyState}),S.addToSessionReplay("network_request",$)}try{const x=await S.originalFetch.apply(b,I);let R=null;return W&&(R=S.reporter.performanceMonitor.endTracking(W,x.status)),await S.handleResponse(x,A,D,R),x}catch(b){throw W&&S.reporter.performanceMonitor.endTracking(W,0),S.handleNetworkError(A,D,b,"fetch_network_error"),b}},this.logger.log("Fetch interceptor setup complete")}async handleResponse(S,b,I,x){const R=this.getNetworkConfig(),A=this.isEndpointExcluded(b,R);let _=null,D=!1;try{_=S.clone()}catch{D=!0}const L="opaque"===S.type,B=_&&_.headers&&_.headers.get("content-type")||"",U={};_&&_.headers&&_.headers.forEach((S,b)=>{U[b]=S});const $=R.captureResponseHeaders?filterSensitiveHeaders(U):{},j=_&&_.headers?_.headers.get("content-length"):null,W=j?parseInt(j,10):null;let H=null,V=!1,Q=null;const G=!L&&!D&&isTextualContentType(B);if(G){try{H=await _.text()}catch{V=!0}if(!V&&null!=H){const S=safeMime(B);if(S&&"json"===classifyMime(S))try{Q=JSON.parse(H)}catch{Q=H}else Q=H}}else D&&!L&&(V=!0);const J=this.buildResponseBodyFields({opaque:L,readError:V,text:G?H:null,contentTypeHeader:B,knownSize:W},R,A),X=this.isStaticResource(b,B);!X&&x?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,Q,x),x?.performanceAlert&&this.logPerformanceAlert(x.metrics),X?this.handleStaticResource(b,I,S.status,S.statusText,B,x,_||S):this.handleApiResponse(b,I,S.status,S.statusText,Q,x,$,J,R)}handleStaticResource(S,b,I,x,R,A,_){const D=_.headers?.get("content-length"),L=D?parseInt(D,10):null,B={interceptor:"fetch",method:b,url:S,status:I,statusText:x,resourceType:this.getResourceType(S,R),size:L,duration:A?.duration||null,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing static resource:",{url:S,status:I,resourceType:B.resourceType,size:L}),this.addToSessionReplay("network_resource",B),I>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(S,b,I,x,null,null,{errorType:"resource_load_error",contentType:R,resourceType:B.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"fetch",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing response:",{url:U.url,status:I,hasHeaders:!!_&&Object.keys(_).length>0,bodyState:$.responseBodyState}),this.addToSessionReplay("network_response",$),I>=400?this.logErrorEvent(S,b,I,x,null,R,{errorType:"fetch_http_error",performanceData:A}):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"fetch_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"fetch_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logger.log(`Slow request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"fetch",method:b,url:R.url,status:0,statusText:"Network Error",errorMessage:I.message||"Network request failed",errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,"Network Error",null,null,{errorType:x,errorMessage:I.message||"Network request failed",errorStack:I.stack})}destroy(){const S=this.realm;S&&S._apiReporter_originalFetch&&(S.fetch=S._apiReporter_originalFetch,delete S._apiReporter_originalFetch),super.destroy()}injectCorrelationHeaders(S){const b=SDKContext.getInstance();if(!b||!b.sessionId)return S;const I=this.realm,x=I.Request,R=I.Headers,A=tracePropagationDecision(x&&S[0]instanceof x?S[0].url:String(S[0]));if(!A.traceparent&&!A.baggage)return S;const _=[];if(A.baggage&&(b.sessionId&&_.push(`sessionId=${encodeURIComponent(b.sessionId)}`),b.userId&&_.push(`userId=${encodeURIComponent(b.userId)}`),b.projectId&&_.push(`projectId=${encodeURIComponent(b.projectId)}`)),x&&S[0]instanceof x){const b=S[0],I=S[1]||{},D=new R(b.headers);if(I.headers)if(R&&I.headers instanceof R)I.headers.forEach((S,b)=>D.set(b,S));else for(const S in I.headers)D.set(S,I.headers[S]);const L=hasHeader(D,"traceparent");A.baggage&&_.length>0&&!getHeader(D,"baggage")&&setHeader(D,"baggage",_.join(",")),A.traceparent&&!L&&setHeader(D,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`);const B={...I};delete B.headers;return[new x(b,{...B,headers:D})]}const D=S[0],L=S[1]||{};if(L.headers=L.headers||{},R&&L.headers instanceof R){const S={};L.headers.forEach((b,I)=>{S[I]=b}),L.headers=S}const B=hasHeader(L.headers,"traceparent");return A.baggage&&_.length>0&&!getHeader(L.headers,"baggage")&&setHeader(L.headers,"baggage",_.join(",")),A.traceparent&&!B&&setHeader(L.headers,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`),[D,L]}generateW3CTraceId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}class XHRInterceptor extends BaseInterceptor{constructor(S,b){super(S,"xhr",b),this.XHR=this.realm&&this.realm.XMLHttpRequest?this.realm.XMLHttpRequest:XMLHttpRequest,this.originalOpen=this.XHR.prototype.open,this.originalSend=this.XHR.prototype.send}setup(){this.logger.log("Initializing XHR interceptor...");const S=this,b=this.XHR.prototype;b.open=function(b,I,...x){return this._apiReporterUrl=I,this._apiReporterMethod=b.toUpperCase(),this._apiReporterRequestHeaders={},this._apiReporterUserSetHeaders=new Set,this._apiReporterHeadersInjected=!1,S.originalOpen.call(this,b,I,...x)};const I=b.setRequestHeader;this._originalSetRequestHeader=I,b.setRequestHeader=function(S,b){return this._apiReporterRequestHeaders||(this._apiReporterRequestHeaders={}),this._apiReporterUserSetHeaders||(this._apiReporterUserSetHeaders=new Set),this._apiReporterUserSetHeaders.add(S.toLowerCase()),setHeader(this._apiReporterRequestHeaders,S,b),I.call(this,S,b)},b.send=function(...b){const I=this;if(!I._apiReporterHeadersInjected){const b=I._apiReporterUserSetHeaders?.has("traceparent");S.injectXHRCorrelationHeaders(I,b),I._apiReporterHeadersInjected=!0}const{_apiReporterUrl:x,_apiReporterMethod:R,_apiReporterRequestHeaders:A}=I,_=filterSensitiveHeaders(A||{}),D=S.shouldMonitor(x),L=S.isStaticResource(x),B=b[0],U=Date.now();I._apiReporterStartTime=U,S.logger.log(`XHR Request: ${R} ${x}, shouldMonitor: ${D}, isResource: ${L}`);let $=null;if(D&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&($=S.reporter.performanceMonitor.generateRequestId(),I._apiReporterRequestId=$,S.reporter.performanceMonitor.startTracking($,x,R)),!L){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(x,b),D=S.sanitizeRequestUrlFields(x,b),L=getHeader(A||{},"content-type"),$=S.buildRequestBodyFields(B,L,b,I),j={interceptor:"xhr",method:R,url:D.url,requestHeaders:b.captureRequestHeaders&&_||{},timestamp:U,...$};D.path&&(j.requestPath=D.path),D.query&&(j.requestQuery=D.query);const W=readTraceContextFromHeaders(A);W&&(j.traceId=W.traceId,j.spanId=W.spanId),S.addToSessionReplay("network_request",j)}return I.addEventListener("load",()=>S.handleXHRLoad(I,x,R,L)),I.addEventListener("error",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Network error"),"xhr_network_error")}),I.addEventListener("timeout",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request timed out"),"xhr_timeout_error")}),I.addEventListener("abort",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request aborted"),"xhr_aborted_error")}),S.originalSend.apply(I,b)},this.logger.log("XHR interceptor setup complete")}handleXHRLoad(S,b,I,x){let R=null;S._apiReporterRequestId&&(R=this.reporter.performanceMonitor.endTracking(S._apiReporterRequestId,S.status));const A=S.getResponseHeader("content-type")||"",_=R?.duration||(S._apiReporterStartTime?Date.now()-S._apiReporterStartTime:null);if(x)return void this.handleStaticResource(S,b,I,A,_);const D=this.getNetworkConfig(),L=this.isEndpointExcluded(b,D);let B=null,U=null;try{const b=S.responseType;if(""===b||"text"===b){const b=S.responseText||null;if(B={text:b,contentTypeHeader:A},b){const S=safeMime(A);if(S&&"json"===classifyMime(S))try{U=JSON.parse(b)}catch{U=b}else U=b}}else if("json"===b){const b=S.response;U=b;let I=null;try{I=null==b?null:JSON.stringify(b)}catch{I=null}B={text:I,contentTypeHeader:A||"application/json"}}else{const I=S.getResponseHeader("content-length");B={binary:!0,contentTypeHeader:A,knownSize:I?parseInt(I,10):null},U=`[${String(b).toUpperCase()} data]`}}catch(S){this.logger.warn(`Failed to read XHR response for ${b}`),B={readError:!0,contentTypeHeader:A},U={error:"Failed to read response",originalError:S.message}}const $=this.parseXHRResponseHeaders(S.getAllResponseHeaders?.()),j=D.captureResponseHeaders?filterSensitiveHeaders($):{},W=this.buildResponseBodyFields(B,D,L);R?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,U,R),R?.performanceAlert&&this.logPerformanceAlert(R.metrics),this.handleApiResponse(b,I,S.status,S.statusText,U,R,j,W,D)}parseXHRResponseHeaders(S){const b={};if(!S||"string"!=typeof S)return b;for(const I of S.trim().split(/[\r\n]+/)){const S=I.indexOf(":");if(-1===S)continue;const x=I.slice(0,S).trim(),R=I.slice(S+1).trim();x&&(b[x]=R)}return b}handleStaticResource(S,b,I,x,R){const A=S.getResponseHeader("content-length"),_=A?parseInt(A,10):null,D={interceptor:"xhr",method:I,url:b,status:S.status,statusText:S.statusText,resourceType:this.getResourceType(b,x),size:_,duration:R,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[XHRInterceptor] Capturing static resource:",{url:b,status:S.status,resourceType:D.resourceType,size:_}),this.addToSessionReplay("network_resource",D),S.status>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(b,I,S.status,S.statusText,null,null,{errorType:"resource_load_error",contentType:x,resourceType:D.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){this.logger.log(`Handling API response: ${b} ${S}, status: ${I}`);const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"xhr",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.addToSessionReplay("network_response",$),I>=400?(this.logger.log(`Logging error event for: ${S} with status ${I}`),this.logErrorEvent(S,b,I,x,null,R,{errorType:"xhr_http_error",performanceData:A})):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"xhr_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"xhr_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logger.log(`Slow XHR request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"xhr",method:b,url:R.url,status:0,statusText:I.message||"Network Error",errorMessage:I.message,errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,I.message,null,null,{errorType:x,errorMessage:I.message,errorStack:I.stack})}destroy(){this.XHR.prototype.open=this.originalOpen,this.XHR.prototype.send=this.originalSend,this._originalSetRequestHeader&&(this.XHR.prototype.setRequestHeader=this._originalSetRequestHeader),super.destroy()}injectXHRCorrelationHeaders(S,b){const I=SDKContext.getInstance();if(!I||!I.sessionId)return;const x=tracePropagationDecision(String(S._apiReporterUrl||""));if(x.traceparent||x.baggage){if(x.baggage&&!getHeader(S._apiReporterRequestHeaders,"baggage")){const b=[];I.sessionId&&b.push(`sessionId=${encodeURIComponent(I.sessionId)}`),I.userId&&b.push(`userId=${encodeURIComponent(I.userId)}`),I.projectId&&b.push(`projectId=${encodeURIComponent(I.projectId)}`),b.length>0&&S.setRequestHeader("baggage",b.join(","))}if(x.traceparent&&!b){const b=`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`;S.setRequestHeader("traceparent",b)}}}generateW3CTraceId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}class ResourceInterceptor{constructor(S){this.reporter=S,this.interceptorName="resource",this.logger=createLogger("ResourceInterceptor"),this.boundErrorHandler=this.handleResourceError.bind(this),this.isDestroyed=!1}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed ResourceInterceptor"):(window.addEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor setup complete"))}handleResourceError(S){if(this.isDestroyed)return;const b=S.target;if(b instanceof HTMLScriptElement||b instanceof HTMLLinkElement||b instanceof HTMLImageElement){const S=b.src||b.href||"",I=b.tagName.toLowerCase(),x=parseUrl(S),R={type:"resource_load_error",request:{method:"GET",url:S,domain:x.hostname||this.#_t(S),path:x.pathname||this.#Ot(S),status:0,statusText:"Resource failed to load",response:`${I} element failed to load`,headers:{},interceptor:"resource"},extraData:{tag:I,elementType:b.constructor.name,errorType:"resource_load_failure",resourceType:this.#Dt(I),crossOrigin:this.#Ft(S),isDomElement:!0,integrity:b.integrity||null,crossorigin:b.crossOrigin||null,async:b.async||!1,defer:b.defer||!1,rel:b.rel||null,type:b.type||null},context:{forceLog:!0,isMonitored:this.shouldMonitor(S),scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logger.log(`Creating resource error event: ${S} [${I}]`),this.reporter&&this.reporter.logEvent?(this.reporter.logEvent(R),this.logger.log(`Resource error event sent for: ${S}`)):this.logger.error("Could not send resource error - reporter.logEvent not available"),this.logger.log(`Resource failed to load: ${S} [${I}]`)}}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!0}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}#_t(S){try{return new URL(S,location.origin).hostname}catch{return""}}#Ot(S){try{return new URL(S,location.origin).pathname}catch{return""}}#Dt(S){switch(S.toLowerCase()){case"script":return"javascript";case"link":return"stylesheet";case"img":return"image";case"video":return"video";case"audio":return"audio";case"source":return"media-source";case"track":return"text-track";case"object":return"object";case"embed":return"embed";case"iframe":return"iframe";default:return"unknown"}}#Ft(S){try{return new URL(S,location.origin).origin!==location.origin}catch{return!1}}destroy(){this.isDestroyed?this.logger.warn("ResourceInterceptor already destroyed"):(this.isDestroyed=!0,window.removeEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor destroyed"),this.reporter=null,this.boundErrorHandler=null)}}const it=["token","access_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","password","pwd","secret","email","jwt","bearer","refresh_token","id_token"];class LRUDedupeCache{constructor(S=5e3){this.maxSize=S,this.cache=new Map}has(S){if(this.cache.has(S)){const b=this.cache.get(S);return this.cache.delete(S),this.cache.set(S,b),!0}return!1}add(S){if(this.cache.has(S))this.cache.delete(S);else if(this.cache.size>=this.maxSize){const S=this.cache.keys().next().value;this.cache.delete(S)}this.cache.set(S,!0)}clear(){this.cache.clear()}get size(){return this.cache.size}}class PerformanceResourceObserver{constructor(S,b={},I=null){this.reporter=S,this.realm=I||("undefined"!=typeof window?window:void 0),this.logger=createLogger("PerformanceResourceObserver"),this.config={captureResources:!1!==b.captureResources,captureNavigation:!1!==b.captureNavigation,maxDedupeEntries:b.maxDedupeEntries||5e3,filterOtherInitiator:!1!==b.filterOtherInitiator,debug:b.debug||this.reporter?.config?.debug||!1,maxResourceEntriesPerSession:b.maxResourceEntriesPerSession||2e3,resourceAllowlist:b.resourceAllowlist||null,resourceBlocklist:b.resourceBlocklist||null},this.allowlistRegexes=this.compilePatterns(this.config.resourceAllowlist),this.blocklistRegexes=this.compilePatterns(this.config.resourceBlocklist),this.resourceObserver=null,this.navigationObserver=null,this.processedEntries=new LRUDedupeCache(this.config.maxDedupeEntries),this.isDestroyed=!1,this.sessionResourceCount=0,this.sessionCapReached=!1,this.eventCount=0,this.eventCountResetTime=Date.now(),this.maxEventsPerMinute=this.reporter?.config?.maxEventsPerMinute||500}compilePatterns(S){if(!S||!Array.isArray(S)||0===S.length)return null;try{return S.map(S=>new RegExp(S,"i"))}catch(S){return this.logger?.warn?.("Invalid regex pattern in allowlist/blocklist:",S.message),null}}passesUrlFilters(S){if(this.blocklistRegexes)for(const b of this.blocklistRegexes)if(b.test(S))return!1;if(this.allowlistRegexes){for(const b of this.allowlistRegexes)if(b.test(S))return!0;return!1}return!0}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed PerformanceResourceObserver"):this.realm&&void 0!==this.realm.PerformanceObserver?(this.config.captureResources&&this.setupResourceObserver(),this.config.captureNavigation&&this.setupNavigationObserver(),this.logger.log("PerformanceResourceObserver setup complete",{captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation})):this.logger.warn("PerformanceObserver not supported in this browser")}setupResourceObserver(){try{this.resourceObserver=new this.realm.PerformanceObserver(S=>{for(const b of S.getEntries())this.processResourceEntry(b)}),this.resourceObserver.observe({type:"resource",buffered:!0}),this.logger.log("Resource observer initialized")}catch(S){this.logger.warn("Failed to setup resource observer:",S.message)}}setupNavigationObserver(){try{this.navigationObserver=new this.realm.PerformanceObserver(S=>{for(const b of S.getEntries())this.processNavigationEntry(b)}),this.navigationObserver.observe({type:"navigation",buffered:!0}),this.logger.log("Navigation observer initialized")}catch(S){this.logger.warn("Failed to setup navigation observer:",S.message)}}processResourceEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(this.sessionResourceCount>=this.config.maxResourceEntriesPerSession)return void(this.sessionCapReached||(this.sessionCapReached=!0,this.logger.warn(`Session resource cap reached (${this.config.maxResourceEntriesPerSession}). Stopping resource capture.`)));if(!this.checkRateLimit())return;const b=S.initiatorType;if("fetch"===b||"xmlhttprequest"===b)return;if(this.config.filterOtherInitiator&&"other"===b){const b=(S.transferSize||S.encodedBodySize||S.decodedBodySize)>0,I=S.duration>10;if(!b&&!I)return}if(!this.passesUrlFilters(S.name))return;const I=`${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(I))return;this.processedEntries.add(I);const x=this.sanitizeUrl(S.name),R=this.mapInitiatorType(b,S.name),A=this.extractTimingPhases(S),_={interceptor:"performance",method:"GET",url:x,status:this.getResponseStatus(S),resourceType:R,initiatorType:b,duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:A,timestamp:Math.round((this.realm?.performance?.timeOrigin||0)+S.startTime)};this.addToSessionReplay("network_resource",_)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured resource:",{url:x.substring(0,80),type:R,duration:_.duration,cached:_.cached,sessionCount:this.sessionResourceCount})}processNavigationEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(!this.checkRateLimit())return;const b=`nav-${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(b))return;this.processedEntries.add(b);const I=this.sanitizeUrl(S.name),x=this.extractTimingPhases(S),R={dns:x.dns,tcp:x.tcp,ssl:x.ssl,ttfb:Math.round(S.responseStart-S.requestStart),download:Math.round(S.responseEnd-S.responseStart),domInteractive:Math.round(S.domInteractive-S.responseEnd),domContentLoaded:Math.round(S.domContentLoadedEventEnd-S.responseEnd),loadComplete:Math.round(S.loadEventEnd-S.startTime)},A={interceptor:"performance",method:"GET",url:I,status:this.getResponseStatus(S),resourceType:"document",initiatorType:"navigation",duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:R,navigationType:S.type,timestamp:Math.round((this.realm?.performance?.timeOrigin||0)+S.startTime)};this.addToSessionReplay("network_resource",A)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured navigation:",{url:I.substring(0,80),type:S.type,loadTime:R.loadComplete,sessionCount:this.sessionResourceCount})}sanitizeUrl(S){if(!S)return S;try{const b=new URL(S);for(const S of it){b.searchParams.has(S)&&b.searchParams.delete(S);for(const[I]of b.searchParams.entries())I.toLowerCase()===S.toLowerCase()&&b.searchParams.delete(I)}return b.hash="",b.toString()}catch(b){return S.length>500?S.substring(0,500):S}}mapInitiatorType(S,b=""){const I={script:"script",link:"stylesheet",css:"stylesheet",img:"image",image:"image",font:"font",video:"media",audio:"media",iframe:"document",navigation:"document",beacon:"beacon"};if(I[S]){if("link"===S){const S=b.toLowerCase();return S.includes(".css")?"stylesheet":S.includes(".woff")||S.includes(".ttf")||S.includes(".eot")?"font":"stylesheet"}return I[S]}return getResourceType(b,"")}extractTimingPhases(S){return{dns:Math.max(0,Math.round(S.domainLookupEnd-S.domainLookupStart)),tcp:Math.max(0,Math.round(S.connectEnd-S.connectStart)),ssl:S.secureConnectionStart>0?Math.max(0,Math.round(S.connectEnd-S.secureConnectionStart)):0,ttfb:Math.max(0,Math.round(S.responseStart-S.requestStart)),download:Math.max(0,Math.round(S.responseEnd-S.responseStart)),total:Math.round(S.duration)}}getResponseStatus(S){return"number"==typeof S.responseStatus?S.responseStatus:0===S.duration&&0===S.transferSize&&0===S.decodedBodySize?0:200}isCached(S){return 0===S.transferSize&&S.decodedBodySize>0||S.domainLookupEnd===S.domainLookupStart&&S.connectEnd===S.connectStart&&S.requestStart>0}checkRateLimit(){const S=Date.now();return S-this.eventCountResetTime>6e4&&(this.eventCount=0,this.eventCountResetTime=S),!(this.eventCount>=this.maxEventsPerMinute)&&(this.eventCount++,!0)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}updateConfig(S){void 0!==S.captureResources&&S.captureResources!==this.config.captureResources&&(this.config.captureResources=S.captureResources,S.captureResources&&!this.resourceObserver?this.setupResourceObserver():!S.captureResources&&this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null)),void 0!==S.captureNavigation&&S.captureNavigation!==this.config.captureNavigation&&(this.config.captureNavigation=S.captureNavigation,S.captureNavigation&&!this.navigationObserver?this.setupNavigationObserver():!S.captureNavigation&&this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null)),void 0!==S.debug&&(this.config.debug=S.debug),void 0!==S.maxDedupeEntries&&(this.config.maxDedupeEntries=S.maxDedupeEntries),void 0!==S.filterOtherInitiator&&(this.config.filterOtherInitiator=S.filterOtherInitiator)}getStats(){return{dedupeEntriesCount:this.processedEntries.size,maxDedupeEntries:this.config.maxDedupeEntries,eventsThisMinute:this.eventCount,maxEventsPerMinute:this.maxEventsPerMinute,captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation,resourceObserverActive:!!this.resourceObserver,navigationObserverActive:!!this.navigationObserver,sessionResourceCount:this.sessionResourceCount,maxResourceEntriesPerSession:this.config.maxResourceEntriesPerSession,sessionCapReached:this.sessionCapReached,hasAllowlist:!!this.allowlistRegexes,hasBlocklist:!!this.blocklistRegexes}}destroy(){this.isDestroyed?this.logger.warn("PerformanceResourceObserver already destroyed"):(this.isDestroyed=!0,this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null),this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null),this.processedEntries.clear(),this.reporter=null,this.logger.log("PerformanceResourceObserver destroyed"))}}class ErrorFingerprint{constructor(S={}){this.maxUniqueErrors=S.maxUniqueErrors||100,this.throttleWindow=S.throttleWindow||6e4,this.maxPerFingerprint=S.maxPerFingerprint||5,this.seenFingerprints=new Map,this.cleanupInterval=null,this.startCleanup()}generateFingerprint(S){if(!S)return"unknown_error";return`${this.getErrorName(S)}::${this.normalizeMessage(this.getErrorMessage(S))}::${this.getFirstMeaningfulStackLine(S.stack)}`}getErrorName(S){return S.name?S.name:S.constructor&&S.constructor.name?S.constructor.name:S.type?S.type:"Error"}getErrorMessage(S){return"string"==typeof S?S:S.message?S.message:S.reason?String(S.reason):String(S)}normalizeMessage(S){return S&&"string"==typeof S?S.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"[UUID]").replace(/\b(0x)?[0-9a-f]{8,}\b/gi,"[HEX]").replace(/\b\d+\b/g,"[N]").replace(/https?:\/\/[^\s'"]+/gi,"[URL]").replace(/\/[\w./-]+\.(js|ts|jsx|tsx|mjs|cjs)/gi,"[PATH]").replace(/"[^"]*"/g,"[STR]").replace(/'[^']*'/g,"[STR]").replace(/[\w.+-]+@[\w.-]+\.\w+/gi,"[EMAIL]").replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,"[IP]").replace(/\s+/g," ").substring(0,200).trim():""}getFirstMeaningfulStackLine(S){if(!S||"string"!=typeof S)return"unknown";const b=[/tracescout/i,/rrweb/i,/node_modules/,/<anonymous>/,/native code/i,/eval at/i,/^\s*at\s*$/],I=S.split("\n");for(const S of I){if(!S.trim()||S.match(/^[\w]*Error:/))continue;if(b.some(b=>b.test(S)))continue;const I=S.match(/(?:at\s+)?(?:[\w.<>[\]]+\s+\()?([^()\s]+):(\d+):(\d+)\)?/);if(I){const[,S,b,x]=I;return`${S.split("/").pop().split("\\").pop()}:${b}:${x}`}const x=S.match(/@([^@]+):(\d+):(\d+)/);if(x){const[,S,b,I]=x;return`${S.split("/").pop().split("\\").pop()}:${b}:${I}`}}return"unknown"}shouldCapture(S){const b=Date.now(),I=this.seenFingerprints.get(S);if(!I)return this.seenFingerprints.set(S,{count:1,firstSeen:b,lastSeen:b,windowStart:b}),this.seenFingerprints.size>this.maxUniqueErrors&&this.evictOldest(),{shouldCapture:!0,count:1,isFirst:!0};if(b-I.windowStart>this.throttleWindow)return I.count=1,I.windowStart=b,I.lastSeen=b,{shouldCapture:!0,count:1,isFirst:!1};I.count++,I.lastSeen=b;const x=I.count<=this.maxPerFingerprint;return{shouldCapture:x,count:I.count,isFirst:!1,throttled:!x}}getStats(S){return this.seenFingerprints.get(S)||null}getAllStats(){const S=[];return this.seenFingerprints.forEach((b,I)=>{S.push({fingerprint:I,...b})}),S.sort((S,b)=>b.count-S.count)}evictOldest(){let S=null,b=1/0;this.seenFingerprints.forEach((I,x)=>{I.lastSeen<b&&(b=I.lastSeen,S=x)}),S&&this.seenFingerprints.delete(S)}startCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanup()},3e5)}cleanup(){const S=Date.now(),b=2*this.throttleWindow;this.seenFingerprints.forEach((I,x)=>{S-I.lastSeen>b&&this.seenFingerprints.delete(x)})}reset(){this.seenFingerprints.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.seenFingerprints.clear()}}class ErrorHandler{constructor(S,b={},I=null,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),this.config={captureErrors:!1!==b.captureErrors,captureUnhandledRejections:!1!==b.captureUnhandledRejections,maxStackTraceLength:b.maxStackTraceLength||5e3,filterErrors:b.filterErrors||[],enableFingerprinting:!1!==b.enableFingerprinting,maxUniqueErrors:b.maxUniqueErrors||100,throttleWindow:b.throttleWindow||6e4,maxPerFingerprint:b.maxPerFingerprint||5,...b},this.logger=createLogger("ErrorHandler"),this.originalHandlers={},this.installed=!1,this.config.enableFingerprinting&&(this.fingerprinter=new ErrorFingerprint({maxUniqueErrors:this.config.maxUniqueErrors,throttleWindow:this.config.throttleWindow,maxPerFingerprint:this.config.maxPerFingerprint}))}install(){if(this.installed)return;const S=this.realm;this.config.captureErrors&&(this.originalHandlers.onerror=S.onerror,S.onerror=this.handleError.bind(this)),this.config.captureUnhandledRejections&&(this.originalHandlers.onunhandledrejection=S.onunhandledrejection,this._boundRejectionHandler=this.handleUnhandledRejection.bind(this),S.addEventListener("unhandledrejection",this._boundRejectionHandler)),this.installed=!0,this.logger.debug("Error handler installed")}uninstall(){if(!this.installed)return;const S=this.realm;this.config.captureErrors&&(S.onerror=this.originalHandlers.onerror||null),this.config.captureUnhandledRejections&&(this._boundRejectionHandler&&(S.removeEventListener("unhandledrejection",this._boundRejectionHandler),this._boundRejectionHandler=null),this.originalHandlers.onunhandledrejection&&(S.onunhandledrejection=this.originalHandlers.onunhandledrejection)),this.fingerprinter&&this.fingerprinter.destroy(),this.originalHandlers={},this.installed=!1,this.logger.debug("Error handler uninstalled")}handleError(S,b,I,x,R){try{if(this.shouldFilterError(S,R))return;let A=null,_=null;if(this.fingerprinter&&(A=this.fingerprinter.generateFingerprint(R||{message:S,stack:`at ${b}:${I}:${x}`}),_=this.fingerprinter.shouldCapture(A),!_.shouldCapture))return _.count===this.config.maxPerFingerprint+1&&this.logger.debug(`Error throttled: "${S.substring(0,50)}..." (${_.count} occurrences)`),this.originalHandlers.onerror?this.originalHandlers.onerror(S,b,I,x,R):void 0;SDKContext.getInstance()?.recordError();const D={type:"error",category:"error",message:String(S),source:b,lineno:I,colno:x,stack:this.getStackTrace(R),timestamp:Date.now(),userAgent:this.realm?.navigator?.userAgent,url:this.realm?.location?.href,fingerprint:A,occurrenceCount:_?.count||1,isFirstOccurrence:_?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",D),console.log("[TraceScout][ErrorHandler] Checking reporter:",{hasReporter:!!this.reporter,hasMethod:!(!this.reporter||!this.reporter.addSessionCustomEvent),isFunction:!(!this.reporter||"function"!=typeof this.reporter.addSessionCustomEvent)}),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{console.log("[TraceScout][ErrorHandler] Adding error to session replay:",D.message),this.reporter.addSessionCustomEvent("error",{message:D.message,stack:D.stack,fingerprint:D.fingerprint,source:D.source,lineno:D.lineno,colno:D.colno,timestamp:D.timestamp,url:D.url,userAgent:D.userAgent,occurrenceCount:D.occurrenceCount,isFirstOccurrence:D.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture error:",S)}if(this.originalHandlers.onerror)return this.originalHandlers.onerror(S,b,I,x,R)}handleUnhandledRejection(S){try{const b=S.reason;let I=null,x=null;if(this.fingerprinter&&(I=this.fingerprinter.generateFingerprint(b||{message:"Unhandled Promise Rejection"}),x=this.fingerprinter.shouldCapture(I),!x.shouldCapture)){if(x.count===this.config.maxPerFingerprint+1){const S=b?String(b).substring(0,50):"Promise rejection";this.logger.debug(`Promise rejection throttled: "${S}..." (${x.count} occurrences)`)}return void(this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S))}SDKContext.getInstance()?.recordError();const R={type:"unhandledRejection",category:"error",message:b?String(b):"Unhandled Promise Rejection",stack:this.getStackTrace(b),promiseState:"rejected",timestamp:Date.now(),userAgent:this.realm?.navigator?.userAgent,url:this.realm?.location?.href,fingerprint:I,occurrenceCount:x?.count||1,isFirstOccurrence:x?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",R),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{this.reporter.addSessionCustomEvent("unhandledRejection",{message:R.message,stack:R.stack,fingerprint:R.fingerprint,timestamp:R.timestamp,url:R.url,userAgent:R.userAgent,occurrenceCount:R.occurrenceCount,isFirstOccurrence:R.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture unhandled rejection:",S)}this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S)}shouldFilterError(S,b){return this.config.filterErrors.some(I=>"string"==typeof I?S.includes(I):I instanceof RegExp?I.test(S):"function"==typeof I&&I(S,b))}getStackTrace(S){if(!S)return"";let b="";return S.stack?b=S.stack:S instanceof Error&&(b=S.toString()),b.length>this.config.maxStackTraceLength&&(b=b.substring(0,this.config.maxStackTraceLength)+"..."),b}getErrorStats(){return this.fingerprinter?this.fingerprinter.getAllStats():[]}resetErrorTracking(){this.fingerprinter&&this.fingerprinter.reset()}}function initializeErrorHandler(S,b={}){const I=new ErrorHandler(S,b);return I.install(),I}class PostMessageInterceptor{constructor(S){this.reporter=S,this.logger=createLogger("PostMessageInterceptor"),this.originalPostMessage=window.postMessage,this.boundMessageHandler=this.handleMessage.bind(this),this.messageCounter=0,this.suspiciousOrigins=[],this.errorCount=0,this.isDestroyed=!1,this.config=null,this.whitelist=[]}setup(){if(this.isDestroyed)return void this.logger.warn("Attempted to setup destroyed PostMessageMonitor");this.logger.log("Initializing PostMessage monitor...");const S=this;this.config=this.reporter.config?.monitorPostMessages||{},this.whitelist=this.config.postMessageOriginWhitelist||[],window.postMessage=function(b,I,...x){const R=window.location.origin;if(S.shouldMonitor(I,"outgoing",b)){const x=S.getEventType(b);S.logger.log(`Outgoing PostMessage [${x}]: ${R} -> ${I}`),S.logPostMessage({direction:"outgoing",message:b,targetOrigin:I,sourceOrigin:R,eventType:x})}return S.originalPostMessage.call(this,b,I,...x)},window.addEventListener("message",this.boundMessageHandler),this.logger.log("PostMessage monitor setup complete")}handleMessage(S){if(!this.isDestroyed)try{if(this.shouldMonitor(S.origin,"incoming",S.data)){const b=this.getEventType(S.data);this.logger.log(`Incoming PostMessage [${b}]: ${S.origin} -> ${window.location.origin}`),this.logPostMessage({direction:"incoming",message:S.data,sourceOrigin:S.origin,targetOrigin:window.location.origin,source:this.getSourceInfo(S.source),eventType:b}),this.shouldExtractFields("postmessage","message")&&this.extractUserData(S.origin,S.data)}}catch(b){this.logger.error("Error handling message:",b),this.logPostMessageError(S,b)}}shouldMonitor(S,b,I){if(!this.config||"object"!=typeof this.config)return!1;if(this.whitelist.length>0&&!this.isOriginWhitelisted(S))return!1;const x=this.getEventType(I),R=(this.config.excludePostMessagesEvents||[]).includes(x),A=this.config.monitorSpecificPostMessagesEvents||[];return!R&&(0===A.length||A.includes(x))}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isOriginWhitelisted(S){if(this.whitelist.includes("*"))return!0;if("null"===S&&this.whitelist.includes("null"))return!0;try{const b=new URL(S).hostname.toLowerCase();return this.whitelist.some(I=>{const x=I.toLowerCase();return x.includes("://")?S.toLowerCase()===x:b===x||b.endsWith(`.${x}`)})}catch{return this.whitelist.includes(S)}}getEventType(S){if(null==S)return"null_message";let b=S;if("string"==typeof S)try{b=JSON.parse(S)}catch{return"string_message"}if("object"!=typeof b)return typeof b+"_message";const I=["event_type","type","action","event","command","method"];for(const S of I)if(b[S])return String(b[S]);return!0===b.init?"init":!0===b.ready?"ready":b.resize?"resize":void 0!==b.height?"height_update":"object_message"}getSourceInfo(S){try{return S===window?"same-window":S===window.parent?"parent-window":S===window.opener?"opener-window":S===window.top?"top-window":S instanceof Window?"other-window":S instanceof MessagePort?"message-port":S instanceof ServiceWorker?"service-worker":"unknown-source"}catch{return"unknown-source"}}logPostMessage(S){const b=this.parseMessage(S.message),I=S.sourceOrigin!==S.targetOrigin,x=this.getSize(S.message),R=x>1e4,A=this.isSuspiciousOrigin(S.sourceOrigin);let _="postmessage_communication";I&&(_="postmessage_cross_origin"),R&&(_="postmessage_large_payload"),A&&(_="postmessage_suspicious_origin",this.trackSuspiciousOrigin(S.sourceOrigin));const D={type:_,request:{method:"POSTMESSAGE",url:"outgoing"===S.direction?S.targetOrigin:S.sourceOrigin,domain:this.getDomain("outgoing"===S.direction?S.targetOrigin:S.sourceOrigin),path:null,status:null,statusText:null,response:b,interceptor:"postMessage"},extraData:{messageId:`pm_${S.direction}_${Date.now()}_${++this.messageCounter}`,direction:S.direction,sourceOrigin:S.sourceOrigin,targetOrigin:S.targetOrigin,messageSize:x,messageType:typeof S.message,detectedEventType:S.eventType,source:S.source||"unknown",isCrossOrigin:I,isLargePayload:R,isSuspicious:A,hasTransferables:S.transferables?.length>0||!1},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(D)}logPostMessageError(S,b){const I={type:"postmessage_error",request:{method:"POSTMESSAGE",url:S?.origin||"unknown",domain:this.getDomain(S?.origin||"unknown"),path:null,status:0,statusText:"PostMessage Error",response:{error:b.message,stack:b.stack},interceptor:"postMessage"},extraData:{errorCount:++this.errorCount,sourceOrigin:S?.origin||"unknown",targetOrigin:window.location.origin,errorType:b.name||"Error",errorMessage:b.message,errorStack:b.stack},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(I)}logEvent(S){this.reporter&&this.reporter.logEvent?this.reporter.logEvent(S):this.logger.error("Could not log event - reporter.logEvent not available")}parseMessage(S){if("string"==typeof S)try{return JSON.parse(S)}catch{return S.length>1e3?S.substring(0,1e3)+"...":S}try{return JSON.stringify(S),S}catch{return"[Circular or Complex Object]"}}getSize(S){try{return"string"==typeof S?S.length:JSON.stringify(S).length}catch{return-1}}getDomain(S){try{return"*"===S||"null"===S||"file://"===S?S:new URL(S).hostname}catch{return"unknown"}}isSuspiciousOrigin(S){if(!S||"null"===S||"file://"===S)return!0;if(this.whitelist.length>0&&!this.whitelist.includes("*")&&!this.isOriginWhitelisted(S))return!0;if("https:"===window.location.protocol&&"https://localhost"!==S&&!S.startsWith("https://"))return!0;const b=this.suspiciousOrigins.filter(b=>b===S).length;return b>100}trackSuspiciousOrigin(S){this.suspiciousOrigins.push(S),this.suspiciousOrigins.length>1e3&&(this.suspiciousOrigins=this.suspiciousOrigins.slice(-1e3))}extractUserData(S,b){try{const I=this.parseMessage(b);I&&"object"==typeof I&&this.reporter.updateUserProfileFromContext&&this.reporter.updateUserProfileFromContext({url:`postmessage://${S}`,source:"message",data:I})}catch(S){this.logger.warn("Failed to extract user data:",S)}}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}destroy(){this.isDestroyed?this.logger.warn("PostMessageMonitor already destroyed"):(this.isDestroyed=!0,this.originalPostMessage&&(window.postMessage=this.originalPostMessage),window.removeEventListener("message",this.boundMessageHandler),this.reporter=null,this.boundMessageHandler=null,this.suspiciousOrigins=[],this.logger.log("PostMessage monitor destroyed"))}}const ot="ts-top";class IframeInstrumentationManager{#ye=null;#Pe=null;#o=null;#j=null;#Nt=Symbol("__tsIframeInstalled__");#te=!1;#Lt=new Map;#Pt=[];#Bt=[];#Y=new WeakSet;#K=new WeakMap;#zt=new Map;#J=0;#Ut=0;#O={installs:0,teardowns:0,reentrySkips:0,inaccessible:0,installErrors:0};#$t=[];constructor({core:S,config:b,logger:I,topWindow:x}={}){this.#ye=S,this.#Pe=b||S?.config||{},this.#o=I||null,this.#j=x||("undefined"!=typeof window?window:void 0)}get isStarted(){return this.#te}start(){if(this.#te)return!0;if(!this.#j)return!1;try{this.#te=!0,this.#jt();const S=this.#j.document;return this.#qt(S,this.#j,ot,1),this.#Wt(S,this.#j,ot,1,null),!0}catch(S){return this.#F("start failed (fail-closed):",S),!0}}shutdown(){try{for(const S of Array.from(this.#Lt.values()))this.#Ht(S,"disconnected");this.#Lt.clear();for(const S of this.#Bt)try{S.mo.disconnect()}catch(S){}this.#Bt.length=0,this.#Pt.length=0}catch(S){this.#F("shutdown error (fail-closed):",S)}finally{this.#te=!1;try{this.#ye?.setIframeTopFrameContext?.(null)}catch(S){}}}#qt(S,b,I,x){if(!S)return;let R=null;try{R=S.querySelectorAll("iframe")}catch(S){R=null}R&&R.forEach(S=>{this.#ie(S,I,x),this.#Vt(S,I,x)});try{const S=b&&b.frames,R=S?S.length:0;for(let b=0;b<R;b++){let R=null;try{R=S[b]&&S[b].frameElement}catch(S){R=null}R&&"IFRAME"===R.tagName&&!this.#K.has(R)&&(this.#ie(R,I,x),this.#Vt(R,I,x))}}catch(S){}}#ie(S,b,I){if(!this.#Y.has(S)){this.#Y.add(S);try{S.addEventListener("load",()=>{try{this.#Vt(S,b,I)}catch(S){this.#F("load-reinstall failed (fail-closed):",S)}})}catch(S){this.#F("hookLoad failed (fail-closed):",S)}}}#Vt(S,b,I){let x=null;try{x=S.contentWindow}catch(S){x=null}x&&this.#Qt(S,x,b,I)}#he(S){let b=this.#K.get(S);return b||(b="ts-frame-"+ ++this.#J,this.#K.set(S,b)),b}#Qt(S,b,I,x){try{const b=S.getAttribute&&S.getAttribute("src");if(b){const I=new URL(b,"undefined"!=typeof location&&location.href||void 0);if(("http:"===I.protocol||"https:"===I.protocol)&&"undefined"!=typeof location&&I.origin!==location.origin)return this.#O.inaccessible++,this.#Gt("inaccessible",{frameId:this.#he(S),depth:x,reason:"cross-origin-src"}),null}}catch(S){}let R;try{if(R=b.document,!R)throw new Error("no document")}catch(b){return this.#O.inaccessible++,this.#Gt("inaccessible",{frameId:this.#he(S),depth:x}),null}const A=this.#he(S),_=b[this.#Nt];if(_&&null!=_.realmEpoch)return this.#O.reentrySkips++,this.#Gt("reentry-skip",{frameId:A,realmEpoch:_.realmEpoch}),_;const D=this.#Lt.get(A);if(D&&D.win!==b){const S="reloaded"===this.#Kt(A,this.#Jt(b))?"reloaded":"navigated";this.#Ht(D,S)}const L=++this.#Ut,B=this.#Xt(b),U=this.#Jt(b),$=this.#Kt(A,U),j=this.#Yt(),W={frameId:A,frameInstanceId:`${A}-r${L}`,parentFrameId:I,topFrameId:ot,frameDepth:x,frameOrigin:B,frameUrl:U,frameLifecycle:$,privacyStatus:j,realmEpoch:L,win:b,el:S,seq:0,interceptors:[],observerRef:null};try{Object.defineProperty(b,this.#Nt,{value:W,configurable:!0,enumerable:!1,writable:!0})}catch(S){return null}const H=this.#Zt(W),V=this.#Pe||{};let Q=!1;try{this.#es(W,()=>{const S=new FetchInterceptor(H,b);return S.setup(),S}),this.#es(W,()=>{const S=new XHRInterceptor(H,b);return S.setup(),S}),this.#es(W,()=>{const S=new ConsoleInterceptor(null,V,H,b);return S.install(),S}),this.#es(W,()=>{const S=new ErrorHandler(null,V,H,b);return S.install(),S}),this.#es(W,()=>{const S=new PerformanceResourceObserver(H,{captureResources:!1!==V.captureResources,captureNavigation:!1!==V.captureNavigation,debug:!!V.debug,maxResourceEntriesPerSession:V.maxResourceEntriesPerSession||2e3},b);return S.setup(),S}),Q=W.interceptors.length>0}catch(S){return this.#O.installErrors++,this.#F("install block failed (fail-closed):",S),this.#Ht(W,"blocked"),null}if(!Q){try{delete b[this.#Nt]}catch(S){}return null}this.#O.installs++,this.#ts(A,U),this.#Lt.set(A,W),this.#ss(A,b),this.#Gt("install",{frameId:A,parentFrameId:I,depth:x,realmEpoch:L,frameLifecycle:$});try{this.#qt(R,b,A,x+1)}catch(S){this.#F("nested scan failed:",S)}return this.#Wt(R,b,A,x+1,W),W}#es(S,b){try{const I=b();I&&S.interceptors.push(I)}catch(S){this.#O.installErrors++,this.#F("interceptor install failed (fail-closed):",S)}}#Zt(S){const b=this.#ye,stamp=(b,I)=>this.#rs(S,b,I);return new Proxy(b,{get(S,b){if("addSessionCustomEvent"===b)return stamp;const I=Reflect.get(S,b,S);return"function"==typeof I?I.bind(S):I}})}#rs(S,b,I){try{const x=I&&"object"==typeof I?I:{},R="number"==typeof x.timestamp?x.timestamp:Date.now(),A=Object.assign({},x,{frameId:S.frameId,topFrameId:S.topFrameId,frameInstanceId:S.frameInstanceId,frameDepth:S.frameDepth,frameOrigin:S.frameOrigin,frameUrl:S.frameUrl,frameLifecycle:S.frameLifecycle,captureRealm:"iframe",privacyStatus:S.privacyStatus,localSequence:S.seq++,tsLocal:R,tsNormalized:R});return null!=S.parentFrameId&&(A.parentFrameId=S.parentFrameId),this.#ye.addSessionCustomEvent(b,A)}catch(S){return this.#F("stamp/emit failed (fail-closed):",S),!1}}#Wt(S,b,I,x,R){try{const A=b.MutationObserver;if(!A)return;const _=new A(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S,I,x)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation handler failed (fail-closed):",S)}});_.observe(S.documentElement||S,{childList:!0,subtree:!0});const D={mo:_,win:b};this.#Bt.push(D),R&&(R.observerRef=()=>{try{_.disconnect()}catch(S){}const S=this.#Bt.indexOf(D);S>=0&&this.#Bt.splice(S,1)})}catch(S){this.#F("observeDocument failed (fail-closed):",S)}}#ae(S,b,I){if(!S||1!==S.nodeType)return;const attach=S=>{this.#ie(S,b,I),this.#Vt(S,b,I)};if("IFRAME"===S.tagName&&attach(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(attach)}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#K.get(S);if(!b)return;if(S.isConnected)return;const I=this.#Lt.get(b);I&&this.#Ht(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#Ht(S,b){for(const b of S.interceptors)try{"function"==typeof b.destroy?b.destroy():"function"==typeof b.uninstall&&b.uninstall()}catch(S){this.#F("interceptor teardown failed (fail-closed):",S)}if(S.interceptors=[],"function"==typeof S.observerRef){try{S.observerRef()}catch(S){}S.observerRef=null}this.#Lt.delete(S.frameId);try{delete S.win[this.#Nt]}catch(S){}if(this.#ns(S.frameId),"detached"===b){const b=this.#zt.get(S.frameId);b&&(b.detached=!0)}S.win=null,S.el=null,this.#O.teardowns++,this.#Gt("teardown",{frameId:S.frameId,reason:b})}#jt(){const S=this.#j;try{this.#ye?.setIframeTopFrameContext?.({frameId:ot,frameInstanceId:`${ot}-r0`,topFrameId:ot,frameOrigin:this.#Xt(S),frameUrl:this.#Jt(S),frameLifecycle:"attached",privacyStatus:this.#Yt()})}catch(S){this.#F("registerTopFrameContext failed (fail-closed):",S)}}#Xt(S){try{const b=S.location&&S.location.origin;if("string"==typeof b&&b)return b.slice(0,256)}catch(S){}}#Jt(S){try{const b=S.location&&S.location.href;if("string"!=typeof b||!b)return;const{url:I}=splitSanitizedUrl(b,{});return(I||b).slice(0,2048)}catch(S){return}}#Yt(){try{const S=SDKContext.getInstance()?.domPrivacy;if("confirmed"===S||"partial"===S||"disabled"===S)return S}catch(S){}return"unknown"}#Kt(S,b){const I=this.#zt.get(S);return I&&I.everInstalled?I.detached?"reattached":null!=I.lastUrl&&null!=b&&I.lastUrl===b?"reloaded":"navigated":"attached"}#ts(S,b){const I=this.#zt.get(S)||{};I.everInstalled=!0,I.detached=!1,I.lastUrl=b,this.#zt.set(S,I)}#ss(S,b){const I=this.#Pt.find(b=>b.frameId===S);I?I.win=b:this.#Pt.push({frameId:S,win:b})}#ns(S){for(let b=this.#Pt.length-1;b>=0;b--)this.#Pt[b].frameId===S&&(this.#Pt[b].win=null,this.#Pt.splice(b,1))}getStats(){return{active:this.#Lt.size,allRealms:this.#Pt.length,observers:this.#Bt.length,...this.#O}}getInstallLog(){return this.#$t.slice()}verifyRestored(){return this.#is().map(S=>{const b={frameId:S.frameId,alive:!1},I=S.win;if(!I)return b;try{b.alive=!0,b.fetchRestored=!(I.fetch&&I.fetch.__tsPoCWrapped),b.consoleRestored="function"==typeof I.console.log}catch(S){b.error=S&&S.name}return b})}#is(){const S=[];for(const b of this.#Lt.values())S.push({frameId:b.frameId,win:b.win});for(const b of this.#Pt)S.some(S=>S.frameId===b.frameId)||S.push(b);return S}#Gt(S,b){this.#$t.push(Object.assign({ev:S,t:Date.now()},b))}#F(...S){try{this.#Pe?.debug&&this.#o?.warn&&this.#o.warn("[IframeInstrumentation]",...S)}catch(S){}}}class InterceptorFeature{#o=null;#Pe=null;#os=null;#as=null;#ls=null;#cs=null;#je=!1;constructor({logger:S,config:b,monitoringCore:I,eventManager:x}){this.#o=S,this.#Pe=b,this.#os=I,this.#as=x}initialize(S,b=null){try{this.#ls={};return S&&S.isRecording?(console.log("[TraceScout] 🔌 Setting up session recording interceptors bundle..."),this.#us(),this.#hs(),this.#ds(),this.#gs(b),this.#ps(),this.#fs(),this.#ms(),console.log("[TraceScout] ✅ Session recording bundle complete (DOM + Network + Console + Errors)"),this.#o?.log("Interceptors setup complete"),this.#je=!0,!0):(console.log("[TraceScout] ⏭️ Interceptors skipped (bundled with session recording - not active)"),!1)}catch(S){return this.#o?.error("Failed to setup interceptors:",S),!1}}#us(){console.log("[TraceScout] 📡 Setting up FetchInterceptor..."),this.#ls.fetch=new FetchInterceptor(this.#os),this.#ls.fetch.setup?.()||this.#ls.fetch.install?.(),console.log("[TraceScout] ✅ FetchInterceptor active")}#hs(){console.log("[TraceScout] 📡 Setting up XHRInterceptor..."),this.#ls.xhr=new XHRInterceptor(this.#os),this.#ls.xhr.setup?.()||this.#ls.xhr.install?.(),console.log("[TraceScout] ✅ XHRInterceptor active")}#ds(){const S=!1!==this.#Pe?.captureResources,b=!1!==this.#Pe?.captureNavigation;if(S||b)try{console.log("[TraceScout] 📊 Setting up PerformanceResourceObserver...",{captureResources:S,captureNavigation:b,maxResourceEntriesPerSession:this.#Pe?.maxResourceEntriesPerSession||2e3}),this.#ls.performanceResource=new PerformanceResourceObserver(this.#os,{captureResources:S,captureNavigation:b,debug:this.#Pe?.debug||!1,maxDedupeEntries:this.#Pe?.maxDedupeEntries||5e3,filterOtherInitiator:!1!==this.#Pe?.filterOtherInitiator,maxResourceEntriesPerSession:this.#Pe?.maxResourceEntriesPerSession||2e3,resourceAllowlist:this.#Pe?.resourceAllowlist||null,resourceBlocklist:this.#Pe?.resourceBlocklist||null}),this.#ls.performanceResource.setup(),console.log("[TraceScout] ✅ PerformanceResourceObserver active")}catch(S){console.warn("[TraceScout] ⚠️ PerformanceResourceObserver setup failed:",S.message)}else console.log("[TraceScout] ⏭️ PerformanceResourceObserver disabled via config")}#gs(S){console.log("[TraceScout] 💬 Setting up ConsoleInterceptor..."),this.#ls.console=new ConsoleInterceptor(this.#as,this.#Pe,this.#os),S&&this.#ls.console.setLogManager(S),this.#ls.console.install?.(),console.log("[TraceScout] ✅ ConsoleInterceptor active")}#ps(){try{console.log("[TraceScout] 🚨 Setting up ErrorHandler..."),this.#ls.errors=new ErrorHandler(this.#as,this.#Pe,this.#os),console.log("[TraceScout] ErrorHandler created, installing...",{hasInstall:"function"==typeof this.#ls.errors?.install,hasReporter:!!this.#os}),this.#ls.errors.install?.(),console.log("[TraceScout] ✅ ErrorHandler active")}catch(S){console.error("[TraceScout] ❌ ErrorHandler setup failed:",S)}}#ms(){try{this.#cs=new IframeInstrumentationManager({core:this.#os,config:this.#Pe,logger:this.#o}),this.#cs.start(),console.log("[TraceScout] 🪟 Same-origin iframe instrumentation active")}catch(S){console.warn("[TraceScout] ⚠️ Iframe instrumentation skipped:",S?.message),this.#cs=null}}get iframeManager(){return this.#cs}#fs(){this.#Pe?.monitorPostMessages&&"object"==typeof this.#Pe.monitorPostMessages&&(this.#ls.postMessage=new PostMessageInterceptor(this.#os),this.#ls.postMessage.setup?.()||this.#ls.postMessage.install?.())}get isInitialized(){return this.#je}get interceptors(){return this.#ls}getInterceptor(S){return this.#ls?.[S]||null}updateDebugMode(S){this.#ls&&Object.values(this.#ls).forEach(b=>{b&&b.updateDebugMode&&b.updateDebugMode(S)})}destroy(){if(this.#cs){try{this.#cs.shutdown()}catch(S){}this.#cs=null}this.#ls&&(Object.values(this.#ls).forEach(S=>{S?.destroy?.()||S?.uninstall?.()}),this.#ls=null),this.#je=!1}}class EventLifecycleFeature{#o=null;#Pe=null;#ys=null;#vs=null;#Ss=null;#ws=null;#bs=null;#Cs=null;#ks=null;#Is=null;#je=!1;#Es=!1;constructor({logger:S,config:b}){this.#o=S,this.#Pe=b}setCallbacks({onCustomApiError:S,onBeforeUnload:b,onUserActivity:I,onVisibilityChange:x}){this.#bs=S,this.#Cs=b,this.#ks=I,this.#Is=x}initialize(){try{return this.#ys=this.#xs.bind(this),this.#vs=this.#Ms.bind(this),this.#Ss=this.#Rs.bind(this),this.#ws=this.#Ts.bind(this),document.addEventListener("custom-api-error",this.#ys),window.addEventListener("beforeunload",this.#vs),document.addEventListener("click",this.#Ss,{passive:!0,capture:!0}),document.addEventListener("keydown",this.#Ss,{passive:!0,capture:!0}),document.addEventListener("scroll",this.#Ss,{passive:!0,capture:!0}),document.addEventListener("visibilitychange",this.#ws),this.#o?.log("Event listeners setup complete"),this.#je=!0,!0}catch(S){return this.#o?.error("Failed to setup event listeners:",S),!1}}#xs(S){this.#bs?.(S)}#Ms(S){this.#Cs?.(S)}#Rs(){this.#Es||this.#ks?.()}#Ts(){this.#Es||("visible"===document.visibilityState?this.#Is?.("visible"):this.#Is?.("hidden"))}get isInitialized(){return this.#je}setQuotaExceeded(S){this.#Es=S,S&&this.#As()}#As(){this.#Ss&&(document.removeEventListener("click",this.#Ss,{capture:!0}),document.removeEventListener("keydown",this.#Ss,{capture:!0}),document.removeEventListener("scroll",this.#Ss,{capture:!0}),this.#Ss=null),this.#ws&&(document.removeEventListener("visibilitychange",this.#ws),this.#ws=null)}destroy(){try{document.removeEventListener("custom-api-error",this.#ys),window.removeEventListener("beforeunload",this.#vs),this.#As(),this.#ys=null,this.#vs=null,this.#je=!1}catch(S){this.#o?.error("Failed to cleanup event listeners:",S)}}}function readInjectedDebugId(){try{const S="undefined"!=typeof globalThis?globalThis.__TRACESCOUT_DEBUG_ID__:void 0;if("string"==typeof S&&/^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$/.test(S))return S}catch(S){}return null}class TraceScoutMonitoringCore{#je=!1;#o=null;#_s=null;#as=null;#Os=null;#Ds=null;#Fs=null;#Ns=null;#Le=null;#Ls=null;#Ps=null;#Bs=null;#zs=null;#ls=null;#Us=null;#$s=null;#js=null;#qs=null;#Ws=null;#Hs=null;#Vs=null;#Qs=null;#Gs=null;_consecutiveFailures=0;#Es=!1;#Ks=null;#Js=!1;#Xs=null;#Ys=0;#Zs=null;#er=null;#tr=!1;static#sr=null;static#rr=!1;constructor(){this.config=x.defaults({retryIntervalMs:x.get(A,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:x.get(A,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:x.get(A,"MAX_QUEUE_SIZE",1e3),maxRetries:x.get(A,"MAX_RETRIES",3),batchSize:x.get(A,"BATCH_SIZE",10),debug:!1,logPreflight:!1,logResourceErrors:!1},{}),this.#o=new Logger("[TraceScoutMonitoringCore]",this.config.debug),"function"!=typeof this.#o.debug&&(this.#o.debug=(...S)=>this.#o.info(...S));try{this.#_s=new ConfigManager(this.config)}catch(S){this.#o.error("Failed to initialize ConfigManager:",S)}this.appContext={appVersion:"1.0.0",environment:"unknown"},"function"==typeof this.sendEvents&&(this.#Vs=throttle$1(this.sendEvents.bind(this),1e3))}static setTransport(S){TraceScoutMonitoringCore.#rr?console.error("[TraceScout] setTransport() must be called before init()"):"object"==typeof S&&null!==S?"string"==typeof S.apiBaseUrl&&S.apiBaseUrl?TraceScoutMonitoringCore.#sr=S:console.error("[TraceScout] setTransport() requires a non-empty apiBaseUrl string"):console.error("[TraceScout] setTransport() requires an object with apiBaseUrl")}async init(S,b={}){if(this.#Js)return this.#o.warn("TraceScoutMonitoringCore already initialized"),{sampled:this.#Ks??!1,sdkVersion:"2.0.0",projectId:"",environment:""};const I=validateConfig(S,b);if(!I.ok){return function surfaceConfigError(S,b){if(b)try{console.error("[TraceScout] init() refused — invalid arguments:",S)}catch{}}(I.keys?{code:I.code,keys:I.keys}:{code:I.code},b?.debug||!1),{sampled:!1,sdkVersion:"2.0.0",projectId:"",environment:""}}this.#Js=!0,TraceScoutMonitoringCore.#rr=!0,this.#Zs=parseIframeConfig(I.options.iframe),!this.#Zs.enabled&&this.#Zs.reason&&"absent"!==this.#Zs.reason&&I.options.debug&&console.warn("[TraceScout] iframe bridge disabled (fail-closed):",this.#Zs.reason),this.#tr=this.#Zs.enabled&&("child"===this.#Zs.role||"both"===this.#Zs.role);const x=TraceScoutMonitoringCore.#sr,R={projectId:I.projectId,environment:I.options.environment||"production",release:I.options.release,dist:I.options.dist,debugId:I.options.debugId??readInjectedDebugId(),sourceName:I.options.sourceName??"web-client",debug:I.options.debug||!1,apiBaseUrl:x?.apiBaseUrl,...void 0!==I.options.network?{network:I.options.network}:{}},A=peekAnonymousId();if(this.#Ks=shouldSampleSession(1,{anonymousId:A}),!this.#Ks)return R.debug&&console.log("[TraceScout] Session not sampled — SDK will not instrument this page-load."),{sampled:!1,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment};try{R.debug&&(console.log("[TraceScout] ============================================"),console.log("[TraceScout] Initializing SDK v2.0..."),console.log("[TraceScout] ============================================"));const S=new InitializationPipeline(this.#o),I=await S.run(R);this.#Ns=I.sessionManager.sessionManager,this.#Le=I.sdkContext,this.#Ls=I.remoteConfigService,this.config=I.config,this.#Ps=R,this.#as=I.managers.eventManager,this.#Os=I.managers.serviceManager,this.#Ds=I.managers.userProfileManager,this.#Fs=I.managers.performanceMonitor,this.config.appName&&(this.appContext.appName=this.config.appName),I.serverConfig?.project?.name&&(this.appContext.appName=I.serverConfig.project.name),this.#o&&"function"==typeof this.#o.updateDebugMode&&this.#o.updateDebugMode(this.config.debug),this.#zs=new LoggingFeature({logger:this.#o,sdkContext:this.#Le,config:this.config}),this.#zs.initialize(I.serverConfig),this.#zs.configure(this.config);const x=I.serverConfig?.features?.performanceMonitoring?.enabled;if(x&&(this.#Hs=new CoreWebVitalsMonitor(this.config),console.log("[TraceScout] ✓ Performance monitoring initialized")),this.#Zs?.enabled)try{this.config.recordCrossOriginIframes=!0,this.#er=new CrossOriginIframeBridge({config:this.#Zs,core:this,projectId:this.#Le.projectId,sessionId:this.#Le.sessionId,logger:this.#o}),this.#er.start()}catch(S){this.config?.debug&&this.#o.warn?.("iframe bridge start failed (fail-closed):",S),this.#er=null}this.#Bs=new SessionRecordingFeature({logger:this.#o,sdkContext:this.#Le,config:this.config,options:{...b,childMode:this.#tr}}),this.#Bs.setCallbacks({onChunkCreated:S=>this.#Ze(S),onSessionEnd:S=>this.#nr(S),onQuotaExceeded:S=>this.#ir(S),onSpaNavigation:(S,b,I)=>{this.#js?.recordNavigation(S,b,I)}});const A=await this.#Bs.initialize(I.serverConfig,this.#Ls);if(this.#js=new PageviewManager({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Le.setPageviewManager(this.#js),this.#$s=new SessionLifecycleEmitter({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),readGuard:()=>this.#Ns?.getLifecycleGuard?.()??null,writeGuard:S=>this.#Ns?.setLifecycleGuard?.(S),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Ns&&!this.#tr&&(this.#Ns.onLifecycleEnd=({reason:S})=>{this.#$s?.emitEnd({reason:S})}),A&&this.#Hs){const S=this.#js.getCurrentPageviewId(),b="undefined"!=typeof window&&"string"==typeof window.location?.href?window.location.href:"";b&&(this.#qs=new WebVitalsEmitter({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),initialPageviewId:S,initialUrl:b,debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Hs.addCallback?.((S,b)=>{this.#qs?.emit(S,b)}),this.#Hs.metrics&&"function"==typeof this.#Hs.metrics.forEach&&this.#Hs.metrics.forEach(S=>{this.#qs?.emit(S.type,S)}))}if(A&&(this.#Ws=new TrackIdentifyEmitter({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}})),A&&!this.#tr){const S=!0===this.#Ns?.isResumedSession?.();this.#js.emitInitialPageView({isResumed:S})}return!A||this.#tr||!this.#Ns||this.#Ns.isResumedSession?.()||this.#Ns.getLifecycleGuard?.()?.sessionStartEmitted||this.#$s.emitStart({}),A?(this.#ls=new InterceptorFeature({logger:this.#o,config:this.config,monitoringCore:this,eventManager:this.#as}),this.#ls.initialize(this.#Bs.recorder,this.#zs.logManager),console.log("[TraceScout] ✓ Session recording bundle initialized (DOM + Network + Console + Errors)")):console.log("[TraceScout] ⏭️ Skipping interceptors (bundled with session recording)"),this.#Us=new EventLifecycleFeature({logger:this.#o,config:this.config}),this.#Us.setCallbacks({onCustomApiError:S=>this.#xs(S),onBeforeUnload:S=>this.#Ms(S),onUserActivity:()=>this.#Rs(),onVisibilityChange:S=>this.#Ts(S)}),this.#Us.initialize(),this.#or(),this.#as&&this.#as.loadFromLocal(),this.#Ds&&this.#Ds.ensureProfile(),this.#je=!0,this.#ar(I.serverConfig),{sampled:!0,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment}}catch(S){throw console.error("[TraceScout] ❌ Initialization failed:",S),this.#o.error("Failed to initialize TraceScoutMonitoringCore:",S),S}}#ar(S){console.log("[TraceScout] ============================================"),console.log("[TraceScout] ✅ SDK Initialized Successfully"),console.log("[TraceScout] ============================================"),console.log(` Workspace: ${S.workspace.name}`),console.log(` Project: ${S.project.name}`),console.log(` Session: ${this.#Le.sessionId}`),console.log(` Environment: ${this.#Le.environment}`),console.log(` Config Version: ${S.configVersion}`);const b=Object.keys(S.features||{}).filter(b=>S.features[b].enabled);console.log(` Features: ${b.join(", ")||"none"}`),console.log("[TraceScout] ============================================"),this.#o.info("TraceScoutMonitoringCore initialized successfully",{configSource:"server",configVersion:S.configVersion,workspace:S.workspace.name,project:S.project.name,sessionId:this.#Le.sessionId})}#lr(S,b){try{const I=Object.keys(b.features||{}).filter(S=>b.features[S].enabled);S({sessionId:this.#Le.sessionId,workspace:b.workspace.name,project:b.project.name,environment:this.#Le.environment,featuresEnabled:I,configVersion:b.configVersion})}catch(S){this.#o.error("Error in onReady callback:",S)}}#Ze(S){this.#Ns&&(this.#Ns.incrementChunkCount(),this.#Ns.incrementEventCount(S.eventCount||0))}#nr(S){if(!S||"object"!=typeof S)return;const b=mapInternalEndReason(S.reason);b&&this.#$s?.emitEnd({reason:b,totalChunks:"number"==typeof S.totalChunks?S.totalChunks:void 0,totalEvents:"number"==typeof S.totalEvents?S.totalEvents:void 0})}#xs(S){}#Ms(S){}#Rs(){this.#Es||this.#Bs?.sessionEnded&&!this.#Bs?.isRecording&&(console.log("[TraceScout] 🔄 User activity detected after session end - starting new session"),this.forceNewSession("activity_after_"+this.#Bs.sessionEndReason))}#Ts(S){this.#Es||"visible"===S&&this.#Bs?.sessionEnded&&!this.#Bs?.isRecording&&(console.log("[TraceScout] 🔄 Tab visible after session end - starting new session"),this.forceNewSession("tab_focus_after_"+this.#Bs.sessionEndReason))}#ir(S){this.#Es||(this.#Es=!0,console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been permanently stopped.","color: #ff4444;"),console.error("%c[TraceScout] Your workspace has reached its monthly session limit.","color: #ff4444;"),S?.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions (${S.usage.percentage}%)`,"color: #ff4444;"),console.error("%c[TraceScout] To continue recording, upgrade your plan at: /billing","color: #ff4444;"),this.#Us?.setQuotaExceeded(!0),this.#Bs?.stop(),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:recording_stopped",{detail:{reason:"quota_exceeded",usage:S?.usage,message:S?.message||"Session quota exceeded"}})))}#or(){"development"===this.config.environment||this.config.debug?this.#o.log("⚠️ Auto-retry DISABLED (development mode) - reduces API spam"):(this.#Qs=setInterval(()=>{this.#cr()},this.config.retryIntervalMs),this.#o.log("Auto-retry enabled (production mode)")),this.#Gs=setInterval(()=>{this.#ur()},6e4),this.#o.log("Background processes started")}#hr(){this.#Qs&&(clearInterval(this.#Qs),this.#Qs=null),this.#Gs&&(clearInterval(this.#Gs),this.#Gs=null)}async#cr(){try{if(this.#Os?.isSending)return;const S=this.#as?.getQueueSize();if(S>0){if(this._consecutiveFailures>=10)return this.#o.warn(`⛔ Stopped retrying after ${this._consecutiveFailures} consecutive failures`),this.#o.warn(`⛔ Clearing ${S} queued events to prevent infinite loop`),this.#as.clearEvents(),void(this._consecutiveFailures=0);this.#o.info(`🔄 Retrying ${S} queued events (attempt ${this._consecutiveFailures+1}/10)`);await this.sendEvents()?(this.#o.info("✅ Retry succeeded - resetting failure counter"),this._consecutiveFailures=0):(this._consecutiveFailures++,this.#o.warn(`❌ Retry failed (${this._consecutiveFailures}/10)`))}else this._consecutiveFailures>0&&(this.#o.info("✅ Queue empty - resetting failure counter"),this._consecutiveFailures=0)}catch(S){this.#o.error("Error during retry:",S),this._consecutiveFailures++}}#ur(){try{if(this.#as){const S=this.config.eventMaxAge||864e5;this.#as.cleanupOldEvents(S)}}catch(S){this.#o.error("Error during cleanup:",S)}}#dr(){return"evt_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}destroy(){if(this.#je)try{try{this.#er?.shutdown()}catch(S){}this.#er=null,this.#zs?.destroy(),this.#ls?.destroy(),this.#Bs?.destroy(),this.#Us?.destroy(),this.#hr(),this.#Ns&&this.#Ns.destroy(),this.#je=!1,this.#o.info("TraceScoutMonitoringCore destroyed successfully")}catch(S){this.#o.error("Error during destruction:",S)}}logEvent(S,b={},I={}){if(this.#je)try{let x;"object"==typeof S&&S.type?(x={id:S.id||this.#dr(),timestamp:S.timestamp||Date.now(),...S},x.context||(x.context={}),void 0===x.context.isMonitored&&(x.context.isMonitored=!0),void 0===x.context.forceLog&&(x.context.forceLog=x.type?.includes("error")||x.type?.includes("alert")||x.type?.includes("p1_incident")||"critical"===x.severity)):x={id:this.#dr(),type:S,data:b,context:{isMonitored:!0,forceLog:I.forceLog||!1,status:I.status||"success",...I.context},timestamp:Date.now()};if(this.#as.addEvent(x)){this.#o.log("Event logged:",x.type);this.#as.getQueueSize()>=this.config.batchSize&&this.sendEvents()}}catch(S){this.#o.error("Failed to log event:",S)}else this.#o.warn("TraceScoutMonitoringCore not initialized")}async sendEvents(S=null){if(!this.#Os||!this.#as)return this.#o.warn("ServiceManager or EventManager not available"),!1;try{const b=S||this.#as.getEvents();if(!b||0===b.length)return!0;this.#o.info(`📤 Attempting to send ${b.length} events`);const I=await this.#Os.sendEvents(b);this.#o.info(`📊 Send results: ${I.length} results received`);const x=I.filter(S=>S.success).map(S=>S.event.id);x.length>0&&(this.#as.removeEvents(x),this.#o.info(`✅ Successfully sent ${x.length}/${b.length} events`));const R=I.filter(S=>!S.success).length;if(R>0){this.#o.warn(`❌ Failed to send ${R}/${b.length} events - will retry`);const S=I.find(S=>!S.success);S&&S.error&&this.#o.error("First failure reason:",S.error.message||S.error)}return 0===x.length&&I.length>0&&this.#o.warn(`⚠️ 0 events succeeded out of ${b.length} - all failed`),0===R}catch(S){return this.#o.error("❌ Failed to send events:",S),!1}}clearEvents(){this.#as?(this.#as.clearEvents(),this.#o.log("Event queue cleared")):this.#o.warn("EventManager not available")}isMonitoredEndpoint(S){if("string"!=typeof S||x.isEmpty(S))return!1;try{const b=this.config.endpoints||[],I=this.config.domainsToTrack||[];if(b.includes("*")||"*"===b)return!0;const R=S.toLowerCase();let A;try{A=new URL(R)}catch{return!1}if(!x.isEmpty(I)){const S=A.hostname;if(I.some(b=>S===b.toLowerCase()||S.endsWith(`.${b.toLowerCase()}`)))return!0}const _=A.pathname;return b.some(S=>_.includes(S.toLowerCase()))}catch(S){return this.#o?.warn("Error checking monitored endpoint:",S),!1}}shouldExtractFields(S,b){return"string"==typeof S&&!x.isEmpty(S)&&(!!x.isArray(this.config.fieldsToExtract)&&this.config.fieldsToExtract.some(I=>{const R=x.toLower(x.get(I,"api","")),A=x.get(I,"source","");return("*"===R||S.toLowerCase().includes(R))&&("*"===A||A===b)}))}extractUserContextFromBody({data:S,source:b="response",url:I=""}){if(!this.#Ds)return{};try{return this.#Ds.extractContextFromData({data:S,source:b,url:I})}catch(S){return this.#o.error("Failed to extract user context:",S),{}}}async startSessionRecording(S={}){return this.#Bs?.start(S)||null}stopSessionRecording(){return this.#Bs?.stop()||null}addSessionCustomEvent(S,b){if(this.#tr&&this.#er?.child)try{return!0===this.#er.child.forwardTelemetry(S,b)}catch(S){return!1}if(this.#Le&&"object"==typeof b&&null!==b){const I=this.#gr(S);if(I){let x;try{const S=this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"});"string"==typeof b.traceId&&b.traceId.length>0&&(S.traceId=b.traceId),"string"==typeof b.spanId&&b.spanId.length>0&&(S.spanId=b.spanId),this.#pr(b,S);x=wrapInEnvelope(I,this.#fr(I,b),S)}catch(S){if(this.config?.debug&&this.#o.warn?.("addSessionCustomEvent: envelope build failed; skipping v1 emit:",S),"function"==typeof this.#Ps?.onError)try{this.#Ps.onError(S)}catch(S){}return!1}return this.#Bs?.addCustomEvent(S,x)||!1}}return this.#Bs?.addCustomEvent(S,b)||!1}setIframeTopFrameContext(S){this.#Xs=S&&"object"==typeof S?S:null,this.#Xs||(this.#Ys=0);try{this.#Le?.setTopFrameIdentity?.(this.#Xs)}catch(S){}}static#mr=["frameId","parentFrameId","topFrameId","frameInstanceId","frameDepth","frameOrigin","frameUrl","frameLifecycle","captureRealm","privacyStatus","bridgeProtocolVersion","localSequence","tsLocal","tsNormalized","clockOffsetMs","clockUncertaintyMs"];#pr(S,b){const I=TraceScoutMonitoringCore.#mr;if("string"==typeof S.frameId&&S.frameId.length>0){for(const x of I){const I=S[x];null!=I&&""!==I&&(b[x]=I)}return}const x=this.#Xs;if(!x)return;b.frameId=x.frameId,b.frameInstanceId=x.frameInstanceId,b.topFrameId=x.topFrameId,b.frameDepth=0,b.captureRealm="top","string"==typeof x.frameOrigin&&(b.frameOrigin=x.frameOrigin),"string"==typeof x.frameUrl&&(b.frameUrl=x.frameUrl),"string"==typeof x.frameLifecycle&&(b.frameLifecycle=x.frameLifecycle),"string"==typeof x.privacyStatus&&(b.privacyStatus=x.privacyStatus);const R="number"==typeof S.timestamp?S.timestamp:Date.now();b.localSequence=this.#Ys++,b.tsLocal=R,b.tsNormalized=R}#gr(S){switch(S){case"network_request":case"network_response":case"network_error":case"network_resource":return"network_request";case"console":return"console_event";case"error":case"unhandledRejection":return"js_error";default:return null}}#fr(S,b){switch(S){case"console_event":{const S=Array.isArray(b.args)?b.args.map(S=>"object"==typeof S&&null!==S&&"type"in S?S:{type:"string"==typeof S?"string":"object",preview:String(S).slice(0,2e3)}):void 0,I={level:b.level||b.method||"log",message:"string"==typeof b.message?b.message:String(b.message??"")};return void 0!==S&&(I.args=S),void 0!==b.stack&&null!==b.stack&&(I.stack=b.stack),"number"==typeof b.timestamp&&(I.timestamp=b.timestamp),I}case"js_error":{const S={handled:b.handled||"window.onerror",message:"string"==typeof b.message?b.message:String(b.message??""),fingerprint:b.fingerprint,occurrenceCount:b.occurrenceCount||1,severity:b.severity||"error"},I=b.errorName??b.name;return null!=I&&(S.errorName=I),void 0!==b.stack&&null!==b.stack&&(S.stack=b.stack),void 0!==b.source&&null!==b.source&&(S.source=b.source),"number"==typeof b.lineno&&(S.lineno=b.lineno),"number"==typeof b.colno&&(S.colno=b.colno),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}case"network_request":{const S={initiator:"xhr"===b.interceptor?"xhr":"fetch",method:(b.method||"GET").toUpperCase(),requestUrl:b.url||b.requestUrl||"",status:"number"==typeof b.status?b.status:0,durationMs:"number"==typeof b.duration?Math.round(b.duration):0,errored:"number"!=typeof b.status||(b.status>=400||0===b.status)};return void 0!==b.statusText&&null!==b.statusText&&(S.statusText=b.statusText),"string"==typeof b.requestPath&&b.requestPath.length>0&&(S.requestPath=b.requestPath),"string"==typeof b.requestQuery&&b.requestQuery.length>0&&(S.requestQuery=b.requestQuery),b.requestHeaders&&"object"==typeof b.requestHeaders&&(S.requestHeaders=b.requestHeaders),b.responseHeaders&&"object"==typeof b.responseHeaders&&(S.responseHeaders=b.responseHeaders),"requestBody"in b&&(S.requestBody="string"==typeof b.requestBody?b.requestBody:null),"responseBody"in b&&(S.responseBody="string"==typeof b.responseBody?b.responseBody:null),"string"==typeof b.requestBodyState&&(S.requestBodyState=b.requestBodyState),"string"==typeof b.responseBodyState&&(S.responseBodyState=b.responseBodyState),"boolean"==typeof b.requestBodyRedacted&&(S.requestBodyRedacted=b.requestBodyRedacted),"boolean"==typeof b.responseBodyRedacted&&(S.responseBodyRedacted=b.responseBodyRedacted),"boolean"==typeof b.requestBodyTruncated&&(S.requestBodyTruncated=b.requestBodyTruncated),"boolean"==typeof b.responseBodyTruncated&&(S.responseBodyTruncated=b.responseBodyTruncated),"number"==typeof b.requestBodySize&&(S.requestBodySize=b.requestBodySize),"number"==typeof b.responseBodySize&&(S.responseBodySize=b.responseBodySize),"number"==typeof b.requestBodyCapturedBytes&&(S.requestBodyCapturedBytes=b.requestBodyCapturedBytes),"number"==typeof b.responseBodyCapturedBytes&&(S.responseBodyCapturedBytes=b.responseBodyCapturedBytes),"string"==typeof b.requestBodyContentType&&(S.requestBodyContentType=b.requestBodyContentType),"string"==typeof b.responseBodyContentType&&(S.responseBodyContentType=b.responseBodyContentType),"number"==typeof b.requestSize&&(S.requestSize=b.requestSize),"number"==typeof b.responseSize&&(S.responseSize=b.responseSize),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}default:return{...b}}}getSessionRecordingStatus(){return this.#Bs?.getStatus()||{available:!1,error:"Session recording not enabled"}}async getSessionEvents(S){return this.#Bs?.getEvents()||[]}exportSessionData(S="json"){if(!this.#Bs?.isAvailable)return this.#o.warn("Session recording not enabled"),null;try{const b=this.#Bs.getEvents(),I=this.#Bs.getChunks(),x=this.#Bs.getMetadata(),R=this.#Bs.getSessionId();let A=b;(!b||0===b.length)&&I&&I.length>0&&(A=[],I.forEach(S=>{S.events&&Array.isArray(S.events)&&A.push(...S.events)}));const _=JSON.stringify(A).length,D=_>5e6,L={sessionId:R,startTime:this.#Bs.recorder?.recordingStartTime,endTime:this.#Bs.isRecording?null:Date.now(),duration:this.#Bs.recorder?.recordingStartTime?Date.now()-this.#Bs.recorder.recordingStartTime:0,eventCount:A.length,chunkCount:I.length,totalSize:_,isLarge:D,metadata:x,events:D?[]:A,chunks:I,userAgent:navigator.userAgent,url:window.location.href,timestamp:Date.now(),...D&&{warning:"Session data is large. Use exportChunk() to get individual chunks for replay."}};return"json"===S?JSON.stringify(L,null,2):"object"===S?L:"blob"===S?new Blob([JSON.stringify(L,null,2)],{type:"application/json"}):L}catch(S){return this.#o.error("Failed to export session data:",S),null}}getSessionChunks(){return this.#Bs?.getChunks()||[]}listChunks(){return(this.#Bs?.getChunks()||[]).map((S,b)=>({index:b,chunkId:S.chunkId,eventCount:S.events?.length||0,size:JSON.stringify(S.events||[]).length,sizeKB:Math.round(JSON.stringify(S.events||[]).length/1024),startTime:S.startTime,endTime:S.endTime,duration:(S.endTime||0)-(S.startTime||0)}))}getUploadQueueStats(){return this.#Bs?.uploadQueue?.getStats()||null}getUploadQueue(){return this.#Bs?.uploadQueue?.getQueue()||null}pauseUploads(){return this.#Bs?.uploadQueue?.pause(),!0}resumeUploads(){return this.#Bs?.uploadQueue?.resume(),!0}getSessionStorageStats(){return this.#Bs?.sessionStorage?.getStorageStats()||null}getStoredSessions(){return this.#Bs?.sessionStorage?.getSessions()||{}}clearSessionStorage(){return this.#Bs?.sessionStorage?.clearAll()||!1}log(S,b,I={}){return this.#zs?.log(S,b,I)||!1}debug(S,b={}){return this.#zs?.debug(S,b)||!1}info(S,b={}){return this.#zs?.info(S,b)||!1}warn(S,b={}){return this.#zs?.warn(S,b)||!1}error(S,b={}){return this.#zs?.error(S,b)||!1}fatal(S,b={}){return this.#zs?.fatal(S,b)||!1}setLogContext(S,b){return this.#zs?.setContext(S,b)||!1}clearLogContext(){return this.#zs?.clearContext()||!1}setLogLevel(S){return this.#zs?.setLogLevel(S)||!1}getLogStats(){return this.#zs?.getStats()||null}async flushLogs(){return this.#zs?.flush()||!1}enableLogging(S,b="info"){return this.#zs?.enableServices(S,b)||!1}disableLogging(S){return this.#zs?.disableServices(S)||!1}enableAllLogging(S="info"){return this.#zs?.enableAll(S)||!1}disableAllLogging(){return this.#zs?.disableAll()||!1}getLoggingConfig(){return this.#zs?.getConfig()||null}getEnabledLogServices(){return this.#zs?.getEnabledServices()||[]}getAvailableLogServices(){return this.#zs?.getAvailableServices()||[]}setUserProfile(S){if(!this.#Ds)return this.#o.warn("UserProfileManager not available"),!1;let b=!1;try{b=!0===this.#Ds.setProfile(S)}catch(S){return this.#o.error("Failed to set user profile:",S),!1}if(S&&"object"==typeof S&&isValidUserId(S.userId)){const{userId:b,...I}=S;try{this.#yr(b,I,{mode:"merge"},{skipUserProfileWrite:!0})}catch(S){this.#o.warn?.("Failed to route setUserProfile through identify:",S)}}return b}getUserProfile(){if(!this.#Ds)return{};try{return this.#Ds.getProfile()}catch(S){return this.#o.error("Failed to get user profile:",S),{}}}getSdkContext(){return!1===this.#Ks?{sampled:!1}:this.#Le}setUserMetadata(S,b={}){return this.identify(S,b,{mode:"merge"})}clearUserMetadata(){return!!this.#Le&&(this.#Le.clearUser(),this.#Ns&&this.#Ns.clearUserMetadata(),!0)}identify(S,b={},I={}){return this.#yr(S,b,I,{skipUserProfileWrite:!1})}#yr(S,b={},I={},x={}){if(!isValidUserId(S))return this.#o.error("identify: userId is required and must be a non-empty string (≤256 chars)"),!1;if(!this.#Le)return this.#o.warn("Cannot identify — SDK not initialized"),!1;const R=I&&"set"===I.mode?"set":"merge",A=[],onDrop=(S,b)=>A.push({reason:S,key:b}),{userEmail:_,userName:D,traits:L}=function extractIdentityFromTraits(S,b){const I="function"==typeof b?b:()=>{};if(!S||"object"!=typeof S||Array.isArray(S))return{userEmail:null,userName:null,traits:{}};const x=Object.assign({},S),R=void 0!==x.userEmail?x.userEmail:x.email;delete x.email,delete x.userEmail;let A=null;null!=R&&(isValidEmail(R)?A=R:I("invalid-email","email"));const _=void 0!==x.userName?x.userName:x.name;delete x.name,delete x.userName;let D=null;return null!=_&&(isValidUserName(_)?D=_:I("invalid-name","name")),{userEmail:A,userName:D,traits:x}}(b||{},onDrop),B=sanitizeScalarBag(L,onDrop);this.config?.debug&&A.length>0&&this.#o.warn?.("identify: dropped invalid trait entries:",A);const U=this.#Le.userAttributes||{},$="set"===R?{}:{...U};null!==_&&($.email=_),null!==D&&($.name=D);const j=Object.assign({},$,B);if(this.#Le.setUser(S,j),this.#Ns)try{this.#Ns.updateUserMetadata(S,j)}catch(S){this.#o.warn?.("SessionManager.updateUserMetadata threw:",S)}if(!x.skipUserProfileWrite&&this.#Ds)try{this.#Ds.setProfile({userId:S,...j})}catch(S){this.#o.warn?.("UserProfileManager.setProfile threw:",S)}return this.#Ws?this.#Ws.emitUserIdentified({userId:S,userEmail:_,userName:D,traits:B,mode:R}):this.config?.debug&&this.#o.warn?.("identify: emitter not available (recording disabled?) — context updated but no v1 envelope emitted"),!0}track(S,b={}){if(!this.#je)return this.#o.warn("SDK not initialized"),!1;try{this.logEvent({type:`custom.${S}`,category:"custom",severity:"info",data:b,timestamp:Date.now()})}catch(S){}return this.#Ws?this.#Ws.emitCustomEvent(S,b):(this.config?.debug&&this.#o.warn?.("track: v1 emitter not available (recording disabled?) — legacy event emitted, no v1 envelope"),!1)}captureException(S,b={}){return this.#je?(this.logEvent({type:"error.captured",category:"error",severity:"error",data:{message:S.message,stack:S.stack,name:S.name,...b},timestamp:Date.now()}),!0):(this.#o.warn("SDK not initialized"),!1)}getStatus(){const S=this.#Ns?.getSessionInfo?.()||{};return{initialized:this.#je,recording:this.#Bs?.isRecording||!1,sessionId:this.#Le?.sessionId||null,eventQueueSize:this.#as?.getQueueSize()||0,session:{id:S.sessionId,duration:S.durationMinutes,events:S.eventCount,chunks:S.chunkCount,pages:S.pageCount,expiresIn:S.willExpireInMinutes}}}forceNewSession(S="manual"){if(!this.#je)return this.#o.warn("SDK not initialized"),null;if(this.#Es)return console.warn("[TraceScout] Cannot start new session - quota exceeded."),null;console.log("[TraceScout] 🔄 Forcing new session, reason:",S),this.#Bs?.stop(),this.#Ns&&this.#Ns.forceNewSession(S);const b=this.#Ns?.getOrCreateSession({projectId:this.#Le.projectId,environment:this.#Le.environment,userId:this.#Le.userId});if(this.#Le&&b&&(this.#Le.sessionId=b,this.#Le.sessionStartTime=Date.now()),this.#Bs&&b){this.#Bs.updateSessionId(b);const S=this.config.apiBaseUrl||"http://localhost:3001";this.#Bs.updateUploadEndpoint(`${S}/api/projects/${this.#Le.projectId}/sessions/${b}/chunks`),this.#Bs.recorder?.start()}return b}debugMode(S){this.config.debug=S,this.#o.updateDebugMode(S),this.#Os&&this.#Os.updateDebugMode(S),this.#ls?.updateDebugMode(S),this.#o.log("Debug mode "+(S?"enabled":"disabled"))}getQueueStatus(){return{queueSize:this.#as?this.#as.getQueueSize():0,isSending:!!this.#Os&&this.#Os.isSending,isInitialized:this.#je,service:this.#Os?this.#Os.getServiceName():"none",configSource:this.config?.configSource||"local",configVersion:this.config?.configVersion||"local"}}getPerformanceMetrics(){return this.#Fs?.getMetrics()||null}getCoreWebVitalsMonitor(){return this.#Hs}getCoreWebVitalsMetrics(){return this.#Hs?.getAllMetrics()||null}getCoreWebVitalsInsights(){return this.#Hs?.getPerformanceInsights()||null}generateCoreWebVitalsReport(){return this.#Hs?.generateReport()||null}updateCoreWebVitalsThresholds(S){this.#Hs?this.#Hs.updateThresholds(S):this.#o.warn("Core Web Vitals monitor not available")}}let at;try{at=new TraceScoutMonitoringCore}catch(S){at={init:()=>Promise.reject(new Error("TraceScoutMonitoringCore failed to initialize")),logEvent:()=>{},destroy:()=>{},debugMode:()=>{},setUserProfile:()=>{},getUserProfile:()=>({}),getQueueStatus:()=>({error:"Not available"}),getPerformanceMetrics:()=>null,getCoreWebVitalsMonitor:()=>null,getCoreWebVitalsMetrics:()=>null,getCoreWebVitalsInsights:()=>null,generateCoreWebVitalsReport:()=>null,updateCoreWebVitalsThresholds:()=>{},getSessionRecorder:()=>null,startSessionRecording:()=>Promise.resolve(null),stopSessionRecording:()=>!1,getSessionRecordingStatus:()=>({available:!1,error:"Not available"}),getStatus:()=>({initialized:!1,error:"Not available"}),forceNewSession:()=>null}}if("undefined"!=typeof window)try{window.monitoringCore=at}catch(S){}var lt=at;function extractRequestDetails(S,b,I,x,R="",A="unknown"){try{const _=new URL(S,location.origin);return{method:b.toUpperCase(),url:S,domain:_.hostname,path:_.pathname,status:I,statusText:x,response:R,interceptor:A}}catch{return{method:b.toUpperCase(),url:S,domain:"",path:"",status:I,statusText:x,response:R,interceptor:A}}}function parseRequestUrl(S){try{return new URL(S,location.origin)}catch(S){return null}}class RemoteConfigService{constructor(S,b=null){this.context=S;const I="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname?"https://api.tracescout.com":"http://localhost:3001";this.baseUrl=b||I,this.config=null,this.lastFetched=null,this.refreshInterval=3e5,this.refreshTimer=null,this.logger=createLogger("RemoteConfig"),this.fetchAttempts=0,this.maxFetchAttempts=3,console.log("[RemoteConfigService] Using API base URL:",this.baseUrl)}async fetchConfig(){try{this.fetchAttempts++,this.logger.log("Fetching remote SDK configuration..."),this.logger.log(` Project: ${this.context.projectId}`),this.logger.log(` Workspace: ${this.context.workspaceId}`),this.logger.log(` Attempt: ${this.fetchAttempts}/${this.maxFetchAttempts}`);const S=`${this.baseUrl}/api/projects/${this.context.projectId}/sdk-config`,b=await fetch(S,{method:"GET",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},signal:AbortSignal.timeout(1e4)});if(!b.ok){const S=await b.text();throw new Error(`Config fetch failed: ${b.status} ${b.statusText} - ${S}`)}const I=await b.json();this.#vr(I),this.config=I,this.lastFetched=Date.now(),this.fetchAttempts=0,this.logger.log("✅ Remote configuration loaded successfully"),this.logger.log(` Config version: ${I.configVersion}`),this.logger.log(` Workspace: ${I.workspace.name}`),this.logger.log(` Project: ${I.project.name}`);const x=Object.keys(I.features).filter(S=>I.features[S].enabled).join(", ");return this.logger.log(` Features enabled: ${x||"none"}`),this.#Sr(),I}catch(S){this.logger.error("Failed to fetch remote config:",S.message),this.fetchAttempts<this.maxFetchAttempts?this.logger.warn(`Will retry... (${this.fetchAttempts}/${this.maxFetchAttempts})`):this.logger.warn("Max fetch attempts reached, using fallback configuration");const b=this.#wr();return this.config=b,b}}#vr(S){if(!S.success)throw new Error("Server returned unsuccessful config response");if(!S.project||S.project.id!==this.context.projectId)throw new Error(`Config projectId mismatch. Expected: ${this.context.projectId}, Got: ${S.project?.id}`);if(!S.workspace||!S.workspace.id)throw new Error("Config missing workspace data");if(!S.features)throw new Error("Config missing features object");if(!S.privacy)throw new Error("Config missing privacy object");if(!S.telemetry)throw new Error("Config missing telemetry object");this.logger.log("✓ Config validation passed")}#wr(){return this.logger.warn("⚠️ Using fallback configuration - limited functionality"),this.logger.warn(" Session recording: enabled (100% sample rate)"),this.logger.warn(" Error tracking: enabled"),this.logger.warn(" Other features: disabled"),{success:!0,configVersion:"2.0.0-fallback",lastUpdated:(new Date).toISOString(),workspace:{id:this.context.workspaceId,name:"Unknown Workspace (Fallback)"},project:{id:this.context.projectId,name:"Unknown Project (Fallback)",environment:this.context.environment,allowedOrigins:[]},features:{sessionRecording:{enabled:!0,sampleRate:1,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[],chunkDuration:3e4,maxChunkSize:5e5,recordCanvas:!1,collectFonts:!1},errorTracking:{enabled:!0,ignoreErrors:[],sourceMaps:!1,stackTraceLimit:30},performanceMonitoring:{enabled:!1,coreWebVitals:!1,longTaskThreshold:50,resourceTimingBufferSize:250},consoleCapture:{enabled:!0,levels:["error","warn"]},networkMonitoring:{enabled:!1,endpoints:[],captureHeaders:!1,captureBody:!1}},privacy:{maskInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},telemetry:{endpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`,sessionEndpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/sessions`,batchSize:10,flushInterval:5e3,enableCompression:!0},service:{send:async S=>{const b=`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`;console.log("[TraceScout][FallbackService] Sending to:",b),console.log("[TraceScout][FallbackService] Events:",S);try{const I=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},body:JSON.stringify({events:S,context:{workspaceId:this.context.workspaceId,projectId:this.context.projectId,environment:this.context.environment,sessionId:this.context.sessionId}})});if(!I.ok)throw new Error(`HTTP ${I.status}: ${I.statusText}`);return await I.json()}catch(S){throw console.error("[TraceScout][FallbackService] Send failed:",S),S}}}}}#Sr(){this.refreshTimer&&clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(async()=>{this.logger.log("⏰ Refreshing remote configuration...");try{await this.fetchConfig(),this.logger.log("✅ Config refreshed successfully")}catch(S){this.logger.error("Config refresh failed:",S.message)}},this.refreshInterval),this.logger.log(`Next config refresh in ${this.refreshInterval/1e3}s`)}stopRefresh(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null,this.logger.log("Config refresh stopped"))}getConfig(){return this.config}isStale(){return!this.lastFetched||Date.now()-this.lastFetched>this.refreshInterval}async refresh(){return this.logger.log("Forcing config refresh..."),await this.fetchConfig()}getConfigAge(){return this.lastFetched?Math.floor((Date.now()-this.lastFetched)/1e3):-1}}function __tsSafeContentDoc(S){try{if(S&&"IFRAME"===S.tagName&&S.src)try{var b=new URL(S.src);if(("http:"===b.protocol||"https:"===b.protocol)&&"undefined"!=typeof location&&b.origin!==location.origin)return null}catch(S){}return S.contentDocument}catch(S){return null}}var ct,ut=Object.defineProperty,__publicField=(S,b,I)=>((S,b,I)=>b in S?ut(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),ht=Object.defineProperty,__publicField$1=(S,b,I)=>((S,b,I)=>b in S?ht(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),dt=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(dt||{});const gt={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},pt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},ft={};function getUntaintedPrototype$1(S){if(ft[S])return ft[S];const b=globalThis[S],I=b.prototype,x=S in gt?gt[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in pt?pt[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return ft[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?ft[S]=A:I}catch{return I}}const mt={};function getUntaintedAccessor$1(S,b,I){var x;const R=`${S}.${String(I)}`;if(mt[R])return mt[R].call(b);const A=getUntaintedPrototype$1(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(mt[R]=_,_.call(b)):b[I]}const yt={};function getUntaintedMethod$1(S,b,I){const x=`${S}.${String(I)}`;if(yt[x])return yt[x].bind(b);const R=getUntaintedPrototype$1(S)[I];return"function"!=typeof R?b[I]:(yt[x]=R,R.bind(b))}const vt={childNodes:function childNodes$1(S){return getUntaintedAccessor$1("Node",S,"childNodes")},parentNode:function parentNode$1(S){return getUntaintedAccessor$1("Node",S,"parentNode")},parentElement:function parentElement$1(S){return getUntaintedAccessor$1("Node",S,"parentElement")},textContent:function textContent$1(S){return getUntaintedAccessor$1("Node",S,"textContent")},contains:function contains$1(S,b){return getUntaintedMethod$1("Node",S,"contains")(b)},getRootNode:function getRootNode$1(S){return getUntaintedMethod$1("Node",S,"getRootNode")()},host:function host$1(S){return S&&"host"in S?getUntaintedAccessor$1("ShadowRoot",S,"host"):null},styleSheets:function styleSheets$1(S){return S.styleSheets},shadowRoot:function shadowRoot$1(S){return S&&"shadowRoot"in S?getUntaintedAccessor$1("Element",S,"shadowRoot"):null},querySelector:function querySelector$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelectorAll")(b)},mutationObserver:function mutationObserverCtor$1(){return getUntaintedPrototype$1("MutationObserver").constructor}};function isElement(S){return S.nodeType===S.ELEMENT_NODE}function isShadowRoot(S){const b=S&&"host"in S&&"mode"in S&&vt.host(S)||null;return Boolean(b&&"shadowRoot"in b&&vt.shadowRoot(b)===S)}function isNativeShadowDom(S){return"[object ShadowRoot]"===Object.prototype.toString.call(S)}function stringifyStylesheet(S){try{const b=S.rules||S.cssRules;if(!b)return null;let I=S.href;!I&&S.ownerNode&&S.ownerNode.ownerDocument&&(I=S.ownerNode.ownerDocument.location.href);return function fixBrowserCompatibilityIssuesInCSS(S){return S.includes(" background-clip: text;")&&!S.includes(" -webkit-background-clip: text;")&&(S=S.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),S}(Array.from(b,S=>stringifyRule(S,I)).join(""))}catch(S){return null}}function stringifyRule(S,b){if(function isCSSImportRule(S){return"styleSheet"in S}(S)){let b;try{b=stringifyStylesheet(S.styleSheet)||function escapeImportStatement(S){const{cssText:b}=S;if(b.split('"').length<3)return b;const I=["@import",`url(${JSON.stringify(S.href)})`];return""===S.layerName?I.push("layer"):S.layerName&&I.push(`layer(${S.layerName})`),S.supportsText&&I.push(`supports(${S.supportsText})`),S.media.length&&I.push(S.media.mediaText),I.join(" ")+";"}(S)}catch(I){b=S.cssText}return S.styleSheet.href?absolutifyURLs(b,S.styleSheet.href):b}{let I=S.cssText;return function isCSSStyleRule(S){return"selectorText"in S}(S)&&S.selectorText.includes(":")&&(I=function fixSafariColons(S){const b=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return S.replace(b,"$1\\$2")}(I)),b?absolutifyURLs(I,b):I}}class Mirror{constructor(){__publicField$1(this,"idNodeMap",new Map),__publicField$1(this,"nodeMetaMap",new WeakMap)}getId(S){var b;if(!S)return-1;return(null==(b=this.getMeta(S))?void 0:b.id)??-1}getNode(S){return this.idNodeMap.get(S)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(S){return this.nodeMetaMap.get(S)||null}removeNodeFromMap(S){const b=this.getId(S);this.idNodeMap.delete(b),S.childNodes&&S.childNodes.forEach(S=>this.removeNodeFromMap(S))}has(S){return this.idNodeMap.has(S)}hasNode(S){return this.nodeMetaMap.has(S)}add(S,b){const I=b.id;this.idNodeMap.set(I,S),this.nodeMetaMap.set(S,b)}replace(S,b){const I=this.getNode(S);if(I){const S=this.nodeMetaMap.get(I);S&&this.nodeMetaMap.set(b,S)}this.idNodeMap.set(S,b)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function maskInputValue({element:S,maskInputOptions:b,tagName:I,type:x,value:R,maskInputFn:A}){let _=R||"";const D=x&&toLowerCase(x);return(b[I.toLowerCase()]||D&&b[D])&&(_=A?A(_,S):"*".repeat(_.length)),_}function toLowerCase(S){return S.toLowerCase()}const St="__rrweb_original__";function getInputType(S){const b=S.type;return S.hasAttribute("data-rr-is-password")?"password":b?toLowerCase(b):null}function extractFileExtension(S,b){let I;try{I=new URL(S,b??window.location.href)}catch(S){return null}const x=I.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==x?void 0:x[1])??null}const wt=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,bt=/^(?:[a-z+]+:)?\/\//i,Ct=/^www\..*/i,kt=/^(data:)([^,]*),(.*)/i;function absolutifyURLs(S,b){return(S||"").replace(wt,(S,I,x,R,A,_)=>{const D=x||A||_,L=I||R||"";if(!D)return S;if(bt.test(D)||Ct.test(D))return`url(${L}${D}${L})`;if(kt.test(D))return`url(${L}${D}${L})`;if("/"===D[0])return`url(${L}${function extractOrigin(S){let b="";return b=S.indexOf("//")>-1?S.split("/").slice(0,3).join("/"):S.split("/")[0],b=b.split("?")[0],b}(b)+D}${L})`;const B=b.split("/"),U=D.split("/");B.pop();for(const S of U)"."!==S&&(".."===S?B.pop():B.push(S));return`url(${L}${B.join("/")}${L})`})}function normalizeCssString(S){return S.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function markCssSplits(S,b){return function splitCssText(S,b){const I=Array.from(b.childNodes),x=[];if(I.length>1&&S&&"string"==typeof S){const b=normalizeCssString(S);for(let R=1;R<I.length;R++)if(I[R].textContent&&"string"==typeof I[R].textContent){const A=normalizeCssString(I[R].textContent);for(let I=3;I<A.length;I++){const R=A.substring(0,I);if(2===b.split(R).length){const I=b.indexOf(R);for(let b=I;b<S.length;b++)if(normalizeCssString(S.substring(0,b)).length===I){x.push(S.substring(0,b)),S=S.substring(b);break}break}}}}return x.push(S),x}(S,b).join("/* rr_split */")}let It=1;const Et=new RegExp("[^a-z0-9-_:]");function genId(){return It++}let xt,Mt;const Rt=/^[^ \t\n\r\u000c]+/,Tt=/^[, \t\n\r\u000c]+/;const At=new WeakMap;function absoluteToDoc(S,b){return b&&""!==b.trim()?getHref(S,b):b}function isSVGElement(S){return Boolean("svg"===S.tagName||S.ownerSVGElement)}function getHref(S,b){let I=At.get(S);if(I||(I=S.createElement("a"),At.set(S,I)),b){if(b.startsWith("blob:")||b.startsWith("data:"))return b}else b="";return I.setAttribute("href",b),I.href}function transformAttribute(S,b,I,x){return x?"src"===I||"href"===I&&("use"!==b||"#"!==x[0])||"xlink:href"===I&&"#"!==x[0]?absoluteToDoc(S,x):"background"!==I||"table"!==b&&"td"!==b&&"th"!==b?"srcset"===I?function getAbsoluteSrcsetString(S,b){if(""===b.trim())return b;let I=0;function collectCharacters(S){let x;const R=S.exec(b.substring(I));return R?(x=R[0],I+=x.length,x):""}const x=[];for(;collectCharacters(Tt),!(I>=b.length);){let R=collectCharacters(Rt);if(","===R.slice(-1))R=absoluteToDoc(S,R.substring(0,R.length-1)),x.push(R);else{let A="";R=absoluteToDoc(S,R);let _=!1;for(;;){const S=b.charAt(I);if(""===S){x.push((R+A).trim());break}if(_)")"===S&&(_=!1);else{if(","===S){I+=1,x.push((R+A).trim());break}"("===S&&(_=!0)}A+=S,I+=1}}}return x.join(", ")}(S,x):"style"===I?absolutifyURLs(x,getHref(S)):"object"===b&&"data"===I?absoluteToDoc(S,x):x:absoluteToDoc(S,x):x}function ignoreAttribute(S,b,I){return("video"===S||"audio"===S)&&"autoplay"===b}function classMatchesRegex(S,b,I){if(!S)return!1;if(S.nodeType!==S.ELEMENT_NODE)return!!I&&classMatchesRegex(vt.parentNode(S),b,I);for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}return!!I&&classMatchesRegex(vt.parentNode(S),b,I)}function needMaskingText(S,b,I,x){let R;if(isElement(S)){if(R=S,!vt.childNodes(R).length)return!1}else{if(null===vt.parentElement(S))return!1;R=vt.parentElement(S)}try{if("string"==typeof b){if(x){if(R.closest(`.${b}`))return!0}else if(R.classList.contains(b))return!0}else if(classMatchesRegex(R,b,x))return!0;if(I)if(x){if(R.closest(I))return!0}else if(R.matches(I))return!0}catch(S){}return!1}function serializeNode(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:_,inlineStylesheet:D,maskInputOptions:L={},maskTextFn:B,maskInputFn:U,dataURLOptions:$={},inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V=!1,cssCaptured:Q=!1}=b,G=function getRootId(S,b){if(!b.hasNode(S))return;const I=b.getId(S);return 1===I?void 0:I}(I,x);switch(S.nodeType){case S.DOCUMENT_NODE:return"CSS1Compat"!==S.compatMode?{type:dt.Document,childNodes:[],compatMode:S.compatMode}:{type:dt.Document,childNodes:[]};case S.DOCUMENT_TYPE_NODE:return{type:dt.DocumentType,name:S.name,publicId:S.publicId,systemId:S.systemId,rootId:G};case S.ELEMENT_NODE:return function serializeElementNode(S,b){const{doc:I,blockClass:x,blockSelector:R,inlineStylesheet:A,maskInputOptions:_={},maskInputFn:D,dataURLOptions:L={},inlineImages:B,recordCanvas:U,keepIframeSrcFn:$,newlyAddedElement:j=!1,rootId:W}=b,H=function _isBlockedElement(S,b,I){try{if("string"==typeof b){if(S.classList.contains(b))return!0}else for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}if(I)return S.matches(I)}catch(S){}return!1}(S,x,R),V=function getValidTagName$1(S){if(S instanceof HTMLFormElement)return"form";const b=toLowerCase(S.tagName);return Et.test(b)?"div":b}(S);let Q={};const G=S.attributes.length;for(let b=0;b<G;b++){const x=S.attributes[b];ignoreAttribute(V,x.name)||(Q[x.name]=transformAttribute(I,V,toLowerCase(x.name),x.value))}if("link"===V&&A){const b=Array.from(I.styleSheets).find(b=>b.href===S.href);let x=null;b&&(x=stringifyStylesheet(b)),x&&(delete Q.rel,delete Q.href,Q._cssText=x)}if("style"===V&&S.sheet){let b=stringifyStylesheet(S.sheet);b&&(S.childNodes.length>1&&(b=markCssSplits(b,S)),Q._cssText=b)}if("input"===V||"textarea"===V||"select"===V){const b=S.value,I=S.checked;"radio"!==Q.type&&"checkbox"!==Q.type&&"submit"!==Q.type&&"button"!==Q.type&&b?Q.value=maskInputValue({element:S,type:getInputType(S),tagName:V,value:b,maskInputOptions:_,maskInputFn:D}):I&&(Q.checked=I)}"option"===V&&(S.selected&&!_.select?Q.selected=!0:delete Q.selected);"dialog"===V&&S.open&&(Q.rr_open_mode=S.matches("dialog:modal")?"modal":"non-modal");if("canvas"===V&&U)if("2d"===S.__context)(function is2DCanvasBlank(S){const b=S.getContext("2d");if(!b)return!0;for(let I=0;I<S.width;I+=50)for(let x=0;x<S.height;x+=50){const R=b.getImageData,A=St in R?R[St]:R;if(new Uint32Array(A.call(b,I,x,Math.min(50,S.width-I),Math.min(50,S.height-x)).data.buffer).some(S=>0!==S))return!1}return!0})(S)||(Q.rr_dataURL=S.toDataURL(L.type,L.quality));else if(!("__context"in S)){const b=S.toDataURL(L.type,L.quality),x=I.createElement("canvas");x.width=S.width,x.height=S.height;b!==x.toDataURL(L.type,L.quality)&&(Q.rr_dataURL=b)}if("img"===V&&B){xt||(xt=I.createElement("canvas"),Mt=xt.getContext("2d"));const b=S,x=b.currentSrc||b.getAttribute("src")||"<unknown-src>",R=b.crossOrigin,recordInlineImage=()=>{b.removeEventListener("load",recordInlineImage);try{xt.width=b.naturalWidth,xt.height=b.naturalHeight,Mt.drawImage(b,0,0),Q.rr_dataURL=xt.toDataURL(L.type,L.quality)}catch(S){if("anonymous"!==b.crossOrigin)return b.crossOrigin="anonymous",void(b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage));console.warn(`Cannot inline img src=${x}! Error: ${S}`)}"anonymous"===b.crossOrigin&&(R?Q.crossOrigin=R:b.removeAttribute("crossorigin"))};b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage)}if("audio"===V||"video"===V){const b=Q;b.rr_mediaState=S.paused?"paused":"played",b.rr_mediaCurrentTime=S.currentTime,b.rr_mediaPlaybackRate=S.playbackRate,b.rr_mediaMuted=S.muted,b.rr_mediaLoop=S.loop,b.rr_mediaVolume=S.volume}j||(S.scrollLeft&&(Q.rr_scrollLeft=S.scrollLeft),S.scrollTop&&(Q.rr_scrollTop=S.scrollTop));if(H){const{width:b,height:I}=S.getBoundingClientRect();Q={class:Q.class,rr_width:`${b}px`,rr_height:`${I}px`}}"iframe"!==V||$(Q.src)||(__tsSafeContentDoc(S)||(Q.rr_src=Q.src),delete Q.src);let J;try{customElements.get(V)&&(J=!0)}catch(S){}return{type:dt.Element,tagName:V,attributes:Q,childNodes:[],isSVG:isSVGElement(S)||void 0,needBlock:H,rootId:W,isCustom:J}}(S,{doc:I,blockClass:R,blockSelector:A,inlineStylesheet:D,maskInputOptions:L,maskInputFn:U,dataURLOptions:$,inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V,rootId:G});case S.TEXT_NODE:return function serializeTextNode(S,b){const{needsMask:I,maskTextFn:x,rootId:R,cssCaptured:A}=b,_=vt.parentNode(S),D=_&&_.tagName;let L="";const B="STYLE"===D||void 0,U="SCRIPT"===D||void 0;U?L="SCRIPT_PLACEHOLDER":A||(L=vt.textContent(S),B&&L&&(L=absolutifyURLs(L,getHref(b.doc))));!B&&!U&&L&&I&&(L=x?x(L,vt.parentElement(S)):L.replace(/[\S]/g,"*"));return{type:dt.Text,textContent:L||"",rootId:R}}(S,{doc:I,needsMask:_,maskTextFn:B,rootId:G,cssCaptured:Q});case S.CDATA_SECTION_NODE:return{type:dt.CDATA,textContent:"",rootId:G};case S.COMMENT_NODE:return{type:dt.Comment,textContent:vt.textContent(S)||"",rootId:G};default:return!1}}function lowerIfExists(S){return null==S?"":S.toLowerCase()}function serializeNodeWithId(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,maskTextClass:_,maskTextSelector:D,skipChild:L=!1,inlineStylesheet:B=!0,maskInputOptions:U={},maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H={},inlineImages:V=!1,recordCanvas:Q=!1,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X=5e3,onStylesheetLoad:Y,stylesheetLoadTimeout:ee=5e3,keepIframeSrcFn:te=()=>!1,newlyAddedElement:se=!1,cssCaptured:re=!1}=b;let{needsMask:ne}=b,{preserveWhiteSpace:ie=!0}=b;if(!ne){ne=needMaskingText(S,_,D,void 0===ne)}const oe=serializeNode(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,dataURLOptions:H,inlineImages:V,recordCanvas:Q,keepIframeSrcFn:te,newlyAddedElement:se,cssCaptured:re});if(!oe)return console.warn(S,"not serialized"),null;let ae;ae=x.hasNode(S)?x.getId(S):function slimDOMExcluded(S,b){if(b.comment&&S.type===dt.Comment)return!0;if(S.type===dt.Element){if(b.script&&("script"===S.tagName||"link"===S.tagName&&("preload"===S.attributes.rel||"modulepreload"===S.attributes.rel)&&"script"===S.attributes.as||"link"===S.tagName&&"prefetch"===S.attributes.rel&&"string"==typeof S.attributes.href&&"js"===extractFileExtension(S.attributes.href)))return!0;if(b.headFavicon&&("link"===S.tagName&&"shortcut icon"===S.attributes.rel||"meta"===S.tagName&&(lowerIfExists(S.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===lowerIfExists(S.attributes.name)||"icon"===lowerIfExists(S.attributes.rel)||"apple-touch-icon"===lowerIfExists(S.attributes.rel)||"shortcut icon"===lowerIfExists(S.attributes.rel))))return!0;if("meta"===S.tagName){if(b.headMetaDescKeywords&&lowerIfExists(S.attributes.name).match(/^description|keywords$/))return!0;if(b.headMetaSocial&&(lowerIfExists(S.attributes.property).match(/^(og|twitter|fb):/)||lowerIfExists(S.attributes.name).match(/^(og|twitter):/)||"pinterest"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaRobots&&("robots"===lowerIfExists(S.attributes.name)||"googlebot"===lowerIfExists(S.attributes.name)||"bingbot"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaHttpEquiv&&void 0!==S.attributes["http-equiv"])return!0;if(b.headMetaAuthorship&&("author"===lowerIfExists(S.attributes.name)||"generator"===lowerIfExists(S.attributes.name)||"framework"===lowerIfExists(S.attributes.name)||"publisher"===lowerIfExists(S.attributes.name)||"progid"===lowerIfExists(S.attributes.name)||lowerIfExists(S.attributes.property).match(/^article:/)||lowerIfExists(S.attributes.property).match(/^product:/)))return!0;if(b.headMetaVerification&&("google-site-verification"===lowerIfExists(S.attributes.name)||"yandex-verification"===lowerIfExists(S.attributes.name)||"csrf-token"===lowerIfExists(S.attributes.name)||"p:domain_verify"===lowerIfExists(S.attributes.name)||"verify-v1"===lowerIfExists(S.attributes.name)||"verification"===lowerIfExists(S.attributes.name)||"shopify-checkout-api-token"===lowerIfExists(S.attributes.name)))return!0}}return!1}(oe,W)||!ie&&oe.type===dt.Text&&!oe.textContent.replace(/^\s+|\s+$/gm,"").length?-2:genId();const le=Object.assign(oe,{id:ae});if(x.add(S,le),-2===ae)return null;G&&G(S);let ce=!L;if(le.type===dt.Element){ce=ce&&!le.needBlock,delete le.needBlock;const b=vt.shadowRoot(S);b&&isNativeShadowDom(b)&&(le.isShadowHost=!0)}if((le.type===dt.Document||le.type===dt.Element)&&ce){W.headWhitespace&&le.type===dt.Element&&"head"===le.tagName&&(ie=!1);const b={doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:L,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te,cssCaptured:!1};if(le.type===dt.Element&&"textarea"===le.tagName&&void 0!==le.attributes.value);else{le.type===dt.Element&&void 0!==le.attributes._cssText&&"string"==typeof le.attributes._cssText&&(b.cssCaptured=!0);for(const I of Array.from(vt.childNodes(S))){const S=serializeNodeWithId(I,b);S&&le.childNodes.push(S)}}let se=null;if(isElement(S)&&(se=vt.shadowRoot(S)))for(const S of Array.from(vt.childNodes(se))){const I=serializeNodeWithId(S,b);I&&(isNativeShadowDom(se)&&(I.isShadow=!0),le.childNodes.push(I))}}const ue=vt.parentNode(S);return ue&&isShadowRoot(ue)&&isNativeShadowDom(ue)&&(le.isShadow=!0),le.type===dt.Element&&"iframe"===le.tagName&&function onceIframeLoaded(S,b,I){const x=S.contentWindow;if(!x)return;let R,A=!1;try{R=x.document.readyState}catch(S){return}if("complete"!==R){const x=setTimeout(()=>{A||(b(),A=!0)},I);return void S.addEventListener("load",()=>{clearTimeout(x),A=!0,b()})}const _="about:blank";if(x.location.href!==_||S.src===_||""===S.src)return setTimeout(b,0),S.addEventListener("load",b);S.addEventListener("load",b)}(S,()=>{const b=__tsSafeContentDoc(S);if(b&&J){const I=serializeNodeWithId(b,{doc:b,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});I&&J(S,I)}},X),le.type===dt.Element&&"link"===le.tagName&&"string"==typeof le.attributes.rel&&("stylesheet"===le.attributes.rel||"preload"===le.attributes.rel&&"string"==typeof le.attributes.href&&"css"===extractFileExtension(le.attributes.href))&&function onceStylesheetLoaded(S,b,I){let x,R=!1;try{x=S.sheet}catch(S){return}if(x)return;const A=setTimeout(()=>{R||(b(),R=!0)},I);S.addEventListener("load",()=>{clearTimeout(A),R=!0,b()})}(S,()=>{if(Y){const b=serializeNodeWithId(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});b&&Y(S,b)}},ee),le}function getAugmentedNamespace$1(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var _t={exports:{}},Ot=String,create$1=function(){return{isColorSupported:!1,reset:Ot,bold:Ot,dim:Ot,italic:Ot,underline:Ot,inverse:Ot,hidden:Ot,strikethrough:Ot,black:Ot,red:Ot,green:Ot,yellow:Ot,blue:Ot,magenta:Ot,cyan:Ot,white:Ot,gray:Ot,bgBlack:Ot,bgRed:Ot,bgGreen:Ot,bgYellow:Ot,bgBlue:Ot,bgMagenta:Ot,bgCyan:Ot,bgWhite:Ot}};_t.exports=create$1(),_t.exports.createColors=create$1;var Dt=_t.exports;const Ft=getAugmentedNamespace$1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Nt=Dt,Lt=Ft,Pt=class CssSyntaxError extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=Nt.isColorSupported),Lt&&S&&(b=Lt(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=Nt.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var Bt=Pt;Pt.default=Pt;var zt={};zt.isClean=Symbol("isClean"),zt.my=Symbol("my");const Ut={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let $t=class Stringifier{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return Ut[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize$1(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=Ut[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var jt=$t;$t.default=$t;let qt=jt;function stringify$4$1(S,b){new qt(b).stringify(S)}var Wt=stringify$4$1;stringify$4$1.default=stringify$4$1;let{isClean:Ht,my:Vt}=zt,Qt=Bt,Gt=jt,Kt=Wt;function cloneNode$1(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode$1(S,I)):("object"===A&&null!==R&&(R=cloneNode$1(R)),I[x]=R)}return I}let Jt=class Node2{constructor(S={}){this.raws={},this[Ht]=!1,this[Vt]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode$1(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new Qt(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[Ht]){this[Ht]=!1;let S=this;for(;S=S.parent;)S[Ht]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new Gt).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=Kt){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var Xt=Jt;Jt.default=Jt;let Yt=Xt,Zt=class Declaration extends Yt{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var es=Zt;Zt.default=Zt;var ts={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:ss,SourceMapGenerator:rs}=Ft,{existsSync:ns,readFileSync:is}=Ft,{dirname:os,join:as}=Ft;let ls=class PreviousMap{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=os(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new ss(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64$1(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=os(S),ns(S))return this.mapFile=S,is(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof ss)return rs.fromSourceMap(b).toString();if(b instanceof rs)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=as(os(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var cs=ls;ls.default=ls;let{SourceMapConsumer:us,SourceMapGenerator:hs}=Ft,{fileURLToPath:ds,pathToFileURL:gs}=Ft,{isAbsolute:ps,resolve:fs}=Ft,{nanoid:ms}=ts,ys=Ft,vs=Bt,Ss=cs,ws=Symbol("fromOffsetCache"),bs=Boolean(us&&hs),Cs=Boolean(fs&&ps),ks=class Input{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!Cs||/^\w+:\/\//.test(b.from)||ps(b.from)?this.file=b.from:this.file=fs(b.from)),Cs&&bs){let S=new Ss(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+ms(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new vs(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new vs(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(gs&&(R.input.url=gs(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[ws])I=this[ws];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[ws]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:fs(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=ps(D.source)?gs(D.source):new URL(D.source,this.map.consumer().sourceRoot||gs(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!ds)throw new Error("file: protocol is not available in this PostCSS build");L.file=ds(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var Is=ks;ks.default=ks,ys&&ys.registerInput&&ys.registerInput(ks);let{SourceMapConsumer:Es,SourceMapGenerator:xs}=Ft,{dirname:Ms,relative:Rs,resolve:Ts,sep:As}=Ft,{pathToFileURL:_s}=Ft,Os=Is,Ds=Boolean(Es&&xs),Fs=Boolean(Ms&&Ts&&Rs&&As);var Ns=class MapGenerator{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||Ms(S.file);!1===this.mapOpts.sourcesContent?(b=new Es(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Fs&&Ds&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=xs.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new xs({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new xs({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?Ms(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Ms(Ts(I,this.mapOpts.annotation)));let x=Rs(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new Os(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(_s){let b=_s(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===As&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let Ls=Xt,Ps=class Comment extends Ls{constructor(S){super(S),this.type="comment"}};var Bs=Ps;Ps.default=Ps;let zs,Us,$s,js,{isClean:qs,my:Ws}=zt,Hs=es,Vs=Bs,Qs=Xt;function cleanSource$1(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource$1(S.nodes)),delete S.source,S))}function markDirtyUp$1(S){if(S[qs]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp$1(b)}let Gs=class Container extends Qs{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource$1(zs(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new Hs(S)]}else if(S.selector)S=[new Us(S)];else if(S.name)S=[new $s(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new Vs(S)]}return S.map(S=>(S[Ws]||Container.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[qs]&&markDirtyUp$1(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Gs.registerParse=S=>{zs=S},Gs.registerRule=S=>{Us=S},Gs.registerAtRule=S=>{$s=S},Gs.registerRoot=S=>{js=S};var Ks=Gs;Gs.default=Gs,Gs.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,$s.prototype):"rule"===S.type?Object.setPrototypeOf(S,Us.prototype):"decl"===S.type?Object.setPrototypeOf(S,Hs.prototype):"comment"===S.type?Object.setPrototypeOf(S,Vs.prototype):"root"===S.type&&Object.setPrototypeOf(S,js.prototype),S[Ws]=!0,S.nodes&&S.nodes.forEach(S=>{Gs.rebuild(S)})};let Js,Xs,Ys=Ks,Zs=class Document2 extends Ys{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Js(new Xs,this,S).stringify()}};Zs.registerLazyResult=S=>{Js=S},Zs.registerProcessor=S=>{Xs=S};var er=Zs;Zs.default=Zs;let tr=class Warning{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var sr=tr;tr.default=tr;let rr=sr,nr=class Result{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new rr(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var ir=nr;nr.default=nr;const or="'".charCodeAt(0),ar='"'.charCodeAt(0),lr="\\".charCodeAt(0),cr="/".charCodeAt(0),ur="\n".charCodeAt(0),hr=" ".charCodeAt(0),dr="\f".charCodeAt(0),gr="\t".charCodeAt(0),pr="\r".charCodeAt(0),fr="[".charCodeAt(0),mr="]".charCodeAt(0),yr="(".charCodeAt(0),vr=")".charCodeAt(0),Sr="{".charCodeAt(0),wr="}".charCodeAt(0),br=";".charCodeAt(0),Cr="*".charCodeAt(0),kr=":".charCodeAt(0),Ir="@".charCodeAt(0),Er=/[\t\n\f\r "#'()/;[\\\]{}]/g,xr=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Mr=/.[\r\n"'(/\\]/,Rr=/[\da-f]/i;let Tr=Ks,Ar=class AtRule extends Tr{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var _r=Ar;Ar.default=Ar,Tr.registerAtRule(Ar);let Or,Dr,Fr=Ks,Nr=class Root extends Fr{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new Or(new Dr,this,S).stringify()}};Nr.registerLazyResult=S=>{Or=S},Nr.registerProcessor=S=>{Dr=S};var Lr=Nr;Nr.default=Nr,Fr.registerRoot(Nr);let Pr={comma:S=>Pr.split(S,[","],!0),space:S=>Pr.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var Br=Pr;Pr.default=Pr;let zr=Ks,Ur=Br,$r=class Rule extends zr{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Ur.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var jr=$r;$r.default=$r,zr.registerRule($r);let qr=es,Wr=function tokenizer(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case ur:case hr:case gr:case pr:case dr:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===hr||I===ur||I===gr||I===pr||I===dr);$=["space",j.slice(V,x)],V=x-1;break;case fr:case mr:case Sr:case wr:case kr:case br:case vr:{let S=String.fromCharCode(I);$=[S,S,V];break}case yr:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==or&&U!==ar&&U!==hr&&U!==ur&&U!==gr&&U!==dr&&U!==pr){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===lr;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||Mr.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case or:case ar:R=I===or?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===lr;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Ir:Er.lastIndex=V+1,Er.test(j),x=0===Er.lastIndex?j.length-1:Er.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case lr:for(x=V,_=!0;j.charCodeAt(x+1)===lr;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==cr&&I!==hr&&I!==ur&&I!==gr&&I!==pr&&I!==dr&&(x+=1,Rr.test(j.charAt(x)))){for(;Rr.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===hr&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===cr&&j.charCodeAt(V+1)===Cr?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(xr.lastIndex=V+1,xr.test(j),x=0===xr.lastIndex?j.length-1:xr.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},Hr=Bs,Vr=_r,Qr=Lr,Gr=jr;const Kr={empty:!0,space:!0};var Jr=class Parser{constructor(S){this.input=S,this.root=new Qr,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new Vr;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new Hr;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=Wr(this.input)}decl(S,b){let I=new qr;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition$1(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new Gr;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",Kr[D]||Kr[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new Gr;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let Xr=Ks,Yr=Jr,Zr=Is;function parse$3$1(S,b){let I=new Zr(S,b),x=new Yr(I);try{x.parse()}catch(S){throw S}return x.root}var en=parse$3$1;parse$3$1.default=parse$3$1,Xr.registerParse(parse$3$1);let{isClean:tn,my:sn}=zt,rn=Ns,nn=Wt,an=Ks,cn=er,un=ir,hn=en,dn=Lr;const gn={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},pn={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},fn={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise$1(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents$1(S){let b=!1,I=gn[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack$1(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents$1(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks$1(S){return S[tn]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks$1(S)),S}let mn={},yn=class LazyResult{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult||b instanceof un)x=cleanMarks$1(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=hn;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[sn]&&an.rebuild(x)}else x=cleanMarks$1(b);this.result=new un(S,x,I),this.helpers={...mn,postcss:mn,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!pn[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!fn[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise$1(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[tn];){S[tn]=!0;let b=[toStack$1(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise$1(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise$1(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=nn;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new rn(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise$1(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[tn];)S[tn]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise$1(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[tn])return x[tn]=!0,void S.push(toStack$1(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[tn]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[tn]=!0;let b=getEvents$1(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[tn]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};yn.registerPostcss=S=>{mn=S};var vn=yn;yn.default=yn,dn.registerLazyResult(yn),cn.registerLazyResult(yn);let Sn=Ns,wn=Wt,bn=en;const Cn=ir;let kn=class NoWorkResult{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=wn;this.result=new Cn(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new Sn(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=bn;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var In=kn;kn.default=kn;let En=In,xn=vn,Mn=er,Rn=Lr,Tn=class Processor{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new xn(this,S,b):new En(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var An=Tn;Tn.default=Tn,Rn.registerProcessor(Tn),Mn.registerProcessor(Tn);let _n=es,On=cs,Dn=Bs,Fn=_r,Nn=Is,Ln=Lr,Pn=jr;function fromJSON$1$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:Nn.prototype};I.map&&(I.map={...I.map,__proto__:On.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new Ln(x);if("decl"===x.type)return new _n(x);if("rule"===x.type)return new Pn(x);if("comment"===x.type)return new Dn(x);if("atrule"===x.type)return new Fn(x);throw new Error("Unknown node type: "+S.type)}var Bn=fromJSON$1$1;fromJSON$1$1.default=fromJSON$1$1;let zn=Bt,Un=es,$n=vn,jn=Ks,qn=An,Wn=Wt,Hn=Bn,Vn=er,Qn=sr,Gn=Bs,Kn=_r,Jn=ir,Xn=Is,Yn=en,Zn=Br,ei=jr,ti=Lr,si=Xt;function postcss$3(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new qn(S)}postcss$3.plugin=function plugin(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new qn).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss$3([creator(I)]).process(S,b)},creator},postcss$3.stringify=Wn,postcss$3.parse=Yn,postcss$3.fromJSON=Hn,postcss$3.list=Zn,postcss$3.comment=S=>new Gn(S),postcss$3.atRule=S=>new Kn(S),postcss$3.decl=S=>new Un(S),postcss$3.rule=S=>new ei(S),postcss$3.root=S=>new ti(S),postcss$3.document=S=>new Vn(S),postcss$3.CssSyntaxError=zn,postcss$3.Declaration=Un,postcss$3.Container=jn,postcss$3.Processor=qn,postcss$3.Document=Vn,postcss$3.Comment=Gn,postcss$3.Warning=Qn,postcss$3.AtRule=Kn,postcss$3.Result=Jn,postcss$3.Input=Xn,postcss$3.Rule=ei,postcss$3.Root=ti,postcss$3.Node=si,$n.registerPostcss(postcss$3),postcss$3.default=postcss$3;var ri=Object.defineProperty,__publicField2=(S,b,I)=>((S,b,I)=>b in S?ri(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I);function getAugmentedNamespace(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var ni={exports:{}},ii=String,create=function(){return{isColorSupported:!1,reset:ii,bold:ii,dim:ii,italic:ii,underline:ii,inverse:ii,hidden:ii,strikethrough:ii,black:ii,red:ii,green:ii,yellow:ii,blue:ii,magenta:ii,cyan:ii,white:ii,gray:ii,bgBlack:ii,bgRed:ii,bgGreen:ii,bgYellow:ii,bgBlue:ii,bgMagenta:ii,bgCyan:ii,bgWhite:ii}};ni.exports=create(),ni.exports.createColors=create;var oi=ni.exports;const ai=getAugmentedNamespace(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let li=oi,ci=ai,ui=class CssSyntaxError2 extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError2)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=li.isColorSupported),ci&&S&&(b=ci(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=li.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var hi=ui;ui.default=ui;var di={};di.isClean=Symbol("isClean"),di.my=Symbol("my");const gi={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let pi=class Stringifier2{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return gi[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=gi[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var fi=pi;pi.default=pi;let mi=fi;function stringify$4(S,b){new mi(b).stringify(S)}var yi=stringify$4;stringify$4.default=stringify$4;let{isClean:vi,my:Si}=di,wi=hi,bi=fi,Ci=yi;function cloneNode(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode(S,I)):("object"===A&&null!==R&&(R=cloneNode(R)),I[x]=R)}return I}let ki=class Node3{constructor(S={}){this.raws={},this[vi]=!1,this[Si]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new wi(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[vi]){this[vi]=!1;let S=this;for(;S=S.parent;)S[vi]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new bi).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=Ci){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var Ii=ki;ki.default=ki;let Ei=Ii,xi=class Declaration2 extends Ei{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var Mi=xi;xi.default=xi;var Ri={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:Ti,SourceMapGenerator:Ai}=ai,{existsSync:_i,readFileSync:Oi}=ai,{dirname:Di,join:Fi}=ai;let Ni=class PreviousMap2{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=Di(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new Ti(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=Di(S),_i(S))return this.mapFile=S,Oi(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof Ti)return Ai.fromSourceMap(b).toString();if(b instanceof Ai)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=Fi(Di(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var Li=Ni;Ni.default=Ni;let{SourceMapConsumer:Pi,SourceMapGenerator:Bi}=ai,{fileURLToPath:zi,pathToFileURL:Ui}=ai,{isAbsolute:$i,resolve:ji}=ai,{nanoid:qi}=Ri,Wi=ai,Hi=hi,Vi=Li,Qi=Symbol("fromOffsetCache"),Gi=Boolean(Pi&&Bi),Ki=Boolean(ji&&$i),Ji=class Input2{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!Ki||/^\w+:\/\//.test(b.from)||$i(b.from)?this.file=b.from:this.file=ji(b.from)),Ki&&Gi){let S=new Vi(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+qi(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new Hi(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new Hi(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(Ui&&(R.input.url=Ui(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[Qi])I=this[Qi];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[Qi]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:ji(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=$i(D.source)?Ui(D.source):new URL(D.source,this.map.consumer().sourceRoot||Ui(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!zi)throw new Error("file: protocol is not available in this PostCSS build");L.file=zi(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var Xi=Ji;Ji.default=Ji,Wi&&Wi.registerInput&&Wi.registerInput(Ji);let{SourceMapConsumer:Yi,SourceMapGenerator:Zi}=ai,{dirname:eo,relative:to,resolve:so,sep:ro}=ai,{pathToFileURL:no}=ai,io=Xi,oo=Boolean(Yi&&Zi),ao=Boolean(eo&&so&&to&&ro);var lo=class MapGenerator2{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||eo(S.file);!1===this.mapOpts.sourcesContent?(b=new Yi(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),ao&&oo&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=Zi.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Zi({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Zi({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?eo(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=eo(so(I,this.mapOpts.annotation)));let x=to(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new io(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(no){let b=no(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===ro&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let co=Ii,uo=class Comment2 extends co{constructor(S){super(S),this.type="comment"}};var ho=uo;uo.default=uo;let go,po,fo,mo,{isClean:yo,my:vo}=di,So=Mi,wo=ho,bo=Ii;function cleanSource(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource(S.nodes)),delete S.source,S))}function markDirtyUp(S){if(S[yo]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp(b)}let Co=class Container2 extends bo{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource(go(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new So(S)]}else if(S.selector)S=[new po(S)];else if(S.name)S=[new fo(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new wo(S)]}return S.map(S=>(S[vo]||Container2.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[yo]&&markDirtyUp(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Co.registerParse=S=>{go=S},Co.registerRule=S=>{po=S},Co.registerAtRule=S=>{fo=S},Co.registerRoot=S=>{mo=S};var ko=Co;Co.default=Co,Co.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,fo.prototype):"rule"===S.type?Object.setPrototypeOf(S,po.prototype):"decl"===S.type?Object.setPrototypeOf(S,So.prototype):"comment"===S.type?Object.setPrototypeOf(S,wo.prototype):"root"===S.type&&Object.setPrototypeOf(S,mo.prototype),S[vo]=!0,S.nodes&&S.nodes.forEach(S=>{Co.rebuild(S)})};let Io,Eo,xo=ko,Mo=class Document23 extends xo{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Io(new Eo,this,S).stringify()}};Mo.registerLazyResult=S=>{Io=S},Mo.registerProcessor=S=>{Eo=S};var Ro=Mo;Mo.default=Mo;let To=class Warning2{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var Ao=To;To.default=To;let _o=Ao,Oo=class Result2{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new _o(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var Do=Oo;Oo.default=Oo;const Fo="'".charCodeAt(0),No='"'.charCodeAt(0),Lo="\\".charCodeAt(0),Po="/".charCodeAt(0),Bo="\n".charCodeAt(0),zo=" ".charCodeAt(0),Uo="\f".charCodeAt(0),$o="\t".charCodeAt(0),jo="\r".charCodeAt(0),qo="[".charCodeAt(0),Wo="]".charCodeAt(0),Ho="(".charCodeAt(0),Vo=")".charCodeAt(0),Qo="{".charCodeAt(0),Go="}".charCodeAt(0),Ko=";".charCodeAt(0),Jo="*".charCodeAt(0),Xo=":".charCodeAt(0),Yo="@".charCodeAt(0),Zo=/[\t\n\f\r "#'()/;[\\\]{}]/g,ea=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,ta=/.[\r\n"'(/\\]/,sa=/[\da-f]/i;let ra=ko,na=class AtRule2 extends ra{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var ia=na;na.default=na,ra.registerAtRule(na);let oa,aa,la=ko,ca=class Root2 extends la{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new oa(new aa,this,S).stringify()}};ca.registerLazyResult=S=>{oa=S},ca.registerProcessor=S=>{aa=S};var ua=ca;ca.default=ca,la.registerRoot(ca);let ha={comma:S=>ha.split(S,[","],!0),space:S=>ha.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var da=ha;ha.default=ha;let ga=ko,pa=da,fa=class Rule2 extends ga{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return pa.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var ma=fa;fa.default=fa,ga.registerRule(fa);let ya=Mi,va=function tokenizer2(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case Bo:case zo:case $o:case jo:case Uo:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===zo||I===Bo||I===$o||I===jo||I===Uo);$=["space",j.slice(V,x)],V=x-1;break;case qo:case Wo:case Qo:case Go:case Xo:case Ko:case Vo:{let S=String.fromCharCode(I);$=[S,S,V];break}case Ho:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==Fo&&U!==No&&U!==zo&&U!==Bo&&U!==$o&&U!==Uo&&U!==jo){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===Lo;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||ta.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case Fo:case No:R=I===Fo?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===Lo;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Yo:Zo.lastIndex=V+1,Zo.test(j),x=0===Zo.lastIndex?j.length-1:Zo.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case Lo:for(x=V,_=!0;j.charCodeAt(x+1)===Lo;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==Po&&I!==zo&&I!==Bo&&I!==$o&&I!==jo&&I!==Uo&&(x+=1,sa.test(j.charAt(x)))){for(;sa.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===zo&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===Po&&j.charCodeAt(V+1)===Jo?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(ea.lastIndex=V+1,ea.test(j),x=0===ea.lastIndex?j.length-1:ea.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},Sa=ho,wa=ia,ba=ua,Ca=ma;const ka={empty:!0,space:!0};var Ia=class Parser2{constructor(S){this.input=S,this.root=new ba,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new wa;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new Sa;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=va(this.input)}decl(S,b){let I=new ya;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new Ca;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",ka[D]||ka[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new Ca;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let Ea=ko,xa=Ia,Ma=Xi;function parse$3(S,b){let I=new Ma(S,b),x=new xa(I);try{x.parse()}catch(S){throw S}return x.root}var Ra=parse$3;parse$3.default=parse$3,Ea.registerParse(parse$3);let{isClean:Ta,my:Aa}=di,_a=lo,Oa=yi,Da=ko,Fa=Ro,Na=Do,La=Ra,Pa=ua;const Ba={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},za={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Ua={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents(S){let b=!1,I=Ba[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks(S){return S[Ta]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks(S)),S}let $a={},ja=class LazyResult2{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult2||b instanceof Na)x=cleanMarks(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=La;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[Aa]&&Da.rebuild(x)}else x=cleanMarks(b);this.result=new Na(S,x,I),this.helpers={...$a,postcss:$a,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!za[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Ua[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[Ta];){S[Ta]=!0;let b=[toStack(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=Oa;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new _a(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[Ta];)S[Ta]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[Ta])return x[Ta]=!0,void S.push(toStack(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[Ta]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[Ta]=!0;let b=getEvents(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[Ta]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};ja.registerPostcss=S=>{$a=S};var qa=ja;ja.default=ja,Pa.registerLazyResult(ja),Fa.registerLazyResult(ja);let Wa=lo,Ha=yi,Va=Ra;const Qa=Do;let Ga=class NoWorkResult2{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=Ha;this.result=new Qa(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new Wa(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=Va;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var Ka=Ga;Ga.default=Ga;let Ja=Ka,Xa=qa,Ya=Ro,Za=ua,el=class Processor2{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new Xa(this,S,b):new Ja(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var tl=el;el.default=el,Za.registerProcessor(el),Ya.registerProcessor(el);let sl=Mi,rl=Li,nl=ho,il=ia,ol=Xi,al=ua,ll=ma;function fromJSON$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:ol.prototype};I.map&&(I.map={...I.map,__proto__:rl.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new al(x);if("decl"===x.type)return new sl(x);if("rule"===x.type)return new ll(x);if("comment"===x.type)return new nl(x);if("atrule"===x.type)return new il(x);throw new Error("Unknown node type: "+S.type)}var cl=fromJSON$1;fromJSON$1.default=fromJSON$1;let ul=hi,hl=Mi,dl=qa,gl=ko,pl=tl,fl=yi,ml=cl,yl=Ro,vl=Ao,Sl=ho,wl=ia,bl=Do,Cl=Xi,kl=Ra,Il=da,El=ma,xl=ua,Ml=Ii;function postcss(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new pl(S)}postcss.plugin=function plugin2(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new pl).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss([creator(I)]).process(S,b)},creator},postcss.stringify=fl,postcss.parse=kl,postcss.fromJSON=ml,postcss.list=Il,postcss.comment=S=>new Sl(S),postcss.atRule=S=>new wl(S),postcss.decl=S=>new hl(S),postcss.rule=S=>new El(S),postcss.root=S=>new xl(S),postcss.document=S=>new yl(S),postcss.CssSyntaxError=ul,postcss.Declaration=hl,postcss.Container=gl,postcss.Processor=pl,postcss.Document=yl,postcss.Comment=Sl,postcss.Warning=vl,postcss.AtRule=wl,postcss.Result=bl,postcss.Input=Cl,postcss.Rule=El,postcss.Root=xl,postcss.Node=Ml,dl.registerPostcss(postcss),postcss.default=postcss;class BaseRRNode{constructor(...S){__publicField2(this,"parentElement",null),__publicField2(this,"parentNode",null),__publicField2(this,"ownerDocument"),__publicField2(this,"firstChild",null),__publicField2(this,"lastChild",null),__publicField2(this,"previousSibling",null),__publicField2(this,"nextSibling",null),__publicField2(this,"ELEMENT_NODE",1),__publicField2(this,"TEXT_NODE",3),__publicField2(this,"nodeType"),__publicField2(this,"nodeName"),__publicField2(this,"RRNodeType")}get childNodes(){const S=[];let b=this.firstChild;for(;b;)S.push(b),b=b.nextSibling;return S}contains(S){if(!(S instanceof BaseRRNode))return!1;if(S.ownerDocument!==this.ownerDocument)return!1;if(S===this)return!0;for(;S.parentNode;){if(S.parentNode===this)return!0;S=S.parentNode}return!1}appendChild(S){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(S,b){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(S){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}}const Rl={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Tl={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Al={};function getUntaintedPrototype(S){if(Al[S])return Al[S];const b=globalThis[S],I=b.prototype,x=S in Rl?Rl[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in Tl?Tl[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return Al[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?Al[S]=A:I}catch{return I}}const _l={};function getUntaintedAccessor(S,b,I){var x;const R=`${S}.${String(I)}`;if(_l[R])return _l[R].call(b);const A=getUntaintedPrototype(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(_l[R]=_,_.call(b)):b[I]}const Ol={};function getUntaintedMethod(S,b,I){const x=`${S}.${String(I)}`;if(Ol[x])return Ol[x].bind(b);const R=getUntaintedPrototype(S)[I];return"function"!=typeof R?b[I]:(Ol[x]=R,R.bind(b))}function mutationObserverCtor(){return getUntaintedPrototype("MutationObserver").constructor}const Dl={childNodes:function childNodes(S){return getUntaintedAccessor("Node",S,"childNodes")},parentNode:function parentNode(S){return getUntaintedAccessor("Node",S,"parentNode")},parentElement:function parentElement(S){return getUntaintedAccessor("Node",S,"parentElement")},textContent:function textContent(S){return getUntaintedAccessor("Node",S,"textContent")},contains:function contains(S,b){return getUntaintedMethod("Node",S,"contains")(b)},getRootNode:function getRootNode(S){return getUntaintedMethod("Node",S,"getRootNode")()},host:function host(S){return S&&"host"in S?getUntaintedAccessor("ShadowRoot",S,"host"):null},styleSheets:function styleSheets(S){return S.styleSheets},shadowRoot:function shadowRoot(S){return S&&"shadowRoot"in S?getUntaintedAccessor("Element",S,"shadowRoot"):null},querySelector:function querySelector(S,b){return getUntaintedAccessor("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll(S,b){return getUntaintedAccessor("Element",S,"querySelectorAll")(b)},mutationObserver:mutationObserverCtor};function on(S,b,I=document){const x={capture:!0,passive:!0};return I.addEventListener(S,b,x),()=>I.removeEventListener(S,b,x)}const Fl="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let Nl={map:{},getId:()=>(console.error(Fl),-1),getNode:()=>(console.error(Fl),null),removeNodeFromMap(){console.error(Fl)},has:()=>(console.error(Fl),!1),reset(){console.error(Fl)}};function throttle(S,b,I={}){let x=null,R=0;return function(...A){const _=Date.now();R||!1!==I.leading||(R=_);const D=b-(_-R),L=this;D<=0||D>b?(x&&(clearTimeout(x),x=null),R=_,S.apply(L,A)):x||!1===I.trailing||(x=setTimeout(()=>{R=!1===I.leading?0:Date.now(),x=null,S.apply(L,A)},D))}}function hookSetter(S,b,I,x,R=window){const A=R.Object.getOwnPropertyDescriptor(S,b);return R.Object.defineProperty(S,b,x?I:{set(S){setTimeout(()=>{I.set.call(this,S)},0),A&&A.set&&A.set.call(this,S)}}),()=>hookSetter(S,b,A||{},!0)}function patch(S,b,I){try{if(!(b in S))return()=>{};const x=S[b],R=I(x);return"function"==typeof R&&(R.prototype=R.prototype||{},Object.defineProperties(R,{__rrweb_original__:{enumerable:!1,value:x}})),S[b]=R,()=>{S[b]=x}}catch{return()=>{}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Nl=new Proxy(Nl,{get:(S,b,I)=>("map"===b&&console.error(Fl),Reflect.get(S,b,I))}));let Ll=Date.now;function getWindowScroll(S){var b,I,x,R;const A=S.document;return{left:A.scrollingElement?A.scrollingElement.scrollLeft:void 0!==S.pageXOffset?S.pageXOffset:A.documentElement.scrollLeft||(null==A?void 0:A.body)&&(null==(b=Dl.parentElement(A.body))?void 0:b.scrollLeft)||(null==(I=null==A?void 0:A.body)?void 0:I.scrollLeft)||0,top:A.scrollingElement?A.scrollingElement.scrollTop:void 0!==S.pageYOffset?S.pageYOffset:(null==A?void 0:A.documentElement.scrollTop)||(null==A?void 0:A.body)&&(null==(x=Dl.parentElement(A.body))?void 0:x.scrollTop)||(null==(R=null==A?void 0:A.body)?void 0:R.scrollTop)||0}}function getWindowHeight(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function getWindowWidth(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function closestElementOfNode(S){if(!S)return null;return S.nodeType===S.ELEMENT_NODE?S:Dl.parentElement(S)}function isBlocked(S,b,I,x){if(!S)return!1;const R=closestElementOfNode(S);if(!R)return!1;try{if("string"==typeof b){if(R.classList.contains(b))return!0;if(x&&null!==R.closest("."+b))return!0}else if(classMatchesRegex(R,b,x))return!0}catch(S){}if(I){if(R.matches(I))return!0;if(x&&null!==R.closest(I))return!0}return!1}function isIgnored(S,b,I){return!("TITLE"!==S.tagName||!I.headTitleMutations)||-2===b.getId(S)}function isAncestorRemoved(S,b){if(isShadowRoot(S))return!1;const I=b.getId(S);if(!b.has(I))return!0;const x=Dl.parentNode(S);return(!x||x.nodeType!==S.DOCUMENT_NODE)&&(!x||isAncestorRemoved(x,b))}function legacy_isTouchEvent(S){return Boolean(S.changedTouches)}function isSerializedIframe(S,b){return Boolean("IFRAME"===S.nodeName&&b.getMeta(S))}function isSerializedStylesheet(S,b){return Boolean("LINK"===S.nodeName&&S.nodeType===S.ELEMENT_NODE&&S.getAttribute&&"stylesheet"===S.getAttribute("rel")&&b.getMeta(S))}function hasShadowRoot(S){return!!S&&(S instanceof BaseRRNode&&"shadowRoot"in S?Boolean(S.shadowRoot):Boolean(Dl.shadowRoot(S)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(Ll=()=>(new Date).getTime());class StyleSheetMirror{constructor(){__publicField(this,"id",1),__publicField(this,"styleIDMap",new WeakMap),__publicField(this,"idStyleMap",new Map)}getId(S){return this.styleIDMap.get(S)??-1}has(S){return this.styleIDMap.has(S)}add(S,b){if(this.has(S))return this.getId(S);let I;return I=void 0===b?this.id++:b,this.styleIDMap.set(S,I),this.idStyleMap.set(I,S),I}getStyle(S){return this.idStyleMap.get(S)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function getShadowHost(S){var b;let I=null;return"getRootNode"in S&&(null==(b=Dl.getRootNode(S))?void 0:b.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&Dl.host(Dl.getRootNode(S))&&(I=Dl.host(Dl.getRootNode(S))),I}function shadowHostInDom(S){const b=S.ownerDocument;if(!b)return!1;const I=function getRootShadowHost(S){let b,I=S;for(;b=getShadowHost(I);)I=b;return I}(S);return Dl.contains(b,I)}function inDom(S){const b=S.ownerDocument;return!!b&&(Dl.contains(b,S)||shadowHostInDom(S))}var Pl=(S=>(S[S.DomContentLoaded=0]="DomContentLoaded",S[S.Load=1]="Load",S[S.FullSnapshot=2]="FullSnapshot",S[S.IncrementalSnapshot=3]="IncrementalSnapshot",S[S.Meta=4]="Meta",S[S.Custom=5]="Custom",S[S.Plugin=6]="Plugin",S))(Pl||{}),Bl=(S=>(S[S.Mutation=0]="Mutation",S[S.MouseMove=1]="MouseMove",S[S.MouseInteraction=2]="MouseInteraction",S[S.Scroll=3]="Scroll",S[S.ViewportResize=4]="ViewportResize",S[S.Input=5]="Input",S[S.TouchMove=6]="TouchMove",S[S.MediaInteraction=7]="MediaInteraction",S[S.StyleSheetRule=8]="StyleSheetRule",S[S.CanvasMutation=9]="CanvasMutation",S[S.Font=10]="Font",S[S.Log=11]="Log",S[S.Drag=12]="Drag",S[S.StyleDeclaration=13]="StyleDeclaration",S[S.Selection=14]="Selection",S[S.AdoptedStyleSheet=15]="AdoptedStyleSheet",S[S.CustomElement=16]="CustomElement",S))(Bl||{}),zl=(S=>(S[S.MouseUp=0]="MouseUp",S[S.MouseDown=1]="MouseDown",S[S.Click=2]="Click",S[S.ContextMenu=3]="ContextMenu",S[S.DblClick=4]="DblClick",S[S.Focus=5]="Focus",S[S.Blur=6]="Blur",S[S.TouchStart=7]="TouchStart",S[S.TouchMove_Departed=8]="TouchMove_Departed",S[S.TouchEnd=9]="TouchEnd",S[S.TouchCancel=10]="TouchCancel",S))(zl||{}),Ul=(S=>(S[S.Mouse=0]="Mouse",S[S.Pen=1]="Pen",S[S.Touch=2]="Touch",S))(Ul||{}),$l=(S=>(S[S["2D"]=0]="2D",S[S.WebGL=1]="WebGL",S[S.WebGL2=2]="WebGL2",S))($l||{}),jl=(S=>(S[S.Play=0]="Play",S[S.Pause=1]="Pause",S[S.Seeked=2]="Seeked",S[S.VolumeChange=3]="VolumeChange",S[S.RateChange=4]="RateChange",S))(jl||{}),ql=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(ql||{});function isNodeInLinkedList(S){return"__ln"in S}class DoubleLinkedList{constructor(){__publicField(this,"length",0),__publicField(this,"head",null),__publicField(this,"tail",null)}get(S){if(S>=this.length)throw new Error("Position outside of list range");let b=this.head;for(let I=0;I<S;I++)b=(null==b?void 0:b.next)||null;return b}addNode(S){const b={value:S,previous:null,next:null};if(S.__ln=b,S.previousSibling&&isNodeInLinkedList(S.previousSibling)){const I=S.previousSibling.__ln.next;b.next=I,b.previous=S.previousSibling.__ln,S.previousSibling.__ln.next=b,I&&(I.previous=b)}else if(S.nextSibling&&isNodeInLinkedList(S.nextSibling)&&S.nextSibling.__ln.previous){const I=S.nextSibling.__ln.previous;b.previous=I,b.next=S.nextSibling.__ln,S.nextSibling.__ln.previous=b,I&&(I.next=b)}else this.head&&(this.head.previous=b),b.next=this.head,this.head=b;null===b.next&&(this.tail=b),this.length++}removeNode(S){const b=S.__ln;this.head&&(b.previous?(b.previous.next=b.next,b.next?b.next.previous=b.previous:this.tail=b.previous):(this.head=b.next,this.head?this.head.previous=null:this.tail=null),S.__ln&&delete S.__ln,this.length--)}}const moveKey=(S,b)=>`${S}@${b}`;class MutationBuffer{constructor(){__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"texts",[]),__publicField(this,"attributes",[]),__publicField(this,"attributeMap",new WeakMap),__publicField(this,"removes",[]),__publicField(this,"mapRemoves",[]),__publicField(this,"movedMap",{}),__publicField(this,"addedSet",new Set),__publicField(this,"movedSet",new Set),__publicField(this,"droppedSet",new Set),__publicField(this,"removesSubTreeCache",new Set),__publicField(this,"mutationCb"),__publicField(this,"blockClass"),__publicField(this,"blockSelector"),__publicField(this,"maskTextClass"),__publicField(this,"maskTextSelector"),__publicField(this,"inlineStylesheet"),__publicField(this,"maskInputOptions"),__publicField(this,"maskTextFn"),__publicField(this,"maskInputFn"),__publicField(this,"keepIframeSrcFn"),__publicField(this,"recordCanvas"),__publicField(this,"inlineImages"),__publicField(this,"slimDOMOptions"),__publicField(this,"dataURLOptions"),__publicField(this,"doc"),__publicField(this,"mirror"),__publicField(this,"iframeManager"),__publicField(this,"stylesheetManager"),__publicField(this,"shadowDomManager"),__publicField(this,"canvasManager"),__publicField(this,"processedNodeManager"),__publicField(this,"unattachedDoc"),__publicField(this,"processMutations",S=>{S.forEach(this.processMutation),this.emit()}),__publicField(this,"emit",()=>{if(this.frozen||this.locked)return;const S=[],b=new Set,I=new DoubleLinkedList,getNextId=S=>{let b=S,I=-2;for(;-2===I;)b=b&&b.nextSibling,I=b&&this.mirror.getId(b);return I},pushAdd=x=>{const R=Dl.parentNode(x);if(!R||!inDom(x))return;let A=!1;if(x.nodeType===Node.TEXT_NODE){const S=R.tagName;if("TEXTAREA"===S)return;"STYLE"===S&&this.addedSet.has(R)&&(A=!0)}const _=isShadowRoot(R)?this.mirror.getId(getShadowHost(x)):this.mirror.getId(R),D=getNextId(x);if(-1===_||-1===D)return I.addNode(x);const L=serializeNodeWithId(x,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:S=>{isSerializedIframe(S,this.mirror)&&this.iframeManager.addIframe(S),isSerializedStylesheet(S,this.mirror)&&this.stylesheetManager.trackLinkElement(S),hasShadowRoot(x)&&this.shadowDomManager.addShadowRoot(Dl.shadowRoot(x),this.doc)},onIframeLoad:(S,b)=>{this.iframeManager.attachIframe(S,b),this.shadowDomManager.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{this.stylesheetManager.attachLinkElement(S,b)},cssCaptured:A});L&&(S.push({parentId:_,nextId:D,node:L}),b.add(L.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const S of this.movedSet)isParentRemoved(this.removesSubTreeCache,S)&&!this.movedSet.has(Dl.parentNode(S))||pushAdd(S);for(const S of this.addedSet)isAncestorInSet(this.droppedSet,S)||isParentRemoved(this.removesSubTreeCache,S)?isAncestorInSet(this.movedSet,S)?pushAdd(S):this.droppedSet.add(S):pushAdd(S);let x=null;for(;I.length;){let S=null;if(x){const b=this.mirror.getId(Dl.parentNode(x.value)),I=getNextId(x.value);-1!==b&&-1!==I&&(S=x)}if(!S){let b=I.tail;for(;b;){const I=b;if(b=b.previous,I){const b=this.mirror.getId(Dl.parentNode(I.value));if(-1===getNextId(I.value))continue;if(-1!==b){S=I;break}{const b=I.value,x=Dl.parentNode(b);if(x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const b=Dl.host(x);if(-1!==this.mirror.getId(b)){S=I;break}}}}}}if(!S){for(;I.head;)I.removeNode(I.head.value);break}x=S.previous,I.removeNode(S.value),pushAdd(S.value)}const R={texts:this.texts.map(S=>{const b=S.node,I=Dl.parentNode(b);return I&&"TEXTAREA"===I.tagName&&this.genTextAreaValueMutation(I),{id:this.mirror.getId(b),value:S.value}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),attributes:this.attributes.map(S=>{const{attributes:b}=S;if("string"==typeof b.style){const I=JSON.stringify(S.styleDiff),x=JSON.stringify(S._unchangedStyles);I.length<b.style.length&&(I+x).split("var(").length===b.style.split("var(").length&&(b.style=S.styleDiff)}return{id:this.mirror.getId(S.node),attributes:b}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),removes:this.removes,adds:S};(R.texts.length||R.attributes.length||R.removes.length||R.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(R))}),__publicField(this,"genTextAreaValueMutation",S=>{let b=this.attributeMap.get(S);b||(b={node:S,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(b),this.attributeMap.set(S,b)),b.attributes.value=Array.from(Dl.childNodes(S),S=>Dl.textContent(S)||"").join("")}),__publicField(this,"processMutation",S=>{if(!isIgnored(S.target,this.mirror,this.slimDOMOptions))switch(S.type){case"characterData":{const b=Dl.textContent(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||b===S.oldValue||this.texts.push({value:needMaskingText(S.target,this.maskTextClass,this.maskTextSelector,!0)&&b?this.maskTextFn?this.maskTextFn(b,closestElementOfNode(S.target)):b.replace(/[\S]/g,"*"):b,node:S.target});break}case"attributes":{const b=S.target;let I=S.attributeName,x=S.target.getAttribute(I);if("value"===I){const S=getInputType(b);x=maskInputValue({element:b,maskInputOptions:this.maskInputOptions,tagName:b.tagName,type:S,value:x,maskInputFn:this.maskInputFn})}if(isBlocked(S.target,this.blockClass,this.blockSelector,!1)||x===S.oldValue)return;let R=this.attributeMap.get(S.target);if("IFRAME"===b.tagName&&"src"===I&&!this.keepIframeSrcFn(x)){if(__tsSafeContentDoc(b))return;I="rr_src"}if(R||(R={node:S.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(R),this.attributeMap.set(S.target,R)),"type"===I&&"INPUT"===b.tagName&&"password"===(S.oldValue||"").toLowerCase()&&b.setAttribute("data-rr-is-password","true"),!ignoreAttribute(b.tagName,I))if(R.attributes[I]=transformAttribute(this.doc,toLowerCase(b.tagName),toLowerCase(I),x),"style"===I){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(S){this.unattachedDoc=this.doc}const I=this.unattachedDoc.createElement("span");S.oldValue&&I.setAttribute("style",S.oldValue);for(const S of Array.from(b.style)){const x=b.style.getPropertyValue(S),A=b.style.getPropertyPriority(S);x!==I.style.getPropertyValue(S)||A!==I.style.getPropertyPriority(S)?R.styleDiff[S]=""===A?x:[x,A]:R._unchangedStyles[S]=[x,A]}for(const S of Array.from(I.style))""===b.style.getPropertyValue(S)&&(R.styleDiff[S]=!1)}else"open"===I&&"DIALOG"===b.tagName&&(b.matches("dialog:modal")?R.attributes.rr_open_mode="modal":R.attributes.rr_open_mode="non-modal");break}case"childList":if(isBlocked(S.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===S.target.tagName)return void this.genTextAreaValueMutation(S.target);S.addedNodes.forEach(b=>this.genAdds(b,S.target)),S.removedNodes.forEach(b=>{const I=this.mirror.getId(b),x=isShadowRoot(S.target)?this.mirror.getId(Dl.host(S.target)):this.mirror.getId(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||isIgnored(b,this.mirror,this.slimDOMOptions)||!function isSerialized(S,b){return-1!==b.getId(S)}(b,this.mirror)||(this.addedSet.has(b)?(deepDelete(this.addedSet,b),this.droppedSet.add(b)):this.addedSet.has(S.target)&&-1===I||isAncestorRemoved(S.target,this.mirror)||(this.movedSet.has(b)&&this.movedMap[moveKey(I,x)]?deepDelete(this.movedSet,b):(this.removes.push({parentId:x,id:I,isShadow:!(!isShadowRoot(S.target)||!isNativeShadowDom(S.target))||void 0}),function processRemoves(S,b){const I=[S];for(;I.length;){const S=I.pop();b.has(S)||(b.add(S),Dl.childNodes(S).forEach(S=>I.push(S)))}return}(b,this.removesSubTreeCache))),this.mapRemoves.push(b))})}}),__publicField(this,"genAdds",(S,b)=>{if(!this.processedNodeManager.inOtherBuffer(S,this)&&!this.addedSet.has(S)&&!this.movedSet.has(S)){if(this.mirror.hasNode(S)){if(isIgnored(S,this.mirror,this.slimDOMOptions))return;this.movedSet.add(S);let I=null;b&&this.mirror.hasNode(b)&&(I=this.mirror.getId(b)),I&&-1!==I&&(this.movedMap[moveKey(this.mirror.getId(S),I)]=!0)}else this.addedSet.add(S),this.droppedSet.delete(S);isBlocked(S,this.blockClass,this.blockSelector,!1)||(Dl.childNodes(S).forEach(S=>this.genAdds(S)),hasShadowRoot(S)&&Dl.childNodes(Dl.shadowRoot(S)).forEach(b=>{this.processedNodeManager.add(b,this),this.genAdds(b,S)}))}})}init(S){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(b=>{this[b]=S[b]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function deepDelete(S,b){S.delete(b),Dl.childNodes(b).forEach(b=>deepDelete(S,b))}function isParentRemoved(S,b,I){return 0!==S.size&&function _isParentRemoved(S,b,I){const x=Dl.parentNode(b);return!!x&&S.has(x)}(S,b)}function isAncestorInSet(S,b){return 0!==S.size&&_isAncestorInSet(S,b)}function _isAncestorInSet(S,b){const I=Dl.parentNode(b);return!!I&&(!!S.has(I)||_isAncestorInSet(S,I))}let Wl;const callbackWrapper=S=>{if(!Wl)return S;return(...b)=>{try{return S(...b)}catch(S){if(Wl&&!0===Wl(S))return;throw S}}},Hl=[];function getEventTarget(S){try{if("composedPath"in S){const b=S.composedPath();if(b.length)return b[0]}else if("path"in S&&S.path.length)return S.path[0]}catch{}return S&&S.target}function initMutationObserver(S,b){const I=new MutationBuffer;Hl.push(I),I.init(S);const x=new(mutationObserverCtor())(callbackWrapper(I.processMutations.bind(I)));return x.observe(b,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),x}function initMouseInteractionObserver({mouseInteractionCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){if(!1===A.mouseInteraction)return()=>{};const _=!0===A.mouseInteraction||void 0===A.mouseInteraction?{}:A.mouseInteraction,D=[];let L=null;return Object.keys(zl).filter(S=>Number.isNaN(Number(S))&&!S.endsWith("_Departed")&&!1!==_[S]).forEach(A=>{let _=toLowerCase(A);const B=(b=>A=>{const _=getEventTarget(A);if(isBlocked(_,x,R,!0))return;let D=null,B=b;if("pointerType"in A){switch(A.pointerType){case"mouse":D=Ul.Mouse;break;case"touch":D=Ul.Touch;break;case"pen":D=Ul.Pen}D===Ul.Touch&&(zl[b]===zl.MouseDown?B="TouchStart":zl[b]===zl.MouseUp&&(B="TouchEnd"))}else legacy_isTouchEvent(A)&&(D=Ul.Touch);null!==D?(L=D,(B.startsWith("Touch")&&D===Ul.Touch||B.startsWith("Mouse")&&D===Ul.Mouse)&&(D=null)):zl[b]===zl.Click&&(D=L,L=null);const U=legacy_isTouchEvent(A)?A.changedTouches[0]:A;if(!U)return;const $=I.getId(_),{clientX:j,clientY:W}=U;callbackWrapper(S)({type:zl[B],id:$,x:j,y:W,...null!==D&&{pointerType:D}})})(A);if(window.PointerEvent)switch(zl[A]){case zl.MouseDown:case zl.MouseUp:_=_.replace("mouse","pointer");break;case zl.TouchStart:case zl.TouchEnd:return}D.push(on(_,B,b))}),callbackWrapper(()=>{D.forEach(S=>S())})}function initScrollObserver({scrollCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){return on("scroll",callbackWrapper(throttle(callbackWrapper(A=>{const _=getEventTarget(A);if(!_||isBlocked(_,x,R,!0))return;const D=I.getId(_);if(_===b&&b.defaultView){const I=getWindowScroll(b.defaultView);S({id:D,x:I.left,y:I.top})}else S({id:D,x:_.scrollLeft,y:_.scrollTop})}),A.scroll||100)),b)}const Vl=["INPUT","TEXTAREA","SELECT"],Ql=new WeakMap;function getNestedCSSRulePositions(S){return function recurse(S,b){if(hasNestedCSSRule("CSSGroupingRule")&&S.parentRule instanceof CSSGroupingRule||hasNestedCSSRule("CSSMediaRule")&&S.parentRule instanceof CSSMediaRule||hasNestedCSSRule("CSSSupportsRule")&&S.parentRule instanceof CSSSupportsRule||hasNestedCSSRule("CSSConditionRule")&&S.parentRule instanceof CSSConditionRule){const I=Array.from(S.parentRule.cssRules).indexOf(S);b.unshift(I)}else if(S.parentStyleSheet){const I=Array.from(S.parentStyleSheet.cssRules).indexOf(S);b.unshift(I)}return b}(S,[])}function getIdAndStyleId(S,b,I){let x,R;return S?(S.ownerNode?x=b.getId(S.ownerNode):R=I.getId(S),{styleId:R,id:x}):{}}function initAdoptedStyleSheetObserver({mirror:S,stylesheetManager:b},I){var x,R,A;let _=null;_="#document"===I.nodeName?S.getId(I):S.getId(Dl.host(I));const D="#document"===I.nodeName?null==(x=I.defaultView)?void 0:x.Document:null==(A=null==(R=I.ownerDocument)?void 0:R.defaultView)?void 0:A.ShadowRoot,L=(null==D?void 0:D.prototype)?Object.getOwnPropertyDescriptor(null==D?void 0:D.prototype,"adoptedStyleSheets"):void 0;return null!==_&&-1!==_&&D&&L?(Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get(){var S;return null==(S=L.get)?void 0:S.call(this)},set(S){var I;const x=null==(I=L.set)?void 0:I.call(this,S);if(null!==_&&-1!==_)try{b.adoptStyleSheets(S,_)}catch(S){}return x}}),callbackWrapper(()=>{Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get:L.get,set:L.set})})):()=>{}}function initObservers(S,b={}){const I=S.doc.defaultView;if(!I)return()=>{};let x;!function mergeHooks(S,b){const{mutationCb:I,mousemoveCb:x,mouseInteractionCb:R,scrollCb:A,viewportResizeCb:_,inputCb:D,mediaInteractionCb:L,styleSheetRuleCb:B,styleDeclarationCb:U,canvasMutationCb:$,fontCb:j,selectionCb:W,customElementCb:H}=S;S.mutationCb=(...S)=>{b.mutation&&b.mutation(...S),I(...S)},S.mousemoveCb=(...S)=>{b.mousemove&&b.mousemove(...S),x(...S)},S.mouseInteractionCb=(...S)=>{b.mouseInteraction&&b.mouseInteraction(...S),R(...S)},S.scrollCb=(...S)=>{b.scroll&&b.scroll(...S),A(...S)},S.viewportResizeCb=(...S)=>{b.viewportResize&&b.viewportResize(...S),_(...S)},S.inputCb=(...S)=>{b.input&&b.input(...S),D(...S)},S.mediaInteractionCb=(...S)=>{b.mediaInteaction&&b.mediaInteaction(...S),L(...S)},S.styleSheetRuleCb=(...S)=>{b.styleSheetRule&&b.styleSheetRule(...S),B(...S)},S.styleDeclarationCb=(...S)=>{b.styleDeclaration&&b.styleDeclaration(...S),U(...S)},S.canvasMutationCb=(...S)=>{b.canvasMutation&&b.canvasMutation(...S),$(...S)},S.fontCb=(...S)=>{b.font&&b.font(...S),j(...S)},S.selectionCb=(...S)=>{b.selection&&b.selection(...S),W(...S)},S.customElementCb=(...S)=>{b.customElement&&b.customElement(...S),H(...S)}}(S,b),S.recordDOM&&(x=initMutationObserver(S,S.doc));const R=function initMoveObserver({mousemoveCb:S,sampling:b,doc:I,mirror:x}){if(!1===b.mousemove)return()=>{};const R="number"==typeof b.mousemove?b.mousemove:50,A="number"==typeof b.mousemoveCallback?b.mousemoveCallback:500;let _,D=[];const L=throttle(callbackWrapper(b=>{const I=Date.now()-_;S(D.map(S=>(S.timeOffset-=I,S)),b),D=[],_=null}),A),B=callbackWrapper(throttle(callbackWrapper(S=>{const b=getEventTarget(S),{clientX:I,clientY:R}=legacy_isTouchEvent(S)?S.changedTouches[0]:S;_||(_=Ll()),D.push({x:I,y:R,id:x.getId(b),timeOffset:Ll()-_}),L("undefined"!=typeof DragEvent&&S instanceof DragEvent?Bl.Drag:S instanceof MouseEvent?Bl.MouseMove:Bl.TouchMove)}),R,{trailing:!1})),U=[on("mousemove",B,I),on("touchmove",B,I),on("drag",B,I)];return callbackWrapper(()=>{U.forEach(S=>S())})}(S),A=initMouseInteractionObserver(S),_=initScrollObserver(S),D=function initViewportResizeObserver({viewportResizeCb:S},{win:b}){let I=-1,x=-1;return on("resize",callbackWrapper(throttle(callbackWrapper(()=>{const b=getWindowHeight(),R=getWindowWidth();I===b&&x===R||(S({width:Number(R),height:Number(b)}),I=b,x=R)}),200)),b)}(S,{win:I}),L=function initInputObserver({inputCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,ignoreClass:A,ignoreSelector:_,maskInputOptions:D,maskInputFn:L,sampling:B,userTriggeredOnInput:U}){function eventHandler(S){let I=getEventTarget(S);const B=S.isTrusted,$=I&&I.tagName;if(I&&"OPTION"===$&&(I=Dl.parentElement(I)),!I||!$||Vl.indexOf($)<0||isBlocked(I,x,R,!0))return;if(I.classList.contains(A)||_&&I.matches(_))return;let j=I.value,W=!1;const H=getInputType(I)||"";"radio"===H||"checkbox"===H?W=I.checked:(D[$.toLowerCase()]||D[H])&&(j=maskInputValue({element:I,maskInputOptions:D,tagName:$,type:H,value:j,maskInputFn:L})),cbWithDedup(I,U?{text:j,isChecked:W,userTriggered:B}:{text:j,isChecked:W});const V=I.name;"radio"===H&&V&&W&&b.querySelectorAll(`input[type="radio"][name="${V}"]`).forEach(S=>{if(S!==I){const b=S.value;cbWithDedup(S,U?{text:b,isChecked:!W,userTriggered:!1}:{text:b,isChecked:!W})}})}function cbWithDedup(b,x){const R=Ql.get(b);if(!R||R.text!==x.text||R.isChecked!==x.isChecked){Ql.set(b,x);const R=I.getId(b);callbackWrapper(S)({...x,id:R})}}const $=("last"===B.input?["change"]:["input","change"]).map(S=>on(S,callbackWrapper(eventHandler),b)),j=b.defaultView;if(!j)return()=>{$.forEach(S=>S())};const W=j.Object.getOwnPropertyDescriptor(j.HTMLInputElement.prototype,"value"),H=[[j.HTMLInputElement.prototype,"value"],[j.HTMLInputElement.prototype,"checked"],[j.HTMLSelectElement.prototype,"value"],[j.HTMLTextAreaElement.prototype,"value"],[j.HTMLSelectElement.prototype,"selectedIndex"],[j.HTMLOptionElement.prototype,"selected"]];return W&&W.set&&$.push(...H.map(S=>hookSetter(S[0],S[1],{set(){callbackWrapper(eventHandler)({target:this,isTrusted:!1})}},!1,j))),callbackWrapper(()=>{$.forEach(S=>S())})}(S),B=function initMediaInteractionObserver({mediaInteractionCb:S,blockClass:b,blockSelector:I,mirror:x,sampling:R,doc:A}){const _=callbackWrapper(A=>throttle(callbackWrapper(R=>{const _=getEventTarget(R);if(!_||isBlocked(_,b,I,!0))return;const{currentTime:D,volume:L,muted:B,playbackRate:U,loop:$}=_;S({type:A,id:x.getId(_),currentTime:D,volume:L,muted:B,playbackRate:U,loop:$})}),R.media||500)),D=[on("play",_(jl.Play),A),on("pause",_(jl.Pause),A),on("seeked",_(jl.Seeked),A),on("volumechange",_(jl.VolumeChange),A),on("ratechange",_(jl.RateChange),A)];return callbackWrapper(()=>{D.forEach(S=>S())})}(S);let styleSheetObserver=()=>{},adoptedStyleSheetObserver=()=>{},styleDeclarationObserver=()=>{},fontObserver=()=>{};S.recordDOM&&(styleSheetObserver=function initStyleSheetObserver({styleSheetRuleCb:S,mirror:b,stylesheetManager:I},{win:x}){if(!x.CSSStyleSheet||!x.CSSStyleSheet.prototype)return()=>{};const R=x.CSSStyleSheet.prototype.insertRule;x.CSSStyleSheet.prototype.insertRule=new Proxy(R,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:D}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.addRule=function(S,b,I=this.cssRules.length){const R=`${S} { ${b} }`;return x.CSSStyleSheet.prototype.insertRule.apply(this,[R,I])};const A=x.CSSStyleSheet.prototype.deleteRule;let _,D;x.CSSStyleSheet.prototype.deleteRule=new Proxy(A,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:_}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.removeRule=function(S){return x.CSSStyleSheet.prototype.deleteRule.apply(this,[S])},x.CSSStyleSheet.prototype.replace&&(_=x.CSSStyleSheet.prototype.replace,x.CSSStyleSheet.prototype.replace=new Proxy(_,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replace:_}),x.apply(R,A)})})),x.CSSStyleSheet.prototype.replaceSync&&(D=x.CSSStyleSheet.prototype.replaceSync,x.CSSStyleSheet.prototype.replaceSync=new Proxy(D,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replaceSync:_}),x.apply(R,A)})}));const L={};canMonkeyPatchNestedCSSRule("CSSGroupingRule")?L.CSSGroupingRule=x.CSSGroupingRule:(canMonkeyPatchNestedCSSRule("CSSMediaRule")&&(L.CSSMediaRule=x.CSSMediaRule),canMonkeyPatchNestedCSSRule("CSSConditionRule")&&(L.CSSConditionRule=x.CSSConditionRule),canMonkeyPatchNestedCSSRule("CSSSupportsRule")&&(L.CSSSupportsRule=x.CSSSupportsRule));const B={};return Object.entries(L).forEach(([x,R])=>{B[x]={insertRule:R.prototype.insertRule,deleteRule:R.prototype.deleteRule},R.prototype.insertRule=new Proxy(B[x].insertRule,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:[...getNestedCSSRulePositions(R),D||0]}]}),x.apply(R,A)})}),R.prototype.deleteRule=new Proxy(B[x].deleteRule,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:[...getNestedCSSRulePositions(R),_]}]}),x.apply(R,A)})})}),callbackWrapper(()=>{x.CSSStyleSheet.prototype.insertRule=R,x.CSSStyleSheet.prototype.deleteRule=A,_&&(x.CSSStyleSheet.prototype.replace=_),D&&(x.CSSStyleSheet.prototype.replaceSync=D),Object.entries(L).forEach(([S,b])=>{b.prototype.insertRule=B[S].insertRule,b.prototype.deleteRule=B[S].deleteRule})})}(S,{win:I}),adoptedStyleSheetObserver=initAdoptedStyleSheetObserver(S,S.doc),styleDeclarationObserver=function initStyleDeclarationObserver({styleDeclarationCb:S,mirror:b,ignoreCSSAttributes:I,stylesheetManager:x},{win:R}){const A=R.CSSStyleDeclaration.prototype.setProperty;R.CSSStyleDeclaration.prototype.setProperty=new Proxy(A,{apply:callbackWrapper((R,_,D)=>{var L;const[B,U,$]=D;if(I.has(B))return A.apply(_,[B,U,$]);const{id:j,styleId:W}=getIdAndStyleId(null==(L=_.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(j&&-1!==j||W&&-1!==W)&&S({id:j,styleId:W,set:{property:B,value:U,priority:$},index:getNestedCSSRulePositions(_.parentRule)}),R.apply(_,D)})});const _=R.CSSStyleDeclaration.prototype.removeProperty;return R.CSSStyleDeclaration.prototype.removeProperty=new Proxy(_,{apply:callbackWrapper((R,A,D)=>{var L;const[B]=D;if(I.has(B))return _.apply(A,[B]);const{id:U,styleId:$}=getIdAndStyleId(null==(L=A.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(U&&-1!==U||$&&-1!==$)&&S({id:U,styleId:$,remove:{property:B},index:getNestedCSSRulePositions(A.parentRule)}),R.apply(A,D)})}),callbackWrapper(()=>{R.CSSStyleDeclaration.prototype.setProperty=A,R.CSSStyleDeclaration.prototype.removeProperty=_})}(S,{win:I}),S.collectFonts&&(fontObserver=function initFontObserver({fontCb:S,doc:b}){const I=b.defaultView;if(!I)return()=>{};const x=[],R=new WeakMap,A=I.FontFace;I.FontFace=function FontFace2(S,b,I){const x=new A(S,b,I);return R.set(x,{family:S,buffer:"string"!=typeof b,descriptors:I,fontSource:"string"==typeof b?b:JSON.stringify(Array.from(new Uint8Array(b)))}),x};const _=patch(b.fonts,"add",function(b){return function(I){return setTimeout(callbackWrapper(()=>{const b=R.get(I);b&&(S(b),R.delete(I))}),0),b.apply(this,[I])}});return x.push(()=>{I.FontFace=A}),x.push(_),callbackWrapper(()=>{x.forEach(S=>S())})}(S)));const U=function initSelectionObserver(S){const{doc:b,mirror:I,blockClass:x,blockSelector:R,selectionCb:A}=S;let _=!0;const D=callbackWrapper(()=>{const S=b.getSelection();if(!S||_&&(null==S?void 0:S.isCollapsed))return;_=S.isCollapsed||!1;const D=[],L=S.rangeCount||0;for(let b=0;b<L;b++){const A=S.getRangeAt(b),{startContainer:_,startOffset:L,endContainer:B,endOffset:U}=A;isBlocked(_,x,R,!0)||isBlocked(B,x,R,!0)||D.push({start:I.getId(_),startOffset:L,end:I.getId(B),endOffset:U})}A({ranges:D})});return D(),on("selectionchange",D)}(S),$=function initCustomElementObserver({doc:S,customElementCb:b}){const I=S.defaultView;return I&&I.customElements?patch(I.customElements,"define",function(S){return function(I,x,R){try{b({define:{name:I}})}catch(S){console.warn(`Custom element callback failed for ${I}`)}return S.apply(this,[I,x,R])}}):()=>{}}(S),j=[];for(const b of S.plugins)j.push(b.observer(b.callback,I,b.options));return callbackWrapper(()=>{Hl.forEach(S=>S.reset()),null==x||x.disconnect(),R(),A(),_(),D(),L(),B(),styleSheetObserver(),adoptedStyleSheetObserver(),styleDeclarationObserver(),fontObserver(),U(),$(),j.forEach(S=>S())})}function hasNestedCSSRule(S){return void 0!==window[S]}function canMonkeyPatchNestedCSSRule(S){return Boolean(void 0!==window[S]&&window[S].prototype&&"insertRule"in window[S].prototype&&"deleteRule"in window[S].prototype)}class CrossOriginIframeMirror{constructor(S){__publicField(this,"iframeIdToRemoteIdMap",new WeakMap),__publicField(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=S}getId(S,b,I,x){const R=I||this.getIdToRemoteIdMap(S),A=x||this.getRemoteIdToIdMap(S);let _=R.get(b);return _||(_=this.generateIdFn(),R.set(b,_),A.set(_,b)),_}getIds(S,b){const I=this.getIdToRemoteIdMap(S),x=this.getRemoteIdToIdMap(S);return b.map(b=>this.getId(S,b,I,x))}getRemoteId(S,b,I){const x=I||this.getRemoteIdToIdMap(S);if("number"!=typeof b)return b;const R=x.get(b);return R||-1}getRemoteIds(S,b){const I=this.getRemoteIdToIdMap(S);return b.map(b=>this.getRemoteId(S,b,I))}reset(S){if(!S)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(S),this.iframeRemoteIdToIdMap.delete(S)}getIdToRemoteIdMap(S){let b=this.iframeIdToRemoteIdMap.get(S);return b||(b=new Map,this.iframeIdToRemoteIdMap.set(S,b)),b}getRemoteIdToIdMap(S){let b=this.iframeRemoteIdToIdMap.get(S);return b||(b=new Map,this.iframeRemoteIdToIdMap.set(S,b)),b}}class IframeManager{constructor(S){__publicField(this,"iframes",new WeakMap),__publicField(this,"crossOriginIframeMap",new WeakMap),__publicField(this,"crossOriginIframeMirror",new CrossOriginIframeMirror(genId)),__publicField(this,"crossOriginIframeStyleMirror"),__publicField(this,"crossOriginIframeRootIdMap",new WeakMap),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"wrappedEmit"),__publicField(this,"loadListener"),__publicField(this,"stylesheetManager"),__publicField(this,"recordCrossOriginIframes"),this.mutationCb=S.mutationCb,this.wrappedEmit=S.wrappedEmit,this.stylesheetManager=S.stylesheetManager,this.recordCrossOriginIframes=S.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=S.mirror,this.recordCrossOriginIframes&&window.__TS_IFRAME_BRIDGE_PARENT_REGISTER&&window.__TS_IFRAME_BRIDGE_PARENT_REGISTER(this)}addIframe(S){this.iframes.set(S,!0),S.contentWindow&&this.crossOriginIframeMap.set(S.contentWindow,S)}addLoadListener(S){this.loadListener=S}attachIframe(S,b){var I;this.mutationCb({adds:[{parentId:this.mirror.getId(S),nextId:null,node:b}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),null==(I=this.loadListener)||I.call(this,S),__tsSafeContentDoc(S)&&__tsSafeContentDoc(S).adoptedStyleSheets&&__tsSafeContentDoc(S).adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(__tsSafeContentDoc(S).adoptedStyleSheets,this.mirror.getId(__tsSafeContentDoc(S)))}handleMessage(S){const b=S;if("rrweb"!==b.data.type||b.origin!==b.data.origin)return;if(!S.source)return;const I=this.crossOriginIframeMap.get(S.source);if(!I)return;const x=this.transformCrossOriginEvent(I,b.data.event);x&&this.wrappedEmit(x,b.data.isCheckout)}transformCrossOriginEvent(S,b){var I;switch(b.type){case Pl.FullSnapshot:{this.crossOriginIframeMirror.reset(S),this.crossOriginIframeStyleMirror.reset(S),this.replaceIdOnNode(b.data.node,S);const I=b.data.node.id;return this.crossOriginIframeRootIdMap.set(S,I),this.patchRootIdOnNode(b.data.node,I),{timestamp:b.timestamp,type:Pl.IncrementalSnapshot,data:{source:Bl.Mutation,adds:[{parentId:this.mirror.getId(S),nextId:null,node:b.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Pl.Meta:case Pl.Load:case Pl.DomContentLoaded:return!1;case Pl.Plugin:return b;case Pl.Custom:return this.replaceIds(b.data.payload,S,["id","parentId","previousId","nextId"]),b;case Pl.IncrementalSnapshot:switch(b.data.source){case Bl.Mutation:return b.data.adds.forEach(b=>{this.replaceIds(b,S,["parentId","nextId","previousId"]),this.replaceIdOnNode(b.node,S);const I=this.crossOriginIframeRootIdMap.get(S);I&&this.patchRootIdOnNode(b.node,I)}),b.data.removes.forEach(b=>{this.replaceIds(b,S,["parentId","id"])}),b.data.attributes.forEach(b=>{this.replaceIds(b,S,["id"])}),b.data.texts.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case Bl.Drag:case Bl.TouchMove:case Bl.MouseMove:return b.data.positions.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case Bl.ViewportResize:return!1;case Bl.MediaInteraction:case Bl.MouseInteraction:case Bl.Scroll:case Bl.CanvasMutation:case Bl.Input:return this.replaceIds(b.data,S,["id"]),b;case Bl.StyleSheetRule:case Bl.StyleDeclaration:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleId"]),b;case Bl.Font:return b;case Bl.Selection:return b.data.ranges.forEach(b=>{this.replaceIds(b,S,["start","end"])}),b;case Bl.AdoptedStyleSheet:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleIds"]),null==(I=b.data.styles)||I.forEach(b=>{this.replaceStyleIds(b,S,["styleId"])}),b}}return!1}replace(S,b,I,x){for(const R of x)(Array.isArray(b[R])||"number"==typeof b[R])&&(Array.isArray(b[R])?b[R]=S.getIds(I,b[R]):b[R]=S.getId(I,b[R]));return b}replaceIds(S,b,I){return this.replace(this.crossOriginIframeMirror,S,b,I)}replaceStyleIds(S,b,I){return this.replace(this.crossOriginIframeStyleMirror,S,b,I)}replaceIdOnNode(S,b){this.replaceIds(S,b,["id","rootId"]),"childNodes"in S&&S.childNodes.forEach(S=>{this.replaceIdOnNode(S,b)})}patchRootIdOnNode(S,b){S.type===ql.Document||S.rootId||(S.rootId=b),"childNodes"in S&&S.childNodes.forEach(S=>{this.patchRootIdOnNode(S,b)})}}class ShadowDomManager{constructor(S){__publicField(this,"shadowDoms",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"scrollCb"),__publicField(this,"bypassOptions"),__publicField(this,"mirror"),__publicField(this,"restoreHandlers",[]),this.mutationCb=S.mutationCb,this.scrollCb=S.scrollCb,this.bypassOptions=S.bypassOptions,this.mirror=S.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(S,b){if(!isNativeShadowDom(S))return;if(this.shadowDoms.has(S))return;this.shadowDoms.add(S);const I=initMutationObserver({...this.bypassOptions,doc:b,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},S);this.restoreHandlers.push(()=>I.disconnect()),this.restoreHandlers.push(initScrollObserver({...this.bypassOptions,scrollCb:this.scrollCb,doc:S,mirror:this.mirror})),setTimeout(()=>{S.adoptedStyleSheets&&S.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(S.adoptedStyleSheets,this.mirror.getId(Dl.host(S))),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},S))},0)}observeAttachShadow(S){S.contentWindow&&__tsSafeContentDoc(S)&&this.patchAttachShadow(S.contentWindow.Element,__tsSafeContentDoc(S))}patchAttachShadow(S,b){const I=this;this.restoreHandlers.push(patch(S.prototype,"attachShadow",function(S){return function(x){const R=S.call(this,x),A=Dl.shadowRoot(this);return A&&inDom(this)&&I.addShadowRoot(A,b),R}}))}reset(){this.restoreHandlers.forEach(S=>{try{S()}catch(S){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}for(var Gl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Kl="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Jl=0;Jl<64;Jl++)Kl[Gl.charCodeAt(Jl)]=Jl;const Xl=new Map;const saveWebGLVar=(S,b,I)=>{if(!S||!isInstanceOfWebGLObject(S,b)&&"object"!=typeof S)return;const x=function variableListFor$1(S,b){let I=Xl.get(S);return I||(I=new Map,Xl.set(S,I)),I.has(b)||I.set(b,[]),I.get(b)}(I,S.constructor.name);let R=x.indexOf(S);return-1===R&&(R=x.length,x.push(S)),R};function serializeArg(S,b,I){if(S instanceof Array)return S.map(S=>serializeArg(S,b,I));if(null===S)return S;if(S instanceof Float32Array||S instanceof Float64Array||S instanceof Int32Array||S instanceof Uint32Array||S instanceof Uint8Array||S instanceof Uint16Array||S instanceof Int16Array||S instanceof Int8Array||S instanceof Uint8ClampedArray){return{rr_type:S.constructor.name,args:[Object.values(S)]}}if(S instanceof ArrayBuffer){return{rr_type:S.constructor.name,base64:function(S){var b,I=new Uint8Array(S),x=I.length,R="";for(b=0;b<x;b+=3)R+=Gl[I[b]>>2],R+=Gl[(3&I[b])<<4|I[b+1]>>4],R+=Gl[(15&I[b+1])<<2|I[b+2]>>6],R+=Gl[63&I[b+2]];return x%3==2?R=R.substring(0,R.length-1)+"=":x%3==1&&(R=R.substring(0,R.length-2)+"=="),R}(S)}}if(S instanceof DataView){return{rr_type:S.constructor.name,args:[serializeArg(S.buffer,b,I),S.byteOffset,S.byteLength]}}if(S instanceof HTMLImageElement){const b=S.constructor.name,{src:I}=S;return{rr_type:b,src:I}}if(S instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:S.toDataURL()}}if(S instanceof ImageData){return{rr_type:S.constructor.name,args:[serializeArg(S.data,b,I),S.width,S.height]}}if(isInstanceOfWebGLObject(S,b)||"object"==typeof S){return{rr_type:S.constructor.name,index:saveWebGLVar(S,b,I)}}return S}const serializeArgs=(S,b,I)=>S.map(S=>serializeArg(S,b,I)),isInstanceOfWebGLObject=(S,b)=>{const I=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(S=>"function"==typeof b[S]);return Boolean(I.find(I=>S instanceof b[I]))};function initCanvasContextObserver(S,b,I,x){const R=[];try{const A=patch(S.HTMLCanvasElement.prototype,"getContext",function(S){return function(R,...A){if(!isBlocked(this,b,I,!0)){const S=function getNormalizedContextName(S){return"experimental-webgl"===S?"webgl":S}(R);if("__context"in this||(this.__context=S),x&&["webgl","webgl2"].includes(S))if(A[0]&&"object"==typeof A[0]){const S=A[0];S.preserveDrawingBuffer||(S.preserveDrawingBuffer=!0)}else A.splice(0,1,{preserveDrawingBuffer:!0})}return S.apply(this,[R,...A])}});R.push(A)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{R.forEach(S=>S())}}function patchGLPrototype(S,b,I,x,R,A){const _=[],D=Object.getOwnPropertyNames(S);for(const L of D)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(L))try{if("function"!=typeof S[L])continue;const D=patch(S,L,function(S){return function(..._){const D=S.apply(this,_);if(saveWebGLVar(D,A,this),"tagName"in this.canvas&&!isBlocked(this.canvas,x,R,!0)){const S=serializeArgs(_,A,this),x={type:b,property:L,args:S};I(this.canvas,x)}return D}});_.push(D)}catch{const x=hookSetter(S,L,{set(S){I(this.canvas,{type:b,property:L,args:[S],setter:!0})}});_.push(x)}return _}const Yl="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Zl="undefined"!=typeof window&&window.Blob&&new Blob([(ec=Yl,Uint8Array.from(atob(ec),S=>S.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});var ec;function WorkerWrapper(S){let b;try{if(b=Zl&&(window.URL||window.webkitURL).createObjectURL(Zl),!b)throw"";const I=new Worker(b,{name:null==S?void 0:S.name});return I.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(b)}),I}catch(b){return new Worker("data:text/javascript;base64,"+Yl,{name:null==S?void 0:S.name})}finally{b&&(window.URL||window.webkitURL).revokeObjectURL(b)}}class CanvasManager{constructor(S){__publicField(this,"pendingCanvasMutations",new Map),__publicField(this,"rafStamps",{latestId:0,invokeId:null}),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"resetObservers"),__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"processMutation",(S,b)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(S)||this.pendingCanvasMutations.set(S,[]),this.pendingCanvasMutations.get(S).push(b)});const{sampling:b="all",win:I,blockClass:x,blockSelector:R,recordCanvas:A,dataURLOptions:_}=S;this.mutationCb=S.mutationCb,this.mirror=S.mirror,A&&"all"===b&&this.initCanvasMutationObserver(I,x,R),A&&"number"==typeof b&&this.initCanvasFPSObserver(b,I,x,R,{dataURLOptions:_})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(S,b,I,x,R){const A=initCanvasContextObserver(b,I,x,!0),_=new Map,D=new WorkerWrapper;D.onmessage=S=>{const{id:b}=S.data;if(_.set(b,!1),!("base64"in S.data))return;const{base64:I,type:x,width:R,height:A}=S.data;this.mutationCb({id:b,type:$l["2D"],commands:[{property:"clearRect",args:[0,0,R,A]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:I}],type:x}]},0,0]}]})};const L=1e3/S;let B,U=0;const takeCanvasSnapshots=S=>{U&&S-U<L||(U=S,(()=>{const S=[];return b.document.querySelectorAll("canvas").forEach(b=>{isBlocked(b,I,x,!0)||S.push(b)}),S})().forEach(async S=>{var b;const I=this.mirror.getId(S);if(_.get(I))return;if(0===S.width||0===S.height)return;if(_.set(I,!0),["webgl","webgl2"].includes(S.__context)){const I=S.getContext(S.__context);!1===(null==(b=null==I?void 0:I.getContextAttributes())?void 0:b.preserveDrawingBuffer)&&I.clear(I.COLOR_BUFFER_BIT)}const x=await createImageBitmap(S);D.postMessage({id:I,bitmap:x,width:S.width,height:S.height,dataURLOptions:R.dataURLOptions},[x])})),B=requestAnimationFrame(takeCanvasSnapshots)};B=requestAnimationFrame(takeCanvasSnapshots),this.resetObservers=()=>{A(),cancelAnimationFrame(B)}}initCanvasMutationObserver(S,b,I){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const x=initCanvasContextObserver(S,b,I,!1),R=function initCanvas2DMutationObserver(S,b,I,x){const R=[],A=Object.getOwnPropertyNames(b.CanvasRenderingContext2D.prototype);for(const _ of A)try{if("function"!=typeof b.CanvasRenderingContext2D.prototype[_])continue;const A=patch(b.CanvasRenderingContext2D.prototype,_,function(R){return function(...A){return isBlocked(this.canvas,I,x,!0)||setTimeout(()=>{const I=serializeArgs(A,b,this);S(this.canvas,{type:$l["2D"],property:_,args:I})},0),R.apply(this,A)}});R.push(A)}catch{const I=hookSetter(b.CanvasRenderingContext2D.prototype,_,{set(b){S(this.canvas,{type:$l["2D"],property:_,args:[b],setter:!0})}});R.push(I)}return()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I),A=function initCanvasWebGLMutationObserver(S,b,I,x){const R=[];return R.push(...patchGLPrototype(b.WebGLRenderingContext.prototype,$l.WebGL,S,I,x,b)),void 0!==b.WebGL2RenderingContext&&R.push(...patchGLPrototype(b.WebGL2RenderingContext.prototype,$l.WebGL2,S,I,x,b)),()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I);this.resetObservers=()=>{x(),R(),A()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const setLatestRAFTimestamp=S=>{this.rafStamps.latestId=S,requestAnimationFrame(setLatestRAFTimestamp)};requestAnimationFrame(setLatestRAFTimestamp)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((S,b)=>{const I=this.mirror.getId(b);this.flushPendingCanvasMutationFor(b,I)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(S,b){if(this.frozen||this.locked)return;const I=this.pendingCanvasMutations.get(S);if(!I||-1===b)return;const x=I.map(S=>{const{type:b,...I}=S;return I}),{type:R}=I[0];this.mutationCb({id:b,type:R,commands:x}),this.pendingCanvasMutations.delete(S)}}class StylesheetManager{constructor(S){__publicField(this,"trackedLinkElements",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"adoptedStyleSheetCb"),__publicField(this,"styleMirror",new StyleSheetMirror),this.mutationCb=S.mutationCb,this.adoptedStyleSheetCb=S.adoptedStyleSheetCb}attachLinkElement(S,b){"_cssText"in b.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:b.id,attributes:b.attributes}]}),this.trackLinkElement(S)}trackLinkElement(S){this.trackedLinkElements.has(S)||(this.trackedLinkElements.add(S),this.trackStylesheetInLinkElement(S))}adoptStyleSheets(S,b){if(0===S.length)return;const I={id:b,styleIds:[]},x=[];for(const b of S){let S;this.styleMirror.has(b)?S=this.styleMirror.getId(b):(S=this.styleMirror.add(b),x.push({styleId:S,rules:Array.from(b.rules||CSSRule,(S,I)=>({rule:stringifyRule(S,b.href),index:I}))})),I.styleIds.push(S)}x.length>0&&(I.styles=x),this.adoptedStyleSheetCb(I)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(S){}}class ProcessedNodeManager{constructor(){__publicField(this,"nodeMap",new WeakMap),__publicField(this,"active",!1)}inOtherBuffer(S,b){const I=this.nodeMap.get(S);return I&&Array.from(I).some(S=>S!==b)}add(S,b){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(S,(this.nodeMap.get(S)||new Set).add(b))}destroy(){}}let tc,sc,rc,nc=!1;try{if(2!==Array.from([1],S=>2*S)[0]){const S=document.createElement("iframe");document.body.appendChild(S),Array.from=(null==(ct=S.contentWindow)?void 0:ct.Array.from)||Array.from,document.body.removeChild(S)}}catch(err){console.debug("Unable to override Array.from",err)}const ic=function createMirror$2(){return new Mirror}();function record(S={}){const{emit:b,checkoutEveryNms:I,checkoutEveryNth:x,blockClass:R="rr-block",blockSelector:A=null,ignoreClass:_="rr-ignore",ignoreSelector:D=null,maskTextClass:L="rr-mask",maskTextSelector:B=null,inlineStylesheet:U=!0,maskAllInputs:$,maskInputOptions:j,slimDOMOptions:W,maskInputFn:H,maskTextFn:V,hooks:Q,packFn:G,sampling:J={},dataURLOptions:X={},mousemoveWait:Y,recordDOM:ee=!0,recordCanvas:te=!1,recordCrossOriginIframes:se=!1,recordAfter:re=("DOMContentLoaded"===S.recordAfter?S.recordAfter:"load"),userTriggeredOnInput:ne=!1,collectFonts:ie=!1,inlineImages:oe=!1,plugins:ae,keepIframeSrcFn:le=()=>!1,ignoreCSSAttributes:ce=new Set([]),errorHandler:ue}=S;!function registerErrorHandler(S){Wl=S}(ue);const he=!se||window.parent===window;let de=!1;if(!he)try{window.parent.document&&(de=!1)}catch(S){de=!0}if(he&&!b)throw new Error("emit function is required");if(!he&&!de)return()=>{};void 0!==Y&&void 0===J.mousemove&&(J.mousemove=Y),ic.reset();const ge=!0===$?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==j?j:{password:!0},pe=!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===W,headMetaDescKeywords:"all"===W,headTitleMutations:"all"===W}:W||{};let fe;!function polyfill$1(S=window){"NodeList"in S&&!S.NodeList.prototype.forEach&&(S.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in S&&!S.DOMTokenList.prototype.forEach&&(S.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let me=0;const eventProcessor=S=>{for(const b of ae||[])b.eventProcessor&&(S=b.eventProcessor(S));return G&&!de&&(S=G(S)),S};tc=(S,R)=>{var A;const _=S;if(_.timestamp=Ll(),!(null==(A=Hl[0])?void 0:A.isFrozen())||_.type===Pl.FullSnapshot||_.type===Pl.IncrementalSnapshot&&_.data.source===Bl.Mutation||Hl.forEach(S=>S.unfreeze()),he)null==b||b(eventProcessor(_),R);else if(de){const S={type:"rrweb",event:eventProcessor(_),origin:window.location.origin,isCheckout:R};window.__TS_IFRAME_BRIDGE&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom(S)}if(_.type===Pl.FullSnapshot)fe=_,me=0;else if(_.type===Pl.IncrementalSnapshot){if(_.data.source===Bl.Mutation&&_.data.isAttachIframe)return;me++;const S=x&&me>=x,b=I&&_.timestamp-fe.timestamp>I;(S||b)&&sc(!0)}};const wrappedMutationEmit=S=>{tc({type:Pl.IncrementalSnapshot,data:{source:Bl.Mutation,...S}})},wrappedScrollEmit=S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.Scroll,...S}}),wrappedCanvasMutationEmit=S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.CanvasMutation,...S}}),ye=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.AdoptedStyleSheet,...S}})}),ve=new IframeManager({mirror:ic,mutationCb:wrappedMutationEmit,stylesheetManager:ye,recordCrossOriginIframes:se,wrappedEmit:tc});for(const S of ae||[])S.getMirror&&S.getMirror({nodeMirror:ic,crossOriginIframeMirror:ve.crossOriginIframeMirror,crossOriginIframeStyleMirror:ve.crossOriginIframeStyleMirror});const Se=new ProcessedNodeManager;rc=new CanvasManager({recordCanvas:te,mutationCb:wrappedCanvasMutationEmit,win:window,blockClass:R,blockSelector:A,mirror:ic,sampling:J.canvas,dataURLOptions:X});const we=new ShadowDomManager({mutationCb:wrappedMutationEmit,scrollCb:wrappedScrollEmit,bypassOptions:{blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskInputOptions:ge,dataURLOptions:X,maskTextFn:V,maskInputFn:H,recordCanvas:te,inlineImages:oe,sampling:J,slimDOMOptions:pe,iframeManager:ve,stylesheetManager:ye,canvasManager:rc,keepIframeSrcFn:le,processedNodeManager:Se},mirror:ic});sc=(S=!1)=>{if(!ee)return;tc({type:Pl.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},S),ye.reset(),we.init(),Hl.forEach(S=>S.lock());const b=function snapshot(S,b){const{mirror:I=new Mirror,blockClass:x="rr-block",blockSelector:R=null,maskTextClass:A="rr-mask",maskTextSelector:_=null,inlineStylesheet:D=!0,inlineImages:L=!1,recordCanvas:B=!1,maskAllInputs:U=!1,maskTextFn:$,maskInputFn:j,slimDOM:W=!1,dataURLOptions:H,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee=()=>!1}=b||{};return serializeNodeWithId(S,{doc:S,mirror:I,blockClass:x,blockSelector:R,maskTextClass:A,maskTextSelector:_,skipChild:!1,inlineStylesheet:D,maskInputOptions:!0===U?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===U?{password:!0}:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===W,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===W?{}:W,dataURLOptions:H,inlineImages:L,recordCanvas:B,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee,newlyAddedElement:!1})}(document,{mirror:ic,blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskAllInputs:ge,maskTextFn:V,maskInputFn:H,slimDOM:pe,dataURLOptions:X,recordCanvas:te,inlineImages:oe,onSerialize:S=>{isSerializedIframe(S,ic)&&ve.addIframe(S),isSerializedStylesheet(S,ic)&&ye.trackLinkElement(S),hasShadowRoot(S)&&we.addShadowRoot(Dl.shadowRoot(S),document)},onIframeLoad:(S,b)=>{ve.attachIframe(S,b),we.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{ye.attachLinkElement(S,b)},keepIframeSrcFn:le});if(!b)return console.warn("Failed to snapshot the document");tc({type:Pl.FullSnapshot,data:{node:b,initialOffset:getWindowScroll(window)}},S),Hl.forEach(S=>S.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,ic.getId(document))};try{const S=[],observe=S=>{var b;return callbackWrapper(initObservers)({mutationCb:wrappedMutationEmit,mousemoveCb:(S,b)=>tc({type:Pl.IncrementalSnapshot,data:{source:b,positions:S}}),mouseInteractionCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.MouseInteraction,...S}}),scrollCb:wrappedScrollEmit,viewportResizeCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.ViewportResize,...S}}),inputCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.Input,...S}}),mediaInteractionCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.MediaInteraction,...S}}),styleSheetRuleCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.StyleSheetRule,...S}}),styleDeclarationCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.StyleDeclaration,...S}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:S=>tc({type:Pl.IncrementalSnapshot,data:{source:Bl.Font,...S}}),selectionCb:S=>{tc({type:Pl.IncrementalSnapshot,data:{source:Bl.Selection,...S}})},customElementCb:S=>{tc({type:Pl.IncrementalSnapshot,data:{source:Bl.CustomElement,...S}})},blockClass:R,ignoreClass:_,ignoreSelector:D,maskTextClass:L,maskTextSelector:B,maskInputOptions:ge,inlineStylesheet:U,sampling:J,recordDOM:ee,recordCanvas:te,inlineImages:oe,userTriggeredOnInput:ne,collectFonts:ie,doc:S,maskInputFn:H,maskTextFn:V,keepIframeSrcFn:le,blockSelector:A,slimDOMOptions:pe,dataURLOptions:X,mirror:ic,iframeManager:ve,stylesheetManager:ye,shadowDomManager:we,processedNodeManager:Se,canvasManager:rc,ignoreCSSAttributes:ce,plugins:(null==(b=null==ae?void 0:ae.filter(S=>S.observer))?void 0:b.map(S=>({observer:S.observer,options:S.options,callback:b=>tc({type:Pl.Plugin,data:{plugin:S.name,payload:b}})})))||[]},Q)};ve.addLoadListener(b=>{try{S.push(observe(__tsSafeContentDoc(b)))}catch(S){console.warn(S)}});const init=()=>{sc(),S.push(observe(document)),nc=!0};return"interactive"===document.readyState||"complete"===document.readyState?init():(S.push(on("DOMContentLoaded",()=>{tc({type:Pl.DomContentLoaded,data:{}}),"DOMContentLoaded"===re&&init()})),S.push(on("load",()=>{tc({type:Pl.Load,data:{}}),"load"===re&&init()},window))),()=>{S.forEach(S=>S()),Se.destroy(),nc=!1,function unregisterErrorHandler(){Wl=void 0}()}}catch(S){console.warn(S)}}var oc,ac;record.addCustomEvent=(S,b)=>{if(!nc)throw new Error("please add custom event after start recording");tc({type:Pl.Custom,data:{tag:S,payload:b}})},record.freezePage=()=>{Hl.forEach(S=>S.freeze())},record.takeFullSnapshot=S=>{if(!nc)throw new Error("please take full snapshot after start recording");sc(S)},record.mirror=ic,(ac=oc||(oc={}))[ac.NotStarted=0]="NotStarted",ac[ac.Running=1]="Running",ac[ac.Stopped=2]="Stopped";const cc=createLogger("RRWeb-Loader");let uc=null,hc=null;try{record?(uc=record,hc={record:record,addCustomEvent:record.addCustomEvent,freezePage:record.freezePage,takeFullSnapshot:record.takeFullSnapshot,mirror:record.mirror},console.log("%c[TraceScout] ✅ rrweb RECORD bundled","color: #00aa00; font-weight: bold;"),cc.log("rrweb record() statically imported and ready")):console.error("[TraceScout] ❌ rrweb record import found but not a function")}catch($){console.error("[TraceScout] ❌ Static rrweb record import failed:",$.message),cc.warn("Static rrweb record import failed:",$.message)}async function loadRRWeb(){if(!hc||!hc.record)throw new Error("rrweb record not available - bundling failed");return hc}function getRRWeb(){return hc}function getRecord(){return uc}function isRRWebLoaded(){return!!hc}function getRRWebSource(){return{isBundled:!0,source:"bundled",details:"@rrweb/record bundled with SDK",isRecordOnly:!0}}var dc=Uint8Array,gc=Uint16Array,pc=Int32Array,fc=new dc([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),mc=new dc([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),yc=new dc([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(S,b){for(var I=new gc(31),x=0;x<31;++x)I[x]=b+=1<<S[x-1];var R=new pc(I[30]);for(x=1;x<30;++x)for(var A=I[x];A<I[x+1];++A)R[A]=A-I[x]<<5|x;return{b:I,r:R}},vc=freb(fc,2),Sc=vc.b,wc=vc.r;Sc[28]=258,wc[258]=28;for(var bc=freb(mc,0),Cc=bc.b,kc=bc.r,Ic=new gc(32768),Ec=0;Ec<32768;++Ec){var xc=(43690&Ec)>>1|(21845&Ec)<<1;xc=(61680&(xc=(52428&xc)>>2|(13107&xc)<<2))>>4|(3855&xc)<<4,Ic[Ec]=((65280&xc)>>8|(255&xc)<<8)>>1}var hMap=function(S,b,I){for(var x=S.length,R=0,A=new gc(b);R<x;++R)S[R]&&++A[S[R]-1];var _,D=new gc(b);for(R=1;R<b;++R)D[R]=D[R-1]+A[R-1]<<1;if(I){_=new gc(1<<b);var L=15-b;for(R=0;R<x;++R)if(S[R])for(var B=R<<4|S[R],U=b-S[R],$=D[S[R]-1]++<<U,j=$|(1<<U)-1;$<=j;++$)_[Ic[$]>>L]=B}else for(_=new gc(x),R=0;R<x;++R)S[R]&&(_[R]=Ic[D[S[R]-1]++]>>15-S[R]);return _},Mc=new dc(288);for(Ec=0;Ec<144;++Ec)Mc[Ec]=8;for(Ec=144;Ec<256;++Ec)Mc[Ec]=9;for(Ec=256;Ec<280;++Ec)Mc[Ec]=7;for(Ec=280;Ec<288;++Ec)Mc[Ec]=8;var Rc=new dc(32);for(Ec=0;Ec<32;++Ec)Rc[Ec]=5;var Tc=hMap(Mc,9,0),Ac=hMap(Mc,9,1),_c=hMap(Rc,5,0),Oc=hMap(Rc,5,1),max=function(S){for(var b=S[0],I=1;I<S.length;++I)S[I]>b&&(b=S[I]);return b},bits=function(S,b,I){var x=b/8|0;return(S[x]|S[x+1]<<8)>>(7&b)&I},bits16=function(S,b){var I=b/8|0;return(S[I]|S[I+1]<<8|S[I+2]<<16)>>(7&b)},shft=function(S){return(S+7)/8|0},slc=function(S,b,I){return(null==b||b<0)&&(b=0),(null==I||I>S.length)&&(I=S.length),new dc(S.subarray(b,I))},Dc=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(S,b,I){var x=new Error(b||Dc[S]);if(x.code=S,Error.captureStackTrace&&Error.captureStackTrace(x,err),!I)throw x;return x},wbits=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8},wbits16=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8,S[x+2]|=I>>16},hTree=function(S,b){for(var I=[],x=0;x<S.length;++x)S[x]&&I.push({s:x,f:S[x]});var R=I.length,A=I.slice();if(!R)return{t:Nc,l:0};if(1==R){var _=new dc(I[0].s+1);return _[I[0].s]=1,{t:_,l:1}}I.sort(function(S,b){return S.f-b.f}),I.push({s:-1,f:25001});var D=I[0],L=I[1],B=0,U=1,$=2;for(I[0]={s:-1,f:D.f+L.f,l:D,r:L};U!=R-1;)D=I[I[B].f<I[$].f?B++:$++],L=I[B!=U&&I[B].f<I[$].f?B++:$++],I[U++]={s:-1,f:D.f+L.f,l:D,r:L};var j=A[0].s;for(x=1;x<R;++x)A[x].s>j&&(j=A[x].s);var W=new gc(j+1),H=ln(I[U-1],W,0);if(H>b){x=0;var V=0,Q=H-b,G=1<<Q;for(A.sort(function(S,b){return W[b.s]-W[S.s]||S.f-b.f});x<R;++x){var J=A[x].s;if(!(W[J]>b))break;V+=G-(1<<H-W[J]),W[J]=b}for(V>>=Q;V>0;){var X=A[x].s;W[X]<b?V-=1<<b-W[X]++-1:++x}for(;x>=0&&V;--x){var Y=A[x].s;W[Y]==b&&(--W[Y],++V)}H=b}return{t:new dc(W),l:H}},ln=function(S,b,I){return-1==S.s?Math.max(ln(S.l,b,I+1),ln(S.r,b,I+1)):b[S.s]=I},lc=function(S){for(var b=S.length;b&&!S[--b];);for(var I=new gc(++b),x=0,R=S[0],A=1,w=function(S){I[x++]=S},_=1;_<=b;++_)if(S[_]==R&&_!=b)++A;else{if(!R&&A>2){for(;A>138;A-=138)w(32754);A>2&&(w(A>10?A-11<<5|28690:A-3<<5|12305),A=0)}else if(A>3){for(w(R),--A;A>6;A-=6)w(8304);A>2&&(w(A-3<<5|8208),A=0)}for(;A--;)w(R);A=1,R=S[_]}return{c:I.subarray(0,x),n:b}},clen=function(S,b){for(var I=0,x=0;x<b.length;++x)I+=S[x]*b[x];return I},wfblk=function(S,b,I){var x=I.length,R=shft(b+2);S[R]=255&x,S[R+1]=x>>8,S[R+2]=255^S[R],S[R+3]=255^S[R+1];for(var A=0;A<x;++A)S[R+A+4]=I[A];return 8*(R+4+x)},wblk=function(S,b,I,x,R,A,_,D,L,B,U){wbits(b,U++,I),++R[256];for(var $=hTree(R,15),j=$.t,W=$.l,H=hTree(A,15),V=H.t,Q=H.l,G=lc(j),J=G.c,X=G.n,Y=lc(V),ee=Y.c,te=Y.n,se=new gc(19),re=0;re<J.length;++re)++se[31&J[re]];for(re=0;re<ee.length;++re)++se[31&ee[re]];for(var ne=hTree(se,7),ie=ne.t,oe=ne.l,ae=19;ae>4&&!ie[yc[ae-1]];--ae);var le,ce,ue,he,de=B+5<<3,ge=clen(R,Mc)+clen(A,Rc)+_,pe=clen(R,j)+clen(A,V)+_+14+3*ae+clen(se,ie)+2*se[16]+3*se[17]+7*se[18];if(L>=0&&de<=ge&&de<=pe)return wfblk(b,U,S.subarray(L,L+B));if(wbits(b,U,1+(pe<ge)),U+=2,pe<ge){le=hMap(j,W,0),ce=j,ue=hMap(V,Q,0),he=V;var fe=hMap(ie,oe,0);wbits(b,U,X-257),wbits(b,U+5,te-1),wbits(b,U+10,ae-4),U+=14;for(re=0;re<ae;++re)wbits(b,U+3*re,ie[yc[re]]);U+=3*ae;for(var me=[J,ee],ye=0;ye<2;++ye){var ve=me[ye];for(re=0;re<ve.length;++re){var Se=31&ve[re];wbits(b,U,fe[Se]),U+=ie[Se],Se>15&&(wbits(b,U,ve[re]>>5&127),U+=ve[re]>>12)}}}else le=Tc,ce=Mc,ue=_c,he=Rc;for(re=0;re<D;++re){var we=x[re];if(we>255){wbits16(b,U,le[(Se=we>>18&31)+257]),U+=ce[Se+257],Se>7&&(wbits(b,U,we>>23&31),U+=fc[Se]);var be=31&we;wbits16(b,U,ue[be]),U+=he[be],be>3&&(wbits16(b,U,we>>5&8191),U+=mc[be])}else wbits16(b,U,le[we]),U+=ce[we]}return wbits16(b,U,le[256]),U+ce[256]},Fc=new pc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Nc=new dc(0),adler=function(){var S=1,b=0;return{p:function(I){for(var x=S,R=b,A=0|I.length,_=0;_!=A;){for(var D=Math.min(_+2655,A);_<D;++_)R+=x+=I[_];x=(65535&x)+15*(x>>16),R=(65535&R)+15*(R>>16)}S=x,b=R},d:function(){return(255&(S%=65521))<<24|(65280&S)<<8|(255&(b%=65521))<<8|b>>8}}},dopt=function(S,b,I,x,R){if(!R&&(R={l:1},b.dictionary)){var A=b.dictionary.subarray(-32768),_=new dc(A.length+S.length);_.set(A),_.set(S,A.length),S=_,R.w=A.length}return function(S,b,I,x,R,A){var _=A.z||S.length,D=new dc(x+_+5*(1+Math.ceil(_/7e3))+R),L=D.subarray(x,D.length-R),B=A.l,U=7&(A.r||0);if(b){U&&(L[0]=A.r>>3);for(var $=Fc[b-1],j=$>>13,W=8191&$,H=(1<<I)-1,V=A.p||new gc(32768),Q=A.h||new gc(H+1),G=Math.ceil(I/3),J=2*G,hsh=function(b){return(S[b]^S[b+1]<<G^S[b+2]<<J)&H},X=new pc(25e3),Y=new gc(288),ee=new gc(32),te=0,se=0,re=A.i||0,ne=0,ie=A.w||0,oe=0;re+2<_;++re){var ae=hsh(re),le=32767&re,ce=Q[ae];if(V[le]=ce,Q[ae]=le,ie<=re){var ue=_-re;if((te>7e3||ne>24576)&&(ue>423||!B)){U=wblk(S,L,0,X,Y,ee,se,ne,oe,re-oe,U),ne=te=se=0,oe=re;for(var he=0;he<286;++he)Y[he]=0;for(he=0;he<30;++he)ee[he]=0}var de=2,ge=0,pe=W,fe=le-ce&32767;if(ue>2&&ae==hsh(re-fe))for(var me=Math.min(j,ue)-1,ye=Math.min(32767,re),ve=Math.min(258,ue);fe<=ye&&--pe&&le!=ce;){if(S[re+de]==S[re+de-fe]){for(var Se=0;Se<ve&&S[re+Se]==S[re+Se-fe];++Se);if(Se>de){if(de=Se,ge=fe,Se>me)break;var we=Math.min(fe,Se-2),be=0;for(he=0;he<we;++he){var Ce=re-fe+he&32767,ke=Ce-V[Ce]&32767;ke>be&&(be=ke,ce=Ce)}}}fe+=(le=ce)-(ce=V[le])&32767}if(ge){X[ne++]=268435456|wc[de]<<18|kc[ge];var Ie=31&wc[de],Ee=31&kc[ge];se+=fc[Ie]+mc[Ee],++Y[257+Ie],++ee[Ee],ie=re+de,++te}else X[ne++]=S[re],++Y[S[re]]}}for(re=Math.max(re,ie);re<_;++re)X[ne++]=S[re],++Y[S[re]];U=wblk(S,L,B,X,Y,ee,se,ne,oe,re-oe,U),B||(A.r=7&U|L[U/8|0]<<3,U-=7,A.h=Q,A.p=V,A.i=re,A.w=ie)}else{for(re=A.w||0;re<_+B;re+=65535){var xe=re+65535;xe>=_&&(L[U/8|0]=B,xe=_),U=wfblk(L,U+1,S.subarray(re,xe))}A.i=_}return slc(D,0,x+shft(U)+R)}(S,null==b.level?6:b.level,null==b.mem?R.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(S.length)))):20:12+b.mem,I,x,R)},wbytes=function(S,b,I){for(;I;++b)S[b]=I,I>>>=8};function zlibSync(S,b){b||(b={});var I=adler();I.p(S);var x=dopt(S,b,b.dictionary?6:2,4);return function(S,b){var I=b.level,x=0==I?0:I<6?1:9==I?3:2;if(S[0]=120,S[1]=x<<6|(b.dictionary&&32),S[1]|=31-(S[0]<<8|S[1])%31,b.dictionary){var R=adler();R.p(b.dictionary),wbytes(S,2,R.d())}}(x,b),wbytes(x,x.length-4,I.d()),x}function unzlibSync(S,b){return function(S,b,I,x){var R=S.length,A=x?x.length:0;if(!R||b.f&&!b.l)return I||new dc(0);var _=!I,D=_||2!=b.i,L=b.i;_&&(I=new dc(3*R));var cbuf=function(S){var b=I.length;if(S>b){var x=new dc(Math.max(2*b,S));x.set(I),I=x}},B=b.f||0,U=b.p||0,$=b.b||0,j=b.l,W=b.d,H=b.m,V=b.n,Q=8*R;do{if(!j){B=bits(S,U,1);var G=bits(S,U+1,3);if(U+=3,!G){var J=S[(le=shft(U)+4)-4]|S[le-3]<<8,X=le+J;if(X>R){L&&err(0);break}D&&cbuf($+J),I.set(S.subarray(le,X),$),b.b=$+=J,b.p=U=8*X,b.f=B;continue}if(1==G)j=Ac,W=Oc,H=9,V=5;else if(2==G){var Y=bits(S,U,31)+257,ee=bits(S,U+10,15)+4,te=Y+bits(S,U+5,31)+1;U+=14;for(var se=new dc(te),re=new dc(19),ne=0;ne<ee;++ne)re[yc[ne]]=bits(S,U+3*ne,7);U+=3*ee;var ie=max(re),oe=(1<<ie)-1,ae=hMap(re,ie,1);for(ne=0;ne<te;){var le,ce=ae[bits(S,U,oe)];if(U+=15&ce,(le=ce>>4)<16)se[ne++]=le;else{var ue=0,he=0;for(16==le?(he=3+bits(S,U,3),U+=2,ue=se[ne-1]):17==le?(he=3+bits(S,U,7),U+=3):18==le&&(he=11+bits(S,U,127),U+=7);he--;)se[ne++]=ue}}var de=se.subarray(0,Y),ge=se.subarray(Y);H=max(de),V=max(ge),j=hMap(de,H,1),W=hMap(ge,V,1)}else err(1);if(U>Q){L&&err(0);break}}D&&cbuf($+131072);for(var pe=(1<<H)-1,fe=(1<<V)-1,me=U;;me=U){var ye=(ue=j[bits16(S,U)&pe])>>4;if((U+=15&ue)>Q){L&&err(0);break}if(ue||err(2),ye<256)I[$++]=ye;else{if(256==ye){me=U,j=null;break}var ve=ye-254;if(ye>264){var Se=fc[ne=ye-257];ve=bits(S,U,(1<<Se)-1)+Sc[ne],U+=Se}var we=W[bits16(S,U)&fe],be=we>>4;if(we||err(3),U+=15&we,ge=Cc[be],be>3&&(Se=mc[be],ge+=bits16(S,U)&(1<<Se)-1,U+=Se),U>Q){L&&err(0);break}D&&cbuf($+131072);var Ce=$+ve;if($<ge){var ke=A-ge,Ie=Math.min(ge,Ce);for(ke+$<0&&err(3);$<Ie;++$)I[$]=x[ke+$]}for(;$<Ce;++$)I[$]=I[$-ge]}}b.l=j,b.p=me,b.b=$,b.f=B,j&&(B=1,b.m=H,b.d=W,b.n=V)}while(!B);return $!=I.length&&_?slc(I,0,$):I.subarray(0,$)}(S.subarray(function(S,b){return(8!=(15&S[0])||S[0]>>4>7||(S[0]<<8|S[1])%31)&&err(6,"invalid zlib data"),(S[1]>>5&1)==+!b&&err(6,"invalid zlib data: "+(32&S[1]?"need":"unexpected")+" dictionary"),2+(S[1]>>3&4)}(S,b&&b.dictionary),-4),{i:2},b&&b.out,b&&b.dictionary)}var Lc="undefined"!=typeof TextEncoder&&new TextEncoder,Pc="undefined"!=typeof TextDecoder&&new TextDecoder;try{Pc.decode(Nc,{stream:!0})}catch($){}function strToU8(S,b){if(b){for(var I=new dc(S.length),x=0;x<S.length;++x)I[x]=S.charCodeAt(x);return I}if(Lc)return Lc.encode(S);var R=S.length,A=new dc(S.length+(S.length>>1)),_=0,w=function(S){A[_++]=S};for(x=0;x<R;++x){if(_+5>A.length){var D=new dc(_+8+(R-x<<1));D.set(A),A=D}var L=S.charCodeAt(x);L<128||b?w(L):L<2048?(w(192|L>>6),w(128|63&L)):L>55295&&L<57344?(w(240|(L=65536+(1047552&L)|1023&S.charCodeAt(++x))>>18),w(128|L>>12&63),w(128|L>>6&63),w(128|63&L)):(w(224|L>>12),w(128|L>>6&63),w(128|63&L))}return slc(A,0,_)}function strFromU8(S,b){if(b){for(var I="",x=0;x<S.length;x+=16384)I+=String.fromCharCode.apply(null,S.subarray(x,x+16384));return I}if(Pc)return Pc.decode(S);var R=function(S){for(var b="",I=0;;){var x=S[I++],R=(x>127)+(x>223)+(x>239);if(I+R>S.length)return{s:b,r:slc(S,I-1)};R?3==R?(x=((15&x)<<18|(63&S[I++])<<12|(63&S[I++])<<6|63&S[I++])-65536,b+=String.fromCharCode(55296|x>>10,56320|1023&x)):b+=1&R?String.fromCharCode((31&x)<<6|63&S[I++]):String.fromCharCode((15&x)<<12|(63&S[I++])<<6|63&S[I++]):b+=String.fromCharCode(x)}}(S),A=R.s;return(I=R.r).length&&err(8),A}const Bc=["token","key","secret","password","auth","api_key","apikey","access_token","refresh_token","jwt","bearer","credential","session_id","session","sid","ssid","private_token"];function sanitizeUrl(S){if(!S)return"";try{const b=new URL(S);for(const S of Bc)b.searchParams.delete(S),b.searchParams.delete(S.toLowerCase()),b.searchParams.delete(S.toUpperCase());return b.toString()}catch{return S.replace(/[?&](token|key|secret|password|auth|api_key|apikey|access_token|jwt)=[^&]*/gi,"$1=[REDACTED]")}}function hashCode(S){let b=0;for(let I=0;I<S.length;I++){b=(b<<5)-b+S.charCodeAt(I),b&=b}return Math.abs(b).toString(36)}function generateNetworkId(S,b,I,x){return`net_${b}_${hashCode(sanitizeUrl(x))}`}function generateConsoleId(S,b,I){return`log_${b}_${hashCode(String(I||"").substring(0,100))}`}function generateResourceId(S,b){return`res_${S}_${hashCode(b)}`}function flatNetworkFields(S){const b=S||{},I=b.requestUrl||b.url||"";return{method:b.method,url:I,status:"number"==typeof b.status?b.status:b.statusCode,duration:"number"==typeof b.durationMs?b.durationMs:b.duration,size:"number"==typeof b.responseSize?b.responseSize:b.size,error:b.error||b.errorMessage,resourceType:b.resourceType||(I?getResourceType(I):void 0)}}function extractNetworkRef(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=flatNetworkFields(S.data?.payload),R=sanitizeUrl(x.url),A={networkId:generateNetworkId(0,S.timestamp,x.method,R),timestamp:S.timestamp,method:x.method||"GET",url:R,status:x.status,duration:x.duration,size:x.size,type:I.replace("network_","")};return"network_resource"===I&&x.resourceType&&(A.resourceType=x.resourceType),A}function extractConsoleRef(S,b){if(5!==S.type)return null;if("console"!==S.data?.tag)return null;const I=S.data?.payload||{};let x="";I.args&&Array.isArray(I.args)?x=JSON.stringify(I.args).substring(0,100):I.message&&(x=String(I.message).substring(0,100));const R=generateConsoleId(0,S.timestamp,x);let A="";return I.message?(A=String(I.message).slice(0,100),I.message.length>100&&(A+="...")):I.args&&Array.isArray(I.args)&&(A=I.args.map(S=>String(S)).join(" ").slice(0,100),A.length>=100&&(A+="...")),{consoleId:R,timestamp:S.timestamp,level:I.level||"log",preview:A}}function extractResourceRef(S){if(5!==S.type)return null;if("network_resource"!==S.data?.tag)return null;const b=S.data?.payload||{};return{resourceId:generateResourceId(S.timestamp,b.url||""),timestamp:S.timestamp,method:b.method||"GET",url:b.url||"",status:b.status||0,resourceType:b.resourceType||"other",size:b.size||null,duration:b.duration||null}}function extractNetworkFull(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=S.data?.payload||{},R=flatNetworkFields(x),A=sanitizeUrl(R.url);return{id:generateNetworkId(0,S.timestamp,R.method,A),timestamp:S.timestamp,method:R.method||"GET",url:A,requestHeaders:x.requestHeaders||{},requestBody:x.requestBody||null,status:R.status,statusText:x.statusText,responseHeaders:x.responseHeaders||{},responseBody:x.responseBody||null,duration:R.duration,size:R.size,timing:x.timing,error:R.error}}function stripNetworkPayload(S){if(5!==S.type)return S;const b=S.data?.tag;if(!b||!b.startsWith("network_"))return S;const I=flatNetworkFields(S.data?.payload);return{...S,data:{tag:S.data.tag,payload:{method:I.method,url:I.url,status:I.status,duration:I.duration,size:I.size,resourceType:I.resourceType,error:I.error}}}}function extractVersion(S,b){const I=S.match(b);return I?I[1]:"unknown"}function parseBrowserInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";return b.includes("edg/")?(I="Edge",x=extractVersion(S,/edg\/(\d+(\.\d+)?)/i)):b.includes("chrome")&&!b.includes("chromium")?(I="Chrome",x=extractVersion(S,/chrome\/(\d+(\.\d+)?)/i)):b.includes("firefox")?(I="Firefox",x=extractVersion(S,/firefox\/(\d+(\.\d+)?)/i)):b.includes("safari")&&!b.includes("chrome")?(I="Safari",x=extractVersion(S,/version\/(\d+(\.\d+)?)/i)):b.includes("opera")||b.includes("opr")?(I="Opera",x=extractVersion(S,/(?:opera|opr)\/(\d+(\.\d+)?)/i)):(b.includes("msie")||b.includes("trident"))&&(I="IE",x=extractVersion(S,/(?:msie |rv:)(\d+(\.\d+)?)/i)),{name:I,version:x}}function parseOSInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";if(b.includes("windows"))I="Windows",b.includes("windows nt 10")?x="10":b.includes("windows nt 6.3")?x="8.1":b.includes("windows nt 6.2")?x="8":b.includes("windows nt 6.1")&&(x="7");else if(b.includes("mac os x")){I="macOS";const b=S.match(/mac os x (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else if(b.includes("android"))I="Android",x=extractVersion(S,/android (\d+(\.\d+)?)/i);else if(b.includes("iphone")||b.includes("ipad")||b.includes("ipod")){I="iOS";const b=S.match(/os (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else b.includes("linux")&&(I="Linux");return{name:I,version:x}}function detectDeviceType(S){if(!S)return"desktop";const b=S.toLowerCase();return/mobile|android|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(b)?/ipad|tablet/i.test(b)||b.includes("android")&&!b.includes("mobile")?"tablet":"mobile":"desktop"}function detectTouchCapability(){return"undefined"!=typeof window&&("ontouchstart"in window||"undefined"!=typeof navigator&&navigator.maxTouchPoints>0)}function getConnectionInfo(){if("undefined"==typeof navigator||!navigator.connection)return null;const S=navigator.connection;return{effectiveType:S.effectiveType||null,downlink:S.downlink||null,rtt:S.rtt||null,saveData:S.saveData||!1}}function getMemoryInfo(){return"undefined"!=typeof navigator&&navigator.deviceMemory?{deviceMemory:navigator.deviceMemory}:null}function collectDeviceMetadata(){const S="undefined"!=typeof navigator?navigator.userAgent:null;return{screen:{width:"undefined"!=typeof screen?screen.width:null,height:"undefined"!=typeof screen?screen.height:null,colorDepth:"undefined"!=typeof screen?screen.colorDepth:null,pixelRatio:"undefined"!=typeof window?window.devicePixelRatio:null},viewport:{width:"undefined"!=typeof window?window.innerWidth:null,height:"undefined"!=typeof window?window.innerHeight:null},userAgent:S,language:"undefined"!=typeof navigator?navigator.language:null,languages:"undefined"!=typeof navigator?navigator.languages:null,platform:"undefined"!=typeof navigator?navigator.platform:null,connection:getConnectionInfo(),deviceType:detectDeviceType(S),touchCapable:detectTouchCapability(),memory:getMemoryInfo(),browser:parseBrowserInfo(S),os:parseOSInfo(S)}}function analyzeSnapshotsInEvents(S){const b=[];let I=-1;for(let x=0;x<S.length;x++){const R=S[x];2===R.type&&(b.push(R.timestamp),-1===I&&(I=x))}return{hasSnapshot:b.length>0,snapshotCount:b.length,snapshotTimestamps:b,firstSnapshotIndex:I}}function buildSnapshotIndex(S){const b=[];for(const I of S)if(I.snapshotInfo?.hasSnapshot)for(let S=0;S<I.events.length;S++){const x=I.events[S];2===x.type&&b.push({chunkSequence:I.sequence,timestamp:x.timestamp,eventIndex:S})}return b.sort((S,b)=>S.timestamp-b.timestamp),b}function findNearestSnapshotBefore(S,b){if(!S||0===S.length)return null;let I=0,x=S.length-1,R=null;for(;I<=x;){const A=Math.floor((I+x)/2),_=S[A];_.timestamp<=b?(R=_,I=A+1):x=A-1}return R}function getEventsAfterSnapshot(S,b,I){if(!S||!S.events)return[];const x=[];for(let R=b;R<S.events.length;R++){const b=S.events[R];if(!(b.timestamp<=I))break;x.push(b)}return x}function chunkHasSnapshot(S){return!0===S?.snapshotInfo?.hasSnapshot}function getSnapshotTimestamps(S){return S?.snapshotInfo?.snapshotTimestamps||[]}const zc=4;function createChunk(S){const{sequence:b,sessionId:I,events:x=[],networkRefs:R=[],consoleRefs:A=[],networkFullData:_=[],metadata:D={},isFirstChunk:L=!1,isLastChunk:B=!1}=S,U=x.map(S=>S.timestamp).filter(S=>"number"==typeof S),$=U.length>0?Math.min(...U):Date.now(),j=U.length>0?Math.max(...U):Date.now(),W=analyzeSnapshotsInEvents(x);return{version:4,chunkId:I?`${I}_chunk_${b}`:`chunk_${b}_${Date.now()}`,sequence:b,sessionId:I,startTimestamp:$,endTimestamp:j,eventCount:x.length,events:x,networkRefs:R,consoleRefs:A,networkFullData:_,snapshotInfo:{hasSnapshot:W.hasSnapshot,snapshotCount:W.snapshotCount,snapshotTimestamps:W.snapshotTimestamps,firstSnapshotIndex:W.firstSnapshotIndex},metadata:{...D,createdAt:Date.now(),isFirstChunk:L,isLastChunk:B,hasSnapshotInChunk:W.hasSnapshot}}}function isCompatibleVersion(S){return 4===S.version}class InactivityManager{constructor(S={}){this.inactivityTimeout=S.inactivityTimeout||3e5,this.maxInactivityDuration=S.maxInactivityDuration||18e5,this.maxSessionDuration=S.maxSessionDuration||36e5,this.enabled=!1!==S.enableInactivityDetection,this.lastActivityTime=Date.now(),this.isPaused=!1,this.pauseStartTime=null,this.totalPausedTime=0,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.inactivityTimer=null,this.sessionEndTimer=null,this.onPause=S.onPause||(()=>{}),this.onResume=S.onResume||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.enabled&&(this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now(),this.totalPausedTime=0,this.isPaused=!1,this.sessionEnded=!1,this.sessionEndReason=null,this.resetInactivityTimer(),this.logger.info?.(`[Inactivity] Detection enabled: pause after ${this.inactivityTimeout/1e3}s, end session after ${this.maxInactivityDuration/1e3}s`))}stop(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null)}trackActivity(S){if(!this.enabled)return;this.isUserActivityEvent(S)&&(this.lastActivityTime=Date.now(),this.isPaused&&this.resumeFromInactivity(),this.resetInactivityTimer())}isUserActivityEvent(S){if(3===S.type&&S.data){return[1,2,3,5,6,7].includes(S.data.source)}return!1}resetInactivityTimer(){if(Date.now()-this.sessionStartTime>this.maxSessionDuration)return this.logger.warn?.(`[Inactivity] Max session duration (${Math.round(this.maxSessionDuration/6e4)}min) exceeded - ending session`),void this.onMaxSessionDurationReached();this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout(()=>{this.onInactivityTimeout()},this.inactivityTimeout)}onInactivityTimeout(){if(this.isPaused)return;const S=Date.now()-this.lastActivityTime;this.logger.info?.(`[Inactivity] User inactive for ${Math.round(S/1e3)}s - pausing recording`),this.pauseForInactivity(),this.sessionEndTimer=setTimeout(()=>{this.onMaxInactivityReached()},this.maxInactivityDuration-this.inactivityTimeout)}pauseForInactivity(){this.isPaused||(this.isPaused=!0,this.pauseStartTime=Date.now(),this.onAddCustomEvent("inactivity",{action:"pause",inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}),this.logger.info?.("[Inactivity] Recording paused - waiting for user activity"),this.onPause({inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}))}resumeFromInactivity(){if(!this.isPaused)return;const S=Date.now()-this.pauseStartTime;this.totalPausedTime+=S;const b=Date.now()-this.sessionStartTime;if(b>this.maxSessionDuration)return this.logger.warn?.("[Inactivity] Max session duration exceeded during pause - ending session"),void this.onMaxSessionDurationReached();this.isPaused=!1,this.pauseStartTime=null,this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null),this.onAddCustomEvent("inactivity",{action:"resume",pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()}),this.logger.info?.(`[Inactivity] Recording resumed after ${Math.round(S/1e3)}s pause (session: ${Math.round(b/6e4)}min)`),this.onResume({pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()})}onMaxInactivityReached(){const S=Date.now()-this.lastActivityTime,b=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Inactivity] Max inactivity (${Math.round(S/1e3)}s) reached - ending session`),this.onAddCustomEvent("inactivity",{action:"session_ended",reason:"max_inactivity",inactiveFor:S,sessionDuration:b,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_inactivity")}onMaxSessionDurationReached(){const S=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Session] Max duration (${Math.round(S/6e4)}min) reached - ending session`),this.onAddCustomEvent("session_lifecycle",{action:"session_ended",reason:"max_duration",sessionDuration:S,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_duration")}endSession(S="manual"){this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.onSessionEnd({reason:S,duration:Date.now()-this.sessionStartTime,totalPausedTime:this.totalPausedTime})}shouldRecordEvent(S){return!this.isPaused||5===S.type}getState(){return{enabled:this.enabled,isPaused:this.isPaused,sessionEnded:this.sessionEnded,sessionEndReason:this.sessionEndReason,lastActivityTime:this.lastActivityTime,totalPausedTime:this.totalPausedTime,sessionDuration:Date.now()-this.sessionStartTime,timeSinceLastActivity:Date.now()-this.lastActivityTime}}updateConfig(S){void 0!==S.inactivityTimeout&&(this.inactivityTimeout=S.inactivityTimeout),void 0!==S.maxInactivityDuration&&(this.maxInactivityDuration=S.maxInactivityDuration),void 0!==S.maxSessionDuration&&(this.maxSessionDuration=S.maxSessionDuration),void 0!==S.enableInactivityDetection&&(this.enabled=S.enableInactivityDetection)}destroy(){this.stop(),this.onPause=null,this.onResume=null,this.onSessionEnd=null,this.onAddCustomEvent=null,this.logger=null}}class PageLifecycleManager{constructor(S={}){this.onFlush=S.onFlush||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.onSendBeacon=S.onSendBeacon||(()=>{}),this.getIsRecording=S.getIsRecording||(()=>!1),this.getCurrentChunkLength=S.getCurrentChunkLength||(()=>0),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.logger=S.logger||console,this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this._pageCloseFlushAttempted=!1}setup(){"undefined"!=typeof window&&(this._pageCloseFlushAttempted=!1,this._boundBeforeUnload=this._handleBeforeUnload.bind(this),this._boundPageHide=this._handlePageHide.bind(this),this._boundVisibilityChange=this._handleVisibilityChange.bind(this),window.addEventListener("beforeunload",this._boundBeforeUnload),window.addEventListener("pagehide",this._boundPageHide),document.addEventListener("visibilitychange",this._boundVisibilityChange),this.logger.info?.("[PageLifecycle] Page close handlers installed"))}remove(){"undefined"!=typeof window&&(this._boundBeforeUnload&&window.removeEventListener("beforeunload",this._boundBeforeUnload),this._boundPageHide&&window.removeEventListener("pagehide",this._boundPageHide),this._boundVisibilityChange&&document.removeEventListener("visibilitychange",this._boundVisibilityChange),this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this.logger.info?.("[PageLifecycle] Page close handlers removed"))}_handleBeforeUnload(S){this._flushOnPageClose("beforeunload")}_handlePageHide(S){this._flushOnPageClose("pagehide",S.persisted)}_handleVisibilityChange(){"hidden"===document.visibilityState&&this._flushOnPageClose("visibilitychange")}_flushOnPageClose(S,b=!1){if(this._pageCloseFlushAttempted)return void this.logger.log?.(`[PageLifecycle] Flush already attempted, skipping duplicate (${S})`);const I=this.getIsRecording(),x=this.getCurrentChunkLength();if(!I||0===x)return void this.logger.log?.(`[PageLifecycle] No pending events to flush on ${S}`);this._pageCloseFlushAttempted=!0,this.logger.log?.(`[PageLifecycle] Flushing ${x} events on ${S}`),this.onAddCustomEvent("session_lifecycle",{action:"page_close",trigger:S,persisted:b,timestamp:Date.now(),pendingEvents:x,sessionDuration:Date.now()-this.getSessionStartTime(),totalChunks:this.getChunkCounter()});const R=this.onFlush();R&&(R.metadata=R.metadata||{},R.metadata.isLastChunk=!0,R.metadata.closeTrigger=S,R.metadata.sessionEndedGracefully=!0,this.onSendBeacon(R,S))}resetFlushGuard(){this._pageCloseFlushAttempted=!1}getState(){return{handlersInstalled:null!==this._boundBeforeUnload,flushAttempted:this._pageCloseFlushAttempted}}destroy(){this.remove(),this.onFlush=null,this.onAddCustomEvent=null,this.onSendBeacon=null,this.getIsRecording=null,this.getCurrentChunkLength=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.logger=null}}class CheckpointManager{constructor(S={}){this.checkpointInterval=S.checkpointInterval||6e4,this.lastCheckpointTime=0,this.checkpointTimer=null,this.checkpointCount=0,this.checkpointAvailable=null,this.getRRWeb=S.getRRWeb||(()=>null),this.getIsRecording=S.getIsRecording||(()=>!1),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.getEventCount=S.getEventCount||(()=>0),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.checkpointTimer&&clearInterval(this.checkpointTimer),this.lastCheckpointTime=Date.now(),this.checkpointCount=0,this.checkpointTimer=setInterval(()=>{this.requestCheckpoint()},this.checkpointInterval),this.logger.info?.(`[Checkpoint] Timer started (interval: ${this.checkpointInterval/1e3}s)`)}stop(){this.checkpointTimer&&(clearInterval(this.checkpointTimer),this.checkpointTimer=null)}requestCheckpoint(){if(!this.getIsRecording())return;const S=Date.now();if(!(S-this.lastCheckpointTime<.9*this.checkpointInterval))try{const b=this.getRRWeb();let I=null;if(b&&("function"==typeof b.takeFullSnapshot?I=b.takeFullSnapshot:b.record&&"function"==typeof b.record.takeFullSnapshot&&(I=b.record.takeFullSnapshot)),I)try{I(),this.lastCheckpointTime=S,this.checkpointAvailable=!0,this.checkpointCount++,this.onAddCustomEvent("checkpoint",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),checkpointNumber:this.checkpointCount,snapshotRequested:!0}),this.logger.info?.(`[Checkpoint] #${this.checkpointCount} at ${Math.round((S-this.getSessionStartTime())/1e3)}s`)}catch(b){this.logger.warn?.("[Checkpoint] takeFullSnapshot error:",b.message),this.checkpointAvailable=!1,this._addCheckpointMarker(S,"takeFullSnapshot error: "+b.message)}else!1!==this.checkpointAvailable&&(this.logger.warn?.("[Checkpoint] Manual snapshots not available - relying on rrweb checkoutEveryNms"),this.checkpointAvailable=!1),this._addCheckpointMarker(S,"using rrweb auto-checkout")}catch(S){this.logger.warn?.("[Checkpoint] Request failed:",S.message),this._addCheckpointMarker(Date.now(),"Error: "+S.message)}}_addCheckpointMarker(S,b){this.onAddCustomEvent("checkpoint_marker",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),snapshotRequested:!1,reason:b})}takeManualCheckpoint(){this.logger.info?.("[Checkpoint] Manual checkpoint requested"),this.requestCheckpoint()}getState(){return{checkpointCount:this.checkpointCount,lastCheckpointTime:this.lastCheckpointTime,checkpointAvailable:this.checkpointAvailable,checkpointInterval:this.checkpointInterval,timerRunning:null!==this.checkpointTimer}}updateConfig(S){void 0!==S.checkpointInterval&&(this.checkpointInterval=S.checkpointInterval,this.checkpointTimer&&(this.stop(),this.start()))}destroy(){this.stop(),this.getRRWeb=null,this.getIsRecording=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.getEventCount=null,this.onAddCustomEvent=null,this.logger=null}}class RecorderMemoryManager{constructor(S={}){this.maxChunksInMemory=S.maxChunksInMemory||10,this.maxEventsPerSession=S.maxEventsPerSession||5e4,this.maxSessionBytes=S.maxSessionBytes||52428800,this.maxEventsInBuffer=S.maxEventsInBuffer||2e3,this.cleanupInterval=S.cleanupInterval||6e4,this.totalSessionBytes=0,this.cleanupTimer=null,this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=S.onForceFlush||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setDataReferences(S){this._allChunks=S.allChunks||null,this._events=S.events||null,this._eventDedupeCache=S.eventDedupeCache||null,this._eventStats=S.eventStats||null}start(){this.cleanupTimer||(this.totalSessionBytes=0,this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.cleanupInterval),this.logger.log?.("[Memory] Started periodic cleanup (60s interval)"))}stop(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.logger.log?.("[Memory] Stopped cleanup timer"))}trackBytes(S){return this.totalSessionBytes+=S,!(this.totalSessionBytes>this.maxSessionBytes)||(this.logger.warn?.(`[Memory] Session size limit reached (${Math.round(this.totalSessionBytes/1024/1024)}MB / ${Math.round(this.maxSessionBytes/1024/1024)}MB)`),!1)}checkEventLimit(S){return!(S>this.maxEventsPerSession)||(this.logger.warn?.(`[Memory] Max events per session (${this.maxEventsPerSession}) exceeded`),!1)}performCleanup(){const S=Date.now();let b={dedupeEntries:0,statsEvents:0,chunks:0,eventsBuffer:0};if(this._eventDedupeCache){const I=S-1e4;for(const[S,x]of this._eventDedupeCache.entries())x<I&&(this._eventDedupeCache.delete(S),b.dedupeEntries++)}if(this._eventStats?.lastMinuteEvents){const I=S-6e4,x=this._eventStats.lastMinuteEvents.length;this._eventStats.lastMinuteEvents=this._eventStats.lastMinuteEvents.filter(S=>S>I),b.statsEvents=x-this._eventStats.lastMinuteEvents.length}if(this._allChunks&&this._allChunks.length>this.maxChunksInMemory)for(;this._allChunks.length>this.maxChunksInMemory;)this._allChunks.shift(),b.chunks++;return this._events&&this._events.length>this.maxEventsInBuffer&&(this.logger.warn?.(`[Memory] Events buffer exceeded ${this.maxEventsInBuffer}, forcing flush`),this.onForceFlush()),(b.dedupeEntries>0||b.statsEvents>0||b.chunks>0)&&this.logger.log?.(`[Memory] Cleanup: ${b.dedupeEntries} dedupe entries, ${b.statsEvents} stat entries, ${b.chunks} chunks`),b}trimEventsArray(S=1e3){if(!this._events||this._events.length<=S)return 0;const b=this._events.length-S;return this._events.splice(0,b),this.logger.log&&this.logger.log?.(`[Memory] Cleared ${b} old events from events array`),b}trimChunksArray(){if(!this._allChunks||this._allChunks.length<=this.maxChunksInMemory)return null;const S=this._allChunks.shift();return this.logger.log?.(`[Memory] Removed old chunk ${S?.sequence} from memory (keeping ${this.maxChunksInMemory} chunks)`),S}getStats(){return{eventsInBuffer:this._events?.length||0,maxEventsInBuffer:this.maxEventsInBuffer,chunksInMemory:this._allChunks?.length||0,maxChunksInMemory:this.maxChunksInMemory,dedupeCacheSize:this._eventDedupeCache?.size||0,totalSessionBytes:this.totalSessionBytes,maxSessionBytes:this.maxSessionBytes,sessionSizePercent:Math.round(this.totalSessionBytes/this.maxSessionBytes*100),statsEventsTracked:this._eventStats?.lastMinuteEvents?.length||0,totalEventsRecorded:this._eventStats?.total||0,estimatedMemoryMB:this.estimateMemoryUsage()}}estimateMemoryUsage(){let S=0;if(S+=500*(this._events?.length||0),this._allChunks)for(const b of this._allChunks)S+=b.sizeBytes||5e4;return S+=100*(this._eventDedupeCache?.size||0),Math.round(S/1048576*100)/100}suggestGC(){if(this._allChunks)for(const S of this._allChunks)S._rawEvents&&(S._rawEvents=null);this.logger.log?.("[Memory] GC hint sent")}updateConfig(S){void 0!==S.maxChunksInMemory&&(this.maxChunksInMemory=S.maxChunksInMemory),void 0!==S.maxEventsPerSession&&(this.maxEventsPerSession=S.maxEventsPerSession),void 0!==S.maxSessionBytes&&(this.maxSessionBytes=S.maxSessionBytes),void 0!==S.maxEventsInBuffer&&(this.maxEventsInBuffer=S.maxEventsInBuffer)}reset(){this.totalSessionBytes=0}destroy(){this.stop(),this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=null,this.onSessionEnd=null,this.logger=null}}const Uc={0:"DomContentLoaded",1:"Load",2:"FullSnapshot",3:"IncrementalSnapshot",4:"Meta",5:"Custom"};class EventOptimizer{constructor(S={}){this.samplingEnabled=S.enableSampling||!1,this.deduplicationEnabled=S.enableDeduplication||!1,this.mousemoveSampling=S.mousemoveSampling||1,this.scrollSampling=S.scrollSampling||1,this.mutationSampling=S.mutationSampling||1,this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0},this.eventDedupeCache=new Map,this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.logger=S.logger||console}getDedupeCache(){return this.eventDedupeCache}getEventStats(){return this.eventStats}shouldRecordEvent(S){const b=this.getEventTypeName(S.type);return!!["DomContentLoaded","Load","FullSnapshot","Meta","Custom"].includes(b)||!(this.samplingEnabled&&!this._applySampling(S))&&(!this.deduplicationEnabled||!this._isDuplicateEvent(S))}updateStats(S){this.eventStats.total++;const b=this.getEventTypeName(S.type);this.eventStats.byType[b]=(this.eventStats.byType[b]||0)+1;try{const I=JSON.stringify(S).length;this.eventStats.sizeByType[b]||(this.eventStats.sizeByType[b]={total:0,count:0,average:0}),this.eventStats.sizeByType[b].total+=I,this.eventStats.sizeByType[b].count++,this.eventStats.sizeByType[b].average=Math.round(this.eventStats.sizeByType[b].total/this.eventStats.sizeByType[b].count)}catch(S){}const I=Date.now();this.eventStats.lastMinuteEvents.push(I),this.eventStats.lastMinuteEvents=this.eventStats.lastMinuteEvents.filter(S=>I-S<6e4),this.eventStats.currentRate=this.eventStats.lastMinuteEvents.length}adaptToEventRate(){if(!this.samplingEnabled)return;const S=this.eventStats.currentRate;S>3e3?(this.mousemoveSampling=Math.max(.1,this.mousemoveSampling-.1),this.scrollSampling=Math.max(.2,this.scrollSampling-.1),this.logger.warn?.(`[Optimizer] High event rate (${S}/min), increasing sampling`)):S<600&&this.mousemoveSampling<.5&&(this.mousemoveSampling=Math.min(.5,this.mousemoveSampling+.05),this.scrollSampling=Math.min(.7,this.scrollSampling+.05))}_applySampling(S){if(3===S.type&&1===S.data?.source){if(Math.random()>=this.mousemoveSampling)return!1;if(S.data.positions&&S.data.positions.length>0){const b=S.data.positions[S.data.positions.length-1];if(Math.sqrt(Math.pow(b.x-this.lastMousePosition.x,2)+Math.pow(b.y-this.lastMousePosition.y,2))<5)return!1;this.lastMousePosition={x:b.x,y:b.y}}}return 3!==S.type||3!==S.data?.source||Math.random()<this.scrollSampling}_isDuplicateEvent(S){const b=this._getEventKey(S),I=Date.now();if(this.eventDedupeCache.has(b)){if(I-this.eventDedupeCache.get(b)<100)return!0}if(this.eventDedupeCache.set(b,I),this.eventDedupeCache.size>1e3){const S=I-5e3;for(const[b,I]of this.eventDedupeCache.entries())I<S&&this.eventDedupeCache.delete(b)}return!1}_getEventKey(S){if(3===S.type){const b=S.data?.source,I=S.data?.id,x=S.data?.action;return`${S.type}-${b}-${I}-${x}`}try{return`${S.type}-${JSON.stringify(S.data).substring(0,50)}`}catch(b){return`${S.type}-unknown`}}getEventTypeName(S){return Uc[S]||`Unknown(${S})`}getOptimizationStats(){return{eventStats:{...this.eventStats},samplingRates:{mousemove:this.mousemoveSampling,scroll:this.scrollSampling},samplingEnabled:this.samplingEnabled,deduplicationEnabled:this.deduplicationEnabled,deduplicatedEvents:this.eventDedupeCache.size}}logOptimizationReport(){const S=this.getOptimizationStats();this.logger.info?.("📊 Optimization Report:"),this.logger.info?.(" Sampling: "+(S.samplingEnabled?"Enabled":"Disabled")),this.logger.info?.(" Deduplication: "+(S.deduplicationEnabled?"Enabled":"Disabled")),this.logger.info?.(` Event Rate: ${S.eventStats.currentRate}/min`),this.logger.info?.(` Total Events: ${S.eventStats.total}`),this.logger.info?.(` Deduplicated: ${S.deduplicatedEvents}`),S.samplingEnabled&&(this.logger.info?.(" Sampling Rates:"),this.logger.info?.(` Mouse Move: ${(100*S.samplingRates.mousemove).toFixed(0)}%`),this.logger.info?.(` Scroll: ${(100*S.samplingRates.scroll).toFixed(0)}%`)),this.logger.info?.(" Event Distribution:");for(const[b,I]of Object.entries(S.eventStats.byType)){const x=(I/S.eventStats.total*100).toFixed(1),R=S.eventStats.sizeByType[b]?.average||0;this.logger.info?.(` ${b}: ${I} (${x}%) - Avg: ${R}B`)}}updateConfig(S){void 0!==S.enableSampling&&(this.samplingEnabled=S.enableSampling),void 0!==S.enableDeduplication&&(this.deduplicationEnabled=S.enableDeduplication),void 0!==S.mousemoveSampling&&(this.mousemoveSampling=S.mousemoveSampling),void 0!==S.scrollSampling&&(this.scrollSampling=S.scrollSampling),void 0!==S.mutationSampling&&(this.mutationSampling=S.mutationSampling)}reset(){this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.eventDedupeCache.clear(),this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0}}destroy(){this.eventDedupeCache.clear(),this.eventStats=null,this.logger=null}}class ChunkManager{constructor(S={}){this.chunkDuration=S.chunkDuration||3e4,this.maxChunkSize=S.maxChunkSize||5e5,this.maxEventsPerChunk=S.maxEventsPerChunk||500,this.minFlushInterval=S.minFlushInterval||1e4,this.firstChunkFlushed=!1,this.firstChunkFlushTimeout=2e3,this.recordingStartTime=null,this._firstChunkTimer=null,this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.chunkTimer=null,this.sessionId=null,this.sdkContext=null,this.onChunkCreated=S.onChunkCreated||(()=>{}),this.onServerUpload=S.onServerUpload||null,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setSessionInfo(S){this.sessionId=S.sessionId,this.sdkContext=S.sdkContext}startRecording(){this.recordingStartTime=Date.now(),this.firstChunkFlushed=!1,this._firstChunkTimer&&clearTimeout(this._firstChunkTimer),this._firstChunkTimer=setTimeout(()=>{!this.firstChunkFlushed&&this.currentChunk.length>0&&(this.logger.info?.("[ChunkManager] Force-flushing first chunk (2s timeout)"),this.flush({force:!0})),this._firstChunkTimer=null},this.firstChunkFlushTimeout)}startTimer(){this.chunkTimer||(this.chunkTimer=setTimeout(()=>{this.flush(),this.startTimer()},this.chunkDuration))}stopTimer(){this.chunkTimer&&(clearTimeout(this.chunkTimer),this.chunkTimer=null)}resetTimer(){this.stopTimer(),this.startTimer()}addEvent(S){return this.currentChunk.push(S),!0}getCurrentChunkLength(){return this.currentChunk.length}checkFlush(){if(0===this.currentChunk.length)return!1;if(!this.firstChunkFlushed&&this.currentChunk.length>0){const S=this.currentChunk.some(S=>2===S.type);if(S)return this.logger.info?.("[ChunkManager] FullSnapshot detected - immediate flush"),this.flush({force:!0}),this.resetTimer(),!0}const S=this.estimateSize(this.currentChunk)>=this.maxChunkSize,b=this.currentChunk.length>=this.maxEventsPerChunk,I=Date.now()-this._lastFlushTime;return(S||!!(b&&I>=this.minFlushInterval))&&(this.flush(),this.resetTimer(),!0)}flush(S={}){if(this._isFlushing)return null;this._isFlushing=!0;try{if(0===this.currentChunk.length)return null;!this.firstChunkFlushed&&(this.firstChunkFlushed=!0,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.logger.info?.("[ChunkManager] First chunk flushed"));const S=this.currentChunk;this.currentChunk=[];const b=this.chunkCounter;this.chunkCounter++,this.sessionId||(this.sessionId=generateSessionId(),this.logger.warn(`[ChunkManager] sessionId was null at flush time for chunk ${b}, generated fallback: ${this.sessionId}`));const I=[],x=[],R=[],A=[];for(const b of S){const S=extractNetworkRef(b,this.sessionId);if(S){I.push(S);const x=extractNetworkFull(b,this.sessionId);x&&R.push(x),A.push(stripNetworkPayload(b));continue}const _=extractConsoleRef(b,this.sessionId);_?(x.push(_),A.push(b)):A.push(b)}const _={projectId:this.sdkContext?.projectId,environment:this.sdkContext?.environment,userId:this.sdkContext?.userId};0===b&&(_.device=collectDeviceMetadata());let D=createChunk({sequence:b,sessionId:this.sessionId,events:A,networkRefs:I,consoleRefs:x,networkFullData:R,metadata:_,isFirstChunk:0===b,isLastChunk:!1});return this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&(D=this.sdkContext.enrichChunk(D)),this.allChunks.push(D),this._lastFlushTime=Date.now(),this.onChunkCreated(D,b),this.onServerUpload&&this.sendToServer(D),D}finally{this._isFlushing=!1}}estimateSize(S){if(!S||0===S.length)return 0;try{if(S.length<=50)return JSON.stringify(S).length;const b=Math.min(50,Math.max(10,Math.floor(.1*S.length))),I=Math.floor(S.length/b);let x=0;for(let b=0;b<S.length;b+=I)x+=JSON.stringify(S[b]).length;const R=x/Math.ceil(S.length/I);return Math.ceil(R*S.length)+2*S.length}catch(S){return 0}}async sendToServer(S){if(this.onServerUpload)try{await this.onServerUpload(S),this.logger.info?.(`Chunk ${S.sequence} sent successfully`)}catch(S){this.logger.warn?.("Failed to send chunk to server:",S)}}getChunks(){return[...this.allChunks]}getChunkCounter(){return this.chunkCounter}setChunkCounter(S){this.chunkCounter=S}getCurrentChunk(){return[...this.currentChunk]}exportChunkedData(S="json"){const b={sessionId:this.sessionId,chunks:this.allChunks,totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length};return"json"===S?JSON.stringify(b,null,2):b}getStats(){const S=this.allChunks.reduce((S,b)=>S+(b.sizeBytes||0),0),b=this.estimateSize(this.currentChunk);return{totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length,currentChunkSize:b,totalSize:S,chunkCounter:this.chunkCounter,avgChunkSize:this.allChunks.length>0?Math.round(S/this.allChunks.length):0}}updateConfig(S){void 0!==S.chunkDuration&&(this.chunkDuration=S.chunkDuration),void 0!==S.maxChunkSize&&(this.maxChunkSize=S.maxChunkSize),void 0!==S.maxEventsPerChunk&&(this.maxEventsPerChunk=S.maxEventsPerChunk),void 0!==S.minFlushInterval&&(this.minFlushInterval=S.minFlushInterval)}reset(){this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.stopTimer(),this.firstChunkFlushed=!1,this.recordingStartTime=null,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null)}destroy(){this.stopTimer(),this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.currentChunk=[],this.allChunks=[],this.onChunkCreated=null,this.onServerUpload=null,this.onSessionEnd=null,this.sdkContext=null,this.logger=null}}class RecorderLogger{constructor(S,b=!1){const I=S.replace(/^\[|\]$/g,"");this.serviceLogger=createLogger(I),this.prefix=`[TraceScout][${S}]`,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.debug&&this.serviceLogger.log(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class Recorder{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[Recorder] No SDKContext provided - running in v1.x compatibility mode");const b=S.preset?Recorder.getPresetConfig(S.preset):{};if(this.config={emit:()=>{},checkoutEveryNms:6e4,checkoutEveryNth:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,debug:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},chunkDuration:3e4,maxChunkSize:5e5,onChunk:null,enableSampling:!1,enableDeduplication:!1,mousemoveSampling:1,scrollSampling:1,mutationSampling:1,inactivityTimeout:3e5,maxInactivityDuration:18e5,maxSessionDuration:36e5,enableInactivityDetection:!0,maxChunksInMemory:S.maxChunksInMemory||10,maxEventsPerSession:S.maxEventsPerSession||5e4,maxSessionBytes:S.maxSessionBytes||52428800,checkpointInterval:S.checkpointInterval||6e4,...b,...S},this.sdkContext&&"function"==typeof this.sdkContext.setDomPrivacy)try{this.sdkContext.setDomPrivacy(function deriveDomPrivacy(S){if(!S||"object"!=typeof S)return"disabled";if(!0===S.maskAllInputs)return"confirmed";const b="string"==typeof S.maskTextClass&&S.maskTextClass.length>0,I="string"==typeof S.blockClass&&S.blockClass.length>0;return b||I?"partial":"disabled"}(this.config))}catch{}this.events=[],this.isRecording=!1,this.stopFn=null,this.metadata={},this.sessionId=null,this.recordingStartTime=null,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.statusTimer=null,this.statusInterval=1e4,this.aggregationTimer=null,this.aggregationInterval=3e4,this.lastAggregationThresholdSec=0,this._uploadQueue=null,this.logger=new RecorderLogger("Recorder",this.config.debug),this._initializeModules()}_initializeModules(){this.inactivityManager=new InactivityManager({inactivityTimeout:this.config.inactivityTimeout,maxInactivityDuration:this.config.maxInactivityDuration,maxSessionDuration:this.config.maxSessionDuration,enableInactivityDetection:this.config.enableInactivityDetection,logger:this.logger,onPause:S=>this._onInactivityPause(S),onResume:S=>this._onInactivityResume(S),onSessionEnd:S=>this._onInactivitySessionEnd(S),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.pageLifecycleManager=new PageLifecycleManager({logger:this.logger,getIsRecording:()=>this.isRecording,getCurrentChunkLength:()=>this.chunkManager.getCurrentChunkLength(),getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),onFlush:()=>this.chunkManager.flush(),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b),onSendBeacon:(S,b)=>this._sendChunkWithBeacon(S,b)}),this.checkpointManager=new CheckpointManager({checkpointInterval:this.config.checkpointInterval,logger:this.logger,getRRWeb:()=>getRRWeb(),getIsRecording:()=>this.isRecording,getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),getEventCount:()=>this.events.length,onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.memoryManager=new RecorderMemoryManager({maxChunksInMemory:this.config.maxChunksInMemory,maxEventsPerSession:this.config.maxEventsPerSession,maxSessionBytes:this.config.maxSessionBytes,logger:this.logger,onForceFlush:()=>this.chunkManager.flush(),onSessionEnd:S=>this.endSession(S)}),this.eventOptimizer=new EventOptimizer({enableSampling:this.config.enableSampling,enableDeduplication:this.config.enableDeduplication,mousemoveSampling:this.config.mousemoveSampling,scrollSampling:this.config.scrollSampling,mutationSampling:this.config.mutationSampling,logger:this.logger}),this.chunkManager=new ChunkManager({chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize,logger:this.logger,onChunkCreated:(S,b)=>this._onChunkCreated(S,b),onServerUpload:this.config.serverUrl?S=>this.sendChunkToServer(S):null})}async start(S={}){if(this.isRecording)return this.logger.warn("Recording already in progress"),this.stopFn;this.logger.info("Starting session recording...");const b=this._getSessionResumeInfo();b.isResumed&&(this.logger.info(`[V3] Resuming session ${b.sessionId}, continuing from chunk ${b.lastChunkSequence}`),this.chunkManager.setChunkCounter(b.lastChunkSequence+1));try{const b=await loadRRWeb();this.sdkContext&&this.sdkContext.sessionId?this.sessionId=this.sdkContext.sessionId:this.sessionId=this.generateSessionId(),this.chunkManager.setSessionInfo({sessionId:this.sessionId,sdkContext:this.sdkContext});let I=0,x=Date.now();const R={...this.config,...S,emit:b=>{if(I++,this.config.debug&&I%50==0){const S=Date.now()-x;this.logger.log(`${I} events captured (${S}ms since last log)`),x=Date.now()}const R={...b,tracescoutVersion:"1.0.0",sessionId:this.getSessionId()},A=this.chunkManager.estimateSize([R]),_=2===R.type||4===R.type;if(A>1e6&&!_)return void(this.config.debug&&this.logger.warn(`Skipping extremely large event: ${A} bytes, type: ${R.type}`));if(!this.onEvent(R))return;this.chunkManager.addEvent(R),this.events.push(R),this.chunkManager.checkFlush();(S.emit||this.config.emit)(R)}};if(this.stopFn=b.record(R),this.isRecording=!0,this.recordingStartTime=Date.now(),this.sessionStartTime=Date.now(),this._rrweb=b,this.chunkManager&&(this.chunkManager.startRecording(),this.logger.info("[Recorder] First-chunk flush timer started (2s)")),this.memoryManager.setDataReferences({allChunks:this.chunkManager.allChunks,events:this.events,eventDedupeCache:this.eventOptimizer.getDedupeCache(),eventStats:this.eventOptimizer.getEventStats()}),this.config.enableStreamingStorage)try{const{ChunkedCompressedStorage:S}=await Promise.resolve().then(function(){return qc});this.__streamStore=S,this.__streamStore.initSession(this.sessionId),this.logger.info("Streaming storage initialized")}catch(S){this.logger.warn("Failed to init streaming storage:",S)}return this.chunkManager.startTimer(),this.checkpointManager.start(),this.memoryManager.start(),this.inactivityManager.start(),this.pageLifecycleManager.setup(),this._startStatusTimer(),this.sessionEnded=!1,this.sessionEndReason=null,this._uploadQueue?.didIndexedDBFail?.()&&(this.logger.warn("[Recorder] IndexedDB failed - scheduling backup snapshot"),this._scheduleBackupSnapshot()),this._uploadQueue?.on&&this._uploadQueue.on("firstSnapshotUploadFailed",()=>{this.logger.warn("[Recorder] First snapshot upload failed 3x - taking immediate backup"),this._takeBackupSnapshot()}),this._setupSPANavigationDetection(),this.logger.info("🔴 Recording started",{sessionId:this.sessionId,startTime:this.recordingStartTime,chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize}),this.stopFn}catch(S){throw this.logger.error("Failed to load or initialize rrweb:",S),S}}stop(){if(!this.isRecording)return this.logger.warn("No recording in progress"),this.events;this.chunkManager.stopTimer(),this.checkpointManager.stop(),this.memoryManager.stop(),this.inactivityManager.stop(),this.pageLifecycleManager.remove(),this._stopStatusTimer(),this._cleanupSPANavigationDetection(),this._backupSnapshotTimer&&(clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=null),this.chunkManager.flush(),this.stopFn&&(this.stopFn(),this.stopFn=null),this._rrweb=null,this.isRecording=!1;const S=Date.now()-this.recordingStartTime;return this.logger.info("Recording stopped",{sessionId:this.sessionId,duration:S,eventCount:this.events.length,totalChunks:this.chunkManager.getChunks().length}),this.events}onEvent(S){return this.eventOptimizer.updateStats(S),this.inactivityManager.trackActivity(S),!!this.inactivityManager.shouldRecordEvent(S)&&(5===S.type||!!this.eventOptimizer.shouldRecordEvent(S)&&(this.eventOptimizer.adaptToEventRate(),!0))}addCustomEvent(S,b){if(!this.isRecording)return!1;if(!S||"string"!=typeof S)return!1;try{let I=b||{};this.sdkContext&&(I={...b,sessionId:this.sdkContext.sessionId,projectId:this.sdkContext.projectId,environment:this.sdkContext.environment,userId:this.sdkContext.userId});const x={type:5,data:{tag:S,payload:I},timestamp:Date.now(),tracescoutVersion:this.sdkContext?"2.0.0":"1.0.0",sessionId:this.getSessionId()};return!!this.onEvent(x)&&(this.chunkManager.addEvent(x),this.events.push(x),this.chunkManager.checkFlush(),!0)}catch(S){return this.logger.error("Failed to add custom event:",S),!1}}_setupSPANavigationDetection(){if("undefined"==typeof window||"undefined"==typeof history)return;this._lastKnownUrl=window.location.href,this._originalPushState=history.pushState,this._originalReplaceState=history.replaceState;const S=this;history.pushState=function(...b){const I=S._originalPushState.apply(this,b);return S._onSPANavigation("pushState"),I},history.replaceState=function(...b){const I=S._originalReplaceState.apply(this,b);return S._onSPANavigation("replaceState"),I},this._popstateHandler=()=>{S._onSPANavigation("popstate")},window.addEventListener("popstate",this._popstateHandler),this._hashchangeHandler=()=>{S._onSPANavigation("hashchange")},window.addEventListener("hashchange",this._hashchangeHandler),this.logger.info("SPA navigation detection enabled")}_onSPANavigation(S){const b=window.location.href;if(b===this._lastKnownUrl)return;const I=this._lastKnownUrl;if(this._lastKnownUrl=b,this.logger.info(`SPA navigation detected (${S}): ${I} → ${b}`),this.addCustomEvent("page_navigation",{url:b,previousUrl:I,title:document.title,navigationType:S,timestamp:Date.now()}),"function"==typeof this.config?.onSpaNavigation)try{this.config.onSpaNavigation(S,I,b)}catch(S){this.logger.warn?.("[Recorder] onSpaNavigation callback threw:",S)}setTimeout(()=>{this._takeFullSnapshotForNavigation(b)},100)}_takeFullSnapshotForNavigation(S){if(this._rrweb&&this.isRecording)try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info(`Taking full snapshot for SPA navigation to: ${S}`),this._rrweb.record.takeFullSnapshot()):this.logger.warn("rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("Failed to take full snapshot for SPA navigation:",S)}}_scheduleBackupSnapshot(){this._backupSnapshotTimer&&clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=setTimeout(()=>{if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] Chunk 0 already acked, skipping backup snapshot");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (2s safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}},2e3)}_takeBackupSnapshot(){if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] First snapshot ACKed - skipping backup");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}}_cleanupSPANavigationDetection(){"undefined"!=typeof window&&"undefined"!=typeof history&&(this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null),this._popstateHandler&&(window.removeEventListener("popstate",this._popstateHandler),this._popstateHandler=null),this._hashchangeHandler&&(window.removeEventListener("hashchange",this._hashchangeHandler),this._hashchangeHandler=null),this._lastKnownUrl=null,this.logger.info("SPA navigation detection disabled"))}_onInactivityPause(S){this.logger.info("[Inactivity] Recording paused")}_onInactivityResume(S){this.logger.info("[Inactivity] Recording resumed")}_onInactivitySessionEnd(S){this.endSession(S.reason)}_onChunkCreated(S,b){const I=this.memoryManager.trackBytes(S.sizeBytes||0);if(this.memoryManager.trimChunksArray(),this.memoryManager.trimEventsArray(1e3),I)if(this.memoryManager.checkEventLimit(this.events.length)){if(this._updateSessionChunkSequence(b),this.__streamStore)try{this.__streamStore.saveChunk(this.sessionId,b,S.events),this.__streamStore.updateSessionInfo(this.sessionId,b+1,this.events.length)}catch(S){}this.config.onChunk&&this.config.onChunk(S)}else this.endSession("max_events");else this.endSession("max_size")}endSession(S="manual"){this.logger.info(`[Session] Ending session: ${this.sessionId} (reason: ${S})`),this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.config.onSessionEnd&&this.config.onSessionEnd({sessionId:this.sessionId,reason:S,duration:Date.now()-this.sessionStartTime,totalEvents:this.events.length,totalPausedTime:this.inactivityManager.totalPausedTime})}_getSessionResumeInfo(){return this.sdkContext?.sessionManager?this.sdkContext.sessionManager.getResumeInfo():this.config.sessionManager?this.config.sessionManager.getResumeInfo():{isResumed:!1,sessionId:null,lastChunkSequence:0}}_updateSessionChunkSequence(S){this.sdkContext?.sessionManager?this.sdkContext.sessionManager.updateLastChunkSequence(S):this.config.sessionManager&&this.config.sessionManager.updateLastChunkSequence(S)}setUploadQueue(S){this._uploadQueue=S}_sendChunkWithBeacon(S,b){if(this._uploadQueue?.sendFinalChunkWithBeacon){if(this._uploadQueue.sendFinalChunkWithBeacon(S,b))return void this.logger.info(`[P0] Chunk ${S.sequence} sent via UploadQueue.sendFinalChunkWithBeacon`)}const I=this.sdkContext?.getChunkEndpoint?.()||(this.config.serverUrl?`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`:null);if(!I)return void(this.config.onChunk&&this.config.onChunk(S));const x={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],metadata:{...S.metadata,sentVia:"sendBeacon",closeTrigger:b},sizeBytes:S.sizeBytes},R=JSON.stringify(x);if("undefined"!=typeof navigator&&navigator.sendBeacon)try{const b=new Blob([R],{type:"application/json"});navigator.sendBeacon(I,b)?this.logger.info(`[P0] Chunk ${S.sequence} sent via sendBeacon`):this.config.onChunk&&this.config.onChunk(S)}catch(b){this.config.onChunk&&this.config.onChunk(S)}else this.config.onChunk&&this.config.onChunk(S)}async sendChunkToServer(S){try{const b={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],networkFullData:S._networkFullData||[],metadata:S.metadata,sizeBytes:S.sizeBytes},I=this.sdkContext?.getChunkEndpoint?.()||`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`,x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!x.ok)throw new Error(`Server responded with ${x.status}`);return await x.json()}catch(S){throw this.logger.warn("Failed to send chunk to server:",S),S}}_startStatusTimer(){this.statusTimer&&clearInterval(this.statusTimer),setTimeout(()=>this.logStatus(),1e3),this.statusTimer=setInterval(()=>{this.logStatus()},this.statusInterval),this.config.debug&&(this.aggregationTimer&&clearInterval(this.aggregationTimer),this.aggregationTimer=setInterval(()=>{this._maybeLogAggregationExport()},this.aggregationInterval))}_stopStatusTimer(){this.statusTimer&&(clearInterval(this.statusTimer),this.statusTimer=null),this.aggregationTimer&&(clearInterval(this.aggregationTimer),this.aggregationTimer=null),this.lastAggregationThresholdSec=0}logStatus(){if(!this.isRecording)return;const S=this.chunkManager.getStats(),b=Date.now()-this.recordingStartTime,I=Math.floor(b/1e3),x=Math.floor(I/60),R=I%60,fmtSize=S=>S>=1048576?`${(S/1048576).toFixed(1)}MB`:`${Math.round(S/1024)}KB`;this.logger.info(`📊 Session Status [${x}m ${R}s]:`,{totalEvents:this.events.length,totalSize:fmtSize(S.totalSize),currentChunk:`${S.currentChunkEvents} events (${fmtSize(S.currentChunkSize)})`,completedChunks:S.totalChunks})}_maybeLogAggregationExport(){if(!this.isRecording||!this.recordingStartTime)return;const S=Date.now()-this.recordingStartTime,b=Math.floor(S/this.aggregationInterval)*(this.aggregationInterval/1e3);if(b>0&&b!==this.lastAggregationThresholdSec){this.lastAggregationThresholdSec=b;try{const S=this.buildReplayExport();this.logger.info(`🧩 Session export (${b}s):`,S)}catch(S){this.logger.warn("Failed to export session data:",S)}}}getStatus(){return{isRecording:this.isRecording,eventCount:this.events.length,duration:this.isRecording?Date.now()-this.recordingStartTime:0}}getSessionId(){return this.sessionId||(this.sessionId=generateSessionId()),this.sessionId}getEvents(){return[...this.events]}getChunks(){return this.chunkManager.getChunks()}getMetadata(){return{...this.metadata,sessionId:this.sessionId,startTime:this.recordingStartTime,isRecording:this.isRecording,eventCount:this.events.length}}getConfig(){return{...this.config}}getMemoryStats(){return this.memoryManager.getStats()}getOptimizationStats(){return this.eventOptimizer.getOptimizationStats()}setMetadata(S){this.metadata={...this.metadata,...S}}updateConfig(S){this.config={...this.config,...S},void 0!==S.debug&&this.logger.updateDebugMode(S.debug),this.inactivityManager.updateConfig(S),this.eventOptimizer.updateConfig(S),this.chunkManager.updateConfig(S),this.memoryManager.updateConfig(S),this.checkpointManager.updateConfig(S)}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode(S)}clear(){this.events=[],this.logger.info("Events cleared")}pause(){this.isRecording?this.stopFn&&(this.stopFn(),this.stopFn=null,this.isRecording=!1,this.logger.info("Recording paused")):this.logger.warn("No recording to pause")}resume(){this.isRecording?this.logger.warn("Recording already active"):(this.start(),this.logger.info("Recording resumed"))}takeCheckpoint(){this.checkpointManager.takeManualCheckpoint()}flushChunk(){return this.chunkManager.flush()}exportEvents(){return JSON.stringify({sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:this.events,metadata:this.metadata},null,2)}exportChunkedData(S="json"){const b=this.chunkManager.getChunks(),I={sessionId:this.getSessionId(),startTime:this.recordingStartTime,chunks:b,totalChunks:b.length,totalEvents:this.events.length,metadata:this.metadata};return"json"===S?JSON.stringify(I,null,2):I}buildReplayExport(){const S=this.chunkManager.getChunks().map(S=>{if(S?.compressed)try{return this.decompressChunk(S)}catch(b){return S}return S}),b=[];for(const I of S)I?.events&&Array.isArray(I.events)&&b.push(...I.events);return{sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:b,chunks:S,totalChunks:S.length,totalEvents:b.length,metadata:this.metadata}}compressChunkSync(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}async compressChunk(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}decompressChunk(S){if(!S.compressed)return S;try{const b=S.compressedData||S.data,I=new Uint8Array(b);if("fflate"===S.compressionType){const S=strFromU8(unzlibSync(I));return JSON.parse(S)}return S}catch(b){return this.logger.error("Failed to decompress chunk:",b),S}}generateSessionId(){return generateSessionId()}getEventTypeName(S){return this.eventOptimizer.getEventTypeName(S)}analyzeLargestEvents(S=5){if(!this.events||0===this.events.length)return void this.logger.info("No events to analyze");const b=this.events.map((S,b)=>({index:b,type:S.type,size:this.chunkManager.estimateSize([S]),timestamp:S.timestamp}));b.sort((S,b)=>b.size-S.size),this.logger.info(`🔍 Top ${S} Largest Events:`),b.slice(0,S).forEach((S,b)=>{this.logger.info(`${b+1}. Event #${S.index}: ${S.type} - ${Math.round(S.size/1024)}KB`)})}logOptimizationReport(){this.eventOptimizer.logOptimizationReport()}static getPresetConfig(S){return{minimal:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:18e4,checkoutEveryNth:300,chunkDuration:9e4,maxChunkSize:2e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.3,scrollSampling:.5,debug:!1},production:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:45e3,maxChunkSize:3e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.7,scrollSampling:.8,debug:!1},standard:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:6e4,maxChunkSize:35e4,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.5,scrollSampling:.7,debug:!1},detailed:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0},checkoutEveryNms:6e4,checkoutEveryNth:100,chunkDuration:3e4,maxChunkSize:5e5,enableSampling:!1,enableDeduplication:!1,debug:!1},full:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!0,collectFonts:!0,slimDOMOptions:!1,checkoutEveryNms:3e4,checkoutEveryNth:50,chunkDuration:15e3,maxChunkSize:1e6,enableSampling:!1,enableDeduplication:!1,debug:!1}}[S]||{}}}const $c={MINIMAL:"minimal",STANDARD:"standard",DETAILED:"detailed",FULL:"full"},jc="pending_chunks";class IndexedDBQueue{constructor(S={}){if(this.db=null,this.isSupported="undefined"!=typeof indexedDB,this.initFailed=!1,this.maxItems=S.maxItems||100,this.onError=S.onError||(()=>{}),"undefined"!=typeof window&&!0===window.__TRACESCOUT_FORCE_DISABLE_INDEXEDDB)return console.warn("[IndexedDBQueue] Disabled via FORCE_DISABLE_INDEXEDDB flag"),this.isSupported=!1,void(this.initFailed=!0);this.isSupported&&this._initDB()}async _initDB(){if(this.isSupported)return new Promise((S,b)=>{const I=indexedDB.open("tracescout_queue",1);I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to open database:",b.target.error),this.isSupported=!1,this.initFailed=!0,S(null)},I.onsuccess=b=>{this.db=b.target.result,S(this.db)},I.onupgradeneeded=S=>{const b=S.target.result;if(!b.objectStoreNames.contains(jc)){const S=b.createObjectStore(jc,{keyPath:"id"});S.createIndex("sessionId","sessionId",{unique:!1}),S.createIndex("createdAt","createdAt",{unique:!1}),S.createIndex("priority","priority",{unique:!1})}}})}async _ensureDB(){if(!this.isSupported)return!1;if(!this.db)try{await this._initDB()}catch(S){return!1}return!!this.db}async enqueue(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([jc],"readwrite"),x=I.objectStore(jc),R={id:S.id||`queue_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:S.chunk?.sessionId||S.sessionId,chunk:S.chunk,priority:S.priority||"normal",attempts:S.attempts||0,createdAt:S.createdAt||Date.now(),lastAttempt:S.lastAttempt||null,error:S.error||null},A=x.add(R);A.onsuccess=()=>{b(!0)},A.onerror=S=>{if("ConstraintError"===S.target.error?.name){const S=x.put(R);S.onsuccess=()=>b(!0),S.onerror=()=>b(!1)}else console.warn("[IndexedDBQueue] Failed to enqueue:",S.target.error),b(!1)},I.oncomplete=async()=>{await this._enforceLimit()}}catch(S){console.warn("[IndexedDBQueue] Enqueue error:",S),b(!1)}})}async getAll(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([jc],"readonly"),I=b.objectStore(jc).getAll();I.onsuccess=b=>{const I=b.target.result||[],x={high:3,normal:2,low:1};I.sort((S,b)=>{const I=x[S.priority]||2,R=x[b.priority]||2;return I!==R?R-I:S.createdAt-b.createdAt}),S(I)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to get items:",b.target.error),S([])}}catch(b){console.warn("[IndexedDBQueue] GetAll error:",b),S([])}}):[]}async getBySession(S){return await this._ensureDB()?new Promise(b=>{try{const I=this.db.transaction([jc],"readonly").objectStore(jc),x=I.index("sessionId").getAll(S);x.onsuccess=S=>{b(S.target.result||[])},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to get by session:",S.target.error),b([])}}catch(S){console.warn("[IndexedDBQueue] GetBySession error:",S),b([])}}):[]}async remove(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([jc],"readwrite"),x=I.objectStore(jc).delete(S);x.onsuccess=()=>{b(!0)},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to remove:",S.target.error),b(!1)}}catch(S){console.warn("[IndexedDBQueue] Remove error:",S),b(!1)}})}async removeMany(S){if(!await this._ensureDB()||!S||0===S.length)return 0;let b=0;for(const I of S)await this.remove(I)&&b++;return b}async update(S,b){return!!await this._ensureDB()&&new Promise(I=>{try{const x=this.db.transaction([jc],"readwrite").objectStore(jc),R=x.get(S);R.onsuccess=S=>{const R=S.target.result;if(!R)return void I(!1);const A={...R,...b},_=x.put(A);_.onsuccess=()=>I(!0),_.onerror=()=>I(!1)},R.onerror=()=>I(!1)}catch(S){console.warn("[IndexedDBQueue] Update error:",S),I(!1)}})}async clear(){return!!await this._ensureDB()&&new Promise(S=>{try{const b=this.db.transaction([jc],"readwrite"),I=b.objectStore(jc).clear();I.onsuccess=()=>{S(!0)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to clear:",b.target.error),S(!1)}}catch(b){console.warn("[IndexedDBQueue] Clear error:",b),S(!1)}})}async count(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([jc],"readonly"),I=b.objectStore(jc).count();I.onsuccess=b=>{S(b.target.result)},I.onerror=()=>S(0)}catch(b){S(0)}}):0}async _enforceLimit(){const S=await this.count();if(S<=this.maxItems)return;const b=await this.getAll(),I=S-this.maxItems,x=[...b].sort((S,b)=>{const I={high:3,normal:2,low:1},x=I[S.priority]||2,R=I[b.priority]||2;return x!==R?x-R:S.createdAt-b.createdAt}),R=x.slice(0,I).map(S=>S.id);await this.removeMany(R),console.log(`[IndexedDBQueue] Removed ${R.length} old items to enforce limit of ${this.maxItems}`)}isAvailable(){return this.isSupported&&null!==this.db}didInitFail(){return!0===this.initFailed}close(){this.db&&(this.db.close(),this.db=null)}}class CircuitBreaker{constructor(S={}){this.threshold=S.threshold||5,this.resetTimeout=S.resetTimeout||6e4,this.halfOpenMaxAttempts=S.halfOpenMaxAttempts||1,this.failures=0,this.lastFailure=null,this.state="closed",this.halfOpenAttempts=0,this.logger=S.logger||console}canMakeRequest(){if("closed"===this.state)return!0;if("open"===this.state){return Date.now()-this.lastFailure>=this.resetTimeout&&(this.state="half-open",this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Transitioning to half-open state"),!0)}return"half-open"!==this.state||this.halfOpenAttempts<this.halfOpenMaxAttempts}recordSuccess(){"half-open"===this.state?(this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Circuit closed after successful request")):"closed"===this.state&&(this.failures=0)}recordFailure(){this.failures++,this.lastFailure=Date.now(),"half-open"===this.state?(this.state="open",this.halfOpenAttempts=0,this.logger.warn?.("[CircuitBreaker] Circuit reopened after failed test request")):"closed"===this.state&&this.failures>=this.threshold&&(this.state="open",this.logger.error?.(`[CircuitBreaker] Circuit OPENED after ${this.failures} consecutive failures`),this.logger.error?.(`[CircuitBreaker] Will retry after ${this.resetTimeout/1e3}s cooldown`))}recordHalfOpenAttempt(){"half-open"===this.state&&this.halfOpenAttempts++}getStatus(){return{state:this.state,failures:this.failures,lastFailure:this.lastFailure,threshold:this.threshold,resetTimeout:this.resetTimeout,timeUntilReset:"open"===this.state&&this.lastFailure?Math.max(0,this.resetTimeout-(Date.now()-this.lastFailure)):null,halfOpenAttempts:this.halfOpenAttempts,halfOpenMaxAttempts:this.halfOpenMaxAttempts}}reset(){this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Manually reset to closed state")}forceOpen(){this.state="open",this.lastFailure=Date.now(),this.logger.warn?.("[CircuitBreaker] Manually forced to open state")}updateConfig(S){void 0!==S.threshold&&(this.threshold=S.threshold),void 0!==S.resetTimeout&&(this.resetTimeout=S.resetTimeout),void 0!==S.halfOpenMaxAttempts&&(this.halfOpenMaxAttempts=S.halfOpenMaxAttempts)}destroy(){this.logger=null}}class NetworkMonitor{constructor(S={}){this.checkInterval=S.checkInterval||3e4,this.isOnline="undefined"==typeof navigator||navigator.onLine,this.onStatusChange=S.onStatusChange||(()=>{}),this.logger=S.logger||console,this.checkTimer=null,this._boundOnline=null,this._boundOffline=null}start(){"undefined"!=typeof window&&(this._boundOnline=()=>this._handleStatusChange(!0),this._boundOffline=()=>this._handleStatusChange(!1),window.addEventListener("online",this._boundOnline),window.addEventListener("offline",this._boundOffline),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval),this.logger.log?.("[NetworkMonitor] Started monitoring"))}stop(){"undefined"!=typeof window&&(this._boundOnline&&window.removeEventListener("online",this._boundOnline),this._boundOffline&&window.removeEventListener("offline",this._boundOffline)),this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null),this._boundOnline=null,this._boundOffline=null,this.logger.log?.("[NetworkMonitor] Stopped monitoring")}_handleStatusChange(S){const b=this.isOnline;this.isOnline=S,b!==S&&(this.logger.log?.("[NetworkMonitor] Status changed: "+(S?"online":"offline")),this.onStatusChange(S,b))}checkStatus(){if("undefined"==typeof navigator)return;const S=navigator.onLine;this.isOnline!==S&&this._handleStatusChange(S)}getStatus(){return this.isOnline}updateConfig(S){void 0!==S.checkInterval&&(this.checkInterval=S.checkInterval,this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval)))}destroy(){this.stop(),this.onStatusChange=null,this.logger=null}}class BeaconSender{constructor(S={}){this.endpoint=S.endpoint||"/api/sessions/upload",this.maxBeaconSize=S.maxBeaconSize||6e4,this.sdkContext=S.sdkContext||null,this.logger=S.logger||console}setEndpoint(S){this.endpoint=S}setSdkContext(S){this.sdkContext=S}send(S,b="unknown"){if(!S||!S.events||0===S.events.length)return this.logger.log?.("[BeaconSender] No events to send"),!1;const I=this._buildPayload(S,b),x=JSON.stringify(I),R=x.length;return R>this.maxBeaconSize?(this.logger.warn?.(`[BeaconSender] Payload too large (${R} bytes), using keepalive fetch`),this._sendWithKeepaliveFetch(x,b)):this._sendWithBeacon(x,b,R)||this._sendWithKeepaliveFetch(x,b)}_buildPayload(S,b){return{chunks:[{id:`final_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunkId:S.chunkId||`chunk_${S.sequence}`,sessionId:S.sessionId,data:S,compressed:!1,originalSize:this._estimateSize(S),projectId:S.metadata?.projectId||this.sdkContext?.projectId,environment:S.metadata?.environment||this.sdkContext?.environment}],batchId:`beacon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:1,sentVia:"sendBeacon",closeTrigger:b}}_sendWithBeacon(S,b,I){if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;try{const x=new Blob([S],{type:"application/json"});return navigator.sendBeacon(this.endpoint,x)?(this.logger.log?.(`[BeaconSender] ✅ Sent via sendBeacon (${b}, ${I} bytes)`),!0):(this.logger.warn?.("[BeaconSender] sendBeacon returned false"),!1)}catch(S){return this.logger.warn?.(`[BeaconSender] sendBeacon failed: ${S.message}`),!1}}_sendWithKeepaliveFetch(S,b){if("undefined"==typeof fetch)return this.logger.warn?.("[BeaconSender] fetch not available"),!1;try{const I={"Content-Type":"application/json","X-SDK-Version":"2.0.0","X-Sent-Via":"keepalive","X-Close-Trigger":b};return this.sdkContext&&(I["X-Project-ID"]=this.sdkContext.projectId||""),fetch(this.endpoint,{method:"POST",headers:I,body:S,keepalive:!0}).catch(S=>{this.logger.warn?.("[BeaconSender] keepalive fetch error:",S)}),this.logger.log?.(`[BeaconSender] ✅ Sent via keepalive fetch (${b})`),!0}catch(S){return this.logger.warn?.(`[BeaconSender] keepalive fetch failed: ${S.message}`),!1}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}updateConfig(S){void 0!==S.endpoint&&(this.endpoint=S.endpoint),void 0!==S.maxBeaconSize&&(this.maxBeaconSize=S.maxBeaconSize)}destroy(){this.sdkContext=null,this.logger=null}}class QueueMemoryManager{constructor(S={}){this.maxQueueSize=S.maxQueueSize||100,this.maxFailedQueueSize=S.maxFailedQueueSize||50,this.maxOfflineItems=S.maxOfflineItems||100,this.logger=S.logger||console}enforceLimit(S,b=this.maxQueueSize){if(S.length<b)return null;const I=S.findIndex(S=>"low"===S.priority);if(I>=0){const x=S.splice(I,1)[0];return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped low-priority chunk:`,x.chunk?.chunkId),x}const x=S.shift();return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped oldest chunk:`,x?.chunk?.chunkId),x}enforceFailedLimit(S){if(S.length<this.maxFailedQueueSize)return null;const b=S.shift();return this.logger.warn?.(`[QueueMemory] Failed queue at max (${this.maxFailedQueueSize}) - dropped oldest:`,b?.chunk?.chunkId),b}enforceOfflineLimit(S){if(S.length<=this.maxOfflineItems)return null;const b=S.pop();return this.logger.warn?.("[QueueMemory] Offline queue full - dropped oldest:",b?.chunk?.chunkId),b}calculateQueueBytes(S){return S.reduce((S,b)=>S+(b.originalSize||0),0)}getStats(S,b){const I=this.calculateQueueBytes(S),x=this.calculateQueueBytes(b);return{uploadQueueSize:S.length,uploadQueueBytes:I,failedQueueSize:b.length,failedQueueBytes:x,totalQueuedItems:S.length+b.length,totalQueuedBytes:I+x,maxQueueSize:this.maxQueueSize,maxFailedQueueSize:this.maxFailedQueueSize,maxOfflineItems:this.maxOfflineItems,uploadQueuePercent:Math.round(S.length/this.maxQueueSize*100),failedQueuePercent:Math.round(b.length/this.maxFailedQueueSize*100)}}forceCleanup(S,b,I={}){const{keepUploads:x=10,keepFailed:R=5,clearAll:A=!1}=I,_={uploadQueue:S.length,failedQueue:b.length};let D=0,L=0;A?(D=S.length,L=b.length,S.length=0,b.length=0):(S.length>x&&(D=S.length-x,S.splice(0,D)),b.length>R&&(L=b.length-R,b.splice(0,L)));const B={uploadQueue:S.length,failedQueue:b.length};return this.logger.log?.(`[QueueMemory] Force cleanup: removed ${D} uploads, ${L} failed items`),{before:_,after:B,removed:{uploadQueue:D,failedQueue:L}}}needsCleanup(S,b){const I=S.length/this.maxQueueSize,x=b.length/this.maxFailedQueueSize;return I>=.8||x>=.8}updateConfig(S){void 0!==S.maxQueueSize&&(this.maxQueueSize=S.maxQueueSize),void 0!==S.maxFailedQueueSize&&(this.maxFailedQueueSize=S.maxFailedQueueSize),void 0!==S.maxOfflineItems&&(this.maxOfflineItems=S.maxOfflineItems)}destroy(){this.logger=null}}class UploadQueue{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[UploadQueue] No SDKContext provided - running in v1.x compatibility mode");const b=this._generateEndpoint(S);this.config={endpoint:S.endpoint||b,batchSize:S.batchSize||5,maxRetries:S.maxRetries||3,retryDelay:S.retryDelay||1e3,maxRetryDelay:S.maxRetryDelay||3e4,uploadTimeout:S.uploadTimeout||3e4,enableOfflineQueue:!1!==S.enableOfflineQueue,maxOfflineItems:S.maxOfflineItems||100,networkCheckInterval:S.networkCheckInterval||3e4,enableCompression:!1!==S.enableCompression,compressionThreshold:S.compressionThreshold||1024,onUploadSuccess:S.onUploadSuccess||(()=>{}),onUploadError:S.onUploadError||(()=>{}),onNetworkChange:S.onNetworkChange||(()=>{}),onQueueEmpty:S.onQueueEmpty||(()=>{}),headers:S.headers||{},authToken:S.authToken||null,...S},this.uploadQueue=[],this.failedQueue=[],this.isUploading=!1,this._uploadLock=null,this.isQuotaExceeded=!1,this.uploadStats={totalUploaded:0,totalFailed:0,totalBytes:0,averageUploadTime:0,lastUploadTime:null},this.firstSnapshotAcked=!1,this.firstSnapshotChunkId=null,this.firstSnapshotAttempts=0,this._backupSnapshotRequested=!1,this._listeners=new Map,this.retryTimer=null,this._processingTimer=null,this.logger=S.logger||createLogger("UploadQueue"),this._initializeModules(S),this._startProcessing(),this._loadPersistentQueue()}on(S,b){this._listeners.has(S)||this._listeners.set(S,[]),this._listeners.get(S).push(b)}emit(S,...b){const I=this._listeners.get(S);if(I)for(const x of I)try{x(...b)}catch(b){this.logger.warn(`[UploadQueue] Event listener error for '${S}':`,b)}}_generateEndpoint(S){if(this.sdkContext){const b="undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname);return`${S.baseUrl||(b?"http://localhost:3001":"https://api.tracescout.com")}/api/projects/${this.sdkContext.projectId}/sessions/${this.sdkContext.sessionId}/chunks`}return"/api/sessions/upload"}_initializeModules(S){this.circuitBreaker=new CircuitBreaker({threshold:S.circuitBreakerThreshold||5,resetTimeout:S.circuitBreakerResetTimeout||6e4,halfOpenMaxAttempts:S.halfOpenMaxAttempts||1,logger:this.logger}),this.networkMonitor=new NetworkMonitor({checkInterval:this.config.networkCheckInterval,logger:this.logger,onStatusChange:(S,b)=>this._handleNetworkChange(S,b)}),this.networkMonitor.start(),this.beaconSender=new BeaconSender({endpoint:this.config.endpoint,sdkContext:this.sdkContext,logger:this.logger}),this.memoryManager=new QueueMemoryManager({maxQueueSize:S.maxQueueSize||100,maxFailedQueueSize:S.maxFailedQueueSize||50,maxOfflineItems:S.maxOfflineItems||100,logger:this.logger}),this.persistentQueue=new IndexedDBQueue({maxItems:this.config.maxOfflineItems,onError:S=>{this.logger.warn("[UploadQueue] IndexedDB error:",S)}})}async _loadPersistentQueue(){try{const S=await this.persistentQueue.getAll();if(S.length>0){this.logger.log(`[UploadQueue] Recovered ${S.length} items from persistent storage`);for(const b of S)this.uploadQueue.push(b);this._sortQueue(),this.networkMonitor.getStatus()&&!this.isUploading&&this._processQueue()}}catch(S){this.logger.warn("[UploadQueue] Failed to load persistent queue:",S)}}enqueue(S,b="normal"){if(this.isQuotaExceeded)return this.logger.warn("[UploadQueue] Quota exceeded - dropping chunk:",S.chunkId),!1;this.memoryManager.enforceLimit(this.uploadQueue);const I=this._validateChunk(S);if(!I.valid)return this.logger.error(`[UploadQueue] Invalid chunk rejected: ${I.reason}`,S),!1;try{const I=0===S.sequence||!0===S.isFirstChunk;I&&!this.firstSnapshotAcked&&(b="high",this.logger.log("[UploadQueue] Chunk 0 prioritized for immediate upload (contains FullSnapshot)"));const x={id:`upload_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunk:S,priority:b,attempts:0,createdAt:Date.now(),lastAttempt:null,error:null,compressed:!1,originalSize:this._estimateSize(S),compressedSize:null,isFirstChunk:I};if(I&&!this.firstSnapshotChunkId&&(this.firstSnapshotChunkId=x.id),this.networkMonitor.getStatus())this.uploadQueue.push(x),this._sortQueue();else{if(!this.config.enableOfflineQueue)return this.logger.warn("Network offline and offline queue disabled, dropping chunk:",S.chunkId),!1;this._addToOfflineQueue(x)}return this.logger.log(`Chunk queued for upload: ${S.chunkId} (queue size: ${this.uploadQueue.length})`),I&&this.networkMonitor.getStatus()&&!this.isUploading?(this.logger.log("[UploadQueue] Triggering immediate upload for chunk 0"),this._processQueue()):this.isUploading||this._processQueue(),x.id}catch(S){return this.logger.error("Failed to enqueue chunk:",S),!1}}async _processQueue(){if(!this.circuitBreaker.canMakeRequest())return void this.logger.warn("[UploadQueue] Circuit breaker is open - request blocked");if(this.isUploading||!this.networkMonitor.getStatus()||0===this.uploadQueue.length)return;if(this._uploadLock)return;let S;this._uploadLock=new Promise(b=>{S=b}),this.isUploading=!0,this.logger.log(`Processing upload queue (${this.uploadQueue.length} items)`);try{for(;this.uploadQueue.length>0&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest();){const S=this._createBatch();if(0===S.length)break;if(await this._uploadBatch(S))this.circuitBreaker.recordSuccess();else if(this.circuitBreaker.recordFailure(),"open"===this.circuitBreaker.getStatus().state){this.logger.warn("[UploadQueue] Circuit breaker opened - pausing uploads");break}await this._delay(100)}0===this.uploadQueue.length&&0===this.failedQueue.length&&(this.config.onQueueEmpty(),this.logger.log("Upload queue is empty"))}catch(S){this.logger.error("Error processing upload queue:",S),this.circuitBreaker.recordFailure()}finally{this.isUploading=!1,this._uploadLock=null,S(),this.failedQueue.length>0&&this._scheduleRetry()}}_createBatch(){const S=[],b=Math.min(this.config.batchSize,this.uploadQueue.length);this._sortQueue();for(let I=0;I<b;I++)this.uploadQueue.length>0&&S.push(this.uploadQueue.shift());return S}async _uploadBatch(S){const b=Date.now();try{this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&S.forEach(S=>{S.chunk=this.sdkContext.enrichChunk(S.chunk)});const I={chunks:(await this._processBatch(S)).map(S=>({id:S.id,chunkId:S.chunk.chunkId,sessionId:S.chunk.sessionId,data:S.compressed?S.compressedData:S.chunk,compressed:S.compressed,originalSize:S.originalSize,compressedSize:S.compressedSize||S.originalSize,projectId:S.chunk.projectId,environment:S.chunk.environment})),batchId:`batch_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:S.length},x=await this._makeRequest(I);if(x.ok){const I=await x.json().catch(()=>({}));if(I.results){const S=I.results.find(S=>429===S.code||"QUOTA_EXCEEDED"===S.data?.code);if(S)return this._handleQuotaExceeded(S.data||S),!1}const R=Date.now()-b;this._updateStats(S,R,!0);for(const b of S)try{await this.persistentQueue.remove(b.id)}catch(S){}for(const b of S)(b.id===this.firstSnapshotChunkId||b.isFirstChunk)&&(this.firstSnapshotAcked=!0,this.logger.log("[UploadQueue] ✓ First snapshot (chunk 0) acknowledged by server - session is replayable"));return S.forEach(S=>{this.config.onUploadSuccess(S.chunk,I)}),this.logger.log(`Batch uploaded successfully: ${S.length} chunks in ${R}ms`),!0}if(429===x.status){const S=await x.json().catch(()=>({}));return this._handleQuotaExceeded(S),!1}throw new Error(`Upload failed with status: ${x.status}`)}catch(b){return this.logger.error("Batch upload failed:",b),S.forEach(S=>{S.attempts++,S.lastAttempt=Date.now(),S.error=b.message,(S.id===this.firstSnapshotChunkId||S.isFirstChunk)&&S.attempts>=3&&!this._backupSnapshotRequested&&(this._backupSnapshotRequested=!0,this.logger.warn("[UploadQueue] First snapshot failed 3+ times - requesting backup"),this.emit("firstSnapshotUploadFailed")),S.attempts<this.config.maxRetries?(this.memoryManager.enforceFailedLimit(this.failedQueue),this.failedQueue.push(S)):(this._updateStats([S],0,!1),this.config.onUploadError(S.chunk,b),this.logger.error(`Chunk permanently failed after ${S.attempts} attempts: ${S.chunk.chunkId}`))}),!1}}_handleQuotaExceeded(S){this.isQuotaExceeded=!0,this.uploadQueue=[],this.failedQueue=[],console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been stopped.","color: #ff4444;"),S.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions`,"color: #ff4444;"),this.config.onUploadError(null,{code:"QUOTA_EXCEEDED",message:S.message||"Session quota exceeded",usage:S.usage}),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:quota_exceeded",{detail:S}))}async _processBatch(S){const b=[];for(const I of S)try{if(this.config.enableCompression&&I.originalSize>this.config.compressionThreshold){const S=await this._compressChunk(I.chunk);S.compressed&&S.compressedSize<I.originalSize&&(I.compressed=!0,I.compressedData=S.data,I.compressedSize=S.compressedSize)}b.push(I)}catch(S){this.logger.warn("Failed to process chunk, using original:",S),b.push(I)}return b}async _makeRequest(S){const b=new AbortController,I=setTimeout(()=>b.abort(),this.config.uploadTimeout);try{const x={"Content-Type":"application/json",...this.config.headers};this.sdkContext&&(x["X-Project-ID"]=this.sdkContext.projectId,x["X-Environment"]=this.sdkContext.environment||"production",x["X-SDK-Version"]="2.0.0");const R=await fetch(this.config.endpoint,{method:"POST",headers:x,body:JSON.stringify(S),signal:b.signal});return clearTimeout(I),R}catch(S){throw clearTimeout(I),S}}async _compressChunk(S){if(!this.config.enableCompression)return this.logger.debug("[UploadQueue] Compression disabled via config"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"!=typeof window&&!0===window.__TRACESCOUT_DISABLE_COMPRESSION)return this.logger.debug("[UploadQueue] Compression disabled via __TRACESCOUT_DISABLE_COMPRESSION"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"==typeof window||"undefined"==typeof CompressionStream)return{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};try{const b=JSON.stringify(S),I=(new TextEncoder).encode(b).length,x=new Blob([b],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),R=await new Response(x).arrayBuffer(),A=new Uint8Array(R),_=this._uint8ArrayToBase64(A),D=(100*(1-A.length/I)).toFixed(0),L=JSON.stringify(Array.from(A)).length,B=_.length+2;return this.logger.debug(`[UploadQueue] Compressed chunk: original=${I}B, gzip=${A.length}B (${D}% saved), base64=${B}B vs array=${L}B`),{compressed:!0,data:_,originalSize:I,compressedSize:A.length}}catch(b){return this.logger.warn("[UploadQueue] Compression failed, using uncompressed:",b.message),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)}}}_uint8ArrayToBase64(S){if(S.length<32768){let b="";for(let I=0;I<S.length;I++)b+=String.fromCharCode(S[I]);return btoa(b)}let b="";for(let I=0;I<S.length;I+=32768){const x=S.subarray(I,Math.min(I+32768,S.length));for(let S=0;S<x.length;S++)b+=String.fromCharCode(x[S])}return btoa(b)}_handleNetworkChange(S,b){this.logger.log("Network status changed: "+(S?"online":"offline")),this.config.onNetworkChange(S,b),S&&!b&&(this._sortQueue(),this.isUploading||this._processQueue())}_sortQueue(){const S={high:3,normal:2,low:1};this.uploadQueue.sort((b,I)=>{const x=S[b.priority]||2,R=S[I.priority]||2;return x!==R?R-x:b.createdAt-I.createdAt})}async _addToOfflineQueue(S){this.uploadQueue.unshift(S);try{await this.persistentQueue.enqueue(S),this.logger.log(`[UploadQueue] Item persisted to IndexedDB: ${S.id}`)}catch(S){this.logger.warn("[UploadQueue] Failed to persist to IndexedDB:",S)}const b=this.memoryManager.enforceOfflineLimit(this.uploadQueue);if(b)try{await this.persistentQueue.remove(b.id)}catch(S){}}_scheduleRetry(){this.retryTimer&&clearTimeout(this.retryTimer);const S=this.circuitBreaker.getStatus();if("open"===S.state){const b=S.timeUntilReset;if(b>0)return this.logger.warn(`[UploadQueue] Delaying retry until circuit resets in ${Math.round(b/1e3)}s`),void(this.retryTimer=setTimeout(()=>{this._scheduleRetry()},b+1e3))}const b=this.config.retryDelay,I=this.config.maxRetryDelay,x=this.failedQueue[0]?.attempts||0,R=b*Math.pow(2,x),A=Math.min(R,I),_=.25*A,D=2*(Math.random()-.5)*_,L=Math.max(b,Math.round(A+D));this.retryTimer=setTimeout(()=>{this.logger.log(`Retrying ${this.failedQueue.length} failed items (attempt ${x+1})`),this.uploadQueue.unshift(...this.failedQueue),this.failedQueue=[],!this.isUploading&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest()&&this._processQueue()},L),this.logger.log(`[Retry] Scheduled in ${L}ms`)}_startProcessing(){this._processingTimer=setInterval(()=>{!this.isUploading&&this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()},5e3)}_updateStats(S,b,I){if(I){this.uploadStats.totalUploaded+=S.length,this.uploadStats.lastUploadTime=Date.now();const I=this.uploadStats.averageUploadTime,x=this.uploadStats.totalUploaded;this.uploadStats.averageUploadTime=(I*(x-S.length)+b)/x}else this.uploadStats.totalFailed+=S.length;S.forEach(S=>{this.uploadStats.totalBytes+=S.compressedSize||S.originalSize})}_validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};if(0===S.events.length&&!S.metadata?.isLastChunk)return{valid:!1,reason:"Empty events array (non-final chunk)"};if("number"!=typeof S.startTimestamp||"number"!=typeof S.endTimestamp)return{valid:!1,reason:"Invalid timestamps"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}_delay(S){return new Promise(b=>setTimeout(b,S))}getStats(){return{...this.uploadStats,queueSize:this.uploadQueue.length,failedQueueSize:this.failedQueue.length,isOnline:this.networkMonitor.getStatus(),isUploading:this.isUploading,isQuotaExceeded:this.isQuotaExceeded,circuitBreaker:this.circuitBreaker.getStatus()}}getCircuitBreakerStatus(){return this.circuitBreaker.getStatus()}resetCircuitBreaker(){this.circuitBreaker.reset()}isQuotaExceededStatus(){return this.isQuotaExceeded}isFirstSnapshotAcked(){return this.firstSnapshotAcked}didIndexedDBFail(){return!!this.persistentQueue&&this.persistentQueue.didInitFail()}getQueue(){return{pending:[...this.uploadQueue],failed:[...this.failedQueue]}}clearQueue(){const S=this.uploadQueue.length+this.failedQueue.length;return this.uploadQueue=[],this.failedQueue=[],this.logger.log(`Cleared ${S} items from queue`),S}pause(){this.isUploading=!0,this.logger.log("Upload queue paused")}resume(){this.isUploading=!1,this.logger.log("Upload queue resumed"),this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()}updateConfig(S){this.config={...this.config,...S},this.logger.log("Upload queue configuration updated")}getMemoryStats(){return this.memoryManager.getStats(this.uploadQueue,this.failedQueue)}forceMemoryCleanup(S={}){return this.memoryManager.forceCleanup(this.uploadQueue,this.failedQueue,S)}sendFinalChunkWithBeacon(S,b="unknown"){const I=this._validateChunk(S);return I.valid?this.beaconSender.send(S,b):(this.logger.warn(`[Beacon] Invalid final chunk: ${I.reason}`),!1)}async getPersistentQueueStats(){return{persistentQueueSize:await this.persistentQueue.count(),isIndexedDBAvailable:this.persistentQueue.isAvailable()}}destroy(){this.networkMonitor.destroy(),this.retryTimer&&clearTimeout(this.retryTimer),this._processingTimer&&clearInterval(this._processingTimer),this.persistentQueue&&this.persistentQueue.close(),this.circuitBreaker.destroy(),this.beaconSender.destroy(),this.memoryManager.destroy(),this.clearQueue(),this.logger.log("Upload queue destroyed")}}class ChunkedCompressedStorage{static CHUNK_SIZE=50;static CHUNK_PREFIX="rrweb_chunk_";static logger=createLogger("ChunkedCompressedStorage");static initSession(S){sessionStorage.setItem(`${S}_info`,JSON.stringify({startTime:Date.now(),chunkCount:0,totalEvents:0,isActive:!0}))}static updateSessionInfo(S,b,I){try{const x=JSON.parse(sessionStorage.getItem(`${S}_info`)||"{}");x.chunkCount=b,x.totalEvents=I,sessionStorage.setItem(`${S}_info`,JSON.stringify(x))}catch(S){this.logger.warn("Failed to update session info",S)}}static compress(S){const b=zlibSync(strToU8(JSON.stringify(S)),{level:6});return Array.from(b)}static decompress(S){const b=strFromU8(unzlibSync(new Uint8Array(S)));return JSON.parse(b)}static saveChunk(S,b,I){try{const x=this.compress({events:I}),R=`${S}_${this.CHUNK_PREFIX}${b}`;return sessionStorage.setItem(R,JSON.stringify(x)),!0}catch(S){return this.logger.error("saveChunk failed",S),!1}}static loadChunk(S,b){const I=`${S}_${this.CHUNK_PREFIX}${b}`,x=sessionStorage.getItem(I);if(!x)return null;try{const S=JSON.parse(x);return this.decompress(S).events||[]}catch(S){return this.logger.warn("loadChunk failed",S),null}}static getChunkCount(S){const b=sessionStorage.getItem(`${S}_info`);return b&&JSON.parse(b).chunkCount||0}static async streamChunks(S,b={}){const{onChunkLoad:I=()=>{},onProgress:x=()=>{},onComplete:R=()=>{},chunkDelay:A=50,startChunk:_=0}=b,D=this.getChunkCount(S);for(let b=_;b<D;b++){const R=this.loadChunk(S,b);R&&R.length&&I(R,b),x(b+1,D),b<D-1&&A>0&&await new Promise(S=>setTimeout(S,A))}R()}static clearSession(S){Object.keys(sessionStorage).forEach(b=>{b.startsWith(S)&&sessionStorage.removeItem(b)}),sessionStorage.removeItem(`${S}_info`)}}var qc=Object.freeze({__proto__:null,ChunkedCompressedStorage:ChunkedCompressedStorage});class SessionStorage{constructor(S={}){this.storageKey=S.storageKey||"__tracescout_sessions__",this.maxStorageSize=S.maxStorageSize||52428800,this.maxSessions=S.maxSessions||10,this.logger=S.logger||createLogger("SessionStorage")}storeChunk(S,b){try{const I=this.getSessions();return I[S]||(I[S]={chunks:[],metadata:{startTime:Date.now(),lastActivity:Date.now(),totalEvents:0,totalChunks:0}}),I[S].chunks.push(b),I[S].metadata.lastActivity=Date.now(),I[S].metadata.totalEvents+=b.eventCount,I[S].metadata.totalChunks+=1,this.calculateSize(I)>this.maxStorageSize&&this.cleanup(I),this.saveSessions(I),this.logger.log(`Stored chunk ${b.chunkId} for session ${S}`),!0}catch(S){return this.logger.error("Failed to store chunk:",S),!1}}getSessions(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.error("Failed to load sessions:",S),{}}}getSession(S){return this.getSessions()[S]||null}saveSessions(S){try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(b){if("QuotaExceededError"===b.name){this.logger.warn("Storage quota exceeded, performing emergency cleanup"),this.emergencyCleanup();try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(S){this.logger.error("Storage failed even after cleanup:",S)}}else this.logger.error("Failed to save sessions:",b)}}calculateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}cleanup(S){const b=Object.entries(S).sort(([,S],[,b])=>S.metadata.lastActivity-b.metadata.lastActivity);for(;this.calculateSize(S)>this.maxStorageSize&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed old session: ${I}`)}for(;Object.keys(S).length>this.maxSessions&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed session due to count limit: ${I}`)}}emergencyCleanup(){try{localStorage.removeItem(this.storageKey),this.logger.warn("Emergency cleanup: cleared all session storage")}catch(S){this.logger.error("Emergency cleanup failed:",S)}}removeSession(S){try{const b=this.getSessions();return!!b[S]&&(delete b[S],this.saveSessions(b),this.logger.log(`Removed session: ${S}`),!0)}catch(S){return this.logger.error("Failed to remove session:",S),!1}}getStorageStats(){try{const S=this.getSessions(),b=this.calculateSize(S),I=Object.keys(S).length;let x=0,R=0;return Object.values(S).forEach(S=>{x+=S.metadata.totalEvents,R+=S.metadata.totalChunks}),{totalSize:b,sessionCount:I,totalEvents:x,totalChunks:R,maxStorageSize:this.maxStorageSize,maxSessions:this.maxSessions,storageUsagePercent:Math.round(b/this.maxStorageSize*100)}}catch(S){return this.logger.error("Failed to get storage stats:",S),null}}exportSession(S,b="json"){try{const I=this.getSession(S);if(!I)return null;const x={sessionId:S,metadata:I.metadata,chunks:I.chunks,totalChunks:I.chunks.length,totalEvents:I.metadata.totalEvents,exportTimestamp:Date.now()};return"json"===b?JSON.stringify(x,null,2):x}catch(S){return this.logger.error("Failed to export session:",S),null}}importSession(S){try{const b="string"==typeof S?JSON.parse(S):S;if(!b.sessionId||!b.chunks)throw new Error("Invalid session data format");const I=this.getSessions();return I[b.sessionId]={chunks:b.chunks,metadata:b.metadata||{startTime:Date.now(),lastActivity:Date.now(),totalEvents:b.totalEvents||0,totalChunks:b.totalChunks||0}},this.saveSessions(I),this.logger.log(`Imported session: ${b.sessionId}`),!0}catch(S){return this.logger.error("Failed to import session:",S),!1}}clearAll(){try{return localStorage.removeItem(this.storageKey),this.logger.log("Cleared all sessions"),!0}catch(S){return this.logger.error("Failed to clear all sessions:",S),!1}}}var Wc=Object.freeze({__proto__:null,BeaconSender:BeaconSender,CHUNK_FORMAT_VERSION:4,CheckpointManager:CheckpointManager,ChunkManager:ChunkManager,ChunkedCompressedStorage:ChunkedCompressedStorage,CircuitBreaker:CircuitBreaker,EventOptimizer:EventOptimizer,InactivityManager:InactivityManager,IndexedDBQueue:IndexedDBQueue,NetworkMonitor:NetworkMonitor,PageLifecycleManager:PageLifecycleManager,QueueMemoryManager:QueueMemoryManager,Recorder:Recorder,RecorderMemoryManager:RecorderMemoryManager,RecorderPresets:$c,SessionStorage:SessionStorage,UploadQueue:UploadQueue,analyzeSnapshotsInEvents:analyzeSnapshotsInEvents,buildSnapshotIndex:buildSnapshotIndex,chunkHasSnapshot:chunkHasSnapshot,collectDeviceMetadata:collectDeviceMetadata,createChunk:createChunk,detectDeviceType:detectDeviceType,detectTouchCapability:detectTouchCapability,extractConsoleRef:extractConsoleRef,extractNetworkFull:extractNetworkFull,extractNetworkRef:extractNetworkRef,extractResourceRef:extractResourceRef,findNearestSnapshotBefore:findNearestSnapshotBefore,generateConsoleId:generateConsoleId,generateNetworkId:generateNetworkId,generateResourceId:generateResourceId,getConnectionInfo:getConnectionInfo,getEventsAfterSnapshot:getEventsAfterSnapshot,getMemoryInfo:getMemoryInfo,getRRWeb:getRRWeb,getRRWebSource:getRRWebSource,getRecord:getRecord,getSnapshotTimestamps:getSnapshotTimestamps,hashCode:hashCode,isCompatibleVersion:isCompatibleVersion,isRRWebLoaded:isRRWebLoaded,loadRRWeb:loadRRWeb,parseBrowserInfo:parseBrowserInfo,parseOSInfo:parseOSInfo,sanitizeUrl:sanitizeUrl,stripNetworkPayload:stripNetworkPayload});"undefined"!=typeof window&&(window.TraceScout=lt,lt.setTransport=TraceScoutMonitoringCore.setTransport.bind(TraceScoutMonitoringCore));export{Je as BODY_REDACTED_VALUE,BaseInterceptor,BeaconSender,zc as CHUNK_FORMAT_VERSION,B as CORE_WEB_VITALS_DEFAULTS,CheckpointManager,ChunkManager,ChunkedCompressedStorage,CircuitBreaker,ConfigManager,ConsoleInterceptor,CoreWebVitalsMonitor,A as DEFAULT_CONFIG,L as DEFAULT_FIELD_PATTERNS,Xe as DEFAULT_MAX_BODY_BYTES,Ke as DEFAULT_MAX_BODY_SIZE,Ze as DEFAULT_SENSITIVE_FIELDS,D as EVENT_TYPES,ErrorFingerprint,ErrorHandler,EventManager,EventOptimizer,FetchInterceptor,InactivityManager,IndexedDBQueue,R as LOCAL_STORAGE_KEYS,LogBuffer,LogManager,Logger,LoggingManager,Ye as MAX_BODY_BYTES_CEILING,NetworkMonitor,PageLifecycleManager,ge as PerformanceMonitor,PerformanceResourceObserver,PostMessageInterceptor,QueueMemoryManager,He as REDACTED_VALUE,_ as REPORTER_LOG_PREFIX,Ve as RESOURCE_EXTENSIONS,Recorder,RecorderMemoryManager,$c as RecorderPresets,RemoteConfigService,ResourceInterceptor,SDKContext,We as SENSITIVE_HEADERS,tt as SENSITIVE_QUERY_PARAMS,ServiceLogger,ServiceManager,SessionManager,SessionStorage,TraceScoutMonitoringCore,UploadQueue,UserProfileManager,XHRInterceptor,analyzeSnapshotsInEvents,buildFieldDenylist,buildSnapshotIndex,captureRequestBody,captureResponseBody,chunkHasSnapshot,classifyMime,collectDeviceMetadata,createChunk,createLogger,createSensitiveHeaderSet,debounce,deepClone,lt as default,detectDeviceType,detectTouchCapability,extractConsoleRef,extractNetworkFull,extractNetworkRef,extractRequestDetails,extractResourceRef,filterSensitiveHeaders,findNearestSnapshotBefore,generateConsoleId,generateId,generateNetworkId,generateResourceId,getConnectionInfo,getEventsAfterSnapshot,getMemoryInfo,getRRWeb,getRRWebSource,getRecord,getResourceType,getSensitiveHeadersList,getSnapshotTimestamps,handleRequestBody,handleResponseBody,hashCode,initializeErrorHandler,isApiEndpoint,isCompatibleVersion,isRRWebLoaded,isResourceUrl,isSensitiveField,isSensitiveHeader,isStaticResource,isTextualContentType,loadRRWeb,U as loggingManager,lt as monitoringCore,parseBrowserInfo,parseFormData,parseOSInfo,parseRequestUrl,parseUrl,redactFormUrlEncoded,redactObject,safeJsonParse,safeJsonStringify,safeMime,safeParseConsoleArgs,b as safeSessionStorage,S as safeStorage,safeStringify,splitSanitizedUrl,stripNetworkPayload,throttle$1 as throttle,truncateToBytes,I as typeUtils,utf8Bytes,x as utils,validateDomains,validateEndpoints,validateService};
1
+ function resolveApiBaseUrl(S={}){if(S&&"string"==typeof S.apiBaseUrl&&S.apiBaseUrl)return S.apiBaseUrl;if(S&&"string"==typeof S.backendUrl&&S.backendUrl)return S.backendUrl;if("undefined"!=typeof window&&window.location&&window.location.hostname){const S=window.location.hostname;if("localhost"===S||"127.0.0.1"===S)return"http://localhost:3001"}return"https://api.tracescout.com"}const S=["/chunks","/logs/batch","/telemetry","/sdk-config"];function isInternalSdkEndpoint(b){if("string"!=typeof b||!b)return!1;if(!b.includes("/api/"))return!1;for(const I of S)if(b.includes(I)){if(b.includes("/api/projects/")||b.includes("/api/sdk-config"))return!0;if("/sdk-config"===I&&b.includes("/sdk-config"))return!0}return!1}function generateId(){return Math.random().toString(36).substr(2,9)+Date.now().toString(36)}function parseUrl(S,b=("undefined"!=typeof location?location.origin:void 0)){try{const I=new URL(S,b);return{hostname:I.hostname,pathname:I.pathname,search:I.search,protocol:I.protocol,origin:I.origin,hash:I.hash}}catch(S){return{hostname:"",pathname:"",search:"",protocol:"",origin:"",hash:""}}}const b={get(S){try{const b=localStorage.getItem(S);return b?JSON.parse(b):null}catch(S){return null}},set(S,b){try{return localStorage.setItem(S,JSON.stringify(b)),!0}catch(S){return!1}},remove(S){try{return localStorage.removeItem(S),!0}catch(S){return!1}},getItem(S){return this.get(S)},setItem(S,b){return this.set(S,b)},removeItem(S){return this.remove(S)}},I={getItem(S){try{return sessionStorage.getItem(S)}catch(S){return null}},setItem(S,b){try{return sessionStorage.setItem(S,b),!0}catch(S){return!1}},removeItem(S){try{return sessionStorage.removeItem(S),!0}catch(S){return!1}}},x={isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isString:S=>"string"==typeof S,isFunction:S=>"function"==typeof S,isEmpty:S=>null==S||""===S||Array.isArray(S)&&0===S.length,get:(S,b,I)=>{if(!S)return I;const x=b.split(".");let R=S;for(const S of x){if(!R||"object"!=typeof R||!(S in R))return I;R=R[S]}return R}};function debounce(S,b){let I;return function executedFunction(...x){clearTimeout(I),I=setTimeout(()=>{clearTimeout(I),S(...x)},b)}}function throttle$1(S,b){let I;return function(...x){I||(S.apply(this,x),I=!0,setTimeout(()=>I=!1,b))}}function deepClone(S){if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>deepClone(S));if(S instanceof Object){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=deepClone(S[I]));return b}}function safeJsonParse(S,b=null){try{return JSON.parse(S)}catch(S){return b}}function safeJsonStringify(S,b="{}"){try{return JSON.stringify(S)}catch(S){return b}}function safeStringify(S,b=10,I=1e4){const x=new WeakSet;let R=0;const A=JSON.stringify(S,function(S,I){if("object"==typeof I&&null!==I&&(R++,R>b))return"[Max Depth Exceeded]";if("object"==typeof I&&null!==I){if(x.has(I))return"[Circular Reference]";x.add(I)}return"function"==typeof I?`[Function: ${I.name||"anonymous"}]`:I instanceof Error?{__type:"Error",name:I.name,message:I.message,stack:I.stack}:I instanceof RegExp?`[RegExp: ${I.toString()}]`:I instanceof Date?`[Date: ${I.toISOString()}]`:"symbol"==typeof I?`[Symbol: ${I.toString()}]`:"bigint"==typeof I?`[BigInt: ${I.toString()}]`:"undefined"!=typeof HTMLElement&&I instanceof HTMLElement?`[HTMLElement: <${I.tagName.toLowerCase()}${I.id?' id="'+I.id+'"':""}>]`:"undefined"!=typeof Window&&I instanceof Window?"[Window]":"undefined"!=typeof Document&&I instanceof Document?"[Document]":I});return A&&A.length>I?A.substring(0,I)+"... [truncated]":A}function safeParseConsoleArgs(S,b=5e3,I=1e4){if(!Array.isArray(S))return[];const x=[];let R=0;for(let A=0;A<S.length;A++){if(R>=I){x.push(`[${S.length-A} more arguments truncated]`);break}const _=S[A];let D;try{D=null===_?"null":void 0===_?"undefined":"string"==typeof _?_.length>b?_.substring(0,b)+"... [truncated]":_:"number"==typeof _||"boolean"==typeof _?String(_):"object"==typeof _?safeStringify(_,5,b):String(_)}catch(S){D=`[Unserializable: ${typeof _}]`}const L="string"==typeof D?D.length:0;if(R+L>I){const S=I-R;if(!(S>50&&"string"==typeof D)){x.push("[Remaining arguments truncated]");break}D=D.substring(0,S)+"... [truncated]"}x.push(D),R+=L}return x}const isResourceUrl=(S,b="")=>{const I=S.split("?")[0].toLowerCase();return[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".woff",".woff2",".ttf",".eot",".otf",".pdf",".mp4",".mp3",".wav",".zip",".tar",".gz",".xml",".txt",".csv"].some(S=>I.endsWith(S))},R={get:(S,b,I)=>{const x=b.split(".");let R=S;for(const S of x){if(null==R)return I;R=R[S]}return void 0!==R?R:I},set:(S,b,I)=>{const x=b.split("."),R=x.pop();let A=S;for(const S of x)S in A&&"object"==typeof A[S]||(A[S]={}),A=A[S];return A[R]=I,S},has:(S,b)=>{const I=b.split(".");let x=S;for(const S of I){if(null==x||!(S in x))return!1;x=x[S]}return!0},isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isArray:S=>Array.isArray(S),isString:S=>"string"==typeof S,isNumber:S=>"number"==typeof S&&!isNaN(S),isBoolean:S=>"boolean"==typeof S,isFunction:S=>"function"==typeof S,isNull:S=>null===S,isUndefined:S=>void 0===S,isEmpty:S=>null==S||("string"==typeof S||Array.isArray(S)?0===S.length:"object"==typeof S&&0===Object.keys(S).length),toLower:S=>String(S).toLowerCase(),toUpper:S=>String(S).toUpperCase(),trim:S=>String(S).trim(),startsWith:(S,b)=>String(S).startsWith(b),endsWith:(S,b)=>String(S).endsWith(b),includes:(S,b)=>String(S).includes(b),filter:(S,b)=>Array.isArray(S)?S.filter(b):[],map:(S,b)=>Array.isArray(S)?S.map(b):[],find:(S,b)=>{if(Array.isArray(S))return S.find(b)},sortBy:(S,b)=>Array.isArray(S)?[...S].sort((S,I)=>{const x="function"==typeof b?b(S):S[b],R="function"==typeof b?b(I):I[b];return x<R?-1:x>R?1:0}):[],keys:S=>Object.keys(S||{}),values:S=>Object.values(S||{}),entries:S=>Object.entries(S||{}),assign:(S,...b)=>Object.assign({},S,...b),cloneDeep:S=>{if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>R.cloneDeep(S));if("object"==typeof S){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=R.cloneDeep(S[I]));return b}return S},merge:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&(R.isObject(S[b])&&R.isObject(I[b])?I[b]=R.merge(I[b],S[b]):I[b]=S[b]);return I},defaults:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&void 0===I[b]&&(I[b]=S[b]);return I},min:(...S)=>Math.min(...S),max:(...S)=>Math.max(...S),round:(S,b=0)=>{const I=Math.pow(10,b);return Math.round(S*I)/I},noop:()=>{},identity:S=>S,isEqual:(S,b)=>{if(S===b)return!0;if(null===S||null===b)return!1;if(typeof S!=typeof b)return!1;if("object"!=typeof S)return!1;const I=Object.keys(S),x=Object.keys(b);if(I.length!==x.length)return!1;for(const A of I){if(!x.includes(A))return!1;if(!R.isEqual(S[A],b[A]))return!1}return!0}},A={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},_={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]},D="[TraceScoutMonitoringCore]",L={FETCH_HTTP_ERROR:"fetch_http_error",FETCH_NETWORK_ERROR:"fetch_network_error",FETCH_SILENT_LOGIN_FAILURE:"fetch_silent_login_failure",XHR_HTTP_ERROR:"xhr_http_error",XHR_NETWORK_ERROR:"xhr_network_error",XHR_TIMEOUT_ERROR:"xhr_timeout_error",XHR_ABORTED_ERROR:"xhr_aborted_error",XHR_SILENT_LOGIN_FAILURE:"xhr_silent_login_failure",RESOURCE_LOAD_ERROR:"resource_load_error",CUSTOM_API_ERROR:"custom_api_error",UNKNOWN_ERROR:"unknown_error",POSTMESSAGE_COMMUNICATION:"postmessage_communication",POSTMESSAGE_CROSS_ORIGIN:"postmessage_cross_origin",POSTMESSAGE_LARGE_PAYLOAD:"postmessage_large_payload",POSTMESSAGE_SUSPICIOUS_ORIGIN:"postmessage_suspicious_origin",POSTMESSAGE_ERROR:"postmessage_error",FETCH_SLOW_REQUEST:"fetch_slow_request",XHR_SLOW_REQUEST:"xhr_slow_request",PERFORMANCE_DEGRADATION_ALERT:"performance_degradation_alert",P1_INCIDENT_EVENT:"p1_incident_event",CORE_WEB_VITAL:"core_web_vital"},B={EMAIL_REGEX:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,PHONE_REGEX:/^[\+]?[1-9][\d]{0,15}$/,UUID_REGEX:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i},U={THRESHOLDS:{lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3}},COLLECT_METRICS:{lcp:!0,fid:!0,cls:!0,inp:!0,ttfb:!0,fcp:!0},USE_WEB_VITALS_LIBRARY:!0,REPORTING_ENABLED:!0,REPORT_THRESHOLD:"needsImprovement"};class LoggingManager{constructor(){this.globalConfig={enabled:!1,level:"info",showTimestamps:!0,showServiceIcons:!0},this.serviceConfig={TraceScoutMonitoringCore:{enabled:!1,level:"info"},ConfigManager:{enabled:!1,level:"info"},EventManager:{enabled:!1,level:"info"},ServiceManager:{enabled:!1,level:"info"},UserProfileManager:{enabled:!1,level:"info"},PerformanceMonitor:{enabled:!1,level:"info"},FetchInterceptor:{enabled:!1,level:"info"},XHRInterceptor:{enabled:!1,level:"info"},ResourceInterceptor:{enabled:!1,level:"info"},PostMessageInterceptor:{enabled:!1,level:"info"},CoreWebVitalsMonitor:{enabled:!1,level:"info"},Recorder:{enabled:!1,level:"info"},SessionStorage:{enabled:!1,level:"info"},UploadQueue:{enabled:!1,level:"info"},"CDN-Loader":{enabled:!1,level:"info"},Replayer:{enabled:!1,level:"info"},Validation:{enabled:!1,level:"info"},BaseService:{enabled:!1,level:"info"}},this.logLevels={error:0,warn:1,info:2,debug:3},this.serviceStyles={TraceScoutMonitoringCore:{icon:"🎯",color:"#009688"},ConfigManager:{icon:"⚙️",color:"#607D8B"},EventManager:{icon:"📝",color:"#4CAF50"},ServiceManager:{icon:"🌐",color:"#9C27B0"},UserProfileManager:{icon:"👤",color:"#FF9800"},PerformanceMonitor:{icon:"⚡",color:"#795548"},FetchInterceptor:{icon:"🔌",color:"#8BC34A"},XHRInterceptor:{icon:"📡",color:"#FFC107"},ResourceInterceptor:{icon:"📦",color:"#E91E63"},PostMessageInterceptor:{icon:"💬",color:"#3F51B5"},CoreWebVitalsMonitor:{icon:"📊",color:"#2196F3"},Recorder:{icon:"🎬",color:"#FF5722"},SessionStorage:{icon:"💾",color:"#673AB7"},UploadQueue:{icon:"📤",color:"#FF9800"},"CDN-Loader":{icon:"📥",color:"#4CAF50"},Replayer:{icon:"▶️",color:"#9C27B0"},Validation:{icon:"✅",color:"#4CAF50"},BaseService:{icon:"🔧",color:"#607D8B"},default:{icon:"🔍",color:"#666"}}}configure(S={}){this.globalConfig={...this.globalConfig,...S},S.services&&Object.keys(S.services).forEach(b=>{this.serviceConfig[b]&&(this.serviceConfig[b]={...this.serviceConfig[b],...S.services[b]})})}enableServices(S,b="info"){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!0,this.serviceConfig[S].level=b)}),this.globalConfig.enabled=!0}disableServices(S){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!1)})}enableAll(S="info"){Object.keys(this.serviceConfig).forEach(b=>{this.serviceConfig[b].enabled=!0,this.serviceConfig[b].level=S}),this.globalConfig.enabled=!0}disableAll(){Object.keys(this.serviceConfig).forEach(S=>{this.serviceConfig[S].enabled=!1}),this.globalConfig.enabled=!1}getConfig(){return{global:{...this.globalConfig},services:{...this.serviceConfig}}}getEnabledServices(){return Object.keys(this.serviceConfig).filter(S=>this.serviceConfig[S].enabled)}isEnabled(S,b="info"){if(!this.globalConfig.enabled)return!1;const I=this.serviceConfig[S];if(!I||!I.enabled)return!1;const x=this.logLevels[I.level]||this.logLevels.info;return(this.logLevels[b]||this.logLevels.info)<=x}createLogger(S){return new ServiceLogger(S,this)}formatMessage(S,b,I){const x=this.serviceStyles[S]||this.serviceStyles.default;return{prefix:`%c${`${this.globalConfig.showTimestamps?`[${(new Date).toLocaleTimeString()}]`:""}[TraceScout][${S}]${this.globalConfig.showServiceIcons?x.icon:""}`}`,style:`color: ${x.color}; font-weight: bold;`,args:I}}}class ServiceLogger{constructor(S,b){this.serviceName=S,this.loggingManager=b}log(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.log(b.prefix,b.style,...b.args)}}info(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.info(b.prefix,b.style,...b.args)}}warn(...S){if(this.loggingManager.isEnabled(this.serviceName,"warn")){const b=this.loggingManager.formatMessage(this.serviceName,"warn",S);console.warn(b.prefix,"color: #FF5722; font-weight: bold;",...b.args)}}error(...S){const b=this.loggingManager.formatMessage(this.serviceName,"error",S);console.error(b.prefix,"color: #F44336; font-weight: bold;",...b.args)}debug(...S){if(this.loggingManager.isEnabled(this.serviceName,"debug")){const b=this.loggingManager.formatMessage(this.serviceName,"debug",S);console.debug(b.prefix,"color: #9E9E9E; font-weight: bold;",...b.args)}}session(...S){this.log("🎬",...S)}performance(...S){this.log("⚡",...S)}network(...S){this.log("🌐",...S)}storage(...S){this.log("💾",...S)}updateDebugMode(S){S?this.loggingManager.enableServices(this.serviceName):this.loggingManager.disableServices(this.serviceName)}}const $=new LoggingManager;function createLogger(S){return $.createLogger(S)}class Logger{constructor(S="",b=!1){this.serviceName=S.replace(/^\[|\]$/g,""),this.serviceLogger=$.createLogger(this.serviceName),b&&$.enableServices(this.serviceName),this.prefix=S,this.debug=Boolean(b)}updateDebugMode(S){this.debug=Boolean(S),this.serviceLogger.updateDebugMode(S)}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.serviceLogger.debug(...S)}success(...S){this.serviceLogger.log("✅",...S)}important(...S){this.serviceLogger.log("⚠️",...S)}session(...S){this.serviceLogger.session(...S)}performance(...S){this.serviceLogger.performance(...S)}interceptor(...S){this.serviceLogger.network(...S)}service(...S){this.serviceLogger.network(...S)}monitor(...S){this.serviceLogger.log("📊",...S)}}function validateEndpoints(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateDomains(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateService(S){return S&&"object"==typeof S&&"function"==typeof S.send}class ConfigManager{constructor(S={}){this.defaultConfig=S,this.config={},this.logger=new Logger("[ConfigManager]",S.debug)}validate(S={}){const b=[];try{const I=validateEndpoints(S.endpoints),x=validateDomains(S.domainsToTrack);I||x||b.push("Either endpoints or domainsToTrack must be provided"),S.service&&!validateService(S.service)&&b.push("Invalid service: must be an object with send() method");const R={retryIntervalMs:{min:1e3,max:3e5},deduplicationWindowMs:{min:100,max:36e5},maxQueueSize:{min:10,max:1e4},maxRetries:{min:1,max:10},batchSize:{min:1,max:100}};if(Object.entries(R).forEach(([I,{min:x,max:R}])=>{const A=S[I];void 0!==A&&("number"!=typeof A||A<x||A>R)&&b.push(`${I} must be a number between ${x} and ${R}`)}),void 0!==S.monitorPostMessages)if("object"!=typeof S.monitorPostMessages||null===S.monitorPostMessages)b.push("monitorPostMessages must be an object");else{const I=S.monitorPostMessages;void 0!==I.postMessageOriginWhitelist&&(Array.isArray(I.postMessageOriginWhitelist)?I.postMessageOriginWhitelist.every(S=>"string"==typeof S)||b.push("postMessageOriginWhitelist must contain only strings"):b.push("postMessageOriginWhitelist must be an array")),void 0===I.excludePostMessagesEvents||Array.isArray(I.excludePostMessagesEvents)||b.push("excludePostMessagesEvents must be an array"),void 0===I.monitorSpecificPostMessagesEvents||Array.isArray(I.monitorSpecificPostMessagesEvents)||b.push("monitorSpecificPostMessagesEvents must be an array")}if(void 0!==S.monitorPerformance&&"boolean"!=typeof S.monitorPerformance&&b.push("monitorPerformance must be a boolean"),void 0!==S.slowRequestThreshold&&("number"!=typeof S.slowRequestThreshold||S.slowRequestThreshold<100||S.slowRequestThreshold>3e4)&&b.push("slowRequestThreshold must be a number between 100 and 30000 milliseconds"),void 0!==S.averageAlertThreshold&&("number"!=typeof S.averageAlertThreshold||S.averageAlertThreshold<100||S.averageAlertThreshold>3e4)&&b.push("averageAlertThreshold must be a number between 100 and 30000 milliseconds"),b.length>0)throw new Error(`Configuration validation failed: ${b.join(", ")}`);return!0}catch(S){throw S}}apply(S={}){this.logger.log("Applying configuration options"),this.validate(S);try{this.config=R.merge({},this.defaultConfig,S,{debug:"boolean"==typeof R.get(S,"debug")?R.get(S,"debug"):Boolean(R.get(S,"debug")),retryIntervalMs:Math.max(1e3,R.get(S,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,R.get(S,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs)),maxQueueSize:Math.max(10,R.get(S,"maxQueueSize",this.defaultConfig.maxQueueSize)),maxRetries:Math.max(1,Math.min(10,R.get(S,"maxRetries",this.defaultConfig.maxRetries))),batchSize:Math.max(1,Math.min(100,R.get(S,"batchSize",this.defaultConfig.batchSize)))}),S.service&&(this.config.service=S.service),S.endpoints&&(this.config.endpoints=S.endpoints),S.domainsToTrack&&(this.config.domainsToTrack=S.domainsToTrack),S.monitorPostMessages&&(this.config.monitorPostMessages={postMessageOriginWhitelist:S.monitorPostMessages.postMessageOriginWhitelist||[],excludePostMessagesEvents:S.monitorPostMessages.excludePostMessagesEvents||[],monitorSpecificPostMessagesEvents:S.monitorPostMessages.monitorSpecificPostMessagesEvents||[]}),void 0!==S.monitorPerformance&&(this.config.monitorPerformance=S.monitorPerformance),void 0!==S.slowRequestThreshold&&(this.config.slowRequestThreshold=Math.max(100,Math.min(3e4,S.slowRequestThreshold))),void 0!==S.averageAlertThreshold&&(this.config.averageAlertThreshold=Math.max(100,Math.min(3e4,S.averageAlertThreshold)));return["appName","appVersion","environment","userId","sessionId","logPreflight","logResourceErrors","enableSessionRecording","sessionRecordingOptions","coreWebVitalsConfig"].forEach(b=>{void 0!==S[b]&&(this.config[b]=S[b])}),this.logger.log("Configuration applied successfully"),this.config}catch(S){throw this.logger.error("Failed to apply configuration:",S),S}}get(S,b=void 0){return R.get(this.config,S,b)}getAll(){return{...this.config}}update(S,b){return"string"==typeof S?this.config[S]=b:"object"==typeof S&&(this.config={...this.config,...S}),this.config}reset(){return this.config={...this.defaultConfig},this.config}}var j,W,H,V,Q,G=-1,o=function(S){addEventListener("pageshow",function(b){b.persisted&&(G=b.timeStamp,S(b))},!0)},c=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},u=function(){var S=c();return S&&S.activationStart||0},f=function(S,b){var I=c(),x="navigate";return G>=0?x="back-forward-cache":I&&(document.prerendering||u()>0?x="prerender":document.wasDiscarded?x="restore":I.type&&(x=I.type.replace(/_/g,"-"))),{name:S,value:void 0===b?-1:b,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:x}},s=function(S,b,I){try{if(PerformanceObserver.supportedEntryTypes.includes(S)){var x=new PerformanceObserver(function(S){Promise.resolve().then(function(){b(S.getEntries())})});return x.observe(Object.assign({type:S,buffered:!0},I||{})),x}}catch(S){}},d=function(S,b,I,x){var R,A;return function(_){b.value>=0&&(_||x)&&((A=b.value-(R||0))||void 0===R)&&(R=b.value,b.delta=A,b.rating=function(S,b){return S>b[1]?"poor":S>b[0]?"needs-improvement":"good"}(b.value,I),S(b))}},l=function(S){requestAnimationFrame(function(){return requestAnimationFrame(function(){return S()})})},p=function(S){var n=function(b){"pagehide"!==b.type&&"hidden"!==document.visibilityState||S(b)};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},v=function(S){var b=!1;return function(I){b||(S(I),b=!0)}},J=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(S){"hidden"===document.visibilityState&&J>-1&&(J="visibilitychange"===S.type?S.timeStamp:0,T())},y=function(){addEventListener("visibilitychange",g,!0),addEventListener("prerenderingchange",g,!0)},T=function(){removeEventListener("visibilitychange",g,!0),removeEventListener("prerenderingchange",g,!0)},E=function(){return J<0&&(J=h(),y(),o(function(){setTimeout(function(){J=h(),y()},0)})),{get firstHiddenTime(){return J}}},C=function(S){document.prerendering?addEventListener("prerenderingchange",function(){return S()},!0):S()},X=[1800,3e3],w=function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FCP"),A=s("paint",function(S){S.forEach(function(S){"first-contentful-paint"===S.name&&(A.disconnect(),S.startTime<x.firstHiddenTime&&(R.value=Math.max(S.startTime-u(),0),R.entries.push(S),I(!0)))})});A&&(I=d(S,R,X,b.reportAllChanges),o(function(x){R=f("FCP"),I=d(S,R,X,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,I(!0)})}))})},Y=[.1,.25],ee={passive:!0,capture:!0},te=new Date,P=function(S,b){j||(j=b,W=S,H=new Date,k(removeEventListener),F())},F=function(){if(W>=0&&W<H-te){var S={entryType:"first-input",name:j.type,target:j.target,cancelable:j.cancelable,startTime:j.timeStamp,processingStart:j.timeStamp+W};V.forEach(function(b){b(S)}),V=[]}},M=function(S){if(S.cancelable){var b=(S.timeStamp>1e12?new Date:performance.now())-S.timeStamp;"pointerdown"==S.type?function(S,b){var t=function(){P(S,b),r()},i=function(){r()},r=function(){removeEventListener("pointerup",t,ee),removeEventListener("pointercancel",i,ee)};addEventListener("pointerup",t,ee),addEventListener("pointercancel",i,ee)}(b,S):P(b,S)}},k=function(S){["mousedown","keydown","touchstart","pointerdown"].forEach(function(b){return S(b,M,ee)})},re=[100,300],se=0,ne=1/0,ie=0,N=function(S){S.forEach(function(S){S.interactionId&&(ne=Math.min(ne,S.interactionId),ie=Math.max(ie,S.interactionId),se=ie?(ie-ne)/7+1:0)})},O=function(){return Q?se:performance.interactionCount||0},q=function(){"interactionCount"in performance||Q||(Q=s("event",N,{type:"event",buffered:!0,durationThreshold:0}))},oe=[200,500],ae=0,z=function(){return O()-ae},le=[],ce={},K=function(S){var b=le[le.length-1],I=ce[S.interactionId];if(I||le.length<10||S.duration>b.latency){if(I)I.entries.push(S),I.latency=Math.max(I.latency,S.duration);else{var x={id:S.interactionId,latency:S.duration,entries:[S]};ce[x.id]=x,le.push(x)}le.sort(function(S,b){return b.latency-S.latency}),le.splice(10).forEach(function(S){delete ce[S.id]})}},ue=[2500,4e3],he={},de=[800,1800],ge=function e(S){document.prerendering?C(function(){return e(S)}):"complete"!==document.readyState?addEventListener("load",function(){return e(S)},!0):setTimeout(S,0)},Z=function(S,b){b=b||{};var I=f("TTFB"),x=d(S,I,de,b.reportAllChanges);ge(function(){var R=c();if(R){var A=R.responseStart;if(A<=0||A>performance.now())return;I.value=Math.max(A-u(),0),I.entries=[R],x(!0),o(function(){I=f("TTFB",0),(x=d(S,I,de,b.reportAllChanges))(!0)})}})};class CoreWebVitalsMonitor{constructor(S={}){this.config=S,this.logger=new Logger("[CoreWebVitalsMonitor]",S.debug),this.enabled=!1!==S.enabled,this.metrics=new Map,this.observers=[],this.callbacks=[],this.useWebVitalsLibrary=!1!==S.useWebVitalsLibrary,this.thresholds={lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3},...S.thresholds},this.collectMetrics={lcp:!1!==S.collectLCP,fid:!1!==S.collectFID,cls:!1!==S.collectCLS,inp:!1!==S.collectINP,ttfb:!1!==S.collectTTFB,fcp:!1!==S.collectFCP},this.reportingEnabled=!1!==S.reportingEnabled,this.reportThreshold=S.reportThreshold||"needsImprovement",this.enabled&&"undefined"!=typeof window&&this.init()}init(){if(this.logger.log("Initializing Core Web Vitals monitoring..."),this.useWebVitalsLibrary)try{return this.initWithWebVitalsLibrary(),void this.logger.log("Core Web Vitals monitoring initialized with web-vitals library")}catch(S){this.logger.warn("web-vitals library subscription failed, falling back to custom implementation:",S)}this.initCustomImplementation(),this.logger.log("Core Web Vitals monitoring initialized with custom implementation")}initWithWebVitalsLibrary(){this.collectMetrics.lcp&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("LCP"),a=function(S){var b=S[S.length-1];b&&b.startTime<x.firstHiddenTime&&(R.value=Math.max(b.startTime-u(),0),R.entries=[b],I())},A=s("largest-contentful-paint",a);if(A){I=d(S,R,ue,b.reportAllChanges);var _=v(function(){he[R.id]||(a(A.takeRecords()),A.disconnect(),he[R.id]=!0,I(!0))});["keydown","click"].forEach(function(S){addEventListener(S,function(){return setTimeout(_,0)},!0)}),p(_),o(function(x){R=f("LCP"),I=d(S,R,ue,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,he[R.id]=!0,I(!0)})})}})}(S=>this.handleWebVitalsMetric("lcp",S)),this.collectMetrics.fid&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FID"),l=function(S){S.startTime<x.firstHiddenTime&&(R.value=S.processingStart-S.startTime,R.entries.push(S),I(!0))},m=function(S){S.forEach(l)},A=s("first-input",m);I=d(S,R,re,b.reportAllChanges),A&&p(v(function(){m(A.takeRecords()),A.disconnect()})),A&&o(function(){var x;R=f("FID"),I=d(S,R,re,b.reportAllChanges),V=[],W=-1,j=null,k(addEventListener),x=l,V.push(x),F()})})}(S=>this.handleWebVitalsMetric("fid",S)),this.collectMetrics.cls&&function(S,b){b=b||{},w(v(function(){var I,x=f("CLS",0),R=0,A=[],c=function(S){S.forEach(function(S){if(!S.hadRecentInput){var b=A[0],I=A[A.length-1];R&&S.startTime-I.startTime<1e3&&S.startTime-b.startTime<5e3?(R+=S.value,A.push(S)):(R=S.value,A=[S])}}),R>x.value&&(x.value=R,x.entries=A,I())},_=s("layout-shift",c);_&&(I=d(S,x,Y,b.reportAllChanges),p(function(){c(_.takeRecords()),I(!0)}),o(function(){R=0,x=f("CLS",0),I=d(S,x,Y,b.reportAllChanges),l(function(){return I()})}),setTimeout(I,0))}))}(S=>this.handleWebVitalsMetric("cls",S)),this.collectMetrics.inp&&function(S,b){b=b||{},C(function(){var I;q();var x,R=f("INP"),a=function(S){S.forEach(function(S){S.interactionId&&K(S),"first-input"===S.entryType&&!le.some(function(b){return b.entries.some(function(b){return S.duration===b.duration&&S.startTime===b.startTime})})&&K(S)});var b,I=(b=Math.min(le.length-1,Math.floor(z()/50)),le[b]);I&&I.latency!==R.value&&(R.value=I.latency,R.entries=I.entries,x())},A=s("event",a,{durationThreshold:null!==(I=b.durationThreshold)&&void 0!==I?I:40});x=d(S,R,oe,b.reportAllChanges),A&&("PerformanceEventTiming"in window&&"interactionId"in PerformanceEventTiming.prototype&&A.observe({type:"first-input",buffered:!0}),p(function(){a(A.takeRecords()),R.value<0&&z()>0&&(R.value=0,R.entries=[]),x(!0)}),o(function(){le=[],ae=O(),R=f("INP"),x=d(S,R,oe,b.reportAllChanges)}))})}(S=>this.handleWebVitalsMetric("inp",S)),this.collectMetrics.ttfb&&Z(S=>this.handleWebVitalsMetric("ttfb",S)),this.collectMetrics.fcp&&w(S=>this.handleWebVitalsMetric("fcp",S)),this.setupVisibilityChangeHandler()}handleWebVitalsMetric(S,b){const I={type:S,value:b.value,id:b.id,timestamp:Date.now(),rating:this.getRating(S,b.value),threshold:this.thresholds[S],libRating:"string"==typeof b.rating?b.rating:null,navigationType:"string"==typeof b.navigationType?b.navigationType:null};this.metrics.set(S,I),this.logger.log(`Web Vital metric captured: ${S} = ${b.value}ms (${I.rating})`),this.reportingEnabled&&this.shouldReport(I)&&this.reportMetric(I),this.triggerCallbacks(S,I)}initCustomImplementation(){this.logger.log("Initializing custom Core Web Vitals implementation..."),this.collectMetrics.fcp&&this.trackFCP(),this.collectMetrics.lcp&&this.trackLCP(),this.collectMetrics.fid&&this.trackFID(),this.collectMetrics.cls&&this.trackCLS(),this.collectMetrics.ttfb&&this.trackTTFB(),this.setupVisibilityChangeHandler()}trackFCP(){try{const S=new PerformanceObserver(b=>{for(const I of b.getEntries())"first-contentful-paint"===I.name&&(this.handleWebVitalsMetric("fcp",{value:I.startTime,id:`fcp-${Date.now()}`,name:"FCP"}),S.disconnect())});S.observe({type:"paint",buffered:!0})}catch(S){this.logger.warn("Failed to track FCP:",S)}}trackLCP(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.size>S&&(S=I.size,this.handleWebVitalsMetric("lcp",{value:I.startTime,id:`lcp-${Date.now()}`,name:"LCP"}))});b.observe({type:"largest-contentful-paint",buffered:!0})}catch(S){this.logger.warn("Failed to track LCP:",S)}}trackFID(){let S=!1;const handleInput=b=>{if(S)return;S=!0;const I=b.timeStamp-b.timeStamp;this.handleWebVitalsMetric("fid",{value:I,id:`fid-${Date.now()}`,name:"FID"}),["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.removeEventListener(S,handleInput)})};["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.addEventListener(S,handleInput,{once:!0,passive:!0})})}trackCLS(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.hadRecentInput||(S+=I.value,this.handleWebVitalsMetric("cls",{value:S,id:`cls-${Date.now()}`,name:"CLS"}))});b.observe({type:"layout-shift",buffered:!0})}catch(S){this.logger.warn("Failed to track CLS:",S)}}trackTTFB(){try{if(window.performance&&window.performance.timing){const S=window.performance.timing,b=S.responseStart-S.navigationStart;b>0&&this.handleWebVitalsMetric("ttfb",{value:b,id:`ttfb-${Date.now()}`,name:"TTFB"})}}catch(S){this.logger.warn("Failed to track TTFB:",S)}}getRating(S,b){const I=this.thresholds[S];return I?b<=I.good?"good":b<=I.needsImprovement?"needsImprovement":"poor":"unknown"}shouldReport(S){return"good"===this.reportThreshold?"good"===S.rating:"needsImprovement"!==this.reportThreshold||("good"===S.rating||"needsImprovement"===S.rating)}reportMetric(S){const b={type:"core_web_vital",context:{forceLog:!0,isMonitored:!0,metricType:S.type,metricValue:S.value,metricRating:S.rating,threshold:S.threshold},data:S};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}triggerCallbacks(S,b){this.callbacks.forEach(I=>{try{I(S,b)}catch(S){this.logger.error("Error in metric callback:",S)}})}setupVisibilityChangeHandler(){document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.reportFinalMetrics()})}reportFinalMetrics(){if(!this.reportingEnabled)return;const S=Array.from(this.metrics.values());if(0===S.length)return;this.logger.log("Reporting final Core Web Vitals metrics:",S);const b={type:"core_web_vitals_final_report",context:{forceLog:!0,isMonitored:!0,timestamp:Date.now(),pageUrl:window.location.href},data:{metrics:S,summary:this.generateSummary(S)}};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}generateSummary(S){const b={total:S.length,byRating:{good:0,needsImprovement:0,poor:0},average:0,worst:null};let I=0,x=null;return S.forEach(S=>{b.byRating[S.rating]++,I+=S.value,(!x||"poor"===S.rating||"needsImprovement"===S.rating&&"poor"!==x.rating)&&(x=S)}),b.average=I/S.length,b.worst=x,b}addCallback(S){"function"==typeof S&&this.callbacks.push(S)}removeCallback(S){const b=this.callbacks.indexOf(S);b>-1&&this.callbacks.splice(b,1)}getMetrics(){return Array.from(this.metrics.values())}getMetric(S){return this.metrics.get(S)}updateThresholds(S){this.thresholds={...this.thresholds,...S},this.logger.log("Core Web Vitals thresholds updated:",this.thresholds)}destroy(){this.observers.forEach(S=>{S&&"function"==typeof S.disconnect&&S.disconnect()}),this.observers=[],this.callbacks=[],this.metrics.clear(),this.logger=null}}let pe=class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=createLogger("PerformanceMonitor"),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}};const fe=/^[A-Za-z0-9_-]{8,64}$/;function readHostWebViewSegmentId(S){try{const b=S||("undefined"!=typeof window?window:null);if(!b)return null;const I=b.__tsRnNative;if(!I||"object"!=typeof I)return null;const x=Object.getOwnPropertyDescriptor(I,"segmentId");if(!x||!("value"in x))return null;const R=x.value;return"string"==typeof R&&fe.test(R)?R:null}catch(S){return null}}const me="0123456789abcdef";function generateSessionId(){return`ts_${Date.now()}_${function randomHexSuffix(S=12){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const b=new Uint8Array(Math.ceil(S/2));crypto.getRandomValues(b);let I="";for(let S=0;S<b.length;S++)I+=me[b[S]>>4]+me[15&b[S]];return I.slice(0,S)}let b="";for(let I=0;I<S;I++)b+=me[Math.floor(16*Math.random())];return b}(12)}`}const ye=new Set(["confirmed","partial","disabled"]),ve="2.9.0",we=`@tracescout/browser/${ve}`;class SDKContext{static#e=null;static initialize(S){return this.#e?(console.warn("[SDKContext] Already initialized, returning existing instance"),this.#e):(this.#e=new SDKContext(S),this.#e)}static updateSessionId(S){this.#e&&(this.#e.sessionId=S,this.#e.sessionStartTime=Date.now(),console.log("[SDKContext] ✅ Session ID updated:",S))}static getInstance(){return this.#e}static resetForTests(){if("undefined"!=typeof process)throw new Error("resetForTests() only allowed in test environment");this.#e=null}constructor({projectId:S,workspaceId:b,environment:I,userId:x,sessionId:R,sessionManager:A}){this.#t({projectId:S}),this.projectId=S,this.workspaceId=null,this.environment=I||"production",this.userId=x||null,this.userEmail=null,this.userAttributes={},this.sessionManager=A||null,this.pageviewManager=null,this.sessionId=R||this.#r(),this.sessionStartTime=Date.now(),this.device={userAgent:navigator.userAgent,viewport:this.#s(),platform:navigator.platform,language:navigator.language,timezone:this.#n(),screen:{width:window.screen.width,height:window.screen.height,colorDepth:window.screen.colorDepth}},this.uaInfo=function parseUserAgent(S){const b={browserName:null,browserVersion:null,osName:null,osVersion:null,deviceType:null};if(!S||"string"!=typeof S)return b;let I;return/iPad|Tablet|PlayBook|Silk/i.test(S)||/Android/i.test(S)&&!/Mobile/i.test(S)?b.deviceType="tablet":/Mobi|iPhone|iPod|Android.*Mobile|Windows Phone|BlackBerry/i.test(S)?b.deviceType="mobile":/Mozilla|Chrome|Safari|Firefox|Edg|Opera|OPR/i.test(S)&&(b.deviceType="desktop"),(I=S.match(/Edg(?:e|A|iOS)?\/([\d.]+)/))?(b.browserName="Edge",b.browserVersion=I[1]):(I=S.match(/(?:OPR|Opera)\/([\d.]+)/))?(b.browserName="Opera",b.browserVersion=I[1]):(I=S.match(/SamsungBrowser\/([\d.]+)/))?(b.browserName="Samsung Internet",b.browserVersion=I[1]):(I=S.match(/(?:FxiOS|Firefox)\/([\d.]+)/))?(b.browserName="Firefox",b.browserVersion=I[1]):(I=S.match(/(?:CriOS|Chrome)\/([\d.]+)/))?(b.browserName="Chrome",b.browserVersion=I[1]):/Safari\//.test(S)&&(I=S.match(/Version\/([\d.]+)/))&&(b.browserName="Safari",b.browserVersion=I[1]),(I=S.match(/Windows NT ([\d.]+)/))?(b.osName="Windows",b.osVersion={"10.0":"10/11",6.3:"8.1",6.2:"8",6.1:"7"}[I[1]]||I[1]):(I=S.match(/iPhone OS ([\d_]+)|iPad; CPU OS ([\d_]+)/))?(b.osName="iOS",b.osVersion=(I[1]||I[2]||"").replace(/_/g,".")||null):(I=S.match(/Mac OS X ([\d_.]+)/))?(b.osName="macOS",b.osVersion=I[1].replace(/_/g,".")):(I=S.match(/Android ([\d.]+)/))?(b.osName="Android",b.osVersion=I[1]):/Android/i.test(S)?b.osName="Android":/CrOS/.test(S)?b.osName="ChromeOS":/Linux/.test(S)&&(b.osName="Linux"),b}(navigator.userAgent),this.domPrivacy=null,this.topFrameIdentity=null,this.errorCount=0,this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] ✅ Initialized successfully"),console.log(` Project ID: ${S}`),console.log(` Session ID: ${this.sessionId}`),console.log(` Environment: ${this.environment}`)}setWorkspaceId(S){this.workspaceId=S,console.log("[SDKContext] ✅ Workspace ID updated:",S)}#t(S){const b=[];if(S.projectId?this.#i(S.projectId)||b.push("projectId must be a valid UUID"):b.push("projectId is required"),b.length>0){const S=new Error(`TraceScout.init() validation failed:\n - ${b.join("\n - ")}`);throw S.name="ValidationError",S.validationErrors=b,S}}#i(S){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(S)}#r(){return generateSessionId()}#s(){return{width:window.innerWidth,height:window.innerHeight}}#n(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}enrichEvent(S){return{...S,sessionId:this.sessionId,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,relativeTime:S.timestamp?S.timestamp-this.sessionStartTime:0,browser:{...this.device,url:window.location.href,referrer:document.referrer,title:document.title},userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0}}enrichChunk(S){return{...S,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,metadata:{...S.metadata,metaSchema:2,sdkVersion:ve,projectId:this.projectId,workspaceId:this.workspaceId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,userName:this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??void 0:void 0,userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0,userTraits:this.userAttributes,browser:this.uaInfo.browserName?{name:this.uaInfo.browserName,version:this.uaInfo.browserVersion||void 0}:void 0,os:this.uaInfo.osName?{name:this.uaInfo.osName,version:this.uaInfo.osVersion||void 0}:void 0,deviceType:this.uaInfo.deviceType||void 0,userAgent:this.device.userAgent,viewport:this.device.viewport,platform:this.device.platform,language:this.device.language,timezone:this.device.timezone,screen:this.device.screen,errorCount:this.errorCount,domPrivacy:this.domPrivacy||void 0,url:window.location.href,referrer:document.referrer,title:document.title}}}recordError(){this.errorCount++}setDomPrivacy(S){"string"==typeof S&&ye.has(S)&&(this.domPrivacy=S)}setTopFrameIdentity(S){this.topFrameIdentity=S&&"object"==typeof S?S:null}setUser(S,b={}){this.userId=S,this.userEmail=b.email||this.userEmail,this.userAttributes=b,console.log("[SDKContext] User updated:",S)}clearUser(){this.userId=null,this.userEmail=null,this.userAttributes={},console.log("[SDKContext] User cleared")}updatePageContext(){this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] Page context updated:",this.page.url)}getContext(){return{workspace:{id:this.workspaceId},project:{id:this.projectId,environment:this.environment},session:{id:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime},user:{id:this.userId,email:this.userEmail,attributes:this.userAttributes},device:this.device,page:{url:window.location.href,referrer:document.referrer,title:document.title}}}getEventContext(S={}){const b=this.sessionManager?.currentSession?.anonymousId??null,I=this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??null:null,x="function"==typeof this.pageviewManager?.getCurrentPageviewId?this.pageviewManager.getCurrentPageviewId():null,R={projectId:this.projectId,sessionId:this.sessionId,anonymousId:b,environment:this.environment,sdkVersion:S.sdkVersion??"1.0.0",workspaceId:this.workspaceId,userId:this.userId,userEmail:this.userEmail,userName:I,release:S.release??null,dist:S.dist??null,debugId:S.debugId??null,sourceName:S.sourceName??null,url:"undefined"!=typeof window?window.location.href:null,pageviewId:x,webViewSegmentId:readHostWebViewSegmentId()},A=this.topFrameIdentity;return A&&"object"==typeof A&&("string"==typeof A.frameId&&A.frameId&&(R.frameId=A.frameId),"string"==typeof A.topFrameId&&A.topFrameId&&(R.topFrameId=A.topFrameId),"string"==typeof A.frameInstanceId&&A.frameInstanceId&&(R.frameInstanceId=A.frameInstanceId),R.frameDepth=0,R.captureRealm="top","string"==typeof A.frameOrigin&&A.frameOrigin&&(R.frameOrigin=A.frameOrigin),"string"==typeof A.frameUrl&&A.frameUrl&&(R.frameUrl=A.frameUrl),"string"==typeof A.frameLifecycle&&A.frameLifecycle&&(R.frameLifecycle=A.frameLifecycle),"string"==typeof A.privacyStatus&&A.privacyStatus&&(R.privacyStatus=A.privacyStatus)),R}setPageviewManager(S){this.pageviewManager=S||null}getSessionInfo(){return{sessionId:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId}}}const Se={CHANNEL_NAME:"ts_session",HEARTBEAT_INTERVAL:5e3,TAB_TIMEOUT:1e4,AWAY_THRESHOLD:12e4};class TabCoordinator{constructor(S={}){this.tabId=`tab_${Date.now()}_${Math.random().toString(36).substr(2,6)}`,this.awayAt=null,this.lastHeartbeat=Date.now(),this.knownTabs=new Map,this.channel=null,this.heartbeatTimer=null,this.channelName=S.channelName||Se.CHANNEL_NAME,this.heartbeatInterval=S.heartbeatInterval||Se.HEARTBEAT_INTERVAL,this.tabTimeout=S.tabTimeout||Se.TAB_TIMEOUT,this.awayThreshold=S.awayThreshold||Se.AWAY_THRESHOLD,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onActivity=S.onActivity||(()=>{}),this.debug=S.debug||!1,this._initBroadcastChannel(),this._initVisibilityTracking(),this._startHeartbeat(),this.debug&&console.log(`[TabCoordinator] Initialized tab: ${this.tabId}`)}_initBroadcastChannel(){if("undefined"!=typeof BroadcastChannel)try{this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=S=>this._handleMessage(S.data),this._broadcast({type:"hb",tabId:this.tabId,timestamp:Date.now()}),this.debug&&console.log("[TabCoordinator] BroadcastChannel connected")}catch(S){console.warn("[TabCoordinator] Failed to create BroadcastChannel:",S)}else console.warn("[TabCoordinator] BroadcastChannel not supported - single-tab mode")}_initVisibilityTracking(){document.addEventListener("visibilitychange",()=>{document.hidden?this._markAway():this._markVisible()}),window.addEventListener("pagehide",()=>{this._markAway(),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt})}),window.addEventListener("beforeunload",()=>{this._markAway()})}_startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.lastHeartbeat=Date.now(),this._broadcast({type:"hb",tabId:this.tabId,timestamp:this.lastHeartbeat,awayAt:this.awayAt}),this._pruneDeadTabs(),this._checkAwayRule()},this.heartbeatInterval)}_broadcast(S){if(this.channel)try{this.channel.postMessage(S)}catch(S){this.debug&&console.warn("[TabCoordinator] Broadcast failed:",S)}}_handleMessage(S){if(S.tabId!==this.tabId)switch(S.type){case"hb":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt}),this.debug&&console.log(`[TabCoordinator] Heartbeat from ${S.tabId}, away: ${S.awayAt?"yes":"no"}`);break;case"activity":this.onActivity(S.timestamp);break;case"away":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt});break;case"visible":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:null});break;case"new_session":this.debug&&console.log("[TabCoordinator] New session broadcast received")}}_markAway(){this.awayAt||(this.awayAt=Date.now(),this.debug&&console.log("[TabCoordinator] Tab marked AWAY"),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt}))}_markVisible(){if(this.awayAt){const S=Date.now()-this.awayAt;this.debug&&console.log(`[TabCoordinator] Tab back VISIBLE after ${Math.round(S/1e3)}s`),this.awayAt=null,this._broadcast({type:"visible",tabId:this.tabId,timestamp:Date.now()})}}_pruneDeadTabs(){const S=Date.now();for(const[b,I]of this.knownTabs.entries())S-I.lastSeen>this.tabTimeout&&(this.debug&&console.log(`[TabCoordinator] Pruning dead tab: ${b}`),this.knownTabs.delete(b))}_checkAwayRule(){const S=Date.now(),b=this.awayAt&&S-this.awayAt>this.awayThreshold;if(this.awayAt){for(const[b,I]of this.knownTabs.entries())if(!I.awayAt||S-I.awayAt<this.awayThreshold)return;b&&(console.log("[TabCoordinator] ALL tabs away >2min - session should end"),this.onSessionEnd("away_rule"))}}reportActivity(){const S=Date.now();this._broadcast({type:"activity",tabId:this.tabId,timestamp:S})}broadcastNewSession(S){this._broadcast({type:"new_session",tabId:this.tabId,sessionId:S,timestamp:Date.now()})}hasActiveTab(){if(!this.awayAt)return!0;for(const[S,b]of this.knownTabs.entries())if(!b.awayAt)return!0;return!1}getTabCount(){return this.knownTabs.size+1}getTabId(){return this.tabId}isAway(){return null!==this.awayAt}getAwayDuration(){return this.awayAt?Date.now()-this.awayAt:0}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.channel&&(this.channel.close(),this.channel=null),this.knownTabs.clear(),this.debug&&console.log(`[TabCoordinator] Destroyed tab: ${this.tabId}`)}}function uuidv4(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID()}catch{}const S=new Uint8Array(16);let b=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(S),b=!0)}catch{}if(!b)for(let b=0;b<16;b++)S[b]=Math.floor(256*Math.random());S[6]=15&S[6]|64,S[8]=63&S[8]|128;const I=Array.from(S,S=>S.toString(16).padStart(2,"0")).join("");return I.slice(0,8)+"-"+I.slice(8,12)+"-"+I.slice(12,16)+"-"+I.slice(16,20)+"-"+I.slice(20)}const be="__ts_aid";let Ce=null;function readCookie(S){if("undefined"==typeof document||"string"!=typeof document.cookie)return null;const b=document.cookie.split("; ");for(const I of b){const b=I.indexOf("=");if(!(b<0)&&I.slice(0,b)===S)try{return decodeURIComponent(I.slice(b+1))}catch{return I.slice(b+1)}}return null}function peekAnonymousId(){const S=readCookie(be);return S||Ce}function getOrCreateAnonymousId(){const S=peekAnonymousId();if(S)return S;const b=uuidv4();return function writeCookie(S,b,I){if("undefined"==typeof document)return!1;let x=`${S}=${encodeURIComponent(b)}; max-age=${I}; path=/; SameSite=Lax`;"undefined"!=typeof window&&window.location&&"https:"===window.location.protocol&&(x+="; Secure");try{document.cookie=x}catch{return!1}return readCookie(S)===b}(be,b,63072e3)||(Ce=b),b}const ke={INACTIVITY_TIMEOUT:18e5,ACTIVITY_THROTTLE:1e3,MAX_SESSION_DURATION:144e5};class SessionManager{constructor(S={}){this.sessionIdCookie=S.sessionIdCookie||"__ts_sid",this.lastActivityCookie=S.lastActivityCookie||"__ts_ts",this.sessionStartCookie=S.sessionStartCookie||"__ts_start",this.storageKey=S.storageKey||"__tracescout_session_stats__",this.inactivityTimeout=S.inactivityTimeout||ke.INACTIVITY_TIMEOUT,this.maxSessionDuration=S.maxSessionDuration||ke.MAX_SESSION_DURATION,this.activityThrottle=S.activityThrottle||ke.ACTIVITY_THROTTLE,this.cookieDomain=S.cookieDomain||window.location.hostname,this.cookiePath=S.cookiePath||"/",this.cookieSameSite=S.cookieSameSite||"Lax",this.debug=S.debug||!1,this.onLifecycleEnd="function"==typeof S.onLifecycleEnd?S.onLifecycleEnd:null,this.currentSession=null,this._lastActivityUpdate=0,this._boundActivityHandler=this._handleActivity.bind(this),this._trackingStarted=!1,this.tabCoordinator=new TabCoordinator({onSessionEnd:S=>this._handleSessionEnd(S),onActivity:S=>this._handleRemoteActivity(S),debug:this.debug,awayThreshold:S.awayThreshold,heartbeatInterval:S.heartbeatInterval,tabTimeout:S.tabTimeout})}getOrCreateSession(S={}){const b=this._getStoredSession();if(b&&this._isSessionValid(b))return console.log("[SessionManager] ✅ Continuing session:",b.sessionId),console.log(" Duration:",Math.round((Date.now()-b.startTime)/1e3/60),"min"),console.log(" Pages so far:",b.pageCount),this.currentSession=b,this.currentSession.pageCount++,this._updateActivity(),this._startActivityTracking(),b.sessionId;const I=generateSessionId(),x=getOrCreateAnonymousId();this.currentSession={sessionId:I,anonymousId:x,startTime:Date.now(),lastActivityTime:Date.now(),pageCount:1,eventCount:0,chunkCount:0,lastChunkSequence:0,projectId:S.projectId,workspaceId:S.workspaceId,environment:S.environment,userId:S.userId||null,userEmail:null,userAttributes:{},lifecycle:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}},this._saveSession(),this._startActivityTracking();const R=b?.expiredReason||(b?"Previous session invalid":"No previous session found");return console.log("[SessionManager] 🆕 Created new session:",I),console.log(" Reason:",R),this.tabCoordinator.broadcastNewSession(I),I}_isSessionValid(S){if(!S?.sessionId)return!1;const b=Date.now(),I=b-(S.lastActivityTime||0),x=b-(S.startTime||0),R=this.tabCoordinator?.awayThreshold||12e4;return I>R?(console.log("[SessionManager] ⏰ Session expired: away rule (all tabs closed)"),console.log(" Away for:",Math.round(I/1e3),"seconds"),console.log(" Threshold:",Math.round(R/1e3),"seconds"),S.expiredReason="away_rule",!1):I>this.inactivityTimeout?(console.log("[SessionManager] ⏰ Session expired: inactivity"),console.log(" Inactive for:",Math.round(I/1e3/60),"min"),S.expiredReason="inactivity",!1):!(x>this.maxSessionDuration)||(console.log("[SessionManager] ⏰ Session expired: max duration"),console.log(" Duration:",Math.round(x/1e3/60),"min"),S.expiredReason="max_duration",!1)}_getStoredSession(){try{const S=this._getCookie(this.sessionIdCookie);if(!S)return null;const b=getOrCreateAnonymousId(),I=parseInt(this._getCookie(this.sessionStartCookie))||Date.now(),x=parseInt(this._getCookie(this.lastActivityCookie))||Date.now();let R={};try{const S=localStorage.getItem(this.storageKey);S&&(R=JSON.parse(S))}catch(S){console.warn("[SessionManager] Failed to load stats from localStorage:",S)}if(R.anonymousId&&R.anonymousId!==b)return console.log("[SessionManager] 🔄 Storage cleared detected (anonymousId mismatch)"),console.log(" Cookie anonymousId:",b),console.log(" localStorage anonymousId:",R.anonymousId),this._clearSession(),null;if("number"==typeof R.schemaVersion&&5!==R.schemaVersion)return console.log("[SessionManager] 🔄 Stats schemaVersion mismatch — dropping cached session"),console.log(" cached schemaVersion:",R.schemaVersion),console.log(" required schemaVersion: 5"),this._clearSession(),null;return{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x,pageCount:R.pageCount||1,eventCount:R.eventCount||0,chunkCount:R.chunkCount||0,lastChunkSequence:R.lastChunkSequence||0,projectId:R.projectId,workspaceId:R.workspaceId,environment:R.environment,userId:R.userId,userEmail:R.userEmail,userAttributes:R.userAttributes||{},lifecycle:R.lifecycle&&"object"==typeof R.lifecycle?{sessionStartEmitted:!0===R.lifecycle.sessionStartEmitted,sessionEndEmitted:!0===R.lifecycle.sessionEndEmitted,startedAt:"number"==typeof R.lifecycle.startedAt?R.lifecycle.startedAt:null,endedAt:"number"==typeof R.lifecycle.endedAt?R.lifecycle.endedAt:null,endReason:"string"==typeof R.lifecycle.endReason?R.lifecycle.endReason:null}:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}}}catch(S){return console.warn("[SessionManager] Failed to load stored session:",S),this._clearSession(),null}}_saveSession(){if(this.currentSession)try{const{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x}=this.currentSession,R=this.maxSessionDuration;this._setCookie(this.sessionIdCookie,S,R),this._setCookie(this.sessionStartCookie,I.toString(),R),this._setCookie(this.lastActivityCookie,x.toString(),R);const A={schemaVersion:5,anonymousId:b,pageCount:this.currentSession.pageCount,eventCount:this.currentSession.eventCount,chunkCount:this.currentSession.chunkCount,lastChunkSequence:this.currentSession.lastChunkSequence,projectId:this.currentSession.projectId,workspaceId:this.currentSession.workspaceId,environment:this.currentSession.environment,userId:this.currentSession.userId,userEmail:this.currentSession.userEmail,userAttributes:this.currentSession.userAttributes||{},lifecycle:this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}};localStorage.setItem(this.storageKey,JSON.stringify(A))}catch(S){console.warn("[SessionManager] Failed to save session:",S)}}_handleActivity(){const S=Date.now();S-this._lastActivityUpdate<this.activityThrottle||(this._lastActivityUpdate=S,this._updateActivity(),this.tabCoordinator.reportActivity())}_handleRemoteActivity(S){this.currentSession&&(this.currentSession.lastActivityTime=S,this._setCookie(this.lastActivityCookie,S.toString(),this.maxSessionDuration))}_updateActivity(){this.currentSession&&(this.currentSession.lastActivityTime=Date.now(),this._saveSession())}_startActivityTracking(){if(this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.addEventListener(S,this._boundActivityHandler,{passive:!0})}),this._trackingStarted=!0,this.debug&&console.log("[SessionManager] ✅ Activity tracking started (mousemove/click/scroll)")}_stopActivityTracking(){if(!this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.removeEventListener(S,this._boundActivityHandler)}),this._trackingStarted=!1}_handleSessionEnd(S){if(console.log("[SessionManager] 🛑 Session ended by TabCoordinator:",S),"away_rule"===S&&"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"allTabsClosed"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}}getLifecycleGuard(){if(!this.currentSession)return null;const S=this.currentSession.lifecycle;return S&&"object"==typeof S?{sessionStartEmitted:!0===S.sessionStartEmitted,sessionEndEmitted:!0===S.sessionEndEmitted,startedAt:"number"==typeof S.startedAt?S.startedAt:null,endedAt:"number"==typeof S.endedAt?S.endedAt:null,endReason:"string"==typeof S.endReason?S.endReason:null}:null}setLifecycleGuard(S){if(!this.currentSession)return;if(!S||"object"!=typeof S)return;const b=this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null};!0===S.sessionStartEmitted&&(b.sessionStartEmitted=!0),!0===S.sessionEndEmitted&&(b.sessionEndEmitted=!0),"number"==typeof S.startedAt&&(b.startedAt=S.startedAt),"number"==typeof S.endedAt&&(b.endedAt=S.endedAt),"string"==typeof S.endReason&&(b.endReason=S.endReason),this.currentSession.lifecycle=b,this._saveSession()}_getCookie(S){return document.cookie.split("; ").reduce((S,b)=>{const[I,x]=b.split("=");return I&&(S[I]=decodeURIComponent(x||"")),S},{})[S]||null}_setCookie(S,b,I){const x=Math.floor(I/1e3);let R=`${S}=${encodeURIComponent(b)}`;R+=`; max-age=${x}`,R+=`; path=${this.cookiePath}`,R+=`; SameSite=${this.cookieSameSite}`,"undefined"!=typeof window&&"https:"===window.location.protocol&&(R+="; Secure"),this.cookieDomain&&!this.cookieDomain.includes("localhost")&&(R+=`; domain=${this.cookieDomain}`),document.cookie=R}_deleteCookie(S){document.cookie=`${S}=; max-age=0; path=${this.cookiePath}`}_clearSession(){this._deleteCookie(this.sessionIdCookie),this._deleteCookie(this.lastActivityCookie),this._deleteCookie(this.sessionStartCookie);try{localStorage.removeItem(this.storageKey)}catch(S){console.warn("[SessionManager] Failed to clear localStorage:",S)}}getSessionInfo(){if(!this.currentSession)return null;const S=Date.now(),b=S-this.currentSession.startTime,I=S-this.currentSession.lastActivityTime;return{...this.currentSession,duration:b,durationMinutes:Math.round(b/1e3/60),timeSinceActivity:I,timeSinceActivityMinutes:Math.round(I/1e3/60),isValid:this._isSessionValid(this.currentSession),willExpireIn:this.inactivityTimeout-I,willExpireInMinutes:Math.round((this.inactivityTimeout-I)/1e3/60),tabCount:this.tabCoordinator.getTabCount(),tabId:this.tabCoordinator.getTabId(),isAway:this.tabCoordinator.isAway()}}incrementEventCount(S=1){this.currentSession&&(this.currentSession.eventCount+=S,this._updateActivity())}incrementPageCount(){this.currentSession&&(this.currentSession.pageCount++,this._updateActivity(),this.debug&&console.log("[SessionManager] 📄 Page navigation, count:",this.currentSession.pageCount))}incrementChunkCount(){this.currentSession&&(this.currentSession.chunkCount++,this._saveSession())}updateLastChunkSequence(S){this.currentSession&&(this.currentSession.lastChunkSequence=S,this._saveSession(),this.debug&&console.log(`[SessionManager] Updated lastChunkSequence to ${S}`))}getLastChunkSequence(){return this.currentSession?.lastChunkSequence||0}getResumeInfo(){const S=this._getStoredSession();return S&&this._isSessionValid(S)&&(S.pageCount||1)>1?{sessionId:S.sessionId,lastChunkSequence:S.lastChunkSequence||0,lastActivityTime:S.lastActivityTime,isResumed:!0,pageCount:S.pageCount||1,eventCount:S.eventCount||0,chunkCount:S.chunkCount||0}:{sessionId:null,lastChunkSequence:0,lastActivityTime:null,isResumed:!1,pageCount:0,eventCount:0,chunkCount:0}}isResumedSession(){return!!this.currentSession&&(this.currentSession.pageCount||1)>1}updateUser(S,b){this.updateUserMetadata(S,{email:b})}updateUserMetadata(S,b={}){this.currentSession&&(this.currentSession.userId=S,this.currentSession.userEmail=b.email||this.currentSession.userEmail,this.currentSession.userAttributes=b,this._saveSession(),console.log("[SessionManager] 👤 User metadata updated"))}clearUserMetadata(){this.currentSession&&(this.currentSession.userId=null,this.currentSession.userEmail=null,this.currentSession.userAttributes={},this._saveSession(),console.log("[SessionManager] 👤 User metadata cleared"))}endSession(){if(!this.currentSession)return;const S=Date.now()-this.currentSession.startTime;if(console.log("[SessionManager] 🛑 Ending session:",this.currentSession.sessionId),console.log(" Duration:",Math.round(S/1e3),"s"),console.log(" Events:",this.currentSession.eventCount),console.log(" Pages:",this.currentSession.pageCount),console.log(" Chunks:",this.currentSession.chunkCount),"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"manual"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}this._stopActivityTracking(),this._clearSession(),this.currentSession=null}forceNewSession(S="manual"){console.log("[SessionManager] 🔄 Force new session, reason:",S),this.currentSession&&console.log(" Ending:",this.currentSession.sessionId),this.endSession()}destroy(){this._stopActivityTracking(),this.tabCoordinator.destroy()}}class EventManager{constructor(S={},b={}){this.config=S,this.storageKeys=b,this.logger=new Logger("[EventManager]",S.debug),this.eventQueue=[],this.eventOccurrenceTracker=new Map,this.debouncedSave=debounce(this.saveToLocal.bind(this),100),this._cleanupInterval=null,this._startCleanupTimer()}_startCleanupTimer(){const S=this.config.memoryCleanupIntervalMs||6e4;this._cleanupInterval=setInterval(()=>{this._cleanupOccurrenceTracker()},S)}_stopCleanupTimer(){this._cleanupInterval&&(clearInterval(this._cleanupInterval),this._cleanupInterval=null)}_cleanupOccurrenceTracker(){const S=Date.now(),b=this.config.deduplicationWindowMs||6e4,I=this.config.maxOccurrenceTrackerSize||5e3;let x=0;for(const[I,R]of this.eventOccurrenceTracker.entries())S-R>b&&(this.eventOccurrenceTracker.delete(I),x++);if(this.eventOccurrenceTracker.size>I){const S=Array.from(this.eventOccurrenceTracker.entries()).sort((S,b)=>b[1]-S[1]);this.eventOccurrenceTracker.clear();const b=S.slice(0,I);for(const[S,I]of b)this.eventOccurrenceTracker.set(S,I);const R=S.length-I;this.config.debug&&this.logger.log(`[Memory] Force-cleaned ${R} entries (exceeded max size ${I})`),x+=R}x>0&&this.config.debug&&this.logger.log(`[Memory] Cleaned up ${x} stale entries from occurrence tracker (size: ${this.eventOccurrenceTracker.size})`)}destroy(){this._stopCleanupTimer(),this.eventOccurrenceTracker.clear(),this.eventQueue=[]}addEvent(S){try{return!!this.shouldLogEvent(S)&&(!!this.deduplicateEvent(S)&&(this.eventQueue.length>=this.config.maxQueueSize&&(this.eventQueue.shift(),this.logger.warn("Queue size limit reached, removing oldest event")),this.eventQueue.push(S),this.debouncedSave(),this.logger.log("Event added:",S.type),!0))}catch(S){return this.logger.error("Failed to add event:",S),!1}}getEvents(){try{return R.sortBy(R.cloneDeep(this.eventQueue),"timestamp")}catch(S){return this.logger.error("Failed to get events:",S),[]}}removeEvents(S){try{const b=new Set(S);this.eventQueue=R.filter(this.eventQueue,S=>!b.has(S.id)),this.debouncedSave()}catch(S){this.logger.error("Failed to remove events:",S)}}clearEvents(){try{this.eventQueue.length=0,this.eventOccurrenceTracker.clear(),this.clearLocal(),this.logger.log("All events cleared")}catch(S){this.logger.error("Failed to clear events:",S)}}getQueueSize(){return this.eventQueue.length}shouldLogEvent(S){try{const b=S.context?.isMonitored,I=S.context?.forceLog;if(!(b||I))return!1;return!(this.config.ignoreEventTypes||[]).includes(S.type)}catch(S){return this.logger.error("Error in shouldLogEvent:",S),!1}}deduplicateEvent(S){try{const b=this.generateDedupeKey(S),I=Date.now(),x=this.eventOccurrenceTracker.get(b);return!(x&&I-x<this.config.deduplicationWindowMs)&&(this.eventOccurrenceTracker.set(b,I),!0)}catch(S){return this.logger.error("Error in deduplicateEvent:",S),!0}}generateDedupeKey(S){try{return`${S.type}_${S.context?.url||"unknown"}_${S.context?.method||"unknown"}`}catch(b){return this.logger.error("Error generating dedupe key:",b),`${S.type}_${Date.now()}`}}saveToLocal(){try{const S={events:this.eventQueue,timestamp:Date.now()};b.set(this.storageKeys.EVENTS||"__api_reporter_events__",S)}catch(S){this.logger.error("Failed to save events to local storage:",S)}}loadFromLocal(){try{const S=b.get(this.storageKeys.EVENTS||"__api_reporter_events__");S&&S.events&&(this.eventQueue=S.events,this.logger.log(`Loaded ${this.eventQueue.length} events from local storage`))}catch(S){this.logger.error("Failed to load events from local storage:",S)}}clearLocal(){try{b.remove(this.storageKeys.EVENTS||"__api_reporter_events__")}catch(S){this.logger.error("Failed to clear local storage:",S)}}getEventById(S){try{return this.eventQueue.find(b=>b.id===S)}catch(S){return this.logger.error("Failed to get event by ID:",S),null}}getEventsByType(S){try{return this.eventQueue.filter(b=>b.type===S)}catch(S){return this.logger.error("Failed to get events by type:",S),[]}}getEventsByTimeRange(S,b){try{return this.eventQueue.filter(I=>{const x=I.timestamp;return x>=S&&x<=b})}catch(S){return this.logger.error("Failed to get events by time range:",S),[]}}getEventStats(){try{const S={total:this.eventQueue.length,byType:{},byStatus:{}};return this.eventQueue.forEach(b=>{S.byType[b.type]=(S.byType[b.type]||0)+1;const I=b.context?.status||"unknown";S.byStatus[I]=(S.byStatus[I]||0)+1}),S}catch(S){return this.logger.error("Failed to get event stats:",S),{total:0,byType:{},byStatus:{}}}}cleanupOldEvents(S=864e5){try{const b=Date.now()-S,I=this.eventQueue.length;this.eventQueue=this.eventQueue.filter(S=>S.timestamp>b);const x=I-this.eventQueue.length;x>0&&(this.logger.log(`Cleaned up ${x} old events`),this.debouncedSave())}catch(S){this.logger.error("Failed to cleanup old events:",S)}}}class ServiceManager{constructor(S={},b=null){this.config=S,this.logger=b||new Logger("[ServiceManager]",S.debug),this.service=null,this.isSending=!1,this.retryCount=0,this.maxRetries=R.get(S,"maxRetries",3),this.initializeService()}initializeService(){if(!R.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(R.get(this.config,"service"),R.get(this.config,"serviceOptions",{}))}setService(S,b={}){if(!R.isObject(S)||!R.isFunction(R.get(S,"send")))throw new Error("Invalid service: must be an object with send() method");this.service=S,this.logger.log(`Service initialized: ${this.getServiceName()}`)}async sendEvents(S){if(this.isSending||R.isEmpty(S)||!this.service)return this.logger.warn("Cannot send events:",{isSending:this.isSending,isEmpty:R.isEmpty(S),noService:!this.service}),R.map(S||[],S=>({event:S,success:!1,error:new Error("Service unavailable")}));this.isSending=!0;try{const b=[];for(const I of S)try{await this.sendSingleEvent(I),b.push({event:I,success:!0}),this.logger.log(`Event sent successfully: ${I.type}`)}catch(S){this.logger.error(`Event failed: ${I.type}`,S),b.push({event:I,success:!1,error:S})}return this.retryCount=0,b}catch(b){return this.logger.error("Failed to send events:",b),this.retryCount++,R.map(S,S=>({event:S,success:!1,error:b}))}finally{this.isSending=!1}}async sendSingleEvent(S){let b;for(let I=1;I<=this.maxRetries;I++)try{return void await this.service.send(S)}catch(x){b=x,this.logger.warn(`Attempt ${I}/${this.maxRetries} failed for event ${S.id}:`,x.message),I<this.maxRetries&&await this.delay(this.getRetryDelay(I))}throw b}getRetryDelay(S){return Math.min(1e3*Math.pow(2,S-1),3e4)}async delay(S){return new Promise(b=>setTimeout(b,S))}getServiceName(){return R.isString(this.config.service)?this.config.service:this.service.constructor.name}isServiceAvailable(){return null!==this.service}getServiceStatus(){return{available:this.isServiceAvailable(),name:this.getServiceName(),isSending:this.isSending,retryCount:this.retryCount}}resetRetryCount(){this.retryCount=0}destroy(){this.service=null,this.isSending=!1,this.retryCount=0}}class UserProfileManager{constructor(S,b=[],I=!1){this.storageKey=S,this.fieldsToExtract=b,this.logger=new Logger("[UserProfileManager]",I)}getProfile(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.warn("Failed to read user profile:",S),{}}}setProfile(S={}){if(!R.isObject(S))return this.logger.warn("Invalid profile object provided"),!1;try{const b=this.getProfile(),I=R.merge(b,S);return localStorage.setItem(this.storageKey,JSON.stringify(I)),this.logger.log("User profile updated:",I),!0}catch(S){return"QuotaExceededError"===S.name?this.logger.warn("Storage quota exceeded for user profile"):this.logger.error("Failed to save user profile:",S),!1}}ensureProfile(){try{const S=this.getProfile();if(R.isEmpty(R.get(S,"uniqId"))){const b=R.merge(S,{uniqId:generateId(),createdAt:(new Date).toISOString()});this.setProfile(b),this.logger.log("Generated new user profile:",R.get(b,"uniqId"))}}catch(S){this.logger.error("Failed to ensure user profile:",S)}}extractContextFromData({data:S,source:b="response",url:I=""}){const x={};try{if(!R.isObject(S)||!R.isArray(this.fieldsToExtract))return x;const A=R.toLower(I);return this.fieldsToExtract.forEach(_=>{try{const D=R.toLower(R.get(_,"api","")),L=R.get(_,"source",""),B="*"===D||A.includes(D);if(!B||!("*"===L||L===b))return;const U=R.get(_,"fields",[]);R.isArray(U)?U.forEach(R=>{try{this.recursiveFieldMatch({context:x,matchRule:R,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with pattern "${R}":`,S)}}):R.isObject(U)&&R.entries(U).forEach(([R,A])=>{try{this.recursiveFieldMatchWithMapping({context:x,newKey:R,matchRule:A,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with mapping "${R}": "${A}":`,S)}})}catch(S){this.logger.warn("Failed to process extraction rule:",S)}}),x}catch(S){return this.logger.error("Failed to extract context from data:",S),x}}updateFromContext({url:S,source:b,data:I}){try{const x=this.extractContextFromData({url:S,source:b,data:I});if(Object.keys(x).length>0){const S=this.getProfile(),b={...S,...x};if(JSON.stringify(S)!==JSON.stringify(b))return this.setProfile(b),!0}return!1}catch(S){return this.logger.warn("Failed to update user profile context:",S),!1}}recursiveFieldMatch({context:S,matchRule:b,data:I,source:x,url:A}){try{if(!R.isObject(I))return;if(R.isString(b)){const x=R.get(I,b);if(void 0!==x)return S[b]=x,void this.logger.log(`Found field by path: ${b} = ${JSON.stringify(x)}`);const A=R.find(R.entries(I),([S])=>R.toLower(S)===R.toLower(b));if(A){const[b,I]=A;return S[b]=I,void this.logger.log(`Found field by name: ${b} = ${JSON.stringify(I)}`)}}if(b instanceof RegExp){const x=R.find(R.entries(I),([S,I])=>R.isString(I)&&b.test(I));if(x){const[b,I]=x;return S[b]=I,void this.logger.log(`Found field by value pattern: ${b} = ${I}`)}}R.values(I).forEach(I=>{R.isObject(I)&&!R.isNull(I)&&this.recursiveFieldMatch({context:S,matchRule:b,data:I,source:x,url:A})})}catch(S){this.logger.warn("Error in recursive field matching:",S)}}recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:x,source:A,url:_}){try{if(!R.isObject(x))return;if(R.isString(I)){const A=R.get(x,I);if(void 0!==A)return S[b]=A,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(A)}`);const _=R.find(R.entries(x),([S])=>R.toLower(S)===R.toLower(I));if(_){const[I,x]=_;return S[b]=x,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(x)}`)}}if(I instanceof RegExp){const A=R.find(R.entries(x),([S,b])=>R.isString(b)&&I.test(b));if(A){const[I,x]=A;return S[b]=x,void this.logger.log(`Found field by pattern with mapping: ${I} -> ${b} = ${x}`)}}R.values(x).forEach(x=>{R.isObject(x)&&!R.isNull(x)&&this.recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:x,source:A,url:_})})}catch(S){this.logger.warn("Error in recursive field matching with mapping:",S)}}validateFieldValue(S,b){try{if(R.isString(b)){const I=R.get(DEFAULT_FIELD_PATTERNS,b);return I&&I.test(S)}if(R.isFunction(b))return b(S);if(R.isObject(b)){const{type:I,min:x,max:R,pattern:A}=b;return(!I||typeof S===I)&&(!(void 0!==x&&S<x)&&(!(void 0!==R&&S>R)&&!(A&&!A.test(S))))}return!0}catch(S){return this.logger.warn("Validation error:",S),!1}}transformFieldValue(S,b){try{if(R.isFunction(b))return b(S);if(R.isString(b))switch(b){case"toLowerCase":return R.toLower(S);case"toUpperCase":return R.toUpper(S);case"trim":return R.trim(S);case"toString":return String(S);case"toNumber":return Number(S);default:return S}return S}catch(b){return this.logger.warn("Transform error:",b),S}}clearProfile(){try{return localStorage.removeItem(this.storageKey),this.logger.log("User profile cleared"),!0}catch(S){return this.logger.error("Failed to clear user profile:",S),!1}}getProfileField(S){try{const b=this.getProfile();return R.get(b,S)}catch(S){return void this.logger.error("Failed to get profile field:",S)}}setProfileField(S,b){try{const I=this.getProfile();return I[S]=b,this.setProfile(I)}catch(S){return this.logger.error("Failed to set profile field:",S),!1}}hasProfile(){try{const S=this.getProfile();return!R.isEmpty(S)}catch(S){return this.logger.error("Failed to check profile existence:",S),!1}}getProfileSize(){try{const S=this.getProfile();return Object.keys(S).length}catch(S){return this.logger.error("Failed to get profile size:",S),0}}}class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=new Logger("[PerformanceMonitor]",this.debug),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class InitializationPipeline{#o=null;#a=null;constructor(S){this.#o=S}async run(S){this.#a=S;try{this.#l();const S=this.#c(),b=this.#u(S),I=this.#h(b),x=this.#d(I,b);x&&(I.service=x);const R=this.#g(I);return{success:!0,sessionManager:S,sdkContext:b,remoteConfigService:null,serverConfig:this.#p(),config:I,managers:R}}catch(S){throw this.#o?.error("Initialization pipeline failed:",S),S}}#l(){const S=this.#a;if(!R.isObject(S))throw new Error("InitializationPipeline.run(options): options must be an object");if(!S.projectId)throw new Error("InitializationPipeline.run(options): projectId missing");S.debug&&console.log("[TraceScout] ✓ Required fields validated")}#c(){const S=this.#a;S.debug&&console.log("[TraceScout] 📅 Initializing session manager...");const b=new SessionManager({inactivityTimeout:18e5,maxSessionDuration:144e5,activityThrottle:1e3,awayThreshold:12e4,heartbeatInterval:5e3,tabTimeout:1e4,debug:S.debug||!1}),I=b.getOrCreateSession({projectId:S.projectId,environment:S.environment});return S.debug&&console.log("[TraceScout] ✓ Session manager initialized"),{sessionManager:b,sessionId:I}}#u(S){const b=this.#a,{sessionManager:I,sessionId:x}=S;try{const S=SDKContext.initialize({projectId:b.projectId,environment:b.environment||"production",userId:void 0,sessionId:x,sessionManager:I});if(I&&I.currentSession){const x=I.currentSession;x.userId&&x.userAttributes&&(S.setUser(x.userId,x.userAttributes),b.debug&&console.log("[TraceScout] ✓ Restored user metadata from session"))}return b.debug&&(console.log("[TraceScout] ✓ SDK Context initialized"),console.log(` Session ID: ${S.sessionId}`),console.log(` Project: ${S.projectId}`),console.log(` Environment: ${S.environment}`)),S}catch(S){throw console.error("[TraceScout] ❌ Failed to initialize SDKContext:",S),S}}#h(S){const b=this.#a,I={projectId:S.projectId,environment:S.environment,release:b.release,dist:b.dist,debugId:b.debugId,sourceName:b.sourceName,debug:b.debug||!1,apiBaseUrl:resolveApiBaseUrl(b),sampleRate:1,sessionChunkDuration:3e4,sessionMaxChunkSize:5e5,privacy:{maskAllInputs:!1,maskTextClass:"ts-mask",blockClass:"ts-block",ignoreClass:"ts-ignore",blockSelectors:[],maskImages:!1},network:(x=b.network,{isEnabled:!0,captureRequestHeaders:!0,captureResponseHeaders:!0,captureRequestBody:!0,captureResponseBody:!0,excludeEndpoints:[],maxBodyBytes:10240,requestSanitizer:null,responseSanitizer:null,sensitiveFields:[],...x&&"object"==typeof x&&!Array.isArray(x)?x:{}})};var x;return b.debug&&console.log("[TraceScout] ✓ Configuration built (SDK defaults)"),I}#p(){return{workspace:{name:"Unknown",id:null},project:{name:"Unknown"},configVersion:"sdk-defaults",features:{sessionRecording:{enabled:!0,sampleRate:1,captureNetwork:!0,captureConsole:!0,captureErrors:!0,networkSettings:{captureHeaders:!0,captureRequestBody:!0,captureResponseBody:!0},chunkDuration:3e4,maxChunkSize:5e5,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},performanceMonitoring:{enabled:!0,coreWebVitals:!0},logging:{enabled:!0,captureConsole:!0,minLevel:"debug",maxBufferSize:1e3,flushInterval:5e3,sampleRate:1}},telemetry:{}}}#d(S,b){const I=`${resolveApiBaseUrl(S)}/api/projects/${b.projectId}/telemetry`;return{send:async S=>{const x=Array.isArray(S)?S:[S];try{const S=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:x,context:{projectId:b.projectId,sessionId:b.sessionId,environment:b.environment}})});if(!S.ok)throw new Error(`Telemetry send failed: ${S.status}`);return await S.json()}catch(S){throw console.error("[TraceScout][TelemetryService] Send failed:",S),S}}}}#g(S){const b=new EventManager(S),I=new ServiceManager(S,this.#o),x=new UserProfileManager(S),R=new PerformanceMonitor(S);return S.debug&&console.log("[TraceScout] ✓ Core managers initialized"),{eventManager:b,serviceManager:I,userProfileManager:x,performanceMonitor:R}}}var Ie={environment:{type:"string",minLength:1,maxLength:64,default:"production"},release:{type:"string",minLength:1,maxLength:255},debug:{type:"boolean",default:!1},sourceName:{type:"string",minLength:1,maxLength:100,pattern:"^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$",default:"web-client",description:"S-2d.2 (step B): optional browser-source attribution. Defaults to 'web-client' when omitted. Emitted on every SDK v1 common envelope as `sourceName`. Pattern matches the API's envelope.schema.json SOURCE_NAME_PATTERN union. NOT named `source` to avoid collision with the existing js_error leaf `source` field (stack-frame URL, up to 2048 chars)."},dist:{type:"string",minLength:1,maxLength:64,description:"B2 source maps: optional build variant (e.g. 'web', 'ios-webview'). Emitted on every v1 envelope as `dist`; used with `release` to match uploaded source-map artifacts."},debugId:{type:"string",minLength:8,maxLength:64,pattern:"^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$",description:"B2 source maps: optional build-pinned debug ID (hex/UUID form). Strongest source-map match identity. May also be supplied by an injected build-time global (globalThis.__TRACESCOUT_DEBUG_ID__) read synchronously at init — never fetched over the network."}};const Ee=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,xe=new Set(["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody","maxBodyBytes","excludeEndpoints","requestSanitizer","responseSanitizer","sensitiveFields"]),Me=["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody"];const Re=/^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$/,Te=new Set(Object.keys(Ie));function validateConfig(S,b){if(null!==S&&"object"==typeof S&&!Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_FIRST_ARG"};if(null==S||""===S||"string"!=typeof S)return{ok:!1,code:"CONFIG_PROJECT_ID_REQUIRED"};if(!Ee.test(S))return{ok:!1,code:"CONFIG_PROJECT_ID_INVALID"};const I=b??{};if("object"!=typeof I||Array.isArray(I)||null===I)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:["(options must be a plain object)"]};const x=[];for(const S of Object.keys(I))"network"!==S&&"iframe"!==S&&(Te.has(S)||x.push(S));if(x.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:x};if(void 0!==I.debugId){const S=/^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$/;if("string"!=typeof I.debugId||!S.test(I.debugId))return{ok:!1,code:"CONFIG_INVALID_DEBUG_ID",keys:["debugId"]}}if(void 0!==I.dist&&("string"!=typeof I.dist||I.dist.length<1||I.dist.length>64))return{ok:!1,code:"CONFIG_INVALID_DIST",keys:["dist"]};if(void 0!==I.network){const S=function validateNetworkOptions(S){if("object"!=typeof S||null===S||Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["(network must be a plain object)"]};const b=[];for(const I of Object.keys(S))xe.has(I)||b.push(`network.${I}`);if(b.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:b};for(const b of Me)if(void 0!==S[b]&&"boolean"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};if(void 0!==S.maxBodyBytes){const b=S.maxBodyBytes;if("number"!=typeof b||!Number.isFinite(b)||b<0)return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.maxBodyBytes"]}}if(void 0!==S.excludeEndpoints){if(!Array.isArray(S.excludeEndpoints))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]};for(const b of S.excludeEndpoints)if("string"!=typeof b&&!(b instanceof RegExp))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]}}if(void 0!==S.sensitiveFields&&(!Array.isArray(S.sensitiveFields)||S.sensitiveFields.some(S=>"string"!=typeof S)))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.sensitiveFields"]};for(const b of["requestSanitizer","responseSanitizer"])if(void 0!==S[b]&&"function"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};return{ok:!0}}(I.network);if(!S.ok)return S}return void 0!==I.sourceName&&("string"!=typeof I.sourceName||I.sourceName.length<1||I.sourceName.length>100||!Re.test(I.sourceName))?{ok:!1,code:"CONFIG_INVALID_SOURCE_NAME"}:{ok:!0,projectId:S,options:I}}function shouldSampleSession(S,b={}){const I=b.anonymousId??null,x=b.randomFn??Math.random;return null==S||"number"!=typeof S||(!!Number.isNaN(S)||(S>=1||!(S<=0)&&("string"==typeof I&&I.length>0?function hashToUnitInterval(S){let b=2166136261;for(let I=0;I<S.length;I++)b^=S.charCodeAt(I),b=Math.imul(b,16777619);return(b>>>0)/4294967296}(I)<S:x()<S)))}const Ae="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ulid(S=Date.now()){return function encodeTimestamp(S){let b="",I=S;for(let S=9;S>=0;S--)b=Ae[I%32]+b,I=Math.floor(I/32);return b}(S)+function encodeRandom(){let S="";const b=new Uint8Array(10);let I=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(b),I=!0)}catch{}if(!I)for(let S=0;S<b.length;S++)b[S]=Math.floor(256*Math.random());let x=0,R=0;for(let I=0;I<b.length;I++)for(x=x<<8|b[I],R+=8;R>=5;)R-=5,S+=Ae[x>>R&31];return S}()}const _e=Object.freeze(["session_start","session_end","replay_chunk","page_view","route_change","network_request","console_event","js_error","performance_metric","custom_event","user_identified","experiment_exposure","feature_flag_evaluation"]),Oe=new Set(_e);function wrapInEnvelope(S,b,I){if(!Oe.has(S))throw new Error(`wrapInEnvelope: unknown eventType "${S}"`);if(null===I||"object"!=typeof I)throw new Error("wrapInEnvelope: context is required");const x={eventId:ulid(),eventType:S,timestamp:Date.now(),contractVersion:"1.0.0",projectId:I.projectId,sessionId:I.sessionId,anonymousId:I.anonymousId,environment:I.environment,sdkVersion:I.sdkVersion};return isNonEmptyString$3(I.workspaceId)&&(x.workspaceId=I.workspaceId),isNonEmptyString$3(I.userId)&&(x.userId=I.userId),isNonEmptyString$3(I.userEmail)&&(x.userEmail=I.userEmail),isNonEmptyString$3(I.userName)&&(x.userName=I.userName),isNonEmptyString$3(I.release)&&(x.release=I.release),isNonEmptyString$3(I.dist)&&(x.dist=I.dist),isNonEmptyString$3(I.debugId)&&(x.debugId=I.debugId),isNonEmptyString$3(I.sourceName)&&(x.sourceName=I.sourceName),isNonEmptyString$3(I.pageviewId)&&(x.pageviewId=I.pageviewId),isNonEmptyString$3(I.url)&&(x.url=I.url),isNonEmptyString$3(I.traceId)&&(x.traceId=I.traceId),isNonEmptyString$3(I.spanId)&&(x.spanId=I.spanId),isNonEmptyString$3(I.frameId)&&(x.frameId=I.frameId),isNonEmptyString$3(I.parentFrameId)&&(x.parentFrameId=I.parentFrameId),isNonEmptyString$3(I.topFrameId)&&(x.topFrameId=I.topFrameId),isNonEmptyString$3(I.frameInstanceId)&&(x.frameInstanceId=I.frameInstanceId),isNonNegativeInt(I.frameDepth)&&(x.frameDepth=I.frameDepth),isNonEmptyString$3(I.frameOrigin)&&(x.frameOrigin=I.frameOrigin),isNonEmptyString$3(I.frameUrl)&&(x.frameUrl=I.frameUrl),isNonEmptyString$3(I.frameLifecycle)&&(x.frameLifecycle=I.frameLifecycle),isNonEmptyString$3(I.captureRealm)&&(x.captureRealm=I.captureRealm),isNonEmptyString$3(I.privacyStatus)&&(x.privacyStatus=I.privacyStatus),isNonNegativeInt(I.bridgeProtocolVersion)&&(x.bridgeProtocolVersion=I.bridgeProtocolVersion),isNonNegativeInt(I.localSequence)&&(x.localSequence=I.localSequence),Number.isFinite(I.tsLocal)&&(x.tsLocal=I.tsLocal),Number.isFinite(I.tsNormalized)&&(x.tsNormalized=I.tsNormalized),Number.isFinite(I.clockOffsetMs)&&(x.clockOffsetMs=I.clockOffsetMs),Number.isFinite(I.clockUncertaintyMs)&&(x.clockUncertaintyMs=I.clockUncertaintyMs),"string"==typeof I.webViewSegmentId&&fe.test(I.webViewSegmentId)&&(x.webViewSegmentId=I.webViewSegmentId),{...x,...b}}function isNonEmptyString$3(S){return"string"==typeof S&&S.length>0}function isNonNegativeInt(S){return Number.isInteger(S)&&S>=0}const De=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/i;function normalizeOrigin(S){if("string"!=typeof S)return null;const b=S.trim();if(!b||"*"===b||"null"===b)return null;if(!De.test(b))return null;if(/^http:\/\//i.test(b)&&!function isLocalhostOrigin(S){return/^https?:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/i.test(S)}(b))return null;try{const S=new URL(b);return S.pathname&&"/"!==S.pathname||(S.search||S.hash)?null:(S.protocol+"//"+S.host).toLowerCase()}catch(S){return null}}function parseIframeConfig(S){const disabled=S=>({enabled:!1,role:null,parentOrigin:null,childOrigins:[],reason:S});if(null==S)return disabled("absent");if("object"!=typeof S||Array.isArray(S))return disabled("not_an_object");if(!0!==S.merge)return disabled("merge_not_enabled");const b="childOrigins"in S&&void 0!==S.childOrigins,I="parentOrigin"in S&&void 0!==S.parentOrigin;if(!b&&!I)return disabled("no_origins_declared");let x=[];if(b){const b=function normalizeChildOrigins(S){if(!Array.isArray(S))return null;const b=[],I=new Set;for(const x of S){const S=normalizeOrigin(x);if(!S)return null;I.has(S)||(I.add(S),b.push(S))}return b.length>0?b:null}(S.childOrigins);if(!b)return disabled("invalid_child_origins");x=b}let R=null;if(I){const b=normalizeOrigin(S.parentOrigin);if(!b)return disabled("invalid_parent_origin");R=b}let A=null;if(x.length>0&&R)A="both";else if(x.length>0)A="parent";else{if(!R)return disabled("no_origins_declared");A="child"}return{enabled:!0,role:A,parentOrigin:R,childOrigins:x,reason:null}}const Fe="undefined"!=typeof TextEncoder?new TextEncoder:null;function getSubtle(){const S="undefined"!=typeof globalThis?globalThis.crypto:void 0;return S&&S.subtle?S.subtle:null}function hex(S){return Array.from(new Uint8Array(S)).map(S=>S.toString(16).padStart(2,"0")).join("")}function fromHex(S){const b=new Uint8Array(S.length/2);for(let I=0;I<b.length;I++)b[I]=parseInt(S.substr(2*I,2),16);return b}async function sha256Hex(S){const b=getSubtle();return hex(await b.digest("SHA-256",Fe.encode(S)))}async function hmacHex(S,b){const I=getSubtle();return hex(await I.sign("HMAC",S,Fe.encode(b)))}function macInput(S){return[S.v,S.frameId,S.frameInstanceId,S.navigationGeneration,S.counter,S.projectId,S.sessionId,S.payloadType,S.payloadHash].join("|")}function safeEq(S,b){if("string"!=typeof S||"string"!=typeof b||S.length!==b.length)return!1;let I=0;for(let x=0;x<S.length;x++)I|=S.charCodeAt(x)^b.charCodeAt(x);return 0===I}const Ne=new Set(["rrweb-dom","telemetry"]);const Le={PROTOCOL_VERSION:1,ALLOWED_PAYLOAD_TYPES:Ne,hex:hex,fromHex:fromHex,sha256Hex:sha256Hex,randHex:function randHex(S){const b=new Uint8Array(S);return globalThis.crypto.getRandomValues(b),hex(b)},importKey:async function importKey(S){return getSubtle().importKey("raw",fromHex(S),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])},hmacHex:hmacHex,macInput:macInput,safeEq:safeEq,sealData:async function sealData(S,b,I){const x=void 0===I.payload?"":JSON.stringify(I.payload),R=await sha256Hex(x),A={v:1,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:I.payloadType,payloadHash:R},_=await hmacHex(S,macInput(A));return{v:1,kind:"data",frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,payloadType:I.payloadType,tag:I.tag,tsLocal:I.tsLocal,tsNormalized:I.tsNormalized,payloadHash:R,hmac:_,payload:I.payload}},validateData:async function validateData(S,b){try{if(!b||b.closed)return{ok:!1,reason:"stale_port"};if(!b.admitted||!b.key)return{ok:!1,reason:"not_admitted"};if(!S||"data"!==S.kind||"number"!=typeof S.counter||"string"!=typeof S.hmac||"string"!=typeof S.payloadHash)return{ok:!1,reason:"bad_shape"};if(S.v!==b.protocolVersion)return{ok:!1,reason:"protocol_mismatch",fatal:!0};if(!Ne.has(S.payloadType))return{ok:!1,reason:"bad_payload_type"};if(S.frameId!==b.frameId)return{ok:!1,reason:"wrong_frame:"+S.frameId};if(S.frameInstanceId!==b.frameInstanceId)return{ok:!1,reason:"stale_frame_instance"};if(S.navigationGeneration!==b.navigationGeneration)return{ok:!1,reason:"stale_generation"};const I=void 0===S.payload?"":JSON.stringify(S.payload);if(I.length>(b.maxBytes||65536))return{ok:!1,reason:"oversize:"+I.length};if(!safeEq(await sha256Hex(I),S.payloadHash))return{ok:!1,reason:"payload_hash_mismatch"};return safeEq(await hmacHex(b.key,macInput({v:S.v,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:S.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:S.payloadType,payloadHash:S.payloadHash})),S.hmac)?S.counter<=b.lastCounter?{ok:!1,reason:"counter_not_monotonic:"+S.counter+"<="+b.lastCounter}:{ok:!0}:{ok:!1,reason:"hmac_mismatch"}}catch(S){return{ok:!1,reason:"validator_error"}}}},Pe=Le.PROTOCOL_VERSION,Be="__TS_IFRAME_BRIDGE",ze="__TS_IFRAME_BRIDGE_PARENT_REGISTER";class BridgeChild{#f;#m;#y;#v;#o;#w;#S=null;#b=null;#C=null;#k=!1;#I=0;#E=null;#x=[];#M=[];#R=!1;#T=0;#A=1/0;#_=new Map;#O={forwarded:0,droppedUnadmitted:0,droppedBackpressure:0,offersRejected:0};constructor({parentOrigin:S,projectId:b,selfWindow:I,parentWindow:x,logger:R,queueCap:A}={}){this.#f=S,this.#m=b,this.#y=I,this.#v=x||I&&I.parent,this.#o=R||null,this.#w=A||1e3}get isAdmitted(){return this.#k}getStats(){return{admitted:this.#k,queued:this.#x.length+this.#M.length,...this.#O}}install(){if(!this.#y)return!1;const S={forwardRrwebDom:S=>this.forwardRrwebDom(S),forwardTelemetry:(S,b)=>this.forwardTelemetry(S,b),isAdmitted:()=>this.#k,__tsRole:"child"};try{Object.defineProperty(this.#y,Be,{value:S,configurable:!0,enumerable:!1,writable:!0})}catch(b){this.#y[Be]=S}this.#E=S=>{try{this.#D(S)}catch(S){this.#F("offer handler failed:",S)}};try{this.#y.addEventListener("message",this.#E)}catch(S){this.#F("addEventListener failed:",S)}return!0}#D(S){const b=S&&S.data;if(!b||"offer"!==b.__tsBridge)return;if(S.origin!==this.#f)return this.#O.offersRejected++,this.#F("offer origin mismatch");if(S.source!==this.#v)return this.#O.offersRejected++,this.#F("offer source mismatch");if(b.v!==Pe)return this.#O.offersRejected++,this.#F("offer protocol mismatch");if(this.#m&&b.projectId&&b.projectId!==this.#m)return this.#O.offersRejected++,this.#F("offer project mismatch");const I=S.ports&&S.ports[0];if(!I)return this.#O.offersRejected++,this.#F("offer missing port");this.#N(),this.#b={frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,projectId:b.projectId,sessionId:b.sessionId},this.#S=I,I.onmessage=S=>{try{this.#L(S.data)}catch(S){this.#F("control handler failed:",S)}};try{I.start&&I.start()}catch(S){}try{I.unref&&I.unref()}catch(S){}try{I.postMessage({c:"hello",v:Pe})}catch(S){this.#F("hello failed:",S)}}async#L(S){if(S&&this.#S)if("secret"!==S.c){if("pong"===S.c){const b=this.#_.get(S.id);if(!b)return;this.#_.delete(S.id);const I=Date.now()-b.sent,x=I/2,R=S.tParent-(b.sent+x);I<this.#A&&(this.#A=I,this.#T=R)}}else{if("string"!=typeof S.secret||!S.secret)return;try{this.#C=await Le.importKey(S.secret),this.#k=!0,this.#P(),this.#B()}catch(S){this.#F("secret import failed:",S)}}}#P(){for(let S=0;S<5;S++){const S=Le.randHex(8),b=Date.now();this.#_.set(S,{sent:b});try{this.#S.postMessage({c:"ping",id:S,t0:b})}catch(S){}}}forwardRrwebDom(S){return this.#z("rrweb-dom",void 0,S)}forwardTelemetry(S,b){return this.#z("telemetry",S,b)}#z(S,b,I){if(!this.#k)return this.#O.droppedUnadmitted++,!1;const x=function priorityForTag(S,b){return"rrweb-dom"===S?"high":"performance_metric"===b||"network_resource"===b?"low":"high"}(S,b),R=Date.now(),A={payloadType:S,tag:b,payload:I,priority:x,tsLocal:R,tsNormalized:this.#A===1/0?R:R+this.#T};if(this.#x.length+this.#M.length>=this.#w){if("low"===x)return this.#O.droppedBackpressure++,!1;this.#M.length>0?(this.#M.shift(),this.#O.droppedBackpressure++):(this.#x.shift(),this.#O.droppedBackpressure++)}return("low"===x?this.#M:this.#x).push(A),this.#B(),!0}async#B(){if(!this.#R&&this.#k&&this.#S&&this.#C){this.#R=!0;try{for(;this.#x.length||this.#M.length;){const S=this.#x.length?this.#x.shift():this.#M.shift(),b=++this.#I;try{const I=await Le.sealData(this.#C,this.#b,{counter:b,payloadType:S.payloadType,tag:S.tag,tsLocal:S.tsLocal,tsNormalized:S.tsNormalized,payload:S.payload});this.#S.postMessage(I),this.#O.forwarded++}catch(S){this.#F("seal/post failed:",S)}}}finally{this.#R=!1}}}#N(){if(this.#S)try{this.#S.close&&this.#S.close()}catch(S){}this.#S=null,this.#C=null,this.#k=!1,this.#I=0,this.#x.length=0,this.#M.length=0,this.#_.clear(),this.#T=0,this.#A=1/0}shutdown(){try{this.#E&&this.#y.removeEventListener("message",this.#E)}catch(S){}this.#N();try{this.#y[Be]&&"child"===this.#y[Be].__tsRole&&delete this.#y[Be]}catch(S){}this.#E=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:child]",...S)}catch(S){}}}class BridgeParent{#U;#m;#$;#j;#o;#w;#q;#W;#H;#V;#Q;#K=new Map;#G=new WeakMap;#J=0;#X=0;#Z=new WeakSet;#Y=null;#ee=null;#te=!1;#O={admitted:0,closed:0,accepted:0,rejected:0,fatal:0};#re=[];constructor({childOrigins:S,projectId:b,sessionId:I,topWindow:x,logger:R,queueCap:A,maxBytes:_,parentFrameId:D,topFrameId:L,feedRrwebDom:B,feedTelemetry:U}={}){this.#U=S instanceof Set?S:new Set(S||[]),this.#m=b,this.#$=I,this.#j=x||("undefined"!=typeof window?window:void 0),this.#o=R||null,this.#w=A||1e3,this.#q=_||65536,this.#W=D||"ts-top",this.#H=L||"ts-top",this.#V="function"==typeof B?B:()=>{},this.#Q="function"==typeof U?U:()=>{}}get isStarted(){return this.#te}getStats(){return{active:this.#K.size,...this.#O}}getRejectLog(){return this.#re.slice()}start(){if(this.#te)return!0;if(!this.#j)return!1;this.#te=!0;try{this.#j[ze]=S=>this.registerRrwebManager(S)}catch(S){}try{this.#se(this.#j.document),this.#ne(this.#j.document)}catch(S){this.#F("start scan failed:",S)}return!0}registerRrwebManager(S){this.#ee=S||null}#se(S){if(!S||"function"!=typeof S.querySelectorAll)return;let b;try{b=S.querySelectorAll("iframe")}catch(S){return}b.forEach(S=>{this.#ie(S),this.#oe(S)})}#ne(S){try{const b=this.#j.MutationObserver;if(!b)return;this.#Y=new b(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation failed:",S)}}),this.#Y.observe(S.documentElement||S,{childList:!0,subtree:!0})}catch(S){this.#F("observe failed:",S)}}#ae(S){if(S&&1===S.nodeType&&("IFRAME"===S.tagName&&(this.#ie(S),this.#oe(S)),S.querySelectorAll))try{S.querySelectorAll("iframe").forEach(S=>{this.#ie(S),this.#oe(S)})}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#G.get(S);if(!b)return;if(S.isConnected)return;const I=this.#K.get(b);I&&this.#ce(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#ie(S){if(!this.#Z.has(S)){this.#Z.add(S);try{S.addEventListener("load",()=>{try{this.#oe(S)}catch(S){this.#F("load re-admit failed:",S)}})}catch(S){}}}#ue(S){let b=null;try{b=S.src||S.getAttribute&&S.getAttribute("src")}catch(S){b=null}if(!b)return null;try{const S=this.#j.location&&this.#j.location.href||void 0,I=new URL(b,S);return(I.protocol+"//"+I.host).toLowerCase()}catch(S){return null}}#he(S){let b=this.#G.get(S);return b||(b="ts-xframe-"+ ++this.#J,this.#G.set(S,b)),b}#oe(S){const b=this.#ue(S);if(!b||!this.#U.has(b))return;let I=null;try{I=S.contentWindow}catch(S){I=null}if(!I)return;const x=this.#he(S),R=++this.#X,A=this.#K.get(x);let _;A&&this.#ce(A,"superseded");try{_=new this.#j.MessageChannel}catch(S){try{_=new MessageChannel}catch(S){return void this.#F("MessageChannel unavailable:",S)}}const D={frameId:x,frameInstanceId:`${x}-g${R}`,navigationGeneration:R,projectId:this.#m,sessionId:this.#$,expectedOrigin:b,sourceWindow:I,protocolVersion:Pe,lastCounter:-1,closed:!1,admitted:!1,key:null,maxBytes:this.#q,port:_.port1,secret:Le.randHex(32),nonce:Le.randHex(16),el:S};D.port.onmessage=S=>{this.#de(D,S&&S.data)};try{D.port.start&&D.port.start()}catch(S){}try{D.port.unref&&D.port.unref()}catch(S){}this.#K.set(x,D);const L={__tsBridge:"offer",v:Pe,projectId:this.#m,sessionId:this.#$,frameId:x,parentFrameId:this.#W,topFrameId:this.#H,frameInstanceId:D.frameInstanceId,navigationGeneration:R};try{I.postMessage(L,b,[_.port2]),this.#O.admitted++}catch(S){this.#F("offer post failed:",S),this.#ce(D,"offer_failed")}}async#de(S,b){if(b&&!S.closed)if("hello"!==b.c)if("ping"!==b.c){if("data"===b.kind){const I=await Le.validateData(b,S);return I.ok?(S.lastCounter=b.counter,this.#O.accepted++,void("rrweb-dom"===b.payloadType?this.#ge(S,b.payload):"telemetry"===b.payloadType&&this.#pe(S,b))):(this.#O.rejected++,this.#fe(S.frameId,I.reason),void(I.fatal&&(this.#O.fatal++,this.#ce(S,"protocol_mismatch"))))}this.#O.rejected++,this.#fe(S.frameId,"unknown_message")}else try{S.port.postMessage({c:"pong",id:b.id,t0:b.t0,tParent:Date.now()})}catch(S){}else try{S.key=await Le.importKey(S.secret),S.admitted=!0,S.port.postMessage({c:"secret",secret:S.secret,nonce:S.nonce}),S.secret=null}catch(S){this.#F("secret delivery failed:",S)}}#ge(S,b){try{const I={data:b,origin:S.expectedOrigin,source:S.sourceWindow};this.#ee&&"function"==typeof this.#ee.handleMessage&&this.#ee.handleMessage(I),this.#V(S,b,I)}catch(S){this.#F("deliverDom failed:",S)}}#pe(S,b){try{this.#Q(S,b)}catch(S){this.#F("deliverTelemetry failed:",S)}}#ce(S,b){S.closed=!0;try{S.port&&S.port.close&&S.port.close()}catch(S){}S.port=null,S.key=null,S.sourceWindow=null,S.el=null,this.#K.get(S.frameId)===S&&this.#K.delete(S.frameId),this.#O.closed++}shutdown(){for(const S of Array.from(this.#K.values()))this.#ce(S,"shutdown");this.#K.clear();try{this.#Y&&this.#Y.disconnect()}catch(S){}this.#Y=null;try{this.#j[ze]&&delete this.#j[ze]}catch(S){}this.#ee=null,this.#te=!1}#fe(S,b){this.#re.push({frameId:S,reason:b,t:Date.now()}),this.#re.length>200&&this.#re.shift()}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:parent]",...S)}catch(S){}}}class CrossOriginIframeBridge{#me;#ye;#m;#$;#o;#j;#ve=null;#we=null;constructor({config:S,core:b,projectId:I,sessionId:x,logger:R,topWindow:A}={}){this.#me=S,this.#ye=b,this.#m=I,this.#$=x,this.#o=R||null,this.#j=A||("undefined"!=typeof window?window:void 0)}get parent(){return this.#ve}get child(){return this.#we}get isChildMode(){return!!this.#we}start(){if(!this.#me||!this.#me.enabled)return!1;const S=this.#me.role;try{return"child"!==S&&"both"!==S||(this.#we=new BridgeChild({parentOrigin:this.#me.parentOrigin,projectId:this.#m,selfWindow:this.#j,parentWindow:this.#j&&this.#j.parent,logger:this.#o}),this.#we.install()),"parent"!==S&&"both"!==S||(this.#ve=new BridgeParent({childOrigins:new Set(this.#me.childOrigins),projectId:this.#m,sessionId:this.#$,topWindow:this.#j,logger:this.#o,feedTelemetry:(S,b)=>this.#Q(S,b)}),this.#ve.start()),!0}catch(S){return this.#F("bridge start failed (fail-closed):",S),!1}}#Q(S,b){const I=b.payload&&"object"==typeof b.payload?b.payload:{},x=Object.assign({},I,{frameId:S.frameId,parentFrameId:"ts-top",topFrameId:"ts-top",frameInstanceId:S.frameInstanceId,frameOrigin:S.expectedOrigin,captureRealm:"iframe",privacyStatus:"unknown",bridgeProtocolVersion:Pe,localSequence:b.counter,tsLocal:b.tsLocal,tsNormalized:b.tsNormalized});try{this.#ye&&this.#ye.addSessionCustomEvent(b.tag,x)}catch(S){this.#F("writer feed failed:",S)}}shutdown(){try{this.#we&&this.#we.shutdown()}catch(S){}try{this.#ve&&this.#ve.shutdown()}catch(S){}this.#we=null,this.#ve=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge]",...S)}catch(S){}}}function mapInternalEndReason(S){switch(S){case"max_inactivity":case"inactivity":return"inactivity";case"max_duration":case"maxDuration":return"maxDuration";case"away_rule":case"allTabsClosed":return"allTabsClosed";case"manual":return"manual";default:return null}}function detectDeviceType$1(S){const b=(S&&"string"==typeof S.userAgent?S.userAgent:"")||("undefined"!=typeof navigator&&navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"");return b?/iPad|Tablet|PlayBook|Silk/i.test(b)||/Android/i.test(b)&&!/Mobile/i.test(b)?"tablet":/Mobi|iPhone|iPod|Android/i.test(b)?"mobile":"desktop":"desktop"}function buildDeviceField(){const S="undefined"!=typeof navigator?navigator:{},b="undefined"!=typeof window?window:{},I=b.screen||{};let x="UTC";try{x=Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch(S){}return{type:detectDeviceType$1(S),userAgent:"string"==typeof S.userAgent?S.userAgent:"",platform:"string"==typeof S.platform?S.platform:"",language:"string"==typeof S.language?S.language:"",timezone:x,viewport:{width:"number"==typeof b.innerWidth?b.innerWidth:0,height:"number"==typeof b.innerHeight?b.innerHeight:0},screen:{width:"number"==typeof I.width?I.width:0,height:"number"==typeof I.height?I.height:0,colorDepth:"number"==typeof I.colorDepth?I.colorDepth:0}}}function isNonEmptyString$2(S){return"string"==typeof S&&S.length>0}class SessionLifecycleEmitter{#Se=!1;#be=!1;#Ce;#ke;#Ie;#Ee;#xe;#Me;constructor(S){if(!S||"object"!=typeof S)throw new Error("SessionLifecycleEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("SessionLifecycleEmitter: addCustomEvent callback is required");if("function"!=typeof S.getContext)throw new Error("SessionLifecycleEmitter: getContext callback is required");if("function"!=typeof S.readGuard||"function"!=typeof S.writeGuard)throw new Error("SessionLifecycleEmitter: readGuard/writeGuard callbacks are required");this.#ke=S.addCustomEvent,this.#Me=S.getContext,this.#Ie=S.readGuard,this.#Ee=S.writeGuard,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitStart(S={}){if(this.#Se)return!1;let b=null;try{b=this.#Ie()}catch(S){b=null}if(b&&!0===b.sessionStartEmitted)return this.#Se=!0,!1;b||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const I=this.#Me(),x="undefined"!=typeof window?window:{},R="undefined"!=typeof document?document:{},A=isNonEmptyString$2(S.landingUrl)?S.landingUrl:"string"==typeof x.location?.href?x.location.href:"";if(!isNonEmptyString$2(A))return this.#xe("[SDK lifecycle] session_start skipped — landingUrl unavailable"),!1;const _={device:buildDeviceField(),landingUrl:A},D=void 0!==S.referrer?S.referrer:"string"==typeof R.referrer?R.referrer:"";isNonEmptyString$2(D)&&(_.referrer=D);const L=void 0!==S.landingTitle?S.landingTitle:"string"==typeof R.title?R.title:"";let B;isNonEmptyString$2(L)&&(_.landingTitle=L),function isPlainObjectWithKeys(S){if(!S||"object"!=typeof S)return!1;for(const b in S)return!0;return!1}(S.userTraits)&&(_.userTraits=S.userTraits);try{B=this.#Ce("session_start",_,I)}catch(S){return this.#xe("[SDK lifecycle] session_start envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_start",B)}catch(S){return this.#xe("[SDK lifecycle] session_start addCustomEvent failed:",S),!1}this.#Se=!0;try{this.#Ee({sessionStartEmitted:!0,startedAt:"number"==typeof B.timestamp?B.timestamp:Date.now()})}catch(S){}return!0}emitEnd(S){if(!S||"object"!=typeof S)return!1;if(this.#be)return!1;const b=mapInternalEndReason(S.reason);if(!b)return this.#xe("[SDK lifecycle] session_end refused for non-logical reason:",S.reason),!1;let I=null;try{I=this.#Ie()}catch(S){I=null}if(I&&!0===I.sessionEndEmitted)return this.#be=!0,!1;I||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const x=this.#Me(),R=Date.now(),A=I&&"number"==typeof I.startedAt?I.startedAt:"number"==typeof x.sessionStartTime?x.sessionStartTime:R,_={endedAt:R,durationMs:Math.max(0,R-A),reason:b};let D;Number.isFinite(S.totalChunks)&&S.totalChunks>=0&&(_.totalChunks=Math.trunc(S.totalChunks)),Number.isFinite(S.totalEvents)&&S.totalEvents>=0&&(_.totalEvents=Math.trunc(S.totalEvents));try{D=this.#Ce("session_end",_,x)}catch(S){return this.#xe("[SDK lifecycle] session_end envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_end",D)}catch(S){return this.#xe("[SDK lifecycle] session_end addCustomEvent failed:",S),!1}this.#be=!0;try{this.#Ee({sessionEndEmitted:!0,endedAt:R,endReason:b})}catch(S){}return!0}get startEmitted(){return this.#Se}get endEmitted(){return this.#be}}function isNonEmptyString$1(S){return"string"==typeof S&&S.length>0}function urlParts(S){if("string"!=typeof S||0===S.length)return{path:null,query:null,hash:null};try{const b=new URL(S);return{path:b.pathname,query:b.search||null,hash:b.hash||null}}catch(S){return{path:null,query:null,hash:null}}}class PageviewManager{#Re;#Te=!1;#Ae=null;#ke;#_e;#Ce;#xe;constructor(S){if(!S||"object"!=typeof S)throw new Error("PageviewManager: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("PageviewManager: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("PageviewManager: getBaseContext callback is required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{},this.#Re=uuidv4()}getCurrentPageviewId(){return this.#Re}emitInitialPageView(S={}){if(this.#Te)return!1;const b="undefined"!=typeof window?window:{},I="undefined"!=typeof document?document:{},x="string"==typeof b.location?.href?b.location.href:"";if(!isNonEmptyString$1(x))return this.#xe("[SDK pageview] initial page_view skipped — url unavailable"),!1;const R=urlParts(x);if(!isNonEmptyString$1(R.path))return this.#xe("[SDK pageview] initial page_view skipped — could not derive path"),!1;const A={url:x,path:R.path,isInitial:!0!==S.isResumed};isNonEmptyString$1(R.query)&&(A.query=R.query),isNonEmptyString$1(R.hash)&&(A.hash=R.hash),isNonEmptyString$1(I.title)&&(A.title=I.title),isNonEmptyString$1(I.referrer)&&(A.referrer=I.referrer);const _=this.#Oe(this.#Re);let D;try{D=this.#Ce("page_view",A,_)}catch(S){return this.#xe("[SDK pageview] initial page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",D)}catch(S){return this.#xe("[SDK pageview] initial page_view addCustomEvent failed:",S),!1}return this.#Te=!0,this.#Ae=x,!0}recordNavigation(S,b,I){if(!isNonEmptyString$1(I))return this.#xe("[SDK pageview] navigation skipped — toUrl unavailable"),!1;if(null!==this.#Ae&&this.#Ae===I)return!1;if(!["pushState","replaceState","popstate","hashchange"].includes(S))return this.#xe("[SDK pageview] navigation skipped — unknown method:",S),!1;const x=isNonEmptyString$1(b)?b:I,R=urlParts(x),A=urlParts(I);if(!isNonEmptyString$1(A.path))return this.#xe("[SDK pageview] navigation skipped — could not derive toPath"),!1;const _=this.#Re,D=uuidv4(),L={fromUrl:x,toUrl:I,method:S,nextPageviewId:D};let B;isNonEmptyString$1(R.path)&&(L.fromPath=R.path),isNonEmptyString$1(A.path)&&(L.toPath=A.path);try{B=this.#Ce("route_change",L,this.#Oe(_))}catch(S){return this.#xe("[SDK pageview] route_change envelope wrap failed:",S),!1}try{this.#ke("tracescout.route_change",B)}catch(S){return this.#xe("[SDK pageview] route_change addCustomEvent failed:",S),!1}this.#Re=D,this.#Ae=I;const U="undefined"!=typeof document?document:{},$={url:I,path:A.path,isInitial:!1};let j;isNonEmptyString$1(A.query)&&($.query=A.query),isNonEmptyString$1(A.hash)&&($.hash=A.hash),isNonEmptyString$1(U.title)&&($.title=U.title),isNonEmptyString$1(x)&&($.referrer=x);try{j=this.#Ce("page_view",$,this.#Oe(D))}catch(S){return this.#xe("[SDK pageview] post-nav page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",j)}catch(S){return this.#xe("[SDK pageview] post-nav page_view addCustomEvent failed:",S),!1}return!0}#Oe(S){const b=this.#_e()||{};return Object.assign({},b,{pageviewId:S})}get initialEmitted(){return this.#Te}get lastUrl(){return this.#Ae}}function normalizeRating(S){if("string"!=typeof S)return null;switch(S){case"good":return"good";case"needs-improvement":case"needsImprovement":return"needs-improvement";case"poor":return"poor";default:return null}}const Ue=new Set(["navigate","reload","back-forward","prerender","back-forward-cache","restore"]);function isNonEmptyString(S){return"string"==typeof S&&S.length>0}class WebVitalsEmitter{#De;#Fe;#Ne=new Set;#ke;#_e;#Ce;#xe;constructor(S){if(!S||"object"!=typeof S)throw new Error("WebVitalsEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("WebVitalsEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("WebVitalsEmitter: getBaseContext callback is required");if(!isNonEmptyString(S.initialPageviewId))throw new Error("WebVitalsEmitter: initialPageviewId is required");if(!isNonEmptyString(S.initialUrl))throw new Error("WebVitalsEmitter: initialUrl is required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#De=S.initialPageviewId,this.#Fe=S.initialUrl,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emit(S,b){if(!b||"object"!=typeof b)return!1;const I=function normalizeMetricType(S){switch((S||"").toString().toLowerCase()){case"lcp":return"LCP";case"fid":return"FID";case"cls":return"CLS";case"inp":return"INP";case"ttfb":return"TTFB";case"fcp":return"FCP";default:return null}}(S);if(!I)return this.#xe("[SDK web-vitals] emit refused — unknown metric type:",S),!1;if(this.#Ne.has(I))return!1;if(!function isPositiveFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)&&S>=0}(b.value))return this.#xe("[SDK web-vitals] emit refused — invalid value for",I,b.value),!1;const x=normalizeRating(b.libRating)??normalizeRating(b.rating);if(!x)return this.#xe("[SDK web-vitals] emit refused — invalid rating for",I,b.libRating,b.rating),!1;const R={metric:I,value:b.value,unit:(A=I,"CLS"===A?"score":"ms"),rating:x};var A;"string"==typeof b.navigationType&&Ue.has(b.navigationType)&&(R.navigationType=b.navigationType);const _=this.#_e()||{},D=Object.assign({},_,{pageviewId:this.#De,url:this.#Fe});let L;try{L=this.#Ce("performance_metric",R,D)}catch(S){return this.#xe("[SDK web-vitals] envelope wrap failed:",S),!1}try{this.#ke("tracescout.performance_metric",L)}catch(S){return this.#xe("[SDK web-vitals] addCustomEvent failed:",S),!1}return this.#Ne.add(I),!0}get emittedMetrics(){return new Set(this.#Ne)}get initialPageviewId(){return this.#De}get initialUrl(){return this.#Fe}}const $e=/^[a-zA-Z][a-zA-Z0-9_.-]*$/,je=["_ts_","internal","system"],qe=["password","token","authorization","cookie","ssn","creditcard","secret","apikey"],We=new Set(["__proto__","constructor","prototype"]);function isValidUserId(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isValidEmail(S){if("string"!=typeof S)return!1;if(0===S.length||S.length>320)return!1;if(/\s/.test(S))return!1;const b=S.indexOf("@");if(b<1||b!==S.lastIndexOf("@"))return!1;const I=S.slice(0,b),x=S.slice(b+1);if(0===I.length||x.length<3)return!1;if(I.startsWith(".")||I.endsWith("."))return!1;if(!x.includes("."))return!1;if(x.startsWith(".")||x.endsWith("."))return!1;if(x.includes("..")||I.includes(".."))return!1;const R=x.lastIndexOf("."),A=x.slice(R+1);return!(A.length<2||!/^[a-zA-Z]+$/.test(A))}function isValidUserName(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)}function sanitizeScalarBag(S,b){const I={};if(!S||"object"!=typeof S||Array.isArray(S))return I;const x="function"==typeof b?b:()=>{};let R=0;for(const b of Object.keys(S)){if(R>=50){x("too-many-keys",b);continue}if("string"!=typeof b||0===b.length){x("invalid-key",String(b));continue}if(b.length>64){x("key-too-long",b);continue}if(We.has(b)){x("pollution-key",b);continue}if(je.some(S=>b.startsWith(S))){x("reserved-key",b);continue}const A=b.toLowerCase();if(qe.some(S=>A.includes(S))){x("sensitive-key",b);continue}const _=S[b];if(null===_){I[b]=null,R++;continue}const D=typeof _;if("string"!==D)if("number"!==D)"boolean"!==D?x(`invalid-type:${Array.isArray(_)?"array":D}`,b):(I[b]=_,R++);else{if(!isFiniteNumber(_)){x("non-finite-number",b);continue}I[b]=_,R++}else{if(_.length>1024){x("string-too-long",b);continue}I[b]=_,R++}}return I}class TrackIdentifyEmitter{#ke;#_e;#Ce;#xe;constructor(S){if(!S||"object"!=typeof S)throw new Error("TrackIdentifyEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("TrackIdentifyEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("TrackIdentifyEmitter: getBaseContext callback is required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitCustomEvent(S,b){if(!function isValidEventName(S){return"string"==typeof S&&S.length>=1&&S.length<=128&&$e.test(S)}(S))return this.#xe("[SDK track] emit refused — invalid event name:",S),!1;const I=[],x=sanitizeScalarBag(b,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#xe("[SDK track] properties keys dropped:",I);const R={name:S};Object.keys(x).length>0&&(R.properties=x);const A=this.#_e()||{};let _;try{_=this.#Ce("custom_event",R,A)}catch(S){return this.#xe("[SDK track] envelope wrap failed:",S),!1}try{this.#ke("tracescout.custom_event",_)}catch(S){return this.#xe("[SDK track] addCustomEvent failed:",S),!1}return!0}emitUserIdentified(S){if(!S||"object"!=typeof S)return!1;if(!isValidUserId(S.userId))return this.#xe("[SDK identify] emit refused — invalid userId"),!1;const b="set"===S.mode?"set":"merge",I=[],x=sanitizeScalarBag(S.traits,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#xe("[SDK identify] traits keys dropped:",I);const R={mode:b};Object.keys(x).length>0&&(R.traits=x);const A=this.#_e()||{},_=Object.assign({},A,{userId:S.userId});let D;isValidEmail(S.userEmail)&&(_.userEmail=S.userEmail),isValidUserName(S.userName)&&(_.userName=S.userName);try{D=this.#Ce("user_identified",R,_)}catch(S){return this.#xe("[SDK identify] envelope wrap failed:",S),!1}try{this.#ke("tracescout.user_identified",D)}catch(S){return this.#xe("[SDK identify] addCustomEvent failed:",S),!1}return!0}}const He=/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]*$/,Ve=/^[a-z0-9][a-z0-9_-]*$/,Qe=/^[A-Za-z0-9_-]{8,64}$/,Ke=128,Ge=Object.freeze(["targeting_match","rule_match","fallthrough","default","split","override","disabled","error","unknown"]);function validKey(S,b){return"string"==typeof S&&S.length>=1&&S.length<=b&&He.test(S)}class ExposureEmitter{#ke;#_e;#Ce;#xe;#Le=new Map;constructor(S){if(!S||"function"!=typeof S.addCustomEvent||"function"!=typeof S.getBaseContext)throw new Error("ExposureEmitter: addCustomEvent + getBaseContext are required");this.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitExperimentExposure(S){return this.#Pe("experiment_exposure",S,{requireExperimentKey:!0})}emitFlagEvaluation(S){return this.#Pe("feature_flag_evaluation",S,{requireFlagKey:!0})}getActiveAssignments(){return[...this.#Le.entries()].map(([S,b])=>`${S}:${b}`)}#Pe(S,b,{requireExperimentKey:I=!1,requireFlagKey:x=!1}={}){if(!b||"object"!=typeof b)return this.#xe("[SDK exposure] refused — options object required"),!1;const{experimentKey:R,flagKey:A,variantKey:_,provider:D,kind:L,evaluationReason:B,experimentVersion:U,eventId:$}=b;if(!validKey(_,64))return this.#xe("[SDK exposure] refused — invalid variantKey:",_),!1;if(I&&!validKey(R,Ke))return this.#xe("[SDK exposure] refused — invalid experimentKey:",R),!1;if(x&&!validKey(A,Ke))return this.#xe("[SDK exposure] refused — invalid flagKey:",A),!1;if(null!=R&&!I&&!validKey(R,Ke))return!1;if(null!=A&&!x&&!validKey(A,Ke))return!1;if(null!=D&&!("string"==typeof D&&D.length<=64&&Ve.test(D)))return this.#xe("[SDK exposure] refused — invalid provider:",D),!1;if(null!=L&&"experiment"!==L&&"feature_rollout"!==L)return!1;if(null!=B&&!Ge.includes(B))return!1;if(null!=U&&!(Number.isInteger(U)&&U>=1&&U<=1e4))return!1;if(null!=$&&!Qe.test($))return this.#xe("[SDK exposure] refused — invalid eventId (idempotency key):",$),!1;const j={variantKey:_};R&&(j.experimentKey=R),null!=U&&(j.experimentVersion=U),j.kind=L||("feature_flag_evaluation"===S?"feature_rollout":"experiment"),D&&(j.provider=D),A&&(j.flagKey=A),"feature_flag_evaluation"===S&&(j.evaluationReason=B||"unknown");const W=this.#_e()||{};let H;try{H=this.#Ce(S,j,W)}catch(S){return this.#xe("[SDK exposure] envelope wrap failed:",S),!1}$&&(H.eventId=$);try{this.#ke(`tracescout.${S}`,H)}catch(S){return this.#xe("[SDK exposure] addCustomEvent failed:",S),!1}const V=`${R||A}@${U||1}`;if(!this.#Le.has(V)&&this.#Le.size>=10){const S=this.#Le.keys().next().value;this.#Le.delete(S)}return this.#Le.set(V,_),!0}}const Je="[REDACTED]",Xe=encodeURIComponent(Je),Ze=["token","access_token","refresh_token","id_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","ssid","password","passwd","pwd","secret","jwt","bearer","credential","credentials","private_token","private_key","client_secret","pin","cvv","cvc","ssn","email","card","ccnum","cc_num","ccnumber","cc_number","iban"],Ye=new Set(["access_token","id_token","refresh_token","api_key","apikey","client_secret","password","passwd","authorization","auth_token","signature","token","auth","session_id","sessionid","session_token","secret","private_key","access_key","client_assertion","code_verifier","otp","pin","cvv","cvc","ssn","email"]),et=/(?<!\d)\d(?:[ .-]?\d){12,18}(?!\d)/g;function isCardRun(S){const b=S.replace(/[ .-]/g,"");if(b.length<13||b.length>19)return!1;const I=b.charCodeAt(0)-48;return!(I<2||I>6)&&function luhnValid(S){let b=0,I=!1;for(let x=S.length-1;x>=0;x--){let R=S.charCodeAt(x)-48;I&&(R*=2,R>9&&(R-=9)),b+=R,I=!I}return b%10==0}(b)}function decodeOnce(S){try{return decodeURIComponent(S.replace(/\+/g," "))}catch{return S}}function containsCardNumber(S){if("string"!=typeof S||S.length<13)return!1;for(const b of[S,decodeOnce(S)]){const S=b.match(et);if(S&&S.some(isCardRun))return!0}return!1}const tt=[{re:/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/gi,replace:"Bearer "+Je},{re:/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,replace:Je},{re:/\bsk-[A-Za-z0-9]{16,}\b/g,replace:Je},{re:/\btsk_[A-Za-z0-9_]{8,}\b/g,replace:Je},{re:/\bAKIA[0-9A-Z]{16}\b/g,replace:Je},{re:/\bghp_[A-Za-z0-9]{36}\b/g,replace:Je},{re:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,replace:Je}];function scanSecretValue(S){if("string"!=typeof S||S.length<8)return S;let b=S;for(const{re:S,replace:I}of tt)b=b.replace(S,I);return redactCardNumbers(b)}function redactCardNumbers(S){return"string"!=typeof S?S:S.replace(et,S=>isCardRun(S)?Je:S)}const rt="(?:[ .+-]|%(?:25)?2[0bBdDeE])",st=new RegExp(`(?<!(?<!%(?:25)?2)\\d)(?<!%(?:25)?)\\d(?:${rt}?\\d){12,18}(?!\\d)`,"g"),nt=new RegExp(rt,"g");function redactCardNumbersInText(S){if("string"!=typeof S||S.length<13)return{text:S,redacted:!1};let b=!1;return{text:S.replace(st,S=>function isBodyCardRun(S){return isCardRun(S.replace(nt,""))}(S)?(b=!0,Je):S),redacted:b}}function isCardNumberValue(S){return"number"==typeof S&&Number.isSafeInteger(S)&&isCardRun(String(Math.abs(S)))}function buildTokens(S=[]){const b=[...Ze];if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.push(I.toLowerCase());return b}function isSensitiveParam(S,b){const I=String(S).toLowerCase();return Ye.has(I)||b.some(S=>I.includes(S))}function scrubSearchParams(S,b,I){let x=!1;const R=[];for(const b of S.keys())R.push(b);const A=new Set;for(const _ of R)if(!A.has(_)){if(A.add(_),!isSensitiveParam(_,b)&&!containsCardNumber(_)&&!S.getAll(_).some(containsCardNumber)){const b=S.getAll(_),I=b.map(scanSecretValue);if(I.some((S,I)=>S!==b[I])){x=!0,S.delete(_);for(const b of I)S.append(_,b)}continue}if(containsCardNumber(_))x=!0,S.delete(_),"delete"!==I&&S.append(Je,Je);else if(x=!0,"delete"===I)S.delete(_);else{const b=S.getAll(_).length;S.delete(_);for(let I=0;I<b;I++)S.append(_,Je)}}return x}function scrubUrlStructure(S,b,I){if((S.username||S.password)&&(S.username="",S.password=""),S.pathname&&S.pathname.length>=13){const b=S.pathname.split("/");let I=!1;for(let S=0;S<b.length;S++)containsCardNumber(b[S])&&(b[S]=Xe,I=!0);I&&(S.pathname=b.join("/"))}if(S.hash&&S.hash.length>1){const x=S.hash.slice(1);if(x.includes("=")){const R=new URLSearchParams(x);scrubSearchParams(R,b,I)&&(S.hash="#"+R.toString())}else containsCardNumber(x)&&(S.hash="#"+Xe)}}function scrubUrlValues(S,b={}){const{mode:I="redact"}=b;if(!S)return S||"";try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,x=new URL(S,b);return scrubSearchParams(x.searchParams,[],I),scrubUrlStructure(x,[],I),x.toString()}catch{return redactCardNumbers(S)}}function splitSanitizedUrl(S,b={}){const{extraParams:I=[],mode:x="redact"}=b;if(!S)return{url:"",path:"",query:""};const R=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);scrubSearchParams(I.searchParams,R,x),scrubUrlStructure(I,R,x);const A=I.searchParams.toString();return{url:I.toString(),path:I.pathname||"",query:A}}catch{const I=function sanitizeUrl$1(S,b={}){const{extraParams:I=[],mode:x="redact",stripHash:R=!1}=b;if(!S)return S||"";const A=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);return scrubSearchParams(I.searchParams,A,x),R&&(I.hash=""),scrubUrlStructure(I,A,x),I.toString()}catch{let b=S.replace(/([?&#][^=&]*(?:token|key|secret|password|passwd|pwd|auth|jwt|bearer|session|sid|credential|pin|cvv|cvc|ssn|email|card|ccnum|cc_num|iban)[^=&]*=)[^&#]*/gi,`$1${Je}`);return b=b.replace(/([?&#](?:otp|signature|client_assertion|code_verifier)=)[^&#]*/gi,`$1${Je}`),b=redactCardNumbers(b),b.length>2048&&(b=b.substring(0,2048)),b}}(S,b),x=I.indexOf("?");return-1===x?{url:I,path:I,query:""}:{url:I,path:I.substring(0,x),query:I.substring(x+1).split("#")[0]}}}const it=/\bhttps?:\/\/[^\s"'`<>()[\]{}]+/gi,ot=/[^\s"'`<>()[\]{}?]*\?[^\s"'`<>()[\]{}=&#?]+=[^\s"'`<>()[\]{}]*/g,at=/^(https?:\/\/)[^/?#@\s]*@/i,lt=/([?&#;])([^=&#;]+)=([^&#;]*)/g,ct=/\b([a-z][a-z0-9+.-]{0,31}:\/\/)([^\s"'`<>/?#@:]*):([^\s"'`<>/?#]+)@(?=[^\s"'`<>@/?#])/gi;const ut=/(^|[^A-Za-z0-9_.\-])([A-Za-z0-9_.\-]{1,128})=(?!=)(?:(\[REDACTED\])|"([^"\n]*)"|'([^'\n]*)'|\{((?:[^}\n]|\}\})*)\}|([^\s;&,"'`<>)\]}][^\s;&,"'`<>)\]}]*))/g,ht=/^(?:password|passwd|pwd|pgpassword|[a-z0-9_-]*[_-](?:password|passwd|pwd))$/i,dt=/^[a-z][a-zA-Z0-9]*(?:Password|Passwd|Pwd)$/;function isPasswordKey(S){const b=S.replace(/^-+/,"").split(".").pop();return ht.test(b)||dt.test(b)}function scrubEmbeddedUrl(S){let b=S.replace(at,"$1");return-1!==b.indexOf("=")&&(b=b.replace(lt,(S,b,I,x)=>""===x||x===Je?S:function isSensitiveQueryName(S){return isSensitiveParam(S,Ze)}(function safeDecode(S){try{return decodeURIComponent(S.replace(/\+/g," "))}catch{return S}}(I))?`${b}${I}=${Je}`:S)),b}function sanitizeEventText(S){if("string"!=typeof S||S.length<8)return S;try{let b=S;return-1!==b.indexOf("://")&&(b=b.replace(it,scrubEmbeddedUrl),b=function scrubTextUserinfo(S){if("string"!=typeof S||-1===S.indexOf("://"))return S;const b=S.replace(ct,(S,b,I,x)=>x===Je?S:`${b}${I}:${Je}@`);return b===S?S:b}(b)),-1!==b.indexOf("?")&&-1!==b.indexOf("=")&&(b=b.replace(ot,scrubEmbeddedUrl)),-1!==b.indexOf("=")&&(b=function scrubTextCredentialAssignment(S){if("string"!=typeof S||-1===S.indexOf("=")||!/p(?:ass)?w(?:or)?d/i.test(S))return S;const b=new RegExp(ut.source,"g");let I,x="",R=0;for(;null!==(I=b.exec(S));){const[A,_,D,L,B,U,$,j]=I,W=I.index+_.length+D.length+1;if(void 0!==L)continue;const H=D.replace(/^-+/,"").split(".").pop();if(!isPasswordKey(D)){b.lastIndex=W-1;continue}const V=B??U??$??j;if(""===V||/^\*+$/.test(V))continue;if(void 0!==j&&/^pwd$/i.test(H)&&/^[/~]/.test(V))continue;const Q=void 0!==B?'"':void 0!==U?"'":void 0!==$?"{":"",G=void 0!==B?'"':void 0!==U?"'":void 0!==$?"}":"";x+=S.slice(R,W)+Q+Je+G,R=I.index+A.length}return 0===R?S:x+S.slice(R)}(b)),b=scanSecretValue(b),b===S?S:b}catch{return S}}const gt=["message","stack","source","url","reason","fingerprint"];class SessionRecordingFeature{#o=null;#Be=null;#ze=null;#a=null;#Ue=null;#$e=null;#je=null;#qe=null;#We=!1;#He=!1;#Ve=null;#Qe=0;#Ke=null;#Ge=null;#Je=null;#Xe=null;constructor({logger:S,sdkContext:b,config:I,options:x}){this.#o=S,this.#Be=b,this.#ze=I,this.#a=x}async initialize(S,b){try{console.log("[TraceScout] Loading recording module..."),this.#Ue=await Promise.resolve().then(function(){return gu});const{SessionStorage:I,UploadQueue:x,Recorder:R}=this.#Ue;return this.#je=new I({storageKey:"__tracescout_sessions_v2__",maxStorageSize:2097152,maxSessions:5,logger:this.#o}),console.log("[TraceScout] ✓ Session storage initialized"),!0===this.#a.childMode?(this.#qe=null,console.log("[TraceScout] ⏭️ Upload queue SUPPRESSED (cross-origin child — parent owns the session)")):(this.#qe=this.#Ze(x,S,b),console.log("[TraceScout] ✓ Upload queue initialized"),console.log(` Endpoint: /api/projects/${this.#Be.projectId}/sessions/${this.#Be.sessionId}/chunks`)),this.#$e=this.#Ye(R,S),console.log("[TraceScout] ✓ Session recorder initialized"),await this.#$e.start(),console.log("[TraceScout] ✓ Session recording started"),this.#a.onSessionStart&&this.#a.onSessionStart(this.#Be.sessionId),this.#We=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize session recording:",S),!1}}#Ze(S,b,I){return new S({sdkContext:this.#Be,apiBaseUrl:this.#ze?.apiBaseUrl,backendUrl:this.#ze?.backendUrl,batchSize:b.telemetry?.batchSize||5,maxRetries:3,retryDelay:2e3,enableCompression:!1!==b.telemetry?.enableCompression,enableOfflineQueue:!0,logger:this.#o,onUploadSuccess:(S,b)=>{this.#o?.log(`✅ Chunk ${S.chunkIndex} uploaded successfully`),this.#a.onChunkUploaded&&this.#a.onChunkUploaded(S,b)},onUploadError:(S,b)=>{if(b&&"QUOTA_EXCEEDED"===b.code)return console.error("[TraceScout] ⛔ QUOTA EXCEEDED - Stopping recording"),void this.#Je?.(b);this.#o?.error(`❌ Chunk ${S?.chunkIndex} upload failed:`,b?.message)},onNetworkChange:S=>{this.#o?.log("Network status: "+(S?"online":"offline"))}})}#Ye(S,b){const I=b.features.sessionRecording;return new S({sdkContext:this.#Be,serverSettings:I,emit:S=>this.#et(S),onChunk:S=>{this.#tt(S),this.#qe&&this.#qe.enqueue(S,"normal")},onSessionEnd:S=>{console.log(`[TraceScout] 🛑 Session ended: ${S.reason}`),console.log(` Session ID: ${S.sessionId}`),console.log(` Duration: ${Math.round(S.duration/6e4)}min`),console.log(` Total events: ${S.totalEvents}`),this.#He=!0,this.#Ve=S.reason,this.#a.onSessionEnd&&this.#a.onSessionEnd(S),this.#Ge?.(S)},chunkDuration:I.chunkDuration||3e4,maxChunkSize:I.maxChunkSize||5e5,blockClass:I.blockClass||"ts-block",ignoreClass:I.ignoreClass||"ts-ignore",maskTextClass:I.maskTextClass||"ts-mask",maskAllInputs:I.maskAllInputs||!1,recordCanvas:I.recordCanvas||!1,collectFonts:I.collectFonts||!1,inactivityTimeout:I.inactivityTimeout||3e5,maxInactivityDuration:I.maxInactivityDuration||18e5,maxSessionDuration:I.maxSessionDuration||36e5,enableInactivityDetection:!0,enableSampling:I.enableSampling||!1,enableDeduplication:I.enableDeduplication||!1,mousemoveSampling:I.mousemoveSampling||1,scrollSampling:I.scrollSampling||1,enableStorage:!0,enableCompression:!0,debug:this.#ze.debug||!1,recordCrossOriginIframes:!0===this.#ze.recordCrossOriginIframes,onSpaNavigation:(S,b,I)=>{"function"==typeof this.#Xe&&this.#Xe(S,b,I)}})}#et(S){}#tt(S){const b=Date.now();if(b-this.#Qe>=1e4){const I="number"==typeof S.size?S.size:S.compressedSize||0;this.#o?.log(`Session chunk created: ${S.chunkId} (${S.eventCount} events, ${I} bytes)`),this.#Qe=b}this.#je&&this.#je.storeChunk(S.sessionId,S),this.#Ke?.(S)}setCallbacks({onChunkCreated:S,onSessionEnd:b,onQuotaExceeded:I,onSpaNavigation:x}){this.#Ke=S,this.#Ge=b,this.#Je=I,this.#Xe=x||null}get isAvailable(){return this.#We&&null!=this.#$e}get isRecording(){return this.#$e?.isRecording||!1}get sessionEnded(){return this.#He}get sessionEndReason(){return this.#Ve}get recorder(){return this.#$e}get uploadQueue(){return this.#qe}get sessionStorage(){return this.#je}async start(S={}){if(!this.#$e)return this.#o?.warn("Session recording not enabled"),null;try{const b=this.#$e.start(S),I=this.#$e.getSessionId();return this.#o?.info("Session recording started:",I),{sessionId:I,startTime:Date.now(),status:"recording",stop:b}}catch(S){return this.#o?.error("Failed to start session recording:",S),null}}stop(){if(!this.#$e)return this.#o?.warn("Session recording not enabled"),null;try{this.#$e.stop();const S=this.#$e.getEvents(),b=this.#$e.getSessionId();return this.#o?.info("Session recording stopped:",b),{sessionId:b,startTime:this.#$e.recordingStartTime,duration:Date.now()-this.#$e.recordingStartTime,totalEvents:S.length,events:S,status:"stopped"}}catch(S){return this.#o?.error("Failed to stop session recording:",S),null}}addCustomEvent(S,b){if(!this.#$e)return!1;try{return this.#$e.addCustomEvent(S,b)}catch(S){return!1}}getStatus(){return this.#$e?{available:!0,isRecording:this.#$e.isRecording,sessionId:this.#$e.getSessionId(),eventCount:this.#$e.getEvents().length,startTime:this.#$e.recordingStartTime}:{available:!1,error:"Session recording not enabled"}}getEvents(){return this.#$e?.getEvents()||[]}getChunks(){return this.#$e?.getChunks?.()||[]}getMetadata(){return this.#$e?.getMetadata?.()||{}}getSessionId(){return this.#$e?.getSessionId()}updateSessionId(S){this.#$e&&(this.#$e.sessionId=S),this.#He=!1,this.#Ve=null}updateUploadEndpoint(S){this.#qe&&(this.#qe.config.endpoint=S)}destroy(){if(this.#$e){try{this.#$e.stop()}catch(S){}this.#$e=null}this.#je=null,this.#qe=null,this.#Ue=null,this.#We=!1}}class LogManager{#o=null;#ze=null;#Be=null;#rt=[];#st={};#nt="debug";#it=1e3;#ot=new Map;#at=5e3;#lt=null;#ct=!0;static LOG_LEVELS={debug:0,info:1,warn:2,error:3,fatal:4};constructor(S={},b=null,I=null){this.#ze=S,this.#Be=b,this.#lt=I,this.#o=new Logger("[LogManager]",S.debug),this.#ct=!1!==S.logs?.enabled,this.#nt=S.logs?.minLevel||"debug",this.#it=S.logs?.maxBufferSize||1e3,this.#o.log("LogManager initialized",{enabled:this.#ct,minLevel:this.#nt,maxBufferSize:this.#it})}log(S,b,I={}){if(!this.#ct)return!1;if(!this.#ut(S))return!1;try{const x=this.#ht(S,b,I);return!this.#dt(x)&&(this.#rt.push(x),this.#rt.length>=this.#it&&this.flush(),"error"!==S&&"fatal"!==S||setTimeout(()=>this.flush(),0),!0)}catch(S){return this.#o.error("Failed to log message:",S),!1}}debug(S,b={}){return this.log("debug",S,b)}info(S,b={}){return this.log("info",S,b)}warn(S,b={}){return this.log("warn",S,b)}error(S,b={}){return this.log("error",S,b)}fatal(S,b={}){return this.log("fatal",S,b)}attachContext(S,b){"string"==typeof S?this.#st[S]=b:"object"==typeof S&&Object.assign(this.#st,S),this.#o.log("Context attached:",S)}clearContext(){this.#st={},this.#o.log("Context cleared")}setLogLevel(S){LogManager.LOG_LEVELS.hasOwnProperty(S)?(this.#nt=S,this.#o.log("Log level set to:",S)):this.#o.warn("Invalid log level:",S)}getLogLevel(){return this.#nt}setEnabled(S){this.#ct=S,this.#o.log("Logging",S?"enabled":"disabled")}isEnabled(){return this.#ct}flush(){if(0===this.#rt.length)return[];const S=[...this.#rt];if(this.#rt=[],this.#o.log(`Flushing ${S.length} logs`),this.#lt)try{this.#lt(S)}catch(S){this.#o.error("Error in flush callback:",S)}return S}getQueueSize(){return this.#rt.length}getQueue(){return[...this.#rt]}clearQueue(){const S=this.#rt.length;this.#rt=[],this.#o.log(`Cleared ${S} logs from queue`)}getStats(){const S={queueSize:this.#rt.length,byLevel:{},enabled:this.#ct,minLevel:this.#nt};return this.#rt.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}#ht(S,b,I={}){const x=Date.now(),R=`log_${x}_${generateId()}`,A={source:"undefined"!=typeof process&&process.versions&&process.versions.node?"server":"client",timestamp:x,...this.#gt(),...this.#st};this.#Be&&(A.sessionId=this.#Be.sessionId,A.projectId=this.#Be.projectId,A.environment=this.#Be.environment,this.#Be.userId&&(A.userId=this.#Be.userId));const _=this.#pt(I);return"error"!==S&&"fatal"!==S||!1===this.#ze.logs?.attachStackTrace||_.stack||(_.stack=this.#ft()),{logId:R,timestamp:x,level:S,message:String(b),metadata:_,context:A}}#gt(){const S={};return"undefined"!=typeof window?(S.url=window.location?.href,S.userAgent=navigator?.userAgent,S.platform=navigator?.platform):"undefined"!=typeof process&&(S.platform=process.platform,S.nodeVersion=process.version,S.pid=process.pid),S}#pt(S){if(!S||"object"!=typeof S)return{};const b={};for(const[I,x]of Object.entries(S))if(x instanceof Error)b[I]={name:x.name,message:x.message,stack:x.stack,...x};else if("object"==typeof x&&null!==x)try{JSON.stringify(x),b[I]=x}catch(S){b[I]="[Circular Reference]"}else b[I]=x;return b}#ft(){try{const S=(new Error).stack||"";return S.split("\n").slice(3).join("\n")}catch(S){return"Stack trace unavailable"}}#ut(S){const b=LogManager.LOG_LEVELS[S],I=LogManager.LOG_LEVELS[this.#nt];return void 0===b||void 0===I||b>=I}#dt(S){const b=`${S.level}:${S.message}`,I=Date.now(),x=this.#ot.get(b);return!!(x&&I-x<this.#at)||(this.#ot.set(b,I),this.#ot.size>1e3&&this.#mt(),!1)}#mt(){const S=Date.now();for(const[b,I]of this.#ot.entries())S-I>this.#at&&this.#ot.delete(b)}destroy(){this.flush(),this.#rt=[],this.#st={},this.#ot.clear(),this.#lt=null,this.#o.log("LogManager destroyed")}}function newOperationId(){return`ts-${uuidv4()}`}class LogBuffer{#o=null;#ze=null;#Be=null;#yt=[];#vt=null;#wt=5e3;#St=100;#bt=!1;#Ct=null;#kt=!0;#It=0;static MAX_CONSECUTIVE_FAILURES=5;#Et=null;constructor(S={},b=null,I=null){this.#ze=S,this.#Be=b,this.#Ct=I,this.#o=new Logger("[LogBuffer]",S.debug),this.#wt=S.logs?.flushInterval||5e3,this.#St=S.logs?.maxBatchSize||100,this.#kt=!1!==S.telemetry?.enableCompression,this.#xt(),this.#o.log("LogBuffer initialized",{flushInterval:this.#wt,maxBatchSize:this.#St,compressionEnabled:this.#kt})}add(S){Array.isArray(S)||(S=[S]),this.#yt.push(...S),this.#o.log(`Added ${S.length} logs to buffer. Buffer size: ${this.#yt.length}`),this.#yt.length>=this.#St&&(this.#o.log("Buffer size threshold reached, flushing..."),this.flush())}async flush(){if(this.#bt)return this.#o.log("Already sending, skipping flush"),{success:!1,reason:"Already sending"};if(null===this.#Et&&0===this.#yt.length)return{success:!0,sent:0};if(null===this.#Et){const S=this.#yt.splice(0,this.#St);if(0===S.length)return{success:!0,sent:0};this.#Et={operationId:newOperationId(),logs:S}}const S=this.#Et.logs;this.#o.log(`Flushing ${S.length} logs (operation ${this.#Et.operationId})`);try{this.#bt=!0;const b=this.#Mt(S,this.#Et.operationId);let I=b,x=!1;if(this.#kt&&"function"==typeof this.#Rt)try{I=await this.#Rt(b),x=!0,this.#o.log(`Compressed batch from ${JSON.stringify(b).length} to ${I.length} bytes`)}catch(S){this.#o.warn("Compression failed, sending uncompressed:",S)}return this.#Ct&&await this.#Ct(I,x),this.#o.log(`Successfully sent batch with ${S.length} logs`),this.#It=0,this.#Et=null,{success:!0,sent:S.length}}catch(b){return this.#It++,this.#o.error(`Failed to flush logs (consecutive failures: ${this.#It}):`,b),this.#It>LogBuffer.MAX_CONSECUTIVE_FAILURES?(this.#o.warn(`Dropping batch of ${S.length} logs after ${this.#It} consecutive failures`),this.#Et=null,{success:!1,dropped:S.length,error:b.message}):{success:!1,error:b.message}}finally{this.#bt=!1}}getConsecutiveFailures(){return this.#It}async forceFlush(){this.#Tt();try{await this.flush()}finally{this.#xt()}}getBufferSize(){return this.#yt.length}getStats(){const S={bufferSize:this.#yt.length,isSending:this.#bt,flushInterval:this.#wt,maxBatchSize:this.#St,byLevel:{}};return this.#yt.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}clear(){const S=this.#yt.length;this.#yt=[],this.#o.log(`Cleared ${S} logs from buffer`)}destroy(){this.#Tt(),this.flush().catch(S=>{this.#o.error("Error during final flush:",S)}),this.clear(),this.#o.log("LogBuffer destroyed")}#Mt(S,b){const I=b||newOperationId(),x=Date.now();return{batchId:I,producer:we,timestamp:x,projectId:this.#Be?.projectId,count:S.length,logs:S}}async#Rt(S){const b=JSON.stringify(S);if("undefined"!=typeof CompressionStream)try{const S=new Blob([b]).stream().pipeThrough(new CompressionStream("gzip")),I=await new Response(S).blob(),x=await I.arrayBuffer();return Array.from(new Uint8Array(x))}catch(S){throw this.#o.warn("Browser compression failed:",S),S}throw new Error("Compression not available - CompressionStream not supported")}#xt(){this.#vt||(this.#vt=setInterval(()=>{this.#yt.length>0&&this.flush().catch(S=>{this.#o.error("Auto-flush failed:",S)})},this.#wt),this.#o.log("Auto-flush started"))}#Tt(){this.#vt&&(clearInterval(this.#vt),this.#vt=null,this.#o.log("Auto-flush stopped"))}}class LoggingFeature{#o=null;#Be=null;#ze=null;#At=null;#_t=null;#We=!1;constructor({logger:S,sdkContext:b,config:I}){this.#o=S,this.#Be=b,this.#ze=I}initialize(S){console.log("[TraceScout] Initializing logging system...");try{return this.#At=new LogManager(this.#ze,this.#Be,S=>{this.#_t&&this.#_t.add(S)}),this.#_t=new LogBuffer(this.#ze,this.#Be,async(S,b)=>this.#Ot(S,b)),console.log("[TraceScout] ✓ Logging system initialized"),this.#We=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize logging:",S),!1}}configure(S){try{const b={enabled:S.debug||!1,level:S.logLevel||"info",showTimestamps:!1!==S.showLogTimestamps,showServiceIcons:!1!==S.showServiceIcons};S.logging&&"object"==typeof S.logging&&(b.services=S.logging),$.configure(b),S.enabledLogServices&&Array.isArray(S.enabledLogServices)?$.enableServices(S.enabledLogServices,S.logLevel||"info"):S.debug&&$.enableServices(["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager"],S.logLevel||"info"),this.#o?.log("Logging system configured successfully")}catch(S){this.#o?.error("Failed to configure logging system:",S)}}async#Ot(S,b){if(!this.#Be)throw new Error("SDK not initialized");const I=this.#Be.projectId,x=`${resolveApiBaseUrl(this.#ze)}/api/projects/${I}/logs/batch`;try{const I={};b?(I["Content-Type"]="application/octet-stream",I["Content-Encoding"]="gzip"):I["Content-Type"]="application/json";const R=await fetch(x,{method:"POST",headers:I,body:b?new Blob([new Uint8Array(S)]):JSON.stringify(S)});if(!R.ok)throw new Error(`HTTP ${R.status}: ${R.statusText}`);const A=await R.json();return this.#o?.log("Log batch sent successfully"),A}catch(S){throw this.#o?.error("Failed to send log batch:",S),S}}get isAvailable(){return this.#We&&null!=this.#At}get logManager(){return this.#At}get logBuffer(){return this.#_t}log(S,b,I={}){return!!this.#At&&this.#At.log(S,b,I)}debug(S,b={}){return this.#At?.debug(S,b)||!1}info(S,b={}){return this.#At?.info(S,b)||!1}warn(S,b={}){return this.#At?.warn(S,b)||!1}error(S,b={}){return this.#At?.error(S,b)||!1}fatal(S,b={}){return this.#At?.fatal(S,b)||!1}setContext(S,b){return!!this.#At&&(this.#At.attachContext(S,b),!0)}clearContext(){return!!this.#At&&(this.#At.clearContext(),!0)}setLogLevel(S){return!!this.#At&&(this.#At.setLogLevel(S),!0)}getStats(){return this.#At?{manager:this.#At.getStats(),buffer:this.#_t?this.#_t.getStats():null}:null}async flush(){if(!this.#_t)return!1;try{return await this.#_t.forceFlush(),!0}catch(S){return this.#o?.error("Failed to flush logs:",S),!1}}enableServices(S,b="info"){try{return $.enableServices(S,b),!0}catch(S){return this.#o?.error("Failed to enable logging:",S),!1}}disableServices(S){try{return $.disableServices(S),!0}catch(S){return this.#o?.error("Failed to disable logging:",S),!1}}enableAll(S="info"){try{return $.enableAll(S),!0}catch(S){return this.#o?.error("Failed to enable all logging:",S),!1}}disableAll(){try{return $.disableAll(),!0}catch(S){return this.#o?.error("Failed to disable all logging:",S),!1}}getConfig(){try{return $.getConfig()}catch(S){return this.#o?.error("Failed to get logging config:",S),null}}getEnabledServices(){try{return $.getEnabledServices()}catch(S){return[]}}getAvailableServices(){return["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager","UserProfileManager","PerformanceMonitor","FetchInterceptor","XHRInterceptor","ResourceInterceptor","PostMessageInterceptor","CoreWebVitalsMonitor","Recorder","SessionStorage","UploadQueue","CDN-Loader","Replayer","Validation","BaseService"]}destroy(){this.#_t&&(this.#_t.destroy(),this.#_t=null),this.#At&&(this.#At.destroy(),this.#At=null),this.#We=!1}}class ConsoleInterceptor{constructor(S,b={},I=null,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),this.realmConsole=x&&x.console?x.console:"undefined"!=typeof console?console:void 0,this.logManager=null,this.config={captureLog:!1!==b.captureLog,captureWarn:!1!==b.captureWarn,captureError:!1!==b.captureError,captureInfo:!1!==b.captureInfo,captureDebug:!1!==b.captureDebug,captureTrace:!1!==b.captureTrace,maxMessageLength:b.maxMessageLength||5e3,maxArgSize:b.maxArgSize||2e3,maxTotalArgsSize:b.maxTotalArgsSize||1e4,...b},this.logger=createLogger("ConsoleInterceptor"),this.originalMethods={},this.installed=!1}setLogManager(S){this.logManager=S,this.logger.debug("LogManager attached to ConsoleInterceptor")}install(){if(this.installed)return;const S=[];this.config.captureLog&&S.push("log"),this.config.captureWarn&&S.push("warn"),this.config.captureError&&S.push("error"),this.config.captureInfo&&S.push("info"),this.config.captureDebug&&S.push("debug"),this.config.captureTrace&&S.push("trace");const b=this.realmConsole;S.forEach(S=>{this.originalMethods[S]=b[S],b[S]=this.createInterceptor(S)}),this.installed=!0,this.logger.debug("Console interceptor installed")}uninstall(){if(!this.installed)return;const S=this.realmConsole;Object.keys(this.originalMethods).forEach(b=>{S[b]=this.originalMethods[b]}),this.originalMethods={},this.installed=!1,this.logger.debug("Console interceptor uninstalled")}createInterceptor(S){const b=this;return function(...I){b.originalMethods[S].apply(b.realmConsole,I);const x=I[0];if("string"!=typeof x||!(x.includes("[TraceScout]")||x.includes("[Recorder]")||x.includes("[SDK]")||x.includes("[ConsoleInterceptor]")||x.includes("[NetworkInterceptor]")||x.includes("[FetchInterceptor]")||x.includes("[XHRInterceptor]")||x.includes("[SessionManager]")||x.includes("[UploadQueue]")||x.includes("[ErrorHandler]")||x.includes("TraceScoutMonitoringCore")))try{const x=sanitizeEventText(b.formatMessage(I)),R=Date.now(),A=b.getLevel(S),_=b.processArgs(I),D=Array.isArray(_)?_.map(sanitizeEventText):_,L={method:S,args:D,source:"console"};if("error"!==S&&"trace"!==S||(L.stack=sanitizeEventText(b.captureStackTrace())),b.logManager&&"function"==typeof b.logManager.log)try{const I=b.truncateMessage(x),R=b.mapToLogLevel(S);b.logManager.log(R,I,L)}catch(S){}const B={type:"console",category:"console",method:S,message:b.truncateMessage(x),timestamp:R,level:A,args:D};if("error"!==S&&"trace"!==S||(B.stack=L.stack),b.eventManager&&"function"==typeof b.eventManager.logEvent&&b.eventManager.logEvent("console",B),b.reporter&&b.reporter.addSessionCustomEvent&&"function"==typeof b.reporter.addSessionCustomEvent)try{b.reporter.addSessionCustomEvent("console",{method:S,message:B.message,args:B.args,level:B.level,stack:B.stack,timestamp:B.timestamp})}catch(S){}}catch(S){}}}formatMessage(S){return S.map(S=>{if(null===S)return"null";if(void 0===S)return"undefined";if("object"==typeof S)try{return safeStringify(S,5,this.config.maxArgSize)}catch{return"[Unserializable Object]"}return"string"==typeof S&&S.length>this.config.maxArgSize?S.substring(0,this.config.maxArgSize)+"... [truncated]":String(S)}).join(" ")}processArgs(S){if(this.config.captureArgs)return safeParseConsoleArgs(S,this.config.maxArgSize,this.config.maxTotalArgsSize)}truncateMessage(S){return S.length>this.config.maxMessageLength?S.substring(0,this.config.maxMessageLength)+"...":S}getLevel(S){return{log:"log",info:"info",warn:"warn",error:"error",debug:"debug",trace:"trace"}[S]||"log"}mapToLogLevel(S){return{log:"info",info:"info",warn:"warn",error:"error",debug:"debug",trace:"debug"}[S]||"info"}captureStackTrace(){return(new Error).stack||""}}const pt=["authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-csrf-token","x-xsrf-token","api-key","apikey","x-amz-security-token","x-ms-client-principal","proxy-authorization","www-authenticate","x-goog-api-key","x-functions-key","x-session-token","x-session-id","x-refresh-token","x-id-token","x-client-secret","x-access-key","x-secret-key","x-auth","x-token","x-user-email","x-email"],ft="[REDACTED]";function filterSensitiveHeaders(S,b=[]){if(!S)return{};const I={},x=new Set([...pt,...b.map(S=>S.toLowerCase())]);if(S instanceof Headers||S.forEach&&"function"==typeof S.forEach)S.forEach((S,b)=>{const R=b.toLowerCase();I[b]=x.has(R)?ft:scanHeaderValue(S)});else if("object"==typeof S)for(const[b,R]of Object.entries(S)){const S=b.toLowerCase();I[b]=x.has(S)?ft:scanHeaderValue(R)}return I}function scanHeaderValue(S){return"string"==typeof S?scanSecretValue(S):S}function isSensitiveHeader(S){return!!S&&pt.includes(S.toLowerCase())}function getSensitiveHeadersList(){return[...pt]}function createSensitiveHeaderSet(S=[]){return new Set([...pt,...S.map(S=>S.toLowerCase())])}const mt=[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".woff",".woff2",".ttf",".eot",".ico",".webp",".avif"],yt=["text/css","text/javascript","application/javascript","image/","font/","application/font","application/x-font"],vt=[/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|ico|webp|avif)(\?|$)/i,/\/static\//i,/\/assets\//i,/\/images\//i,/\/fonts\//i,/\/_next\/static\//i,/\/webpack\//i,/\/node_modules\//i];function isStaticResource(S,b=""){if(!S)return!1;if(mt.some(b=>S.toLowerCase().includes(b)))return!0;const I=yt.some(S=>b.toLowerCase().startsWith(S));return!!I||vt.some(b=>b.test(S))}function getResourceType(S,b=""){const I=S.toLowerCase(),x=b.toLowerCase();return I.includes(".js")||x.includes("javascript")?"script":I.includes(".css")||x.includes("text/css")?"stylesheet":/\.(woff2?|ttf|eot|otf)(\?|$)/i.test(S)||x.includes("font")?"font":/\.(png|jpg|jpeg|gif|svg|ico|webp|avif)(\?|$)/i.test(S)||x.includes("image")?"image":"other"}function isApiEndpoint(S){if(!S)return!1;const b=S.toLowerCase();return!![/\/api\//i,/\/v\d+\//i,/\/graphql/i,/\/rest\//i,/\/rpc\//i,/\.json(\?|$)/i].some(S=>S.test(b))||!isStaticResource(S)}const wt=1e4;function parseFormData(S){try{const b=new URLSearchParams(S),I={};for(const[S,x]of b)I[S]=x;return I}catch(S){return null}}function createTruncatedBody(S,b,I="body"){return{_truncated:!0,_originalSize:S.length,_message:`${I} body truncated (${S.length} bytes, limit ${b} bytes)`,_preview:S.substring(0,b)+"...",_tip:"Enable full body capture in project settings if needed"}}function handleRequestBody(S,b={}){const{maxSize:I=wt,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Request");try{const S=JSON.parse(b),x=JSON.stringify(S);return x.length>I?createTruncatedBody(x,I,"Request"):S}catch{const S=parseFormData(b);return S||b}}else{if(b instanceof FormData){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if(b instanceof URLSearchParams){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Request"):b}}}catch(S){x("Failed to parse request data:",S)}return null}function handleResponseBody(S,b={}){const{maxSize:I=wt,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Response");try{b=JSON.parse(b)}catch{return b}}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Response"):b}return b}catch(S){x("Failed to parse response data:",S)}return null}const St="[REDACTED]",bt=10240,Ct=65536,kt=["password","passwd","pwd","secret","token","access_token","refresh_token","id_token","authorization","auth","api_key","apikey","x-api-key","cookie","session","sessionid","session_id","sid","jwt","bearer","credential","credentials","private_key","client_secret","card","cardnumber","card_number","cvv","cvc","pin","ssn","social_security","dob","date_of_birth","email","phone","address"];function utf8Bytes(S){return"string"!=typeof S||0===S.length?0:(new TextEncoder).encode(S).length}function truncateToBytes(S,b){const I=new TextEncoder,x=I.encode(S),R=x.length;if(R<=b)return{text:S,truncated:!1,capturedBytes:R,originalBytes:R};if(b<=0)return{text:"",truncated:!0,capturedBytes:0,originalBytes:R};const A=x.subarray(0,b);let _=new TextDecoder("utf-8",{fatal:!1}).decode(A);_.length&&65533===_.charCodeAt(_.length-1)&&(_=_.slice(0,-1));return{text:_,truncated:!0,capturedBytes:I.encode(_).length,originalBytes:R}}function safeMime(S){if(!S||"string"!=typeof S)return null;const b=S.split(";")[0].trim().toLowerCase();return b&&/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(b)?b.length>128?b.slice(0,128):b:null}function classifyMime(S){return S?"application/json"===S||"application/ld+json"===S||"application/graphql"===S||"application/graphql+json"===S||S.endsWith("+json")?"json":"application/x-www-form-urlencoded"===S?"form":"image/svg+xml"===S||"application/xml"===S||"text/xml"===S||"application/xhtml+xml"===S||"application/javascript"===S||"application/x-javascript"===S||"text/javascript"===S||S.startsWith("text/")?"text":S.startsWith("image/")||S.startsWith("audio/")||S.startsWith("video/")||S.startsWith("font/")||"application/octet-stream"===S||"application/zip"===S||"application/gzip"===S||"application/pdf"===S||"application/x-protobuf"===S||"application/protobuf"===S||S.startsWith("multipart/")?"binary":"unknown":"unknown"}function isTextualContentType(S){const b=classifyMime(safeMime(S));return"json"===b||"form"===b||"text"===b}function buildFieldDenylist(S=[]){const b=new Set(kt);if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.add(I.toLowerCase());return b}function isSensitiveField(S,b){const I=String(S).toLowerCase();for(const S of b)if(I.includes(S))return!0;return!1}function redactObject(S,b){let I=!1;const walk=S=>{if(Array.isArray(S))return S.map(walk);if(S&&"object"==typeof S){const x={};for(const R of Object.keys(S))isSensitiveField(R,b)?(x[R]=St,I=!0):x[R]=walk(S[R]);return x}if("string"==typeof S){const b=redactCardNumbersInText(S);return b.redacted&&(I=!0),b.text}return isCardNumberValue(S)?(I=!0,St):S};return{value:walk(S),redacted:I}}function redactCardNumbersDeep(S){try{const walk=(S,b)=>{if(b>64)return S;if("string"==typeof S)return redactCardNumbersInText(S).text;if(isCardNumberValue(S))return St;if(Array.isArray(S))return S.map(S=>walk(S,b+1));if(S&&"object"==typeof S&&Object.getPrototypeOf(S)===Object.prototype){const I={};for(const x of Object.keys(S))I[x]=walk(S[x],b+1);return I}return S};return walk(S,0)}catch{return null}}function redactFormUrlEncoded(S,b){let I;try{I=new URLSearchParams(S)}catch{return{text:S,redacted:!1}}let x=!1;const R=new URLSearchParams;for(const[S,A]of I){if(isSensitiveField(S,b)){R.append(S,St),x=!0;continue}const I=redactCardNumbersInText(A);I.redacted&&(x=!0),R.append(S,I.text)}return{text:R.toString(),redacted:x}}function rawBodyBinarySize(S){return"undefined"!=typeof Blob&&S instanceof Blob&&"number"==typeof S.size?S.size:"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(S)?S.byteLength:null}function makeResult({state:S,contentType:b=null,originalBytes:I=null,redacted:x=!1}){return{text:null,state:S,redacted:!!x,truncated:!1,originalBytes:"number"==typeof I&&I>=0?I:null,capturedBytes:null,contentType:b||null}}function runSanitizer(S,b){try{return{threw:!1,value:S(b)}}catch{return{threw:!0}}}function safeToString(S){try{return"string"==typeof S?S:JSON.stringify(S)}catch{return String(S)}}function finalizeText(S,{mime:b,maxBytes:I,redacted:x}){const{text:R,truncated:A,capturedBytes:_,originalBytes:D}=truncateToBytes(S,I);let L;return L=A?"truncated":x?"redacted":"captured",{text:R,state:L,redacted:!!x,truncated:A,originalBytes:D,capturedBytes:_,contentType:b||null}}function finalizeStructured(S,{redacted:b,mime:I,maxBytes:x,sanitizer:R}){let A,_=S;if(R){const x=runSanitizer(R,S);if(x.threw)return makeResult({state:"failed",contentType:I,redacted:b});if(null===x.value||void 0===x.value)return makeResult({state:"excluded",contentType:I});_=x.value}try{A=JSON.stringify(_)}catch{return makeResult({state:"failed",contentType:I,redacted:b})}return void 0===A&&(A=""),finalizeText(A,{mime:I,maxBytes:x,redacted:b})}function captureText(S,{mime:b,maxBytes:I,sanitizer:x}){const R=redactCardNumbersInText(S);let A=R.text;if(x){const S=runSanitizer(x,A);if(S.threw)return makeResult({state:"failed",contentType:b,redacted:R.redacted});if(null===S.value||void 0===S.value)return makeResult({state:"excluded",contentType:b});A="string"==typeof S.value?S.value:safeToString(S.value)}return finalizeText(A,{mime:b,maxBytes:I,redacted:R.redacted})}function captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const{text:A,redacted:_}=redactFormUrlEncoded(S,x);let D=A;if(R){const S=runSanitizer(R,D);if(S.threw)return makeResult({state:"failed",contentType:b,redacted:_});if(null===S.value||void 0===S.value)return makeResult({state:"excluded",contentType:b});D="string"==typeof S.value?S.value:safeToString(S.value)}return finalizeText(D,{mime:b,maxBytes:I,redacted:_})}function captureStringByMime(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const A=classifyMime(b);if("binary"===A||"unknown"===A)return makeResult({state:"binary",contentType:b,originalBytes:utf8Bytes(S)});if("form"===A)return captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R});if("json"===A){let A;try{A=JSON.parse(S)}catch{return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}const{value:_,redacted:D}=redactObject(A,x);return finalizeStructured(_,{redacted:D,mime:b,maxBytes:I,sanitizer:R})}return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}function normalizeOpts(S){let b="number"==typeof S.maxBytes&&S.maxBytes>=0?S.maxBytes:bt;return b>Ct&&(b=Ct),{maxBytes:b,denylist:S.denylist instanceof Set?S.denylist:buildFieldDenylist(S.sensitiveFields),sanitizer:"function"==typeof S.sanitizer?S.sanitizer:null,captureEnabled:!1!==S.captureEnabled,excluded:!0===S.excluded}}function captureRequestBody(S,b={}){const I=safeMime(b.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(null==S||""===S)return makeResult({state:"unavailable",contentType:I});try{if("undefined"!=typeof FormData&&S instanceof FormData){const{obj:b,redacted:_}=function sanitizeFormData(S,b){let I=!1;const x={};for(const[R,A]of S.entries()){let S;if("undefined"!=typeof File&&A instanceof File||"undefined"!=typeof Blob&&A instanceof Blob)S={_type:"file",mime:safeMime(A.type)||null,bytes:"number"==typeof A.size?A.size:null};else if(isSensitiveField(R,b))S=St,I=!0;else{const b=redactCardNumbersInText(String(A));b.redacted&&(I=!0),S=b.text}Object.prototype.hasOwnProperty.call(x,R)?Array.isArray(x[R])?x[R].push(S):x[R]=[x[R],S]:x[R]=S}return{obj:x,redacted:I}}(S,R);return finalizeStructured(b,{redacted:_,mime:I||"multipart/form-data",maxBytes:x,sanitizer:A})}if("undefined"!=typeof URLSearchParams&&S instanceof URLSearchParams)return captureFormString(S.toString(),{mime:I||"application/x-www-form-urlencoded",maxBytes:x,denylist:R,sanitizer:A});if(function isBinaryRawBody(S){return"undefined"!=typeof Blob&&S instanceof Blob||"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||!("undefined"==typeof ArrayBuffer||!ArrayBuffer.isView||!ArrayBuffer.isView(S))||"undefined"!=typeof ReadableStream&&S instanceof ReadableStream}(S))return makeResult({state:"binary",contentType:I||(L=S,"undefined"!=typeof Blob&&L instanceof Blob&&L.type?safeMime(L.type):null),originalBytes:rawBodyBinarySize(S)});if("string"==typeof S)return captureStringByMime(S,{mime:I,maxBytes:x,denylist:R,sanitizer:A});if("object"==typeof S){const{value:b,redacted:_}=redactObject(S,R);return finalizeStructured(b,{redacted:_,mime:I||"application/json",maxBytes:x,sanitizer:A})}return captureStringByMime(String(S),{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}var L}function captureResponseBody(S={},b={}){const I=safeMime(S.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(S.opaque)return makeResult({state:"inaccessible",contentType:I});if(S.readError)return makeResult({state:"failed",contentType:I});if(S.binary){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}const L=classifyMime(I);if("binary"===L||"unknown"===L){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}if(S.empty||null===S.text||void 0===S.text||""===S.text)return makeResult({state:"unavailable",contentType:I});try{return captureStringByMime(S.text,{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}}class InterceptorLogger{constructor(S,b=!1){let I=S.replace(/^\[|\]$/g,"").replace(":","");I="xhrinterceptor"===I.toLowerCase()?"XHRInterceptor":I.charAt(0).toUpperCase()+I.slice(1),this.serviceLogger=createLogger(I),this.prefix=S,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class BaseInterceptor{constructor(S,b,I){this.reporter=S,this.interceptorName=b,this.realm=I||("undefined"!=typeof window?window:void 0),this.logger=new InterceptorLogger(`[${this.interceptorName}Interceptor]`,this.reporter.config?.debug||!1)}updateDebugMode(S){this.logger.updateDebugMode(S)}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!1}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isStaticResource(S,b=""){return isStaticResource(S,b)}isResourceUrl(S,b=""){return isStaticResource(S,b)}getResourceType(S,b=""){return getResourceType(S,b)}extractRequestDetails(S,b,I,x,R){const A=parseUrl(S);return{method:b.toUpperCase(),url:S,domain:A.hostname,path:A.pathname,status:I,statusText:x,response:redactCardNumbersDeep(R),interceptor:this.interceptorName}}logEvent(S){const b=S?.url||S?.request?.url;if(b&&isInternalSdkEndpoint(b))return;if(this.reporter?._sessionRecorder?.isRecording||this.reporter?.sessionRecording?.isRecording)return;const I={id:generateId(),timestamp:Date.now(),...S};this.reporter.logEvent&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(I)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("string"==typeof S&&0===S.indexOf("network")){const S=this.reporter.config&&this.reporter.config.network;if(S&&!1===S.isEnabled)return!1}const I=b?.url||b?.request?.url;if(I&&isInternalSdkEndpoint(I))return!1;if(!this.reporter.addSessionCustomEvent)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateUserProfileFromContext({url:S,source:b,data:I}){try{if(this.reporter.extractUserContextFromBody&&"function"==typeof this.reporter.extractUserContextFromBody){const x=this.reporter.extractUserContextFromBody({url:S,source:b,data:I});if(Object.keys(x).length>0){let S={};this.reporter._getUserProfile&&"function"==typeof this.reporter._getUserProfile?S=this.reporter._getUserProfile():this.reporter.getUserProfile&&"function"==typeof this.reporter.getUserProfile&&(S=this.reporter.getUserProfile());const b={...S,...x};JSON.stringify(S)!==JSON.stringify(b)&&this.reporter.setUserProfile&&"function"==typeof this.reporter.setUserProfile&&this.reporter.setUserProfile(b)}}}catch(S){this.logger.warn("Failed to update user profile context:",S)}}getNetworkConfig(){const S=this.reporter&&this.reporter.config&&this.reporter.config.network||{};let b="number"==typeof S.maxBodyBytes?S.maxBodyBytes:bt;b>=0||(b=bt),b>Ct&&(b=Ct);const I=Array.isArray(S.sensitiveFields)?S.sensitiveFields:[];return{isEnabled:!1!==S.isEnabled,captureRequestHeaders:!1!==S.captureRequestHeaders,captureResponseHeaders:!1!==S.captureResponseHeaders,captureRequestBody:!1!==S.captureRequestBody,captureResponseBody:!1!==S.captureResponseBody,maxBodyBytes:b,excludeEndpoints:Array.isArray(S.excludeEndpoints)?S.excludeEndpoints:[],requestSanitizer:"function"==typeof S.requestSanitizer?S.requestSanitizer:null,responseSanitizer:"function"==typeof S.responseSanitizer?S.responseSanitizer:null,sensitiveFields:I,_denylist:buildFieldDenylist(I)}}isEndpointExcluded(S,b){const I=b&&b.excludeEndpoints||[],x=String(S||"");for(const S of I)try{if(S instanceof RegExp){if(S.test(x))return!0}else if("string"==typeof S&&S&&x.includes(S))return!0}catch{}return!1}sanitizeRequestUrlFields(S,b){try{return splitSanitizedUrl(S,{extraParams:b&&b.sensitiveFields||[]})}catch{return{url:String(S||""),path:"",query:""}}}mapCaptureToFields(S,b){const I={};return I[`${b}Body`]="string"==typeof S.text?S.text:null,I[`${b}BodyState`]=S.state,I[`${b}BodyRedacted`]=!!S.redacted,I[`${b}BodyTruncated`]=!!S.truncated,"number"==typeof S.originalBytes&&(I[`${b}BodySize`]=S.originalBytes),"number"==typeof S.capturedBytes&&(I[`${b}BodyCapturedBytes`]=S.capturedBytes),S.contentType&&(I[`${b}BodyContentType`]=S.contentType),I}buildRequestBodyFields(S,b,I,x){const R=captureRequestBody(S,{contentTypeHeader:b,maxBytes:I.maxBodyBytes,denylist:I._denylist,sanitizer:I.requestSanitizer,captureEnabled:I.captureRequestBody,excluded:x});return this.mapCaptureToFields(R,"request")}buildResponseBodyFields(S,b,I){const x=captureResponseBody(S,{maxBytes:b.maxBodyBytes,denylist:b._denylist,sanitizer:b.responseSanitizer,captureEnabled:b.captureResponseBody,excluded:I});return this.mapCaptureToFields(x,"response")}handleRequestData(S,b){return handleRequestBody(b,{maxSize:wt,onWarn:(...S)=>this.logger.warn(...S)})}handleResponseData(S,b){return handleResponseBody(b,{maxSize:wt,onWarn:(...S)=>this.logger.warn(...S)})}createEvent(S,b,I,x,R,A=null,_=null,D={}){const L={type:S,context:{url:b,method:I.toUpperCase(),status:x,statusText:R,requestData:this.handleRequestData(b,A),responseData:this.handleResponseData(b,_),isMonitored:this.shouldMonitor(b),...D}};return this.shouldExtractFields(b,"response")&&_&&this.updateUserProfileFromContext({url:b,source:"response",data:_}),L}logErrorEvent(S,b,I,x,R=null,A=null,_={}){S=this.sanitizeRequestUrlFields(S,this.getNetworkConfig()).url;const D={type:_.errorType||`${this.interceptorName}_http_error`,request:this.extractRequestDetails(S,b,I,x,A),extraData:_,context:{isMonitored:this.shouldMonitor(S),forceLog:I>=400,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}handleSilentLoginFailure(S,b,I,x,R,A){(S=this.sanitizeRequestUrlFields(S,this.getNetworkConfig()).url).toLowerCase().includes("/myava/login")&&(I>=200&&I<300)&&null==R?.LoginToken&&this.logEvent({type:A,request:this.extractRequestDetails(S,b,I,x,R),extraData:redactCardNumbersDeep(R)})}logCustomApiError(S,b,I,x,R,A,_={}){S=this.sanitizeRequestUrlFields(S,this.getNetworkConfig()).url;const D={type:"custom_api_error",request:this.extractRequestDetails(S,b,I,x,R),extraData:{errorCondition:A,..._},context:{isMonitored:this.shouldMonitor(S),forceLog:!0,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}logUnknownError(S,b,I,x={}){const R={type:"unknown_error",request:{method:b||"UNKNOWN",url:S||"unknown",domain:S?this.extractDomain(S):"unknown",path:S?this.extractPath(S):"unknown",status:0,statusText:"Unknown Error",response:{error:I?.message||"Unknown error occurred",stack:I?.stack||""},interceptor:this.interceptorName},extraData:{errorType:I?.name||"UnknownError",errorMessage:I?.message||"Unknown error",...x},context:{forceLog:!0,isMonitored:!0,scriptOrigin:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logEvent(R)}extractDomain(S){try{return new URL(S,this.realm?.location?.origin).hostname}catch{return"unknown"}}extractPath(S){try{return new URL(S,this.realm?.location?.origin).pathname}catch{return"unknown"}}destroy(){this.reporter=null,this.logger=null}}function getHeader(S,b){if(!S)return null;const I=b.toLowerCase();if(S instanceof Headers)return S.get(I);for(const b in S)if(b.toLowerCase()===I)return S[b];return null}function setHeader(S,b,I){if(!S)return;if(S instanceof Headers)return void S.set(b,I);const x=b.toLowerCase();for(const b in S)b.toLowerCase()===x&&delete S[b];S[b]=I}function hasHeader(S,b){if(!S)return!1;const I=b.toLowerCase();if(S instanceof Headers)return S.has(I);for(const b in S)if(b.toLowerCase()===I)return!0;return!1}const It=/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/,Et=/^0+$/;function readTraceContextFromHeaders(S){return function parseTraceparent(S){if("string"!=typeof S)return null;const b=S.match(It);if(!b)return null;const I=b[1],x=b[2];return Et.test(I)||Et.test(x)?null:{traceId:I,spanId:x}}(function readTraceparentFromHeaders(S){if(!S)return null;if("undefined"!=typeof Headers&&S instanceof Headers){const b=S.get("traceparent");return"string"==typeof b?b:null}if("object"==typeof S)for(const b of Object.keys(S))if("traceparent"===b.toLowerCase()){const I=S[b];return"string"==typeof I?I:null}return null}(S))}function isSameOrigin(S,b,I){const x=function resolveOrigin(S,b){try{const I=b||"undefined"!=typeof window&&window.location&&window.location.href||void 0;return new URL(S,I).origin}catch{return null}}(S,I),R=function currentOrigin(S){return S||("undefined"!=typeof window&&window.location?window.location.origin:null)}(b);return null!==x&&null!==R&&x===R}function tracePropagationDecision(S,b={}){const{pageOrigin:I,pageHref:x}=b;return"string"==typeof S&&isInternalSdkEndpoint(S)?{traceparent:!1,baggage:!1,reason:"sdk_ingest_excluded"}:isSameOrigin(S,I,x)?{traceparent:!0,baggage:!0,reason:"same_origin"}:{traceparent:!1,baggage:!1,reason:"third_party"}}const xt="undefined"!=typeof window&&window.fetch?window.fetch.bind(window):void 0;class FetchInterceptor extends BaseInterceptor{constructor(S,b){super(S,"fetch",b),this.originalFetch=this.realm&&this.realm.fetch?this.realm.fetch.bind(this.realm):xt}setup(){this.logger.log("Initializing Fetch interceptor...");const S=this,b=this.realm;b._apiReporter_originalFetch||(b._apiReporter_originalFetch=this.originalFetch),b.fetch=async function(...I){I=S.injectCorrelationHeaders(I);const x=b.Request,R=b.Headers,A=x&&I[0]instanceof x?I[0].url:String(I[0]),_=I[1]||{},D=_.method||(x&&I[0]instanceof x?I[0].method:"GET"),L=_.body;let B={};x&&I[0]instanceof x?I[0].headers.forEach((S,b)=>{B[b]=S}):_.headers&&(R&&_.headers instanceof R?_.headers.forEach((S,b)=>{B[b]=S}):Object.assign(B,_.headers));const U=filterSensitiveHeaders(B),$=S.shouldMonitor(A),j=S.isStaticResource(A);let W=null;$&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&(W=S.reporter.performanceMonitor.generateRequestId(),S.reporter.performanceMonitor.startTracking(W,A,D));const H=Date.now();if(!j){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(A,b),x=S.sanitizeRequestUrlFields(A,b),R=getHeader(B,"content-type"),_=S.buildRequestBodyFields(L,R,b,I),$={interceptor:"fetch",method:D,url:x.url,requestHeaders:b.captureRequestHeaders?U:{},timestamp:H,..._};x.path&&($.requestPath=x.path),x.query&&($.requestQuery=x.query);const j=readTraceContextFromHeaders(B);j&&($.traceId=j.traceId,$.spanId=j.spanId),S.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing API request:",{url:x.url,hasHeaders:!!U&&Object.keys(U).length>0,bodyState:_.requestBodyState}),S.addToSessionReplay("network_request",$)}try{const x=await S.originalFetch.apply(b,I);let R=null;return W&&(R=S.reporter.performanceMonitor.endTracking(W,x.status)),await S.handleResponse(x,A,D,R),x}catch(b){throw W&&S.reporter.performanceMonitor.endTracking(W,0),S.handleNetworkError(A,D,b,"fetch_network_error"),b}},this.logger.log("Fetch interceptor setup complete")}async handleResponse(S,b,I,x){const R=this.getNetworkConfig(),A=this.isEndpointExcluded(b,R);let _=null,D=!1;try{_=S.clone()}catch{D=!0}const L="opaque"===S.type,B=_&&_.headers&&_.headers.get("content-type")||"",U={};_&&_.headers&&_.headers.forEach((S,b)=>{U[b]=S});const $=R.captureResponseHeaders?filterSensitiveHeaders(U):{},j=_&&_.headers?_.headers.get("content-length"):null,W=j?parseInt(j,10):null;let H=null,V=!1,Q=null;const G=!L&&!D&&isTextualContentType(B);if(G){try{H=await _.text()}catch{V=!0}if(!V&&null!=H){const S=safeMime(B);if(S&&"json"===classifyMime(S))try{Q=JSON.parse(H)}catch{Q=H}else Q=H}}else D&&!L&&(V=!0);const J=this.buildResponseBodyFields({opaque:L,readError:V,text:G?H:null,contentTypeHeader:B,knownSize:W},R,A),X=this.isStaticResource(b,B);!X&&x?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,Q,x),x?.performanceAlert&&this.logPerformanceAlert(x.metrics),X?this.handleStaticResource(b,I,S.status,S.statusText,B,x,_||S):this.handleApiResponse(b,I,S.status,S.statusText,Q,x,$,J,R)}handleStaticResource(S,b,I,x,R,A,_){const D=_.headers?.get("content-length"),L=D?parseInt(D,10):null,B=this.sanitizeRequestUrlFields(S,this.getNetworkConfig()).url,U={interceptor:"fetch",method:b,url:B,status:I,statusText:x,resourceType:this.getResourceType(S,R),size:L,duration:A?.duration||null,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing static resource:",{url:B,status:I,resourceType:U.resourceType,size:L}),this.addToSessionReplay("network_resource",U),I>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(S,b,I,x,null,null,{errorType:"resource_load_error",contentType:R,resourceType:U.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"fetch",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing response:",{url:U.url,status:I,hasHeaders:!!_&&Object.keys(_).length>0,bodyState:$.responseBodyState}),this.addToSessionReplay("network_response",$),I>=400?this.logErrorEvent(S,b,I,x,null,R,{errorType:"fetch_http_error",performanceData:A}):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"fetch_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"fetch_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logger.log(`Slow request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"fetch",method:b,url:R.url,status:0,statusText:"Network Error",errorMessage:I.message||"Network request failed",errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,"Network Error",null,null,{errorType:x,errorMessage:I.message||"Network request failed",errorStack:I.stack})}destroy(){const S=this.realm;S&&S._apiReporter_originalFetch&&(S.fetch=S._apiReporter_originalFetch,delete S._apiReporter_originalFetch),super.destroy()}injectCorrelationHeaders(S){const b=SDKContext.getInstance();if(!b||!b.sessionId)return S;const I=this.realm,x=I.Request,R=I.Headers,A=tracePropagationDecision(x&&S[0]instanceof x?S[0].url:String(S[0]));if(!A.traceparent&&!A.baggage)return S;const _=[];if(A.baggage&&(b.sessionId&&_.push(`sessionId=${encodeURIComponent(b.sessionId)}`),b.userId&&_.push(`userId=${encodeURIComponent(b.userId)}`),b.projectId&&_.push(`projectId=${encodeURIComponent(b.projectId)}`)),x&&S[0]instanceof x){const b=S[0],I=S[1]||{},D=new R(b.headers);if(I.headers)if(R&&I.headers instanceof R)I.headers.forEach((S,b)=>D.set(b,S));else for(const S in I.headers)D.set(S,I.headers[S]);const L=hasHeader(D,"traceparent");A.baggage&&_.length>0&&!getHeader(D,"baggage")&&setHeader(D,"baggage",_.join(",")),A.traceparent&&!L&&setHeader(D,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`);const B={...I};delete B.headers;return[new x(b,{...B,headers:D})]}const D=S[0],L=S[1]||{};if(L.headers=L.headers||{},R&&L.headers instanceof R){const S={};L.headers.forEach((b,I)=>{S[I]=b}),L.headers=S}const B=hasHeader(L.headers,"traceparent");return A.baggage&&_.length>0&&!getHeader(L.headers,"baggage")&&setHeader(L.headers,"baggage",_.join(",")),A.traceparent&&!B&&setHeader(L.headers,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`),[D,L]}generateW3CTraceId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}class XHRInterceptor extends BaseInterceptor{constructor(S,b){super(S,"xhr",b),this.XHR=this.realm&&this.realm.XMLHttpRequest?this.realm.XMLHttpRequest:XMLHttpRequest,this.originalOpen=this.XHR.prototype.open,this.originalSend=this.XHR.prototype.send}setup(){this.logger.log("Initializing XHR interceptor...");const S=this,b=this.XHR.prototype;b.open=function(b,I,...x){return this._apiReporterUrl=I,this._apiReporterMethod=b.toUpperCase(),this._apiReporterRequestHeaders={},this._apiReporterUserSetHeaders=new Set,this._apiReporterHeadersInjected=!1,S.originalOpen.call(this,b,I,...x)};const I=b.setRequestHeader;this._originalSetRequestHeader=I,b.setRequestHeader=function(S,b){return this._apiReporterRequestHeaders||(this._apiReporterRequestHeaders={}),this._apiReporterUserSetHeaders||(this._apiReporterUserSetHeaders=new Set),this._apiReporterUserSetHeaders.add(S.toLowerCase()),setHeader(this._apiReporterRequestHeaders,S,b),I.call(this,S,b)},b.send=function(...b){const I=this;if(!I._apiReporterHeadersInjected){const b=I._apiReporterUserSetHeaders?.has("traceparent");S.injectXHRCorrelationHeaders(I,b),I._apiReporterHeadersInjected=!0}const{_apiReporterUrl:x,_apiReporterMethod:R,_apiReporterRequestHeaders:A}=I,_=filterSensitiveHeaders(A||{}),D=S.shouldMonitor(x),L=S.isStaticResource(x),B=b[0],U=Date.now();I._apiReporterStartTime=U,S.logger.log(`XHR Request: ${R} ${x}, shouldMonitor: ${D}, isResource: ${L}`);let $=null;if(D&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&($=S.reporter.performanceMonitor.generateRequestId(),I._apiReporterRequestId=$,S.reporter.performanceMonitor.startTracking($,x,R)),!L){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(x,b),D=S.sanitizeRequestUrlFields(x,b),L=getHeader(A||{},"content-type"),$=S.buildRequestBodyFields(B,L,b,I),j={interceptor:"xhr",method:R,url:D.url,requestHeaders:b.captureRequestHeaders&&_||{},timestamp:U,...$};D.path&&(j.requestPath=D.path),D.query&&(j.requestQuery=D.query);const W=readTraceContextFromHeaders(A);W&&(j.traceId=W.traceId,j.spanId=W.spanId),S.addToSessionReplay("network_request",j)}return I.addEventListener("load",()=>S.handleXHRLoad(I,x,R,L)),I.addEventListener("error",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Network error"),"xhr_network_error")}),I.addEventListener("timeout",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request timed out"),"xhr_timeout_error")}),I.addEventListener("abort",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request aborted"),"xhr_aborted_error")}),S.originalSend.apply(I,b)},this.logger.log("XHR interceptor setup complete")}handleXHRLoad(S,b,I,x){let R=null;S._apiReporterRequestId&&(R=this.reporter.performanceMonitor.endTracking(S._apiReporterRequestId,S.status));const A=S.getResponseHeader("content-type")||"",_=R?.duration||(S._apiReporterStartTime?Date.now()-S._apiReporterStartTime:null);if(x)return void this.handleStaticResource(S,b,I,A,_);const D=this.getNetworkConfig(),L=this.isEndpointExcluded(b,D);let B=null,U=null;try{const b=S.responseType;if(""===b||"text"===b){const b=S.responseText||null;if(B={text:b,contentTypeHeader:A},b){const S=safeMime(A);if(S&&"json"===classifyMime(S))try{U=JSON.parse(b)}catch{U=b}else U=b}}else if("json"===b){const b=S.response;U=b;let I=null;try{I=null==b?null:JSON.stringify(b)}catch{I=null}B={text:I,contentTypeHeader:A||"application/json"}}else{const I=S.getResponseHeader("content-length");B={binary:!0,contentTypeHeader:A,knownSize:I?parseInt(I,10):null},U=`[${String(b).toUpperCase()} data]`}}catch(S){this.logger.warn(`Failed to read XHR response for ${b}`),B={readError:!0,contentTypeHeader:A},U={error:"Failed to read response",originalError:S.message}}const $=this.parseXHRResponseHeaders(S.getAllResponseHeaders?.()),j=D.captureResponseHeaders?filterSensitiveHeaders($):{},W=this.buildResponseBodyFields(B,D,L);R?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,U,R),R?.performanceAlert&&this.logPerformanceAlert(R.metrics),this.handleApiResponse(b,I,S.status,S.statusText,U,R,j,W,D)}parseXHRResponseHeaders(S){const b={};if(!S||"string"!=typeof S)return b;for(const I of S.trim().split(/[\r\n]+/)){const S=I.indexOf(":");if(-1===S)continue;const x=I.slice(0,S).trim(),R=I.slice(S+1).trim();x&&(b[x]=R)}return b}handleStaticResource(S,b,I,x,R){const A=S.getResponseHeader("content-length"),_=A?parseInt(A,10):null,D=this.sanitizeRequestUrlFields(b,this.getNetworkConfig()).url,L={interceptor:"xhr",method:I,url:D,status:S.status,statusText:S.statusText,resourceType:this.getResourceType(b,x),size:_,duration:R,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[XHRInterceptor] Capturing static resource:",{url:D,status:S.status,resourceType:L.resourceType,size:_}),this.addToSessionReplay("network_resource",L),S.status>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(b,I,S.status,S.statusText,null,null,{errorType:"resource_load_error",contentType:x,resourceType:L.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){this.logger.log(`Handling API response: ${b} ${S}, status: ${I}`);const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"xhr",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.addToSessionReplay("network_response",$),I>=400?(this.logger.log(`Logging error event for: ${S} with status ${I}`),this.logErrorEvent(S,b,I,x,null,R,{errorType:"xhr_http_error",performanceData:A})):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"xhr_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"xhr_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logger.log(`Slow XHR request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"xhr",method:b,url:R.url,status:0,statusText:I.message||"Network Error",errorMessage:I.message,errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,I.message,null,null,{errorType:x,errorMessage:I.message,errorStack:I.stack})}destroy(){this.XHR.prototype.open=this.originalOpen,this.XHR.prototype.send=this.originalSend,this._originalSetRequestHeader&&(this.XHR.prototype.setRequestHeader=this._originalSetRequestHeader),super.destroy()}injectXHRCorrelationHeaders(S,b){const I=SDKContext.getInstance();if(!I||!I.sessionId)return;const x=tracePropagationDecision(String(S._apiReporterUrl||""));if(x.traceparent||x.baggage){if(x.baggage&&!getHeader(S._apiReporterRequestHeaders,"baggage")){const b=[];I.sessionId&&b.push(`sessionId=${encodeURIComponent(I.sessionId)}`),I.userId&&b.push(`userId=${encodeURIComponent(I.userId)}`),I.projectId&&b.push(`projectId=${encodeURIComponent(I.projectId)}`),b.length>0&&S.setRequestHeader("baggage",b.join(","))}if(x.traceparent&&!b){const b=`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`;S.setRequestHeader("traceparent",b)}}}generateW3CTraceId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}class ResourceInterceptor{constructor(S){this.reporter=S,this.interceptorName="resource",this.logger=createLogger("ResourceInterceptor"),this.boundErrorHandler=this.handleResourceError.bind(this),this.isDestroyed=!1}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed ResourceInterceptor"):(window.addEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor setup complete"))}handleResourceError(S){if(this.isDestroyed)return;const b=S.target;if(b instanceof HTMLScriptElement||b instanceof HTMLLinkElement||b instanceof HTMLImageElement){const S=b.src||b.href||"",I=b.tagName.toLowerCase(),x=parseUrl(S),R={type:"resource_load_error",request:{method:"GET",url:S,domain:x.hostname||this.#Dt(S),path:x.pathname||this.#Ft(S),status:0,statusText:"Resource failed to load",response:`${I} element failed to load`,headers:{},interceptor:"resource"},extraData:{tag:I,elementType:b.constructor.name,errorType:"resource_load_failure",resourceType:this.#Nt(I),crossOrigin:this.#Lt(S),isDomElement:!0,integrity:b.integrity||null,crossorigin:b.crossOrigin||null,async:b.async||!1,defer:b.defer||!1,rel:b.rel||null,type:b.type||null},context:{forceLog:!0,isMonitored:this.shouldMonitor(S),scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logger.log(`Creating resource error event: ${S} [${I}]`),this.reporter&&this.reporter.logEvent?(this.reporter.logEvent(R),this.logger.log(`Resource error event sent for: ${S}`)):this.logger.error("Could not send resource error - reporter.logEvent not available"),this.logger.log(`Resource failed to load: ${S} [${I}]`)}}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!0}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}#Dt(S){try{return new URL(S,location.origin).hostname}catch{return""}}#Ft(S){try{return new URL(S,location.origin).pathname}catch{return""}}#Nt(S){switch(S.toLowerCase()){case"script":return"javascript";case"link":return"stylesheet";case"img":return"image";case"video":return"video";case"audio":return"audio";case"source":return"media-source";case"track":return"text-track";case"object":return"object";case"embed":return"embed";case"iframe":return"iframe";default:return"unknown"}}#Lt(S){try{return new URL(S,location.origin).origin!==location.origin}catch{return!1}}destroy(){this.isDestroyed?this.logger.warn("ResourceInterceptor already destroyed"):(this.isDestroyed=!0,window.removeEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor destroyed"),this.reporter=null,this.boundErrorHandler=null)}}const Mt=["token","access_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","password","pwd","secret","email","jwt","bearer","refresh_token","id_token"];class LRUDedupeCache{constructor(S=5e3){this.maxSize=S,this.cache=new Map}has(S){if(this.cache.has(S)){const b=this.cache.get(S);return this.cache.delete(S),this.cache.set(S,b),!0}return!1}add(S){if(this.cache.has(S))this.cache.delete(S);else if(this.cache.size>=this.maxSize){const S=this.cache.keys().next().value;this.cache.delete(S)}this.cache.set(S,!0)}clear(){this.cache.clear()}get size(){return this.cache.size}}class PerformanceResourceObserver{constructor(S,b={},I=null){this.reporter=S,this.realm=I||("undefined"!=typeof window?window:void 0),this.logger=createLogger("PerformanceResourceObserver"),this.config={captureResources:!1!==b.captureResources,captureNavigation:!1!==b.captureNavigation,maxDedupeEntries:b.maxDedupeEntries||5e3,filterOtherInitiator:!1!==b.filterOtherInitiator,debug:b.debug||this.reporter?.config?.debug||!1,maxResourceEntriesPerSession:b.maxResourceEntriesPerSession||2e3,resourceAllowlist:b.resourceAllowlist||null,resourceBlocklist:b.resourceBlocklist||null},this.allowlistRegexes=this.compilePatterns(this.config.resourceAllowlist),this.blocklistRegexes=this.compilePatterns(this.config.resourceBlocklist),this.resourceObserver=null,this.navigationObserver=null,this.processedEntries=new LRUDedupeCache(this.config.maxDedupeEntries),this.isDestroyed=!1,this.sessionResourceCount=0,this.sessionCapReached=!1,this.eventCount=0,this.eventCountResetTime=Date.now(),this.maxEventsPerMinute=this.reporter?.config?.maxEventsPerMinute||500}compilePatterns(S){if(!S||!Array.isArray(S)||0===S.length)return null;try{return S.map(S=>new RegExp(S,"i"))}catch(S){return this.logger?.warn?.("Invalid regex pattern in allowlist/blocklist:",S.message),null}}passesUrlFilters(S){if(this.blocklistRegexes)for(const b of this.blocklistRegexes)if(b.test(S))return!1;if(this.allowlistRegexes){for(const b of this.allowlistRegexes)if(b.test(S))return!0;return!1}return!0}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed PerformanceResourceObserver"):this.realm&&void 0!==this.realm.PerformanceObserver?(this.config.captureResources&&this.setupResourceObserver(),this.config.captureNavigation&&this.setupNavigationObserver(),this.logger.log("PerformanceResourceObserver setup complete",{captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation})):this.logger.warn("PerformanceObserver not supported in this browser")}setupResourceObserver(){try{this.resourceObserver=new this.realm.PerformanceObserver(S=>{for(const b of S.getEntries())this.processResourceEntry(b)}),this.resourceObserver.observe({type:"resource",buffered:!0}),this.logger.log("Resource observer initialized")}catch(S){this.logger.warn("Failed to setup resource observer:",S.message)}}setupNavigationObserver(){try{this.navigationObserver=new this.realm.PerformanceObserver(S=>{for(const b of S.getEntries())this.processNavigationEntry(b)}),this.navigationObserver.observe({type:"navigation",buffered:!0}),this.logger.log("Navigation observer initialized")}catch(S){this.logger.warn("Failed to setup navigation observer:",S.message)}}processResourceEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(this.sessionResourceCount>=this.config.maxResourceEntriesPerSession)return void(this.sessionCapReached||(this.sessionCapReached=!0,this.logger.warn(`Session resource cap reached (${this.config.maxResourceEntriesPerSession}). Stopping resource capture.`)));if(!this.checkRateLimit())return;const b=S.initiatorType;if("fetch"===b||"xmlhttprequest"===b)return;if(this.config.filterOtherInitiator&&"other"===b){const b=(S.transferSize||S.encodedBodySize||S.decodedBodySize)>0,I=S.duration>10;if(!b&&!I)return}if(!this.passesUrlFilters(S.name))return;const I=`${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(I))return;this.processedEntries.add(I);const x=this.sanitizeUrl(S.name),R=this.mapInitiatorType(b,S.name),A=this.extractTimingPhases(S),_={interceptor:"performance",method:"GET",url:x,status:this.getResponseStatus(S),resourceType:R,initiatorType:b,duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:A,timestamp:Math.round((this.realm?.performance?.timeOrigin||0)+S.startTime)};this.addToSessionReplay("network_resource",_)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured resource:",{url:x.substring(0,80),type:R,duration:_.duration,cached:_.cached,sessionCount:this.sessionResourceCount})}processNavigationEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(!this.checkRateLimit())return;const b=`nav-${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(b))return;this.processedEntries.add(b);const I=this.sanitizeUrl(S.name),x=this.extractTimingPhases(S),R={dns:x.dns,tcp:x.tcp,ssl:x.ssl,ttfb:Math.round(S.responseStart-S.requestStart),download:Math.round(S.responseEnd-S.responseStart),domInteractive:Math.round(S.domInteractive-S.responseEnd),domContentLoaded:Math.round(S.domContentLoadedEventEnd-S.responseEnd),loadComplete:Math.round(S.loadEventEnd-S.startTime)},A={interceptor:"performance",method:"GET",url:I,status:this.getResponseStatus(S),resourceType:"document",initiatorType:"navigation",duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:R,navigationType:S.type,timestamp:Math.round((this.realm?.performance?.timeOrigin||0)+S.startTime)};this.addToSessionReplay("network_resource",A)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured navigation:",{url:I.substring(0,80),type:S.type,loadTime:R.loadComplete,sessionCount:this.sessionResourceCount})}sanitizeUrl(S){if(!S)return S;try{const b=new URL(S);for(const S of Mt){b.searchParams.has(S)&&b.searchParams.delete(S);for(const[I]of b.searchParams.entries())I.toLowerCase()===S.toLowerCase()&&b.searchParams.delete(I)}return b.hash="",scrubUrlValues(b.toString(),{mode:"delete"})}catch(b){const I=redactCardNumbers(S);return I.length>500?I.substring(0,500):I}}mapInitiatorType(S,b=""){const I={script:"script",link:"stylesheet",css:"stylesheet",img:"image",image:"image",font:"font",video:"media",audio:"media",iframe:"document",navigation:"document",beacon:"beacon"};if(I[S]){if("link"===S){const S=b.toLowerCase();return S.includes(".css")?"stylesheet":S.includes(".woff")||S.includes(".ttf")||S.includes(".eot")?"font":"stylesheet"}return I[S]}return getResourceType(b,"")}extractTimingPhases(S){return{dns:Math.max(0,Math.round(S.domainLookupEnd-S.domainLookupStart)),tcp:Math.max(0,Math.round(S.connectEnd-S.connectStart)),ssl:S.secureConnectionStart>0?Math.max(0,Math.round(S.connectEnd-S.secureConnectionStart)):0,ttfb:Math.max(0,Math.round(S.responseStart-S.requestStart)),download:Math.max(0,Math.round(S.responseEnd-S.responseStart)),total:Math.round(S.duration)}}getResponseStatus(S){return"number"==typeof S.responseStatus?S.responseStatus:0===S.duration&&0===S.transferSize&&0===S.decodedBodySize?0:200}isCached(S){return 0===S.transferSize&&S.decodedBodySize>0||S.domainLookupEnd===S.domainLookupStart&&S.connectEnd===S.connectStart&&S.requestStart>0}checkRateLimit(){const S=Date.now();return S-this.eventCountResetTime>6e4&&(this.eventCount=0,this.eventCountResetTime=S),!(this.eventCount>=this.maxEventsPerMinute)&&(this.eventCount++,!0)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}updateConfig(S){void 0!==S.captureResources&&S.captureResources!==this.config.captureResources&&(this.config.captureResources=S.captureResources,S.captureResources&&!this.resourceObserver?this.setupResourceObserver():!S.captureResources&&this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null)),void 0!==S.captureNavigation&&S.captureNavigation!==this.config.captureNavigation&&(this.config.captureNavigation=S.captureNavigation,S.captureNavigation&&!this.navigationObserver?this.setupNavigationObserver():!S.captureNavigation&&this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null)),void 0!==S.debug&&(this.config.debug=S.debug),void 0!==S.maxDedupeEntries&&(this.config.maxDedupeEntries=S.maxDedupeEntries),void 0!==S.filterOtherInitiator&&(this.config.filterOtherInitiator=S.filterOtherInitiator)}getStats(){return{dedupeEntriesCount:this.processedEntries.size,maxDedupeEntries:this.config.maxDedupeEntries,eventsThisMinute:this.eventCount,maxEventsPerMinute:this.maxEventsPerMinute,captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation,resourceObserverActive:!!this.resourceObserver,navigationObserverActive:!!this.navigationObserver,sessionResourceCount:this.sessionResourceCount,maxResourceEntriesPerSession:this.config.maxResourceEntriesPerSession,sessionCapReached:this.sessionCapReached,hasAllowlist:!!this.allowlistRegexes,hasBlocklist:!!this.blocklistRegexes}}destroy(){this.isDestroyed?this.logger.warn("PerformanceResourceObserver already destroyed"):(this.isDestroyed=!0,this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null),this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null),this.processedEntries.clear(),this.reporter=null,this.logger.log("PerformanceResourceObserver destroyed"))}}class ErrorFingerprint{constructor(S={}){this.maxUniqueErrors=S.maxUniqueErrors||100,this.throttleWindow=S.throttleWindow||6e4,this.maxPerFingerprint=S.maxPerFingerprint||5,this.seenFingerprints=new Map,this.cleanupInterval=null,this.startCleanup()}generateFingerprint(S){if(!S)return"unknown_error";return sanitizeEventText(`${this.getErrorName(S)}::${this.normalizeMessage(this.getErrorMessage(S))}::${this.getFirstMeaningfulStackLine(S.stack)}`)}getErrorName(S){return S.name?S.name:S.constructor&&S.constructor.name?S.constructor.name:S.type?S.type:"Error"}getErrorMessage(S){return"string"==typeof S?S:S.message?S.message:S.reason?String(S.reason):String(S)}normalizeMessage(S){return S&&"string"==typeof S?S.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"[UUID]").replace(/\b(0x)?[0-9a-f]{8,}\b/gi,"[HEX]").replace(/\b\d+\b/g,"[N]").replace(/https?:\/\/[^\s'"]+/gi,"[URL]").replace(/\/[\w./-]+\.(js|ts|jsx|tsx|mjs|cjs)/gi,"[PATH]").replace(/"[^"]*"/g,"[STR]").replace(/'[^']*'/g,"[STR]").replace(/[\w.+-]+@[\w.-]+\.\w+/gi,"[EMAIL]").replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,"[IP]").replace(/\s+/g," ").substring(0,200).trim():""}getFirstMeaningfulStackLine(S){if(!S||"string"!=typeof S)return"unknown";const b=[/tracescout/i,/rrweb/i,/node_modules/,/<anonymous>/,/native code/i,/eval at/i,/^\s*at\s*$/],I=S.split("\n");for(const S of I){if(!S.trim()||S.match(/^[\w]*Error:/))continue;if(b.some(b=>b.test(S)))continue;const I=S.match(/(?:at\s+)?(?:[\w.<>[\]]+\s+\()?([^()\s]+):(\d+):(\d+)\)?/);if(I){const[,S,b,x]=I;return`${S.split("/").pop().split("\\").pop()}:${b}:${x}`}const x=S.match(/@([^@]+):(\d+):(\d+)/);if(x){const[,S,b,I]=x;return`${S.split("/").pop().split("\\").pop()}:${b}:${I}`}}return"unknown"}shouldCapture(S){const b=Date.now(),I=this.seenFingerprints.get(S);if(!I)return this.seenFingerprints.set(S,{count:1,firstSeen:b,lastSeen:b,windowStart:b}),this.seenFingerprints.size>this.maxUniqueErrors&&this.evictOldest(),{shouldCapture:!0,count:1,isFirst:!0};if(b-I.windowStart>this.throttleWindow)return I.count=1,I.windowStart=b,I.lastSeen=b,{shouldCapture:!0,count:1,isFirst:!1};I.count++,I.lastSeen=b;const x=I.count<=this.maxPerFingerprint;return{shouldCapture:x,count:I.count,isFirst:!1,throttled:!x}}getStats(S){return this.seenFingerprints.get(S)||null}getAllStats(){const S=[];return this.seenFingerprints.forEach((b,I)=>{S.push({fingerprint:I,...b})}),S.sort((S,b)=>b.count-S.count)}evictOldest(){let S=null,b=1/0;this.seenFingerprints.forEach((I,x)=>{I.lastSeen<b&&(b=I.lastSeen,S=x)}),S&&this.seenFingerprints.delete(S)}startCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanup()},3e5)}cleanup(){const S=Date.now(),b=2*this.throttleWindow;this.seenFingerprints.forEach((I,x)=>{S-I.lastSeen>b&&this.seenFingerprints.delete(x)})}reset(){this.seenFingerprints.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.seenFingerprints.clear()}}class ErrorHandler{constructor(S,b={},I=null,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),this.config={captureErrors:!1!==b.captureErrors,captureUnhandledRejections:!1!==b.captureUnhandledRejections,maxStackTraceLength:b.maxStackTraceLength||5e3,filterErrors:b.filterErrors||[],enableFingerprinting:!1!==b.enableFingerprinting,maxUniqueErrors:b.maxUniqueErrors||100,throttleWindow:b.throttleWindow||6e4,maxPerFingerprint:b.maxPerFingerprint||5,...b},this.logger=createLogger("ErrorHandler"),this.originalHandlers={},this.installed=!1,this.config.enableFingerprinting&&(this.fingerprinter=new ErrorFingerprint({maxUniqueErrors:this.config.maxUniqueErrors,throttleWindow:this.config.throttleWindow,maxPerFingerprint:this.config.maxPerFingerprint}))}install(){if(this.installed)return;const S=this.realm;this.config.captureErrors&&(this.originalHandlers.onerror=S.onerror,S.onerror=this.handleError.bind(this)),this.config.captureUnhandledRejections&&(this.originalHandlers.onunhandledrejection=S.onunhandledrejection,this._boundRejectionHandler=this.handleUnhandledRejection.bind(this),S.addEventListener("unhandledrejection",this._boundRejectionHandler)),this.installed=!0,this.logger.debug("Error handler installed")}uninstall(){if(!this.installed)return;const S=this.realm;this.config.captureErrors&&(S.onerror=this.originalHandlers.onerror||null),this.config.captureUnhandledRejections&&(this._boundRejectionHandler&&(S.removeEventListener("unhandledrejection",this._boundRejectionHandler),this._boundRejectionHandler=null),this.originalHandlers.onunhandledrejection&&(S.onunhandledrejection=this.originalHandlers.onunhandledrejection)),this.fingerprinter&&this.fingerprinter.destroy(),this.originalHandlers={},this.installed=!1,this.logger.debug("Error handler uninstalled")}handleError(S,b,I,x,R){try{if(this.shouldFilterError(S,R))return;let A=null,_=null;if(this.fingerprinter&&(A=this.fingerprinter.generateFingerprint(R||{message:S,stack:`at ${b}:${I}:${x}`}),_=this.fingerprinter.shouldCapture(A),!_.shouldCapture))return _.count===this.config.maxPerFingerprint+1&&this.logger.debug(`Error throttled: "${S.substring(0,50)}..." (${_.count} occurrences)`),this.originalHandlers.onerror?this.originalHandlers.onerror(S,b,I,x,R):void 0;SDKContext.getInstance()?.recordError();const D={type:"error",category:"error",message:sanitizeEventText(String(S)),source:sanitizeEventText(b),lineno:I,colno:x,stack:sanitizeEventText(this.getStackTrace(R)),timestamp:Date.now(),userAgent:this.realm?.navigator?.userAgent,url:sanitizeEventText(this.realm?.location?.href),fingerprint:A,occurrenceCount:_?.count||1,isFirstOccurrence:_?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",D),console.log("[TraceScout][ErrorHandler] Checking reporter:",{hasReporter:!!this.reporter,hasMethod:!(!this.reporter||!this.reporter.addSessionCustomEvent),isFunction:!(!this.reporter||"function"!=typeof this.reporter.addSessionCustomEvent)}),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{console.log("[TraceScout][ErrorHandler] Adding error to session replay:",D.message),this.reporter.addSessionCustomEvent("error",{message:D.message,stack:D.stack,fingerprint:D.fingerprint,source:D.source,lineno:D.lineno,colno:D.colno,timestamp:D.timestamp,url:D.url,userAgent:D.userAgent,occurrenceCount:D.occurrenceCount,isFirstOccurrence:D.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture error:",S)}if(this.originalHandlers.onerror)return this.originalHandlers.onerror(S,b,I,x,R)}handleUnhandledRejection(S){try{const b=S.reason;let I=null,x=null;if(this.fingerprinter&&(I=this.fingerprinter.generateFingerprint(b||{message:"Unhandled Promise Rejection"}),x=this.fingerprinter.shouldCapture(I),!x.shouldCapture)){if(x.count===this.config.maxPerFingerprint+1){const S=b?String(b).substring(0,50):"Promise rejection";this.logger.debug(`Promise rejection throttled: "${S}..." (${x.count} occurrences)`)}return void(this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S))}SDKContext.getInstance()?.recordError();const R={type:"unhandledRejection",category:"error",message:sanitizeEventText(b?String(b):"Unhandled Promise Rejection"),stack:sanitizeEventText(this.getStackTrace(b)),promiseState:"rejected",timestamp:Date.now(),userAgent:this.realm?.navigator?.userAgent,url:sanitizeEventText(this.realm?.location?.href),fingerprint:I,occurrenceCount:x?.count||1,isFirstOccurrence:x?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",R),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{this.reporter.addSessionCustomEvent("unhandledRejection",{message:R.message,stack:R.stack,fingerprint:R.fingerprint,timestamp:R.timestamp,url:R.url,userAgent:R.userAgent,occurrenceCount:R.occurrenceCount,isFirstOccurrence:R.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture unhandled rejection:",S)}this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S)}shouldFilterError(S,b){return this.config.filterErrors.some(I=>"string"==typeof I?S.includes(I):I instanceof RegExp?I.test(S):"function"==typeof I&&I(S,b))}getStackTrace(S){if(!S)return"";let b="";return S.stack?b=S.stack:S instanceof Error&&(b=S.toString()),b.length>this.config.maxStackTraceLength&&(b=b.substring(0,this.config.maxStackTraceLength)+"..."),b}getErrorStats(){return this.fingerprinter?this.fingerprinter.getAllStats():[]}resetErrorTracking(){this.fingerprinter&&this.fingerprinter.reset()}}function initializeErrorHandler(S,b={}){const I=new ErrorHandler(S,b);return I.install(),I}class PostMessageInterceptor{constructor(S){this.reporter=S,this.logger=createLogger("PostMessageInterceptor"),this.originalPostMessage=window.postMessage,this.boundMessageHandler=this.handleMessage.bind(this),this.messageCounter=0,this.suspiciousOrigins=[],this.errorCount=0,this.isDestroyed=!1,this.config=null,this.whitelist=[]}setup(){if(this.isDestroyed)return void this.logger.warn("Attempted to setup destroyed PostMessageMonitor");this.logger.log("Initializing PostMessage monitor...");const S=this;this.config=this.reporter.config?.monitorPostMessages||{},this.whitelist=this.config.postMessageOriginWhitelist||[],window.postMessage=function(b,I,...x){const R=window.location.origin;if(S.shouldMonitor(I,"outgoing",b)){const x=S.getEventType(b);S.logger.log(`Outgoing PostMessage [${x}]: ${R} -> ${I}`),S.logPostMessage({direction:"outgoing",message:b,targetOrigin:I,sourceOrigin:R,eventType:x})}return S.originalPostMessage.call(this,b,I,...x)},window.addEventListener("message",this.boundMessageHandler),this.logger.log("PostMessage monitor setup complete")}handleMessage(S){if(!this.isDestroyed)try{if(this.shouldMonitor(S.origin,"incoming",S.data)){const b=this.getEventType(S.data);this.logger.log(`Incoming PostMessage [${b}]: ${S.origin} -> ${window.location.origin}`),this.logPostMessage({direction:"incoming",message:S.data,sourceOrigin:S.origin,targetOrigin:window.location.origin,source:this.getSourceInfo(S.source),eventType:b}),this.shouldExtractFields("postmessage","message")&&this.extractUserData(S.origin,S.data)}}catch(b){this.logger.error("Error handling message:",b),this.logPostMessageError(S,b)}}shouldMonitor(S,b,I){if(!this.config||"object"!=typeof this.config)return!1;if(this.whitelist.length>0&&!this.isOriginWhitelisted(S))return!1;const x=this.getEventType(I),R=(this.config.excludePostMessagesEvents||[]).includes(x),A=this.config.monitorSpecificPostMessagesEvents||[];return!R&&(0===A.length||A.includes(x))}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isOriginWhitelisted(S){if(this.whitelist.includes("*"))return!0;if("null"===S&&this.whitelist.includes("null"))return!0;try{const b=new URL(S).hostname.toLowerCase();return this.whitelist.some(I=>{const x=I.toLowerCase();return x.includes("://")?S.toLowerCase()===x:b===x||b.endsWith(`.${x}`)})}catch{return this.whitelist.includes(S)}}getEventType(S){if(null==S)return"null_message";let b=S;if("string"==typeof S)try{b=JSON.parse(S)}catch{return"string_message"}if("object"!=typeof b)return typeof b+"_message";const I=["event_type","type","action","event","command","method"];for(const S of I)if(b[S])return String(b[S]);return!0===b.init?"init":!0===b.ready?"ready":b.resize?"resize":void 0!==b.height?"height_update":"object_message"}getSourceInfo(S){try{return S===window?"same-window":S===window.parent?"parent-window":S===window.opener?"opener-window":S===window.top?"top-window":S instanceof Window?"other-window":S instanceof MessagePort?"message-port":S instanceof ServiceWorker?"service-worker":"unknown-source"}catch{return"unknown-source"}}logPostMessage(S){const b=this.parseMessage(S.message),I=S.sourceOrigin!==S.targetOrigin,x=this.getSize(S.message),R=x>1e4,A=this.isSuspiciousOrigin(S.sourceOrigin);let _="postmessage_communication";I&&(_="postmessage_cross_origin"),R&&(_="postmessage_large_payload"),A&&(_="postmessage_suspicious_origin",this.trackSuspiciousOrigin(S.sourceOrigin));const D={type:_,request:{method:"POSTMESSAGE",url:"outgoing"===S.direction?S.targetOrigin:S.sourceOrigin,domain:this.getDomain("outgoing"===S.direction?S.targetOrigin:S.sourceOrigin),path:null,status:null,statusText:null,response:b,interceptor:"postMessage"},extraData:{messageId:`pm_${S.direction}_${Date.now()}_${++this.messageCounter}`,direction:S.direction,sourceOrigin:S.sourceOrigin,targetOrigin:S.targetOrigin,messageSize:x,messageType:typeof S.message,detectedEventType:S.eventType,source:S.source||"unknown",isCrossOrigin:I,isLargePayload:R,isSuspicious:A,hasTransferables:S.transferables?.length>0||!1},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(D)}logPostMessageError(S,b){const I={type:"postmessage_error",request:{method:"POSTMESSAGE",url:S?.origin||"unknown",domain:this.getDomain(S?.origin||"unknown"),path:null,status:0,statusText:"PostMessage Error",response:{error:b.message,stack:b.stack},interceptor:"postMessage"},extraData:{errorCount:++this.errorCount,sourceOrigin:S?.origin||"unknown",targetOrigin:window.location.origin,errorType:b.name||"Error",errorMessage:b.message,errorStack:b.stack},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(I)}logEvent(S){this.reporter&&this.reporter.logEvent?this.reporter.logEvent(S):this.logger.error("Could not log event - reporter.logEvent not available")}parseMessage(S){if("string"==typeof S)try{return JSON.parse(S)}catch{return S.length>1e3?S.substring(0,1e3)+"...":S}try{return JSON.stringify(S),S}catch{return"[Circular or Complex Object]"}}getSize(S){try{return"string"==typeof S?S.length:JSON.stringify(S).length}catch{return-1}}getDomain(S){try{return"*"===S||"null"===S||"file://"===S?S:new URL(S).hostname}catch{return"unknown"}}isSuspiciousOrigin(S){if(!S||"null"===S||"file://"===S)return!0;if(this.whitelist.length>0&&!this.whitelist.includes("*")&&!this.isOriginWhitelisted(S))return!0;if("https:"===window.location.protocol&&"https://localhost"!==S&&!S.startsWith("https://"))return!0;const b=this.suspiciousOrigins.filter(b=>b===S).length;return b>100}trackSuspiciousOrigin(S){this.suspiciousOrigins.push(S),this.suspiciousOrigins.length>1e3&&(this.suspiciousOrigins=this.suspiciousOrigins.slice(-1e3))}extractUserData(S,b){try{const I=this.parseMessage(b);I&&"object"==typeof I&&this.reporter.updateUserProfileFromContext&&this.reporter.updateUserProfileFromContext({url:`postmessage://${S}`,source:"message",data:I})}catch(S){this.logger.warn("Failed to extract user data:",S)}}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}destroy(){this.isDestroyed?this.logger.warn("PostMessageMonitor already destroyed"):(this.isDestroyed=!0,this.originalPostMessage&&(window.postMessage=this.originalPostMessage),window.removeEventListener("message",this.boundMessageHandler),this.reporter=null,this.boundMessageHandler=null,this.suspiciousOrigins=[],this.logger.log("PostMessage monitor destroyed"))}}const Rt="ts-top";class IframeInstrumentationManager{#ye=null;#ze=null;#o=null;#j=null;#Pt=Symbol("__tsIframeInstalled__");#te=!1;#Le=new Map;#Bt=[];#zt=[];#Z=new WeakSet;#G=new WeakMap;#Ut=new Map;#J=0;#$t=0;#O={installs:0,teardowns:0,reentrySkips:0,inaccessible:0,installErrors:0};#jt=[];constructor({core:S,config:b,logger:I,topWindow:x}={}){this.#ye=S,this.#ze=b||S?.config||{},this.#o=I||null,this.#j=x||("undefined"!=typeof window?window:void 0)}get isStarted(){return this.#te}start(){if(this.#te)return!0;if(!this.#j)return!1;try{this.#te=!0,this.#qt();const S=this.#j.document;return this.#Wt(S,this.#j,Rt,1),this.#Ht(S,this.#j,Rt,1,null),!0}catch(S){return this.#F("start failed (fail-closed):",S),!0}}shutdown(){try{for(const S of Array.from(this.#Le.values()))this.#Vt(S,"disconnected");this.#Le.clear();for(const S of this.#zt)try{S.mo.disconnect()}catch(S){}this.#zt.length=0,this.#Bt.length=0}catch(S){this.#F("shutdown error (fail-closed):",S)}finally{this.#te=!1;try{this.#ye?.setIframeTopFrameContext?.(null)}catch(S){}}}#Wt(S,b,I,x){if(!S)return;let R=null;try{R=S.querySelectorAll("iframe")}catch(S){R=null}R&&R.forEach(S=>{this.#ie(S,I,x),this.#Qt(S,I,x)});try{const S=b&&b.frames,R=S?S.length:0;for(let b=0;b<R;b++){let R=null;try{R=S[b]&&S[b].frameElement}catch(S){R=null}R&&"IFRAME"===R.tagName&&!this.#G.has(R)&&(this.#ie(R,I,x),this.#Qt(R,I,x))}}catch(S){}}#ie(S,b,I){if(!this.#Z.has(S)){this.#Z.add(S);try{S.addEventListener("load",()=>{try{this.#Qt(S,b,I)}catch(S){this.#F("load-reinstall failed (fail-closed):",S)}})}catch(S){this.#F("hookLoad failed (fail-closed):",S)}}}#Qt(S,b,I){let x=null;try{x=S.contentWindow}catch(S){x=null}x&&this.#Kt(S,x,b,I)}#he(S){let b=this.#G.get(S);return b||(b="ts-frame-"+ ++this.#J,this.#G.set(S,b)),b}#Kt(S,b,I,x){try{const b=S.getAttribute&&S.getAttribute("src");if(b){const I=new URL(b,"undefined"!=typeof location&&location.href||void 0);if(("http:"===I.protocol||"https:"===I.protocol)&&"undefined"!=typeof location&&I.origin!==location.origin)return this.#O.inaccessible++,this.#Gt("inaccessible",{frameId:this.#he(S),depth:x,reason:"cross-origin-src"}),null}}catch(S){}let R;try{if(R=b.document,!R)throw new Error("no document")}catch(b){return this.#O.inaccessible++,this.#Gt("inaccessible",{frameId:this.#he(S),depth:x}),null}const A=this.#he(S),_=b[this.#Pt];if(_&&null!=_.realmEpoch)return this.#O.reentrySkips++,this.#Gt("reentry-skip",{frameId:A,realmEpoch:_.realmEpoch}),_;const D=this.#Le.get(A);if(D&&D.win!==b){const S="reloaded"===this.#Jt(A,this.#Xt(b))?"reloaded":"navigated";this.#Vt(D,S)}const L=++this.#$t,B=this.#Zt(b),U=this.#Xt(b),$=this.#Jt(A,U),j=this.#Yt(),W={frameId:A,frameInstanceId:`${A}-r${L}`,parentFrameId:I,topFrameId:Rt,frameDepth:x,frameOrigin:B,frameUrl:U,frameLifecycle:$,privacyStatus:j,realmEpoch:L,win:b,el:S,seq:0,interceptors:[],observerRef:null};try{Object.defineProperty(b,this.#Pt,{value:W,configurable:!0,enumerable:!1,writable:!0})}catch(S){return null}const H=this.#er(W),V=this.#ze||{};let Q=!1;try{this.#tr(W,()=>{const S=new FetchInterceptor(H,b);return S.setup(),S}),this.#tr(W,()=>{const S=new XHRInterceptor(H,b);return S.setup(),S}),this.#tr(W,()=>{const S=new ConsoleInterceptor(null,V,H,b);return S.install(),S}),this.#tr(W,()=>{const S=new ErrorHandler(null,V,H,b);return S.install(),S}),this.#tr(W,()=>{const S=new PerformanceResourceObserver(H,{captureResources:!1!==V.captureResources,captureNavigation:!1!==V.captureNavigation,debug:!!V.debug,maxResourceEntriesPerSession:V.maxResourceEntriesPerSession||2e3},b);return S.setup(),S}),Q=W.interceptors.length>0}catch(S){return this.#O.installErrors++,this.#F("install block failed (fail-closed):",S),this.#Vt(W,"blocked"),null}if(!Q){try{delete b[this.#Pt]}catch(S){}return null}this.#O.installs++,this.#rr(A,U),this.#Le.set(A,W),this.#sr(A,b),this.#Gt("install",{frameId:A,parentFrameId:I,depth:x,realmEpoch:L,frameLifecycle:$});try{this.#Wt(R,b,A,x+1)}catch(S){this.#F("nested scan failed:",S)}return this.#Ht(R,b,A,x+1,W),W}#tr(S,b){try{const I=b();I&&S.interceptors.push(I)}catch(S){this.#O.installErrors++,this.#F("interceptor install failed (fail-closed):",S)}}#er(S){const b=this.#ye,stamp=(b,I)=>this.#nr(S,b,I);return new Proxy(b,{get(S,b){if("addSessionCustomEvent"===b)return stamp;const I=Reflect.get(S,b,S);return"function"==typeof I?I.bind(S):I}})}#nr(S,b,I){try{const x=I&&"object"==typeof I?I:{},R="number"==typeof x.timestamp?x.timestamp:Date.now(),A=Object.assign({},x,{frameId:S.frameId,topFrameId:S.topFrameId,frameInstanceId:S.frameInstanceId,frameDepth:S.frameDepth,frameOrigin:S.frameOrigin,frameUrl:S.frameUrl,frameLifecycle:S.frameLifecycle,captureRealm:"iframe",privacyStatus:S.privacyStatus,localSequence:S.seq++,tsLocal:R,tsNormalized:R});return null!=S.parentFrameId&&(A.parentFrameId=S.parentFrameId),this.#ye.addSessionCustomEvent(b,A)}catch(S){return this.#F("stamp/emit failed (fail-closed):",S),!1}}#Ht(S,b,I,x,R){try{const A=b.MutationObserver;if(!A)return;const _=new A(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S,I,x)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation handler failed (fail-closed):",S)}});_.observe(S.documentElement||S,{childList:!0,subtree:!0});const D={mo:_,win:b};this.#zt.push(D),R&&(R.observerRef=()=>{try{_.disconnect()}catch(S){}const S=this.#zt.indexOf(D);S>=0&&this.#zt.splice(S,1)})}catch(S){this.#F("observeDocument failed (fail-closed):",S)}}#ae(S,b,I){if(!S||1!==S.nodeType)return;const attach=S=>{this.#ie(S,b,I),this.#Qt(S,b,I)};if("IFRAME"===S.tagName&&attach(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(attach)}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#G.get(S);if(!b)return;if(S.isConnected)return;const I=this.#Le.get(b);I&&this.#Vt(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#Vt(S,b){for(const b of S.interceptors)try{"function"==typeof b.destroy?b.destroy():"function"==typeof b.uninstall&&b.uninstall()}catch(S){this.#F("interceptor teardown failed (fail-closed):",S)}if(S.interceptors=[],"function"==typeof S.observerRef){try{S.observerRef()}catch(S){}S.observerRef=null}this.#Le.delete(S.frameId);try{delete S.win[this.#Pt]}catch(S){}if(this.#ir(S.frameId),"detached"===b){const b=this.#Ut.get(S.frameId);b&&(b.detached=!0)}S.win=null,S.el=null,this.#O.teardowns++,this.#Gt("teardown",{frameId:S.frameId,reason:b})}#qt(){const S=this.#j;try{this.#ye?.setIframeTopFrameContext?.({frameId:Rt,frameInstanceId:`${Rt}-r0`,topFrameId:Rt,frameOrigin:this.#Zt(S),frameUrl:this.#Xt(S),frameLifecycle:"attached",privacyStatus:this.#Yt()})}catch(S){this.#F("registerTopFrameContext failed (fail-closed):",S)}}#Zt(S){try{const b=S.location&&S.location.origin;if("string"==typeof b&&b)return b.slice(0,256)}catch(S){}}#Xt(S){try{const b=S.location&&S.location.href;if("string"!=typeof b||!b)return;const{url:I}=splitSanitizedUrl(b,{});return(I||b).slice(0,2048)}catch(S){return}}#Yt(){try{const S=SDKContext.getInstance()?.domPrivacy;if("confirmed"===S||"partial"===S||"disabled"===S)return S}catch(S){}return"unknown"}#Jt(S,b){const I=this.#Ut.get(S);return I&&I.everInstalled?I.detached?"reattached":null!=I.lastUrl&&null!=b&&I.lastUrl===b?"reloaded":"navigated":"attached"}#rr(S,b){const I=this.#Ut.get(S)||{};I.everInstalled=!0,I.detached=!1,I.lastUrl=b,this.#Ut.set(S,I)}#sr(S,b){const I=this.#Bt.find(b=>b.frameId===S);I?I.win=b:this.#Bt.push({frameId:S,win:b})}#ir(S){for(let b=this.#Bt.length-1;b>=0;b--)this.#Bt[b].frameId===S&&(this.#Bt[b].win=null,this.#Bt.splice(b,1))}getStats(){return{active:this.#Le.size,allRealms:this.#Bt.length,observers:this.#zt.length,...this.#O}}getInstallLog(){return this.#jt.slice()}verifyRestored(){return this.#or().map(S=>{const b={frameId:S.frameId,alive:!1},I=S.win;if(!I)return b;try{b.alive=!0,b.fetchRestored=!(I.fetch&&I.fetch.__tsPoCWrapped),b.consoleRestored="function"==typeof I.console.log}catch(S){b.error=S&&S.name}return b})}#or(){const S=[];for(const b of this.#Le.values())S.push({frameId:b.frameId,win:b.win});for(const b of this.#Bt)S.some(S=>S.frameId===b.frameId)||S.push(b);return S}#Gt(S,b){this.#jt.push(Object.assign({ev:S,t:Date.now()},b))}#F(...S){try{this.#ze?.debug&&this.#o?.warn&&this.#o.warn("[IframeInstrumentation]",...S)}catch(S){}}}class InterceptorFeature{#o=null;#ze=null;#ar=null;#lr=null;#cr=null;#ur=null;#We=!1;constructor({logger:S,config:b,monitoringCore:I,eventManager:x}){this.#o=S,this.#ze=b,this.#ar=I,this.#lr=x}initialize(S,b=null){try{this.#cr={};return S&&S.isRecording?(console.log("[TraceScout] 🔌 Setting up session recording interceptors bundle..."),this.#hr(),this.#dr(),this.#gr(),this.#pr(b),this.#fr(),this.#mr(),this.#yr(),console.log("[TraceScout] ✅ Session recording bundle complete (DOM + Network + Console + Errors)"),this.#o?.log("Interceptors setup complete"),this.#We=!0,!0):(console.log("[TraceScout] ⏭️ Interceptors skipped (bundled with session recording - not active)"),!1)}catch(S){return this.#o?.error("Failed to setup interceptors:",S),!1}}#hr(){console.log("[TraceScout] 📡 Setting up FetchInterceptor..."),this.#cr.fetch=new FetchInterceptor(this.#ar),this.#cr.fetch.setup?.()||this.#cr.fetch.install?.(),console.log("[TraceScout] ✅ FetchInterceptor active")}#dr(){console.log("[TraceScout] 📡 Setting up XHRInterceptor..."),this.#cr.xhr=new XHRInterceptor(this.#ar),this.#cr.xhr.setup?.()||this.#cr.xhr.install?.(),console.log("[TraceScout] ✅ XHRInterceptor active")}#gr(){const S=!1!==this.#ze?.captureResources,b=!1!==this.#ze?.captureNavigation;if(S||b)try{console.log("[TraceScout] 📊 Setting up PerformanceResourceObserver...",{captureResources:S,captureNavigation:b,maxResourceEntriesPerSession:this.#ze?.maxResourceEntriesPerSession||2e3}),this.#cr.performanceResource=new PerformanceResourceObserver(this.#ar,{captureResources:S,captureNavigation:b,debug:this.#ze?.debug||!1,maxDedupeEntries:this.#ze?.maxDedupeEntries||5e3,filterOtherInitiator:!1!==this.#ze?.filterOtherInitiator,maxResourceEntriesPerSession:this.#ze?.maxResourceEntriesPerSession||2e3,resourceAllowlist:this.#ze?.resourceAllowlist||null,resourceBlocklist:this.#ze?.resourceBlocklist||null}),this.#cr.performanceResource.setup(),console.log("[TraceScout] ✅ PerformanceResourceObserver active")}catch(S){console.warn("[TraceScout] ⚠️ PerformanceResourceObserver setup failed:",S.message)}else console.log("[TraceScout] ⏭️ PerformanceResourceObserver disabled via config")}#pr(S){console.log("[TraceScout] 💬 Setting up ConsoleInterceptor..."),this.#cr.console=new ConsoleInterceptor(this.#lr,this.#ze,this.#ar),S&&this.#cr.console.setLogManager(S),this.#cr.console.install?.(),console.log("[TraceScout] ✅ ConsoleInterceptor active")}#fr(){try{console.log("[TraceScout] 🚨 Setting up ErrorHandler..."),this.#cr.errors=new ErrorHandler(this.#lr,this.#ze,this.#ar),console.log("[TraceScout] ErrorHandler created, installing...",{hasInstall:"function"==typeof this.#cr.errors?.install,hasReporter:!!this.#ar}),this.#cr.errors.install?.(),console.log("[TraceScout] ✅ ErrorHandler active")}catch(S){console.error("[TraceScout] ❌ ErrorHandler setup failed:",S)}}#yr(){try{this.#ur=new IframeInstrumentationManager({core:this.#ar,config:this.#ze,logger:this.#o}),this.#ur.start(),console.log("[TraceScout] 🪟 Same-origin iframe instrumentation active")}catch(S){console.warn("[TraceScout] ⚠️ Iframe instrumentation skipped:",S?.message),this.#ur=null}}get iframeManager(){return this.#ur}#mr(){this.#ze?.monitorPostMessages&&"object"==typeof this.#ze.monitorPostMessages&&(this.#cr.postMessage=new PostMessageInterceptor(this.#ar),this.#cr.postMessage.setup?.()||this.#cr.postMessage.install?.())}get isInitialized(){return this.#We}get interceptors(){return this.#cr}getInterceptor(S){return this.#cr?.[S]||null}updateDebugMode(S){this.#cr&&Object.values(this.#cr).forEach(b=>{b&&b.updateDebugMode&&b.updateDebugMode(S)})}destroy(){if(this.#ur){try{this.#ur.shutdown()}catch(S){}this.#ur=null}this.#cr&&(Object.values(this.#cr).forEach(S=>{S?.destroy?.()||S?.uninstall?.()}),this.#cr=null),this.#We=!1}}class EventLifecycleFeature{#o=null;#ze=null;#vr=null;#wr=null;#Sr=null;#br=null;#Cr=null;#kr=null;#Ir=null;#Er=null;#We=!1;#xr=!1;constructor({logger:S,config:b}){this.#o=S,this.#ze=b}setCallbacks({onCustomApiError:S,onBeforeUnload:b,onUserActivity:I,onVisibilityChange:x}){this.#Cr=S,this.#kr=b,this.#Ir=I,this.#Er=x}initialize(){try{return this.#vr=this.#Mr.bind(this),this.#wr=this.#Rr.bind(this),this.#Sr=this.#Tr.bind(this),this.#br=this.#Ar.bind(this),document.addEventListener("custom-api-error",this.#vr),window.addEventListener("beforeunload",this.#wr),document.addEventListener("click",this.#Sr,{passive:!0,capture:!0}),document.addEventListener("keydown",this.#Sr,{passive:!0,capture:!0}),document.addEventListener("scroll",this.#Sr,{passive:!0,capture:!0}),document.addEventListener("visibilitychange",this.#br),this.#o?.log("Event listeners setup complete"),this.#We=!0,!0}catch(S){return this.#o?.error("Failed to setup event listeners:",S),!1}}#Mr(S){this.#Cr?.(S)}#Rr(S){this.#kr?.(S)}#Tr(){this.#xr||this.#Ir?.()}#Ar(){this.#xr||("visible"===document.visibilityState?this.#Er?.("visible"):this.#Er?.("hidden"))}get isInitialized(){return this.#We}setQuotaExceeded(S){this.#xr=S,S&&this.#_r()}#_r(){this.#Sr&&(document.removeEventListener("click",this.#Sr,{capture:!0}),document.removeEventListener("keydown",this.#Sr,{capture:!0}),document.removeEventListener("scroll",this.#Sr,{capture:!0}),this.#Sr=null),this.#br&&(document.removeEventListener("visibilitychange",this.#br),this.#br=null)}destroy(){try{document.removeEventListener("custom-api-error",this.#vr),window.removeEventListener("beforeunload",this.#wr),this.#_r(),this.#vr=null,this.#wr=null,this.#We=!1}catch(S){this.#o?.error("Failed to cleanup event listeners:",S)}}}function readInjectedDebugId(){try{const S="undefined"!=typeof globalThis?globalThis.__TRACESCOUT_DEBUG_ID__:void 0;if("string"==typeof S&&/^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$/.test(S))return S}catch(S){}return null}class TraceScoutMonitoringCore{#We=!1;#o=null;#Or=null;#lr=null;#Dr=null;#Fr=null;#Nr=null;#Lr=null;#Be=null;#Pr=null;#Br=null;#zr=null;#Ur=null;#cr=null;#$r=null;#jr=null;#qr=null;#Wr=null;#Hr=null;#Vr=null;#Qr=null;#Kr=null;#Gr=null;#Jr=null;_consecutiveFailures=0;#xr=!1;#Xr=null;#Zr=!1;#Yr=null;#es=0;#ts=null;#rs=null;#ss=!1;static#ns=null;static#is=!1;constructor(){this.config=R.defaults({retryIntervalMs:R.get(_,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:R.get(_,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:R.get(_,"MAX_QUEUE_SIZE",1e3),maxRetries:R.get(_,"MAX_RETRIES",3),batchSize:R.get(_,"BATCH_SIZE",10),debug:!1,logPreflight:!1,logResourceErrors:!1},{}),this.#o=new Logger("[TraceScoutMonitoringCore]",this.config.debug),"function"!=typeof this.#o.debug&&(this.#o.debug=(...S)=>this.#o.info(...S));try{this.#Or=new ConfigManager(this.config)}catch(S){this.#o.error("Failed to initialize ConfigManager:",S)}this.appContext={appVersion:"1.0.0",environment:"unknown"},"function"==typeof this.sendEvents&&(this.#Kr=throttle$1(this.sendEvents.bind(this),1e3))}static setTransport(S){TraceScoutMonitoringCore.#is?console.error("[TraceScout] setTransport() must be called before init()"):"object"==typeof S&&null!==S?"string"==typeof S.apiBaseUrl&&S.apiBaseUrl?TraceScoutMonitoringCore.#ns=S:console.error("[TraceScout] setTransport() requires a non-empty apiBaseUrl string"):console.error("[TraceScout] setTransport() requires an object with apiBaseUrl")}async init(S,b={}){if(this.#Zr)return this.#o.warn("TraceScoutMonitoringCore already initialized"),{sampled:this.#Xr??!1,sdkVersion:"2.0.0",projectId:"",environment:""};const I=validateConfig(S,b);if(!I.ok){return function surfaceConfigError(S,b){if(b)try{console.error("[TraceScout] init() refused — invalid arguments:",S)}catch{}}(I.keys?{code:I.code,keys:I.keys}:{code:I.code},b?.debug||!1),{sampled:!1,sdkVersion:"2.0.0",projectId:"",environment:""}}this.#Zr=!0,TraceScoutMonitoringCore.#is=!0,this.#ts=parseIframeConfig(I.options.iframe),!this.#ts.enabled&&this.#ts.reason&&"absent"!==this.#ts.reason&&I.options.debug&&console.warn("[TraceScout] iframe bridge disabled (fail-closed):",this.#ts.reason),this.#ss=this.#ts.enabled&&("child"===this.#ts.role||"both"===this.#ts.role);const x=TraceScoutMonitoringCore.#ns,R={projectId:I.projectId,environment:I.options.environment||"production",release:I.options.release,dist:I.options.dist,debugId:I.options.debugId??readInjectedDebugId(),sourceName:I.options.sourceName??"web-client",debug:I.options.debug||!1,apiBaseUrl:x?.apiBaseUrl,...void 0!==I.options.network?{network:I.options.network}:{}},A=peekAnonymousId();if(this.#Xr=shouldSampleSession(1,{anonymousId:A}),!this.#Xr)return R.debug&&console.log("[TraceScout] Session not sampled — SDK will not instrument this page-load."),{sampled:!1,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment};try{R.debug&&(console.log("[TraceScout] ============================================"),console.log("[TraceScout] Initializing SDK v2.0..."),console.log("[TraceScout] ============================================"));const S=new InitializationPipeline(this.#o),I=await S.run(R);this.#Lr=I.sessionManager.sessionManager,this.#Be=I.sdkContext,this.#Pr=I.remoteConfigService,this.config=I.config,this.#Br=R,this.#lr=I.managers.eventManager,this.#Dr=I.managers.serviceManager,this.#Fr=I.managers.userProfileManager,this.#Nr=I.managers.performanceMonitor,this.config.appName&&(this.appContext.appName=this.config.appName),I.serverConfig?.project?.name&&(this.appContext.appName=I.serverConfig.project.name),this.#o&&"function"==typeof this.#o.updateDebugMode&&this.#o.updateDebugMode(this.config.debug),this.#Ur=new LoggingFeature({logger:this.#o,sdkContext:this.#Be,config:this.config}),this.#Ur.initialize(I.serverConfig),this.#Ur.configure(this.config);const x=I.serverConfig?.features?.performanceMonitoring?.enabled;if(x&&(this.#Qr=new CoreWebVitalsMonitor(this.config),console.log("[TraceScout] ✓ Performance monitoring initialized")),this.#ts?.enabled)try{this.config.recordCrossOriginIframes=!0,this.#rs=new CrossOriginIframeBridge({config:this.#ts,core:this,projectId:this.#Be.projectId,sessionId:this.#Be.sessionId,logger:this.#o}),this.#rs.start()}catch(S){this.config?.debug&&this.#o.warn?.("iframe bridge start failed (fail-closed):",S),this.#rs=null}this.#zr=new SessionRecordingFeature({logger:this.#o,sdkContext:this.#Be,config:this.config,options:{...b,childMode:this.#ss}}),this.#zr.setCallbacks({onChunkCreated:S=>this.#tt(S),onSessionEnd:S=>this.#os(S),onQuotaExceeded:S=>this.#as(S),onSpaNavigation:(S,b,I)=>{this.#qr?.recordNavigation(S,b,I)}});const A=await this.#zr.initialize(I.serverConfig,this.#Pr);if(this.#qr=new PageviewManager({addCustomEvent:(S,b)=>this.#zr?.addCustomEvent(S,b),getBaseContext:()=>this.#Be.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Be.setPageviewManager(this.#qr),this.#jr=new SessionLifecycleEmitter({addCustomEvent:(S,b)=>this.#zr?.addCustomEvent(S,b),getContext:()=>this.#Be.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),readGuard:()=>this.#Lr?.getLifecycleGuard?.()??null,writeGuard:S=>this.#Lr?.setLifecycleGuard?.(S),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Lr&&!this.#ss&&(this.#Lr.onLifecycleEnd=({reason:S})=>{this.#jr?.emitEnd({reason:S})}),A&&this.#Qr){const S=this.#qr.getCurrentPageviewId(),b="undefined"!=typeof window&&"string"==typeof window.location?.href?window.location.href:"";b&&(this.#Wr=new WebVitalsEmitter({addCustomEvent:(S,b)=>this.#zr?.addCustomEvent(S,b),getBaseContext:()=>this.#Be.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),initialPageviewId:S,initialUrl:b,debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Qr.addCallback?.((S,b)=>{this.#Wr?.emit(S,b)}),this.#Qr.metrics&&"function"==typeof this.#Qr.metrics.forEach&&this.#Qr.metrics.forEach(S=>{this.#Wr?.emit(S.type,S)}))}if(A&&(this.#Hr=new TrackIdentifyEmitter({addCustomEvent:(S,b)=>this.#zr?.addCustomEvent(S,b),getBaseContext:()=>this.#Be.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Vr=new ExposureEmitter({addCustomEvent:(S,b)=>this.#zr?.addCustomEvent(S,b),getBaseContext:()=>this.#Be.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}})),A&&!this.#ss){const S=!0===this.#Lr?.isResumedSession?.();this.#qr.emitInitialPageView({isResumed:S})}return!A||this.#ss||!this.#Lr||this.#Lr.isResumedSession?.()||this.#Lr.getLifecycleGuard?.()?.sessionStartEmitted||this.#jr.emitStart({}),A?(this.#cr=new InterceptorFeature({logger:this.#o,config:this.config,monitoringCore:this,eventManager:this.#lr}),this.#cr.initialize(this.#zr.recorder,this.#Ur.logManager),console.log("[TraceScout] ✓ Session recording bundle initialized (DOM + Network + Console + Errors)")):console.log("[TraceScout] ⏭️ Skipping interceptors (bundled with session recording)"),this.#$r=new EventLifecycleFeature({logger:this.#o,config:this.config}),this.#$r.setCallbacks({onCustomApiError:S=>this.#Mr(S),onBeforeUnload:S=>this.#Rr(S),onUserActivity:()=>this.#Tr(),onVisibilityChange:S=>this.#Ar(S)}),this.#$r.initialize(),this.#ls(),this.#lr&&this.#lr.loadFromLocal(),this.#Fr&&this.#Fr.ensureProfile(),this.#We=!0,this.#cs(I.serverConfig),{sampled:!0,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment}}catch(S){throw console.error("[TraceScout] ❌ Initialization failed:",S),this.#o.error("Failed to initialize TraceScoutMonitoringCore:",S),S}}#cs(S){console.log("[TraceScout] ============================================"),console.log("[TraceScout] ✅ SDK Initialized Successfully"),console.log("[TraceScout] ============================================"),console.log(` Workspace: ${S.workspace.name}`),console.log(` Project: ${S.project.name}`),console.log(` Session: ${this.#Be.sessionId}`),console.log(` Environment: ${this.#Be.environment}`),console.log(` Config Version: ${S.configVersion}`);const b=Object.keys(S.features||{}).filter(b=>S.features[b].enabled);console.log(` Features: ${b.join(", ")||"none"}`),console.log("[TraceScout] ============================================"),this.#o.info("TraceScoutMonitoringCore initialized successfully",{configSource:"server",configVersion:S.configVersion,workspace:S.workspace.name,project:S.project.name,sessionId:this.#Be.sessionId})}#us(S,b){try{const I=Object.keys(b.features||{}).filter(S=>b.features[S].enabled);S({sessionId:this.#Be.sessionId,workspace:b.workspace.name,project:b.project.name,environment:this.#Be.environment,featuresEnabled:I,configVersion:b.configVersion})}catch(S){this.#o.error("Error in onReady callback:",S)}}#tt(S){this.#Lr&&(this.#Lr.incrementChunkCount(),this.#Lr.incrementEventCount(S.eventCount||0))}#os(S){if(!S||"object"!=typeof S)return;const b=mapInternalEndReason(S.reason);b&&this.#jr?.emitEnd({reason:b,totalChunks:"number"==typeof S.totalChunks?S.totalChunks:void 0,totalEvents:"number"==typeof S.totalEvents?S.totalEvents:void 0})}#Mr(S){}#Rr(S){}#Tr(){this.#xr||this.#zr?.sessionEnded&&!this.#zr?.isRecording&&(console.log("[TraceScout] 🔄 User activity detected after session end - starting new session"),this.forceNewSession("activity_after_"+this.#zr.sessionEndReason))}#Ar(S){this.#xr||"visible"===S&&this.#zr?.sessionEnded&&!this.#zr?.isRecording&&(console.log("[TraceScout] 🔄 Tab visible after session end - starting new session"),this.forceNewSession("tab_focus_after_"+this.#zr.sessionEndReason))}#as(S){this.#xr||(this.#xr=!0,console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been permanently stopped.","color: #ff4444;"),console.error("%c[TraceScout] Your workspace has reached its monthly session limit.","color: #ff4444;"),S?.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions (${S.usage.percentage}%)`,"color: #ff4444;"),console.error("%c[TraceScout] To continue recording, upgrade your plan at: /billing","color: #ff4444;"),this.#$r?.setQuotaExceeded(!0),this.#zr?.stop(),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:recording_stopped",{detail:{reason:"quota_exceeded",usage:S?.usage,message:S?.message||"Session quota exceeded"}})))}#ls(){"development"===this.config.environment||this.config.debug?this.#o.log("⚠️ Auto-retry DISABLED (development mode) - reduces API spam"):(this.#Gr=setInterval(()=>{this.#hs()},this.config.retryIntervalMs),this.#o.log("Auto-retry enabled (production mode)")),this.#Jr=setInterval(()=>{this.#ds()},6e4),this.#o.log("Background processes started")}#gs(){this.#Gr&&(clearInterval(this.#Gr),this.#Gr=null),this.#Jr&&(clearInterval(this.#Jr),this.#Jr=null)}async#hs(){try{if(this.#Dr?.isSending)return;const S=this.#lr?.getQueueSize();if(S>0){if(this._consecutiveFailures>=10)return this.#o.warn(`⛔ Stopped retrying after ${this._consecutiveFailures} consecutive failures`),this.#o.warn(`⛔ Clearing ${S} queued events to prevent infinite loop`),this.#lr.clearEvents(),void(this._consecutiveFailures=0);this.#o.info(`🔄 Retrying ${S} queued events (attempt ${this._consecutiveFailures+1}/10)`);await this.sendEvents()?(this.#o.info("✅ Retry succeeded - resetting failure counter"),this._consecutiveFailures=0):(this._consecutiveFailures++,this.#o.warn(`❌ Retry failed (${this._consecutiveFailures}/10)`))}else this._consecutiveFailures>0&&(this.#o.info("✅ Queue empty - resetting failure counter"),this._consecutiveFailures=0)}catch(S){this.#o.error("Error during retry:",S),this._consecutiveFailures++}}#ds(){try{if(this.#lr){const S=this.config.eventMaxAge||864e5;this.#lr.cleanupOldEvents(S)}}catch(S){this.#o.error("Error during cleanup:",S)}}#ps(){return"evt_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}destroy(){if(this.#We)try{try{this.#rs?.shutdown()}catch(S){}this.#rs=null,this.#Ur?.destroy(),this.#cr?.destroy(),this.#zr?.destroy(),this.#$r?.destroy(),this.#gs(),this.#Lr&&this.#Lr.destroy(),this.#We=!1,this.#o.info("TraceScoutMonitoringCore destroyed successfully")}catch(S){this.#o.error("Error during destruction:",S)}}logEvent(S,b={},I={}){if(this.#We)try{let x;"object"==typeof S&&S.type?(x={id:S.id||this.#ps(),timestamp:S.timestamp||Date.now(),...S},x.context||(x.context={}),void 0===x.context.isMonitored&&(x.context.isMonitored=!0),void 0===x.context.forceLog&&(x.context.forceLog=x.type?.includes("error")||x.type?.includes("alert")||x.type?.includes("p1_incident")||"critical"===x.severity)):x={id:this.#ps(),type:S,data:b,context:{isMonitored:!0,forceLog:I.forceLog||!1,status:I.status||"success",...I.context},timestamp:Date.now()};if(this.#lr.addEvent(x)){this.#o.log("Event logged:",x.type);this.#lr.getQueueSize()>=this.config.batchSize&&this.sendEvents()}}catch(S){this.#o.error("Failed to log event:",S)}else this.#o.warn("TraceScoutMonitoringCore not initialized")}async sendEvents(S=null){if(!this.#Dr||!this.#lr)return this.#o.warn("ServiceManager or EventManager not available"),!1;try{const b=S||this.#lr.getEvents();if(!b||0===b.length)return!0;this.#o.info(`📤 Attempting to send ${b.length} events`);const I=await this.#Dr.sendEvents(b);this.#o.info(`📊 Send results: ${I.length} results received`);const x=I.filter(S=>S.success).map(S=>S.event.id);x.length>0&&(this.#lr.removeEvents(x),this.#o.info(`✅ Successfully sent ${x.length}/${b.length} events`));const R=I.filter(S=>!S.success).length;if(R>0){this.#o.warn(`❌ Failed to send ${R}/${b.length} events - will retry`);const S=I.find(S=>!S.success);S&&S.error&&this.#o.error("First failure reason:",S.error.message||S.error)}return 0===x.length&&I.length>0&&this.#o.warn(`⚠️ 0 events succeeded out of ${b.length} - all failed`),0===R}catch(S){return this.#o.error("❌ Failed to send events:",S),!1}}clearEvents(){this.#lr?(this.#lr.clearEvents(),this.#o.log("Event queue cleared")):this.#o.warn("EventManager not available")}isMonitoredEndpoint(S){if("string"!=typeof S||R.isEmpty(S))return!1;try{const b=this.config.endpoints||[],I=this.config.domainsToTrack||[];if(b.includes("*")||"*"===b)return!0;const x=S.toLowerCase();let A;try{A=new URL(x)}catch{return!1}if(!R.isEmpty(I)){const S=A.hostname;if(I.some(b=>S===b.toLowerCase()||S.endsWith(`.${b.toLowerCase()}`)))return!0}const _=A.pathname;return b.some(S=>_.includes(S.toLowerCase()))}catch(S){return this.#o?.warn("Error checking monitored endpoint:",S),!1}}shouldExtractFields(S,b){return"string"==typeof S&&!R.isEmpty(S)&&(!!R.isArray(this.config.fieldsToExtract)&&this.config.fieldsToExtract.some(I=>{const x=R.toLower(R.get(I,"api","")),A=R.get(I,"source","");return("*"===x||S.toLowerCase().includes(x))&&("*"===A||A===b)}))}extractUserContextFromBody({data:S,source:b="response",url:I=""}){if(!this.#Fr)return{};try{return this.#Fr.extractContextFromData({data:S,source:b,url:I})}catch(S){return this.#o.error("Failed to extract user context:",S),{}}}async startSessionRecording(S={}){return this.#zr?.start(S)||null}stopSessionRecording(){return this.#zr?.stop()||null}addSessionCustomEvent(S,b){if("console"!==S&&"error"!==S&&"unhandledRejection"!==S||(b=function sanitizeEventTextFields(S){if(!S||"object"!=typeof S)return S;let b=!1;const I={...S};for(const S of gt)if("string"==typeof I[S]){const x=sanitizeEventText(I[S]);x!==I[S]&&(I[S]=x,b=!0)}if(Array.isArray(I.args)){const S=I.args.map(S=>{if("string"==typeof S)return sanitizeEventText(S);if(S&&"object"==typeof S&&"string"==typeof S.preview){const b=sanitizeEventText(S.preview);return b===S.preview?S:{...S,preview:b}}return S});S.some((S,b)=>S!==I.args[b])&&(I.args=S,b=!0)}return b?I:S}(b)),this.#ss&&this.#rs?.child)try{return!0===this.#rs.child.forwardTelemetry(S,b)}catch(S){return!1}if(this.#Be&&"object"==typeof b&&null!==b){const I=this.#fs(S);if(I){let x;try{const S=this.#Be.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"});"string"==typeof b.traceId&&b.traceId.length>0&&(S.traceId=b.traceId),"string"==typeof b.spanId&&b.spanId.length>0&&(S.spanId=b.spanId),this.#ms(b,S);x=wrapInEnvelope(I,this.#ys(I,b),S)}catch(S){if(this.config?.debug&&this.#o.warn?.("addSessionCustomEvent: envelope build failed; skipping v1 emit:",S),"function"==typeof this.#Br?.onError)try{this.#Br.onError(S)}catch(S){}return!1}return this.#zr?.addCustomEvent(S,x)||!1}}return this.#zr?.addCustomEvent(S,b)||!1}setIframeTopFrameContext(S){this.#Yr=S&&"object"==typeof S?S:null,this.#Yr||(this.#es=0);try{this.#Be?.setTopFrameIdentity?.(this.#Yr)}catch(S){}}static#vs=["frameId","parentFrameId","topFrameId","frameInstanceId","frameDepth","frameOrigin","frameUrl","frameLifecycle","captureRealm","privacyStatus","bridgeProtocolVersion","localSequence","tsLocal","tsNormalized","clockOffsetMs","clockUncertaintyMs"];#ms(S,b){const I=TraceScoutMonitoringCore.#vs;if("string"==typeof S.frameId&&S.frameId.length>0){for(const x of I){const I=S[x];null!=I&&""!==I&&(b[x]=I)}return}const x=this.#Yr;if(!x)return;b.frameId=x.frameId,b.frameInstanceId=x.frameInstanceId,b.topFrameId=x.topFrameId,b.frameDepth=0,b.captureRealm="top","string"==typeof x.frameOrigin&&(b.frameOrigin=x.frameOrigin),"string"==typeof x.frameUrl&&(b.frameUrl=x.frameUrl),"string"==typeof x.frameLifecycle&&(b.frameLifecycle=x.frameLifecycle),"string"==typeof x.privacyStatus&&(b.privacyStatus=x.privacyStatus);const R="number"==typeof S.timestamp?S.timestamp:Date.now();b.localSequence=this.#es++,b.tsLocal=R,b.tsNormalized=R}#fs(S){switch(S){case"network_request":case"network_response":case"network_error":case"network_resource":return"network_request";case"console":return"console_event";case"error":case"unhandledRejection":return"js_error";default:return null}}#ys(S,b){switch(S){case"console_event":{const S=Array.isArray(b.args)?b.args.map(S=>"object"==typeof S&&null!==S&&"type"in S?S:{type:"string"==typeof S?"string":"object",preview:String(S).slice(0,2e3)}):void 0,I={level:b.level||b.method||"log",message:"string"==typeof b.message?b.message:String(b.message??"")};return void 0!==S&&(I.args=S),void 0!==b.stack&&null!==b.stack&&(I.stack=b.stack),"number"==typeof b.timestamp&&(I.timestamp=b.timestamp),I}case"js_error":{const S={handled:b.handled||"window.onerror",message:"string"==typeof b.message?b.message:String(b.message??""),fingerprint:b.fingerprint,occurrenceCount:b.occurrenceCount||1,severity:b.severity||"error"},I=b.errorName??b.name;return null!=I&&(S.errorName=I),void 0!==b.stack&&null!==b.stack&&(S.stack=b.stack),void 0!==b.source&&null!==b.source&&(S.source=b.source),"number"==typeof b.lineno&&(S.lineno=b.lineno),"number"==typeof b.colno&&(S.colno=b.colno),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}case"network_request":{const S={initiator:"xhr"===b.interceptor?"xhr":"fetch",method:(b.method||"GET").toUpperCase(),requestUrl:b.url||b.requestUrl||"",status:"number"==typeof b.status?b.status:0,durationMs:"number"==typeof b.duration?Math.round(b.duration):0,errored:"number"!=typeof b.status||(b.status>=400||0===b.status)};return void 0!==b.statusText&&null!==b.statusText&&(S.statusText=b.statusText),"string"==typeof b.requestPath&&b.requestPath.length>0&&(S.requestPath=b.requestPath),"string"==typeof b.requestQuery&&b.requestQuery.length>0&&(S.requestQuery=b.requestQuery),b.requestHeaders&&"object"==typeof b.requestHeaders&&(S.requestHeaders=b.requestHeaders),b.responseHeaders&&"object"==typeof b.responseHeaders&&(S.responseHeaders=b.responseHeaders),"requestBody"in b&&(S.requestBody="string"==typeof b.requestBody?b.requestBody:null),"responseBody"in b&&(S.responseBody="string"==typeof b.responseBody?b.responseBody:null),"string"==typeof b.requestBodyState&&(S.requestBodyState=b.requestBodyState),"string"==typeof b.responseBodyState&&(S.responseBodyState=b.responseBodyState),"boolean"==typeof b.requestBodyRedacted&&(S.requestBodyRedacted=b.requestBodyRedacted),"boolean"==typeof b.responseBodyRedacted&&(S.responseBodyRedacted=b.responseBodyRedacted),"boolean"==typeof b.requestBodyTruncated&&(S.requestBodyTruncated=b.requestBodyTruncated),"boolean"==typeof b.responseBodyTruncated&&(S.responseBodyTruncated=b.responseBodyTruncated),"number"==typeof b.requestBodySize&&(S.requestBodySize=b.requestBodySize),"number"==typeof b.responseBodySize&&(S.responseBodySize=b.responseBodySize),"number"==typeof b.requestBodyCapturedBytes&&(S.requestBodyCapturedBytes=b.requestBodyCapturedBytes),"number"==typeof b.responseBodyCapturedBytes&&(S.responseBodyCapturedBytes=b.responseBodyCapturedBytes),"string"==typeof b.requestBodyContentType&&(S.requestBodyContentType=b.requestBodyContentType),"string"==typeof b.responseBodyContentType&&(S.responseBodyContentType=b.responseBodyContentType),"number"==typeof b.requestSize&&(S.requestSize=b.requestSize),"number"==typeof b.responseSize&&(S.responseSize=b.responseSize),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}default:return{...b}}}getSessionRecordingStatus(){return this.#zr?.getStatus()||{available:!1,error:"Session recording not enabled"}}async getSessionEvents(S){return this.#zr?.getEvents()||[]}exportSessionData(S="json"){if(!this.#zr?.isAvailable)return this.#o.warn("Session recording not enabled"),null;try{const b=this.#zr.getEvents(),I=this.#zr.getChunks(),x=this.#zr.getMetadata(),R=this.#zr.getSessionId();let A=b;(!b||0===b.length)&&I&&I.length>0&&(A=[],I.forEach(S=>{S.events&&Array.isArray(S.events)&&A.push(...S.events)}));const _=JSON.stringify(A).length,D=_>5e6,L={sessionId:R,startTime:this.#zr.recorder?.recordingStartTime,endTime:this.#zr.isRecording?null:Date.now(),duration:this.#zr.recorder?.recordingStartTime?Date.now()-this.#zr.recorder.recordingStartTime:0,eventCount:A.length,chunkCount:I.length,totalSize:_,isLarge:D,metadata:x,events:D?[]:A,chunks:I,userAgent:navigator.userAgent,url:window.location.href,timestamp:Date.now(),...D&&{warning:"Session data is large. Use exportChunk() to get individual chunks for replay."}};return"json"===S?JSON.stringify(L,null,2):"object"===S?L:"blob"===S?new Blob([JSON.stringify(L,null,2)],{type:"application/json"}):L}catch(S){return this.#o.error("Failed to export session data:",S),null}}getSessionChunks(){return this.#zr?.getChunks()||[]}listChunks(){return(this.#zr?.getChunks()||[]).map((S,b)=>({index:b,chunkId:S.chunkId,eventCount:S.events?.length||0,size:JSON.stringify(S.events||[]).length,sizeKB:Math.round(JSON.stringify(S.events||[]).length/1024),startTime:S.startTime,endTime:S.endTime,duration:(S.endTime||0)-(S.startTime||0)}))}getUploadQueueStats(){return this.#zr?.uploadQueue?.getStats()||null}getUploadQueue(){return this.#zr?.uploadQueue?.getQueue()||null}pauseUploads(){return this.#zr?.uploadQueue?.pause(),!0}resumeUploads(){return this.#zr?.uploadQueue?.resume(),!0}getSessionStorageStats(){return this.#zr?.sessionStorage?.getStorageStats()||null}getStoredSessions(){return this.#zr?.sessionStorage?.getSessions()||{}}clearSessionStorage(){return this.#zr?.sessionStorage?.clearAll()||!1}log(S,b,I={}){return this.#Ur?.log(S,b,I)||!1}debug(S,b={}){return this.#Ur?.debug(S,b)||!1}info(S,b={}){return this.#Ur?.info(S,b)||!1}warn(S,b={}){return this.#Ur?.warn(S,b)||!1}error(S,b={}){return this.#Ur?.error(S,b)||!1}fatal(S,b={}){return this.#Ur?.fatal(S,b)||!1}setLogContext(S,b){return this.#Ur?.setContext(S,b)||!1}clearLogContext(){return this.#Ur?.clearContext()||!1}setLogLevel(S){return this.#Ur?.setLogLevel(S)||!1}getLogStats(){return this.#Ur?.getStats()||null}async flushLogs(){return this.#Ur?.flush()||!1}enableLogging(S,b="info"){return this.#Ur?.enableServices(S,b)||!1}disableLogging(S){return this.#Ur?.disableServices(S)||!1}enableAllLogging(S="info"){return this.#Ur?.enableAll(S)||!1}disableAllLogging(){return this.#Ur?.disableAll()||!1}getLoggingConfig(){return this.#Ur?.getConfig()||null}getEnabledLogServices(){return this.#Ur?.getEnabledServices()||[]}getAvailableLogServices(){return this.#Ur?.getAvailableServices()||[]}setUserProfile(S){if(!this.#Fr)return this.#o.warn("UserProfileManager not available"),!1;let b=!1;try{b=!0===this.#Fr.setProfile(S)}catch(S){return this.#o.error("Failed to set user profile:",S),!1}if(S&&"object"==typeof S&&isValidUserId(S.userId)){const{userId:b,...I}=S;try{this.#ws(b,I,{mode:"merge"},{skipUserProfileWrite:!0})}catch(S){this.#o.warn?.("Failed to route setUserProfile through identify:",S)}}return b}getUserProfile(){if(!this.#Fr)return{};try{return this.#Fr.getProfile()}catch(S){return this.#o.error("Failed to get user profile:",S),{}}}getSdkContext(){return!1===this.#Xr?{sampled:!1}:this.#Be}setUserMetadata(S,b={}){return this.identify(S,b,{mode:"merge"})}clearUserMetadata(){return!!this.#Be&&(this.#Be.clearUser(),this.#Lr&&this.#Lr.clearUserMetadata(),!0)}identify(S,b={},I={}){return this.#ws(S,b,I,{skipUserProfileWrite:!1})}#ws(S,b={},I={},x={}){if(!isValidUserId(S))return this.#o.error("identify: userId is required and must be a non-empty string (≤256 chars)"),!1;if(!this.#Be)return this.#o.warn("Cannot identify — SDK not initialized"),!1;const R=I&&"set"===I.mode?"set":"merge",A=[],onDrop=(S,b)=>A.push({reason:S,key:b}),{userEmail:_,userName:D,traits:L}=function extractIdentityFromTraits(S,b){const I="function"==typeof b?b:()=>{};if(!S||"object"!=typeof S||Array.isArray(S))return{userEmail:null,userName:null,traits:{}};const x=Object.assign({},S),R=void 0!==x.userEmail?x.userEmail:x.email;delete x.email,delete x.userEmail;let A=null;null!=R&&(isValidEmail(R)?A=R:I("invalid-email","email"));const _=void 0!==x.userName?x.userName:x.name;delete x.name,delete x.userName;let D=null;return null!=_&&(isValidUserName(_)?D=_:I("invalid-name","name")),{userEmail:A,userName:D,traits:x}}(b||{},onDrop),B=sanitizeScalarBag(L,onDrop);this.config?.debug&&A.length>0&&this.#o.warn?.("identify: dropped invalid trait entries:",A);const U=this.#Be.userAttributes||{},$="set"===R?{}:{...U};null!==_&&($.email=_),null!==D&&($.name=D);const j=Object.assign({},$,B);if(this.#Be.setUser(S,j),this.#Lr)try{this.#Lr.updateUserMetadata(S,j)}catch(S){this.#o.warn?.("SessionManager.updateUserMetadata threw:",S)}if(!x.skipUserProfileWrite&&this.#Fr)try{this.#Fr.setProfile({userId:S,...j})}catch(S){this.#o.warn?.("UserProfileManager.setProfile threw:",S)}return this.#Hr?this.#Hr.emitUserIdentified({userId:S,userEmail:_,userName:D,traits:B,mode:R}):this.config?.debug&&this.#o.warn?.("identify: emitter not available (recording disabled?) — context updated but no v1 envelope emitted"),!0}track(S,b={}){if(!this.#We)return this.#o.warn("SDK not initialized"),!1;try{this.logEvent({type:`custom.${S}`,category:"custom",severity:"info",data:b,timestamp:Date.now()})}catch(S){}return this.#Hr?this.#Hr.emitCustomEvent(S,b):(this.config?.debug&&this.#o.warn?.("track: v1 emitter not available (recording disabled?) — legacy event emitted, no v1 envelope"),!1)}recordExperimentExposure(S){return this.#We?this.#Vr?this.#Vr.emitExperimentExposure(S):(this.config?.debug&&this.#o.warn?.("recordExperimentExposure: emitter not available (recording disabled?)"),!1):(this.#o.warn("SDK not initialized"),!1)}recordFlagEvaluation(S){return this.#We?this.#Vr?this.#Vr.emitFlagEvaluation(S):(this.config?.debug&&this.#o.warn?.("recordFlagEvaluation: emitter not available (recording disabled?)"),!1):(this.#o.warn("SDK not initialized"),!1)}getActiveAssignments(){return this.#Vr?this.#Vr.getActiveAssignments():[]}createOpenFeatureHook(){return function makeOpenFeatureHook(S){const b={TARGETING_MATCH:"targeting_match",SPLIT:"split",DEFAULT:"default",DISABLED:"disabled",STATIC:"default",CACHED:"unknown",UNKNOWN:"unknown",ERROR:"error"};return{after(I,x){try{const R=I?.flagKey??x?.flagKey,A=String(null!=x?.variant?x.variant:x?.value);S({flagKey:R,variantKey:A.slice(0,64).replace(/[^a-zA-Z0-9_.:/-]/g,"_")||"unknown",provider:"openfeature",evaluationReason:b[String(x?.reason||"").toUpperCase()]||"unknown"})}catch{}},error(){}}}(S=>this.recordFlagEvaluation(S))}captureException(S,b={}){return this.#We?(this.logEvent({type:"error.captured",category:"error",severity:"error",data:{message:S.message,stack:S.stack,name:S.name,...b},timestamp:Date.now()}),!0):(this.#o.warn("SDK not initialized"),!1)}getStatus(){const S=this.#Lr?.getSessionInfo?.()||{};return{initialized:this.#We,recording:this.#zr?.isRecording||!1,sessionId:this.#Be?.sessionId||null,eventQueueSize:this.#lr?.getQueueSize()||0,session:{id:S.sessionId,duration:S.durationMinutes,events:S.eventCount,chunks:S.chunkCount,pages:S.pageCount,expiresIn:S.willExpireInMinutes}}}forceNewSession(S="manual"){if(!this.#We)return this.#o.warn("SDK not initialized"),null;if(this.#xr)return console.warn("[TraceScout] Cannot start new session - quota exceeded."),null;console.log("[TraceScout] 🔄 Forcing new session, reason:",S),this.#zr?.stop(),this.#Lr&&this.#Lr.forceNewSession(S);const b=this.#Lr?.getOrCreateSession({projectId:this.#Be.projectId,environment:this.#Be.environment,userId:this.#Be.userId});if(this.#Be&&b&&(this.#Be.sessionId=b,this.#Be.sessionStartTime=Date.now()),this.#zr&&b){this.#zr.updateSessionId(b);const S=resolveApiBaseUrl(this.config);this.#zr.updateUploadEndpoint(`${S}/api/projects/${this.#Be.projectId}/sessions/${b}/chunks`),this.#zr.recorder?.start()}return b}debugMode(S){this.config.debug=S,this.#o.updateDebugMode(S),this.#Dr&&this.#Dr.updateDebugMode(S),this.#cr?.updateDebugMode(S),this.#o.log("Debug mode "+(S?"enabled":"disabled"))}getQueueStatus(){return{queueSize:this.#lr?this.#lr.getQueueSize():0,isSending:!!this.#Dr&&this.#Dr.isSending,isInitialized:this.#We,service:this.#Dr?this.#Dr.getServiceName():"none",configSource:this.config?.configSource||"local",configVersion:this.config?.configVersion||"local"}}getPerformanceMetrics(){return this.#Nr?.getMetrics()||null}getCoreWebVitalsMonitor(){return this.#Qr}getCoreWebVitalsMetrics(){return this.#Qr?.getAllMetrics()||null}getCoreWebVitalsInsights(){return this.#Qr?.getPerformanceInsights()||null}generateCoreWebVitalsReport(){return this.#Qr?.generateReport()||null}updateCoreWebVitalsThresholds(S){this.#Qr?this.#Qr.updateThresholds(S):this.#o.warn("Core Web Vitals monitor not available")}}let Tt;try{Tt=new TraceScoutMonitoringCore}catch(S){Tt={init:()=>Promise.reject(new Error("TraceScoutMonitoringCore failed to initialize")),logEvent:()=>{},destroy:()=>{},debugMode:()=>{},setUserProfile:()=>{},getUserProfile:()=>({}),getQueueStatus:()=>({error:"Not available"}),getPerformanceMetrics:()=>null,getCoreWebVitalsMonitor:()=>null,getCoreWebVitalsMetrics:()=>null,getCoreWebVitalsInsights:()=>null,generateCoreWebVitalsReport:()=>null,updateCoreWebVitalsThresholds:()=>{},getSessionRecorder:()=>null,startSessionRecording:()=>Promise.resolve(null),stopSessionRecording:()=>!1,getSessionRecordingStatus:()=>({available:!1,error:"Not available"}),getStatus:()=>({initialized:!1,error:"Not available"}),forceNewSession:()=>null}}if("undefined"!=typeof window)try{window.monitoringCore=Tt}catch(S){}var At=Tt;function extractRequestDetails(S,b,I,x,R="",A="unknown"){try{const _=new URL(S,location.origin);return{method:b.toUpperCase(),url:S,domain:_.hostname,path:_.pathname,status:I,statusText:x,response:R,interceptor:A}}catch{return{method:b.toUpperCase(),url:S,domain:"",path:"",status:I,statusText:x,response:R,interceptor:A}}}function parseRequestUrl(S){try{return new URL(S,location.origin)}catch(S){return null}}class RemoteConfigService{constructor(S,b=null){this.context=S;const I="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname?"https://api.tracescout.com":"http://localhost:3001";this.baseUrl=b||I,this.config=null,this.lastFetched=null,this.refreshInterval=3e5,this.refreshTimer=null,this.logger=createLogger("RemoteConfig"),this.fetchAttempts=0,this.maxFetchAttempts=3,console.log("[RemoteConfigService] Using API base URL:",this.baseUrl)}async fetchConfig(){try{this.fetchAttempts++,this.logger.log("Fetching remote SDK configuration..."),this.logger.log(` Project: ${this.context.projectId}`),this.logger.log(` Workspace: ${this.context.workspaceId}`),this.logger.log(` Attempt: ${this.fetchAttempts}/${this.maxFetchAttempts}`);const S=`${this.baseUrl}/api/projects/${this.context.projectId}/sdk-config`,b=await fetch(S,{method:"GET",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},signal:AbortSignal.timeout(1e4)});if(!b.ok){const S=await b.text();throw new Error(`Config fetch failed: ${b.status} ${b.statusText} - ${S}`)}const I=await b.json();this.#Ss(I),this.config=I,this.lastFetched=Date.now(),this.fetchAttempts=0,this.logger.log("✅ Remote configuration loaded successfully"),this.logger.log(` Config version: ${I.configVersion}`),this.logger.log(` Workspace: ${I.workspace.name}`),this.logger.log(` Project: ${I.project.name}`);const x=Object.keys(I.features).filter(S=>I.features[S].enabled).join(", ");return this.logger.log(` Features enabled: ${x||"none"}`),this.#bs(),I}catch(S){this.logger.error("Failed to fetch remote config:",S.message),this.fetchAttempts<this.maxFetchAttempts?this.logger.warn(`Will retry... (${this.fetchAttempts}/${this.maxFetchAttempts})`):this.logger.warn("Max fetch attempts reached, using fallback configuration");const b=this.#Cs();return this.config=b,b}}#Ss(S){if(!S.success)throw new Error("Server returned unsuccessful config response");if(!S.project||S.project.id!==this.context.projectId)throw new Error(`Config projectId mismatch. Expected: ${this.context.projectId}, Got: ${S.project?.id}`);if(!S.workspace||!S.workspace.id)throw new Error("Config missing workspace data");if(!S.features)throw new Error("Config missing features object");if(!S.privacy)throw new Error("Config missing privacy object");if(!S.telemetry)throw new Error("Config missing telemetry object");this.logger.log("✓ Config validation passed")}#Cs(){return this.logger.warn("⚠️ Using fallback configuration - limited functionality"),this.logger.warn(" Session recording: enabled (100% sample rate)"),this.logger.warn(" Error tracking: enabled"),this.logger.warn(" Other features: disabled"),{success:!0,configVersion:"2.0.0-fallback",lastUpdated:(new Date).toISOString(),workspace:{id:this.context.workspaceId,name:"Unknown Workspace (Fallback)"},project:{id:this.context.projectId,name:"Unknown Project (Fallback)",environment:this.context.environment,allowedOrigins:[]},features:{sessionRecording:{enabled:!0,sampleRate:1,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[],chunkDuration:3e4,maxChunkSize:5e5,recordCanvas:!1,collectFonts:!1},errorTracking:{enabled:!0,ignoreErrors:[],sourceMaps:!1,stackTraceLimit:30},performanceMonitoring:{enabled:!1,coreWebVitals:!1,longTaskThreshold:50,resourceTimingBufferSize:250},consoleCapture:{enabled:!0,levels:["error","warn"]},networkMonitoring:{enabled:!1,endpoints:[],captureHeaders:!1,captureBody:!1}},privacy:{maskInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},telemetry:{endpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`,sessionEndpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/sessions`,batchSize:10,flushInterval:5e3,enableCompression:!0},service:{send:async S=>{const b=`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`;console.log("[TraceScout][FallbackService] Sending to:",b),console.log("[TraceScout][FallbackService] Events:",S);try{const I=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},body:JSON.stringify({events:S,context:{workspaceId:this.context.workspaceId,projectId:this.context.projectId,environment:this.context.environment,sessionId:this.context.sessionId}})});if(!I.ok)throw new Error(`HTTP ${I.status}: ${I.statusText}`);return await I.json()}catch(S){throw console.error("[TraceScout][FallbackService] Send failed:",S),S}}}}}#bs(){this.refreshTimer&&clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(async()=>{this.logger.log("⏰ Refreshing remote configuration...");try{await this.fetchConfig(),this.logger.log("✅ Config refreshed successfully")}catch(S){this.logger.error("Config refresh failed:",S.message)}},this.refreshInterval),this.logger.log(`Next config refresh in ${this.refreshInterval/1e3}s`)}stopRefresh(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null,this.logger.log("Config refresh stopped"))}getConfig(){return this.config}isStale(){return!this.lastFetched||Date.now()-this.lastFetched>this.refreshInterval}async refresh(){return this.logger.log("Forcing config refresh..."),await this.fetchConfig()}getConfigAge(){return this.lastFetched?Math.floor((Date.now()-this.lastFetched)/1e3):-1}}function __tsSafeContentDoc(S){try{if(S&&"IFRAME"===S.tagName&&S.src)try{var b=new URL(S.src);if(("http:"===b.protocol||"https:"===b.protocol)&&"undefined"!=typeof location&&b.origin!==location.origin)return null}catch(S){}return S.contentDocument}catch(S){return null}}var _t,Ot=Object.defineProperty,__publicField=(S,b,I)=>((S,b,I)=>b in S?Ot(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),Dt=Object.defineProperty,__publicField$1=(S,b,I)=>((S,b,I)=>b in S?Dt(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),Ft=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(Ft||{});const Nt={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Lt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Pt={};function getUntaintedPrototype$1(S){if(Pt[S])return Pt[S];const b=globalThis[S],I=b.prototype,x=S in Nt?Nt[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in Lt?Lt[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return Pt[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?Pt[S]=A:I}catch{return I}}const Bt={};function getUntaintedAccessor$1(S,b,I){var x;const R=`${S}.${String(I)}`;if(Bt[R])return Bt[R].call(b);const A=getUntaintedPrototype$1(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(Bt[R]=_,_.call(b)):b[I]}const zt={};function getUntaintedMethod$1(S,b,I){const x=`${S}.${String(I)}`;if(zt[x])return zt[x].bind(b);const R=getUntaintedPrototype$1(S)[I];return"function"!=typeof R?b[I]:(zt[x]=R,R.bind(b))}const Ut={childNodes:function childNodes$1(S){return getUntaintedAccessor$1("Node",S,"childNodes")},parentNode:function parentNode$1(S){return getUntaintedAccessor$1("Node",S,"parentNode")},parentElement:function parentElement$1(S){return getUntaintedAccessor$1("Node",S,"parentElement")},textContent:function textContent$1(S){return getUntaintedAccessor$1("Node",S,"textContent")},contains:function contains$1(S,b){return getUntaintedMethod$1("Node",S,"contains")(b)},getRootNode:function getRootNode$1(S){return getUntaintedMethod$1("Node",S,"getRootNode")()},host:function host$1(S){return S&&"host"in S?getUntaintedAccessor$1("ShadowRoot",S,"host"):null},styleSheets:function styleSheets$1(S){return S.styleSheets},shadowRoot:function shadowRoot$1(S){return S&&"shadowRoot"in S?getUntaintedAccessor$1("Element",S,"shadowRoot"):null},querySelector:function querySelector$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelectorAll")(b)},mutationObserver:function mutationObserverCtor$1(){return getUntaintedPrototype$1("MutationObserver").constructor}};function isElement(S){return S.nodeType===S.ELEMENT_NODE}function isShadowRoot(S){const b=S&&"host"in S&&"mode"in S&&Ut.host(S)||null;return Boolean(b&&"shadowRoot"in b&&Ut.shadowRoot(b)===S)}function isNativeShadowDom(S){return"[object ShadowRoot]"===Object.prototype.toString.call(S)}function stringifyStylesheet(S){try{const b=S.rules||S.cssRules;if(!b)return null;let I=S.href;!I&&S.ownerNode&&S.ownerNode.ownerDocument&&(I=S.ownerNode.ownerDocument.location.href);return function fixBrowserCompatibilityIssuesInCSS(S){return S.includes(" background-clip: text;")&&!S.includes(" -webkit-background-clip: text;")&&(S=S.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),S}(Array.from(b,S=>stringifyRule(S,I)).join(""))}catch(S){return null}}function stringifyRule(S,b){if(function isCSSImportRule(S){return"styleSheet"in S}(S)){let b;try{b=stringifyStylesheet(S.styleSheet)||function escapeImportStatement(S){const{cssText:b}=S;if(b.split('"').length<3)return b;const I=["@import",`url(${JSON.stringify(S.href)})`];return""===S.layerName?I.push("layer"):S.layerName&&I.push(`layer(${S.layerName})`),S.supportsText&&I.push(`supports(${S.supportsText})`),S.media.length&&I.push(S.media.mediaText),I.join(" ")+";"}(S)}catch(I){b=S.cssText}return S.styleSheet.href?absolutifyURLs(b,S.styleSheet.href):b}{let I=S.cssText;return function isCSSStyleRule(S){return"selectorText"in S}(S)&&S.selectorText.includes(":")&&(I=function fixSafariColons(S){const b=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return S.replace(b,"$1\\$2")}(I)),b?absolutifyURLs(I,b):I}}class Mirror{constructor(){__publicField$1(this,"idNodeMap",new Map),__publicField$1(this,"nodeMetaMap",new WeakMap)}getId(S){var b;if(!S)return-1;return(null==(b=this.getMeta(S))?void 0:b.id)??-1}getNode(S){return this.idNodeMap.get(S)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(S){return this.nodeMetaMap.get(S)||null}removeNodeFromMap(S){const b=this.getId(S);this.idNodeMap.delete(b),S.childNodes&&S.childNodes.forEach(S=>this.removeNodeFromMap(S))}has(S){return this.idNodeMap.has(S)}hasNode(S){return this.nodeMetaMap.has(S)}add(S,b){const I=b.id;this.idNodeMap.set(I,S),this.nodeMetaMap.set(S,b)}replace(S,b){const I=this.getNode(S);if(I){const S=this.nodeMetaMap.get(I);S&&this.nodeMetaMap.set(b,S)}this.idNodeMap.set(S,b)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function maskInputValue({element:S,maskInputOptions:b,tagName:I,type:x,value:R,maskInputFn:A}){let _=R||"";const D=x&&toLowerCase(x);return(b[I.toLowerCase()]||D&&b[D])&&(_=A?A(_,S):"*".repeat(_.length)),_}function toLowerCase(S){return S.toLowerCase()}const $t="__rrweb_original__";function getInputType(S){const b=S.type;return S.hasAttribute("data-rr-is-password")?"password":b?toLowerCase(b):null}function extractFileExtension(S,b){let I;try{I=new URL(S,b??window.location.href)}catch(S){return null}const x=I.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==x?void 0:x[1])??null}const jt=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,qt=/^(?:[a-z+]+:)?\/\//i,Wt=/^www\..*/i,Ht=/^(data:)([^,]*),(.*)/i;function absolutifyURLs(S,b){return(S||"").replace(jt,(S,I,x,R,A,_)=>{const D=x||A||_,L=I||R||"";if(!D)return S;if(qt.test(D)||Wt.test(D))return`url(${L}${D}${L})`;if(Ht.test(D))return`url(${L}${D}${L})`;if("/"===D[0])return`url(${L}${function extractOrigin(S){let b="";return b=S.indexOf("//")>-1?S.split("/").slice(0,3).join("/"):S.split("/")[0],b=b.split("?")[0],b}(b)+D}${L})`;const B=b.split("/"),U=D.split("/");B.pop();for(const S of U)"."!==S&&(".."===S?B.pop():B.push(S));return`url(${L}${B.join("/")}${L})`})}function normalizeCssString(S){return S.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function markCssSplits(S,b){return function splitCssText(S,b){const I=Array.from(b.childNodes),x=[];if(I.length>1&&S&&"string"==typeof S){const b=normalizeCssString(S);for(let R=1;R<I.length;R++)if(I[R].textContent&&"string"==typeof I[R].textContent){const A=normalizeCssString(I[R].textContent);for(let I=3;I<A.length;I++){const R=A.substring(0,I);if(2===b.split(R).length){const I=b.indexOf(R);for(let b=I;b<S.length;b++)if(normalizeCssString(S.substring(0,b)).length===I){x.push(S.substring(0,b)),S=S.substring(b);break}break}}}}return x.push(S),x}(S,b).join("/* rr_split */")}let Vt=1;const Qt=new RegExp("[^a-z0-9-_:]");function genId(){return Vt++}let Kt,Gt;const Jt=/^[^ \t\n\r\u000c]+/,Xt=/^[, \t\n\r\u000c]+/;const Zt=new WeakMap;function absoluteToDoc(S,b){return b&&""!==b.trim()?getHref(S,b):b}function isSVGElement(S){return Boolean("svg"===S.tagName||S.ownerSVGElement)}function getHref(S,b){let I=Zt.get(S);if(I||(I=S.createElement("a"),Zt.set(S,I)),b){if(b.startsWith("blob:")||b.startsWith("data:"))return b}else b="";return I.setAttribute("href",b),I.href}function transformAttribute(S,b,I,x){return x?"src"===I||"href"===I&&("use"!==b||"#"!==x[0])||"xlink:href"===I&&"#"!==x[0]?absoluteToDoc(S,x):"background"!==I||"table"!==b&&"td"!==b&&"th"!==b?"srcset"===I?function getAbsoluteSrcsetString(S,b){if(""===b.trim())return b;let I=0;function collectCharacters(S){let x;const R=S.exec(b.substring(I));return R?(x=R[0],I+=x.length,x):""}const x=[];for(;collectCharacters(Xt),!(I>=b.length);){let R=collectCharacters(Jt);if(","===R.slice(-1))R=absoluteToDoc(S,R.substring(0,R.length-1)),x.push(R);else{let A="";R=absoluteToDoc(S,R);let _=!1;for(;;){const S=b.charAt(I);if(""===S){x.push((R+A).trim());break}if(_)")"===S&&(_=!1);else{if(","===S){I+=1,x.push((R+A).trim());break}"("===S&&(_=!0)}A+=S,I+=1}}}return x.join(", ")}(S,x):"style"===I?absolutifyURLs(x,getHref(S)):"object"===b&&"data"===I?absoluteToDoc(S,x):x:absoluteToDoc(S,x):x}function ignoreAttribute(S,b,I){return("video"===S||"audio"===S)&&"autoplay"===b}function classMatchesRegex(S,b,I){if(!S)return!1;if(S.nodeType!==S.ELEMENT_NODE)return!!I&&classMatchesRegex(Ut.parentNode(S),b,I);for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}return!!I&&classMatchesRegex(Ut.parentNode(S),b,I)}function needMaskingText(S,b,I,x){let R;if(isElement(S)){if(R=S,!Ut.childNodes(R).length)return!1}else{if(null===Ut.parentElement(S))return!1;R=Ut.parentElement(S)}try{if("string"==typeof b){if(x){if(R.closest(`.${b}`))return!0}else if(R.classList.contains(b))return!0}else if(classMatchesRegex(R,b,x))return!0;if(I)if(x){if(R.closest(I))return!0}else if(R.matches(I))return!0}catch(S){}return!1}function serializeNode(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:_,inlineStylesheet:D,maskInputOptions:L={},maskTextFn:B,maskInputFn:U,dataURLOptions:$={},inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V=!1,cssCaptured:Q=!1}=b,G=function getRootId(S,b){if(!b.hasNode(S))return;const I=b.getId(S);return 1===I?void 0:I}(I,x);switch(S.nodeType){case S.DOCUMENT_NODE:return"CSS1Compat"!==S.compatMode?{type:Ft.Document,childNodes:[],compatMode:S.compatMode}:{type:Ft.Document,childNodes:[]};case S.DOCUMENT_TYPE_NODE:return{type:Ft.DocumentType,name:S.name,publicId:S.publicId,systemId:S.systemId,rootId:G};case S.ELEMENT_NODE:return function serializeElementNode(S,b){const{doc:I,blockClass:x,blockSelector:R,inlineStylesheet:A,maskInputOptions:_={},maskInputFn:D,dataURLOptions:L={},inlineImages:B,recordCanvas:U,keepIframeSrcFn:$,newlyAddedElement:j=!1,rootId:W}=b,H=function _isBlockedElement(S,b,I){try{if("string"==typeof b){if(S.classList.contains(b))return!0}else for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}if(I)return S.matches(I)}catch(S){}return!1}(S,x,R),V=function getValidTagName$1(S){if(S instanceof HTMLFormElement)return"form";const b=toLowerCase(S.tagName);return Qt.test(b)?"div":b}(S);let Q={};const G=S.attributes.length;for(let b=0;b<G;b++){const x=S.attributes[b];ignoreAttribute(V,x.name)||(Q[x.name]=transformAttribute(I,V,toLowerCase(x.name),x.value))}if("link"===V&&A){const b=Array.from(I.styleSheets).find(b=>b.href===S.href);let x=null;b&&(x=stringifyStylesheet(b)),x&&(delete Q.rel,delete Q.href,Q._cssText=x)}if("style"===V&&S.sheet){let b=stringifyStylesheet(S.sheet);b&&(S.childNodes.length>1&&(b=markCssSplits(b,S)),Q._cssText=b)}if("input"===V||"textarea"===V||"select"===V){const b=S.value,I=S.checked;"radio"!==Q.type&&"checkbox"!==Q.type&&"submit"!==Q.type&&"button"!==Q.type&&b?Q.value=maskInputValue({element:S,type:getInputType(S),tagName:V,value:b,maskInputOptions:_,maskInputFn:D}):I&&(Q.checked=I)}"option"===V&&(S.selected&&!_.select?Q.selected=!0:delete Q.selected);"dialog"===V&&S.open&&(Q.rr_open_mode=S.matches("dialog:modal")?"modal":"non-modal");if("canvas"===V&&U)if("2d"===S.__context)(function is2DCanvasBlank(S){const b=S.getContext("2d");if(!b)return!0;for(let I=0;I<S.width;I+=50)for(let x=0;x<S.height;x+=50){const R=b.getImageData,A=$t in R?R[$t]:R;if(new Uint32Array(A.call(b,I,x,Math.min(50,S.width-I),Math.min(50,S.height-x)).data.buffer).some(S=>0!==S))return!1}return!0})(S)||(Q.rr_dataURL=S.toDataURL(L.type,L.quality));else if(!("__context"in S)){const b=S.toDataURL(L.type,L.quality),x=I.createElement("canvas");x.width=S.width,x.height=S.height;b!==x.toDataURL(L.type,L.quality)&&(Q.rr_dataURL=b)}if("img"===V&&B){Kt||(Kt=I.createElement("canvas"),Gt=Kt.getContext("2d"));const b=S,x=b.currentSrc||b.getAttribute("src")||"<unknown-src>",R=b.crossOrigin,recordInlineImage=()=>{b.removeEventListener("load",recordInlineImage);try{Kt.width=b.naturalWidth,Kt.height=b.naturalHeight,Gt.drawImage(b,0,0),Q.rr_dataURL=Kt.toDataURL(L.type,L.quality)}catch(S){if("anonymous"!==b.crossOrigin)return b.crossOrigin="anonymous",void(b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage));console.warn(`Cannot inline img src=${x}! Error: ${S}`)}"anonymous"===b.crossOrigin&&(R?Q.crossOrigin=R:b.removeAttribute("crossorigin"))};b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage)}if("audio"===V||"video"===V){const b=Q;b.rr_mediaState=S.paused?"paused":"played",b.rr_mediaCurrentTime=S.currentTime,b.rr_mediaPlaybackRate=S.playbackRate,b.rr_mediaMuted=S.muted,b.rr_mediaLoop=S.loop,b.rr_mediaVolume=S.volume}j||(S.scrollLeft&&(Q.rr_scrollLeft=S.scrollLeft),S.scrollTop&&(Q.rr_scrollTop=S.scrollTop));if(H){const{width:b,height:I}=S.getBoundingClientRect();Q={class:Q.class,rr_width:`${b}px`,rr_height:`${I}px`}}"iframe"!==V||$(Q.src)||(__tsSafeContentDoc(S)||(Q.rr_src=Q.src),delete Q.src);let J;try{customElements.get(V)&&(J=!0)}catch(S){}return{type:Ft.Element,tagName:V,attributes:Q,childNodes:[],isSVG:isSVGElement(S)||void 0,needBlock:H,rootId:W,isCustom:J}}(S,{doc:I,blockClass:R,blockSelector:A,inlineStylesheet:D,maskInputOptions:L,maskInputFn:U,dataURLOptions:$,inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V,rootId:G});case S.TEXT_NODE:return function serializeTextNode(S,b){const{needsMask:I,maskTextFn:x,rootId:R,cssCaptured:A}=b,_=Ut.parentNode(S),D=_&&_.tagName;let L="";const B="STYLE"===D||void 0,U="SCRIPT"===D||void 0;U?L="SCRIPT_PLACEHOLDER":A||(L=Ut.textContent(S),B&&L&&(L=absolutifyURLs(L,getHref(b.doc))));!B&&!U&&L&&I&&(L=x?x(L,Ut.parentElement(S)):L.replace(/[\S]/g,"*"));return{type:Ft.Text,textContent:L||"",rootId:R}}(S,{doc:I,needsMask:_,maskTextFn:B,rootId:G,cssCaptured:Q});case S.CDATA_SECTION_NODE:return{type:Ft.CDATA,textContent:"",rootId:G};case S.COMMENT_NODE:return{type:Ft.Comment,textContent:Ut.textContent(S)||"",rootId:G};default:return!1}}function lowerIfExists(S){return null==S?"":S.toLowerCase()}function serializeNodeWithId(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,maskTextClass:_,maskTextSelector:D,skipChild:L=!1,inlineStylesheet:B=!0,maskInputOptions:U={},maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H={},inlineImages:V=!1,recordCanvas:Q=!1,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X=5e3,onStylesheetLoad:Y,stylesheetLoadTimeout:ee=5e3,keepIframeSrcFn:te=()=>!1,newlyAddedElement:re=!1,cssCaptured:se=!1}=b;let{needsMask:ne}=b,{preserveWhiteSpace:ie=!0}=b;if(!ne){ne=needMaskingText(S,_,D,void 0===ne)}const oe=serializeNode(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,dataURLOptions:H,inlineImages:V,recordCanvas:Q,keepIframeSrcFn:te,newlyAddedElement:re,cssCaptured:se});if(!oe)return console.warn(S,"not serialized"),null;let ae;ae=x.hasNode(S)?x.getId(S):function slimDOMExcluded(S,b){if(b.comment&&S.type===Ft.Comment)return!0;if(S.type===Ft.Element){if(b.script&&("script"===S.tagName||"link"===S.tagName&&("preload"===S.attributes.rel||"modulepreload"===S.attributes.rel)&&"script"===S.attributes.as||"link"===S.tagName&&"prefetch"===S.attributes.rel&&"string"==typeof S.attributes.href&&"js"===extractFileExtension(S.attributes.href)))return!0;if(b.headFavicon&&("link"===S.tagName&&"shortcut icon"===S.attributes.rel||"meta"===S.tagName&&(lowerIfExists(S.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===lowerIfExists(S.attributes.name)||"icon"===lowerIfExists(S.attributes.rel)||"apple-touch-icon"===lowerIfExists(S.attributes.rel)||"shortcut icon"===lowerIfExists(S.attributes.rel))))return!0;if("meta"===S.tagName){if(b.headMetaDescKeywords&&lowerIfExists(S.attributes.name).match(/^description|keywords$/))return!0;if(b.headMetaSocial&&(lowerIfExists(S.attributes.property).match(/^(og|twitter|fb):/)||lowerIfExists(S.attributes.name).match(/^(og|twitter):/)||"pinterest"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaRobots&&("robots"===lowerIfExists(S.attributes.name)||"googlebot"===lowerIfExists(S.attributes.name)||"bingbot"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaHttpEquiv&&void 0!==S.attributes["http-equiv"])return!0;if(b.headMetaAuthorship&&("author"===lowerIfExists(S.attributes.name)||"generator"===lowerIfExists(S.attributes.name)||"framework"===lowerIfExists(S.attributes.name)||"publisher"===lowerIfExists(S.attributes.name)||"progid"===lowerIfExists(S.attributes.name)||lowerIfExists(S.attributes.property).match(/^article:/)||lowerIfExists(S.attributes.property).match(/^product:/)))return!0;if(b.headMetaVerification&&("google-site-verification"===lowerIfExists(S.attributes.name)||"yandex-verification"===lowerIfExists(S.attributes.name)||"csrf-token"===lowerIfExists(S.attributes.name)||"p:domain_verify"===lowerIfExists(S.attributes.name)||"verify-v1"===lowerIfExists(S.attributes.name)||"verification"===lowerIfExists(S.attributes.name)||"shopify-checkout-api-token"===lowerIfExists(S.attributes.name)))return!0}}return!1}(oe,W)||!ie&&oe.type===Ft.Text&&!oe.textContent.replace(/^\s+|\s+$/gm,"").length?-2:genId();const le=Object.assign(oe,{id:ae});if(x.add(S,le),-2===ae)return null;G&&G(S);let ce=!L;if(le.type===Ft.Element){ce=ce&&!le.needBlock,delete le.needBlock;const b=Ut.shadowRoot(S);b&&isNativeShadowDom(b)&&(le.isShadowHost=!0)}if((le.type===Ft.Document||le.type===Ft.Element)&&ce){W.headWhitespace&&le.type===Ft.Element&&"head"===le.tagName&&(ie=!1);const b={doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:L,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te,cssCaptured:!1};if(le.type===Ft.Element&&"textarea"===le.tagName&&void 0!==le.attributes.value);else{le.type===Ft.Element&&void 0!==le.attributes._cssText&&"string"==typeof le.attributes._cssText&&(b.cssCaptured=!0);for(const I of Array.from(Ut.childNodes(S))){const S=serializeNodeWithId(I,b);S&&le.childNodes.push(S)}}let re=null;if(isElement(S)&&(re=Ut.shadowRoot(S)))for(const S of Array.from(Ut.childNodes(re))){const I=serializeNodeWithId(S,b);I&&(isNativeShadowDom(re)&&(I.isShadow=!0),le.childNodes.push(I))}}const ue=Ut.parentNode(S);return ue&&isShadowRoot(ue)&&isNativeShadowDom(ue)&&(le.isShadow=!0),le.type===Ft.Element&&"iframe"===le.tagName&&function onceIframeLoaded(S,b,I){const x=S.contentWindow;if(!x)return;let R,A=!1;try{R=x.document.readyState}catch(S){return}if("complete"!==R){const x=setTimeout(()=>{A||(b(),A=!0)},I);return void S.addEventListener("load",()=>{clearTimeout(x),A=!0,b()})}const _="about:blank";if(x.location.href!==_||S.src===_||""===S.src)return setTimeout(b,0),S.addEventListener("load",b);S.addEventListener("load",b)}(S,()=>{const b=__tsSafeContentDoc(S);if(b&&J){const I=serializeNodeWithId(b,{doc:b,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});I&&J(S,I)}},X),le.type===Ft.Element&&"link"===le.tagName&&"string"==typeof le.attributes.rel&&("stylesheet"===le.attributes.rel||"preload"===le.attributes.rel&&"string"==typeof le.attributes.href&&"css"===extractFileExtension(le.attributes.href))&&function onceStylesheetLoaded(S,b,I){let x,R=!1;try{x=S.sheet}catch(S){return}if(x)return;const A=setTimeout(()=>{R||(b(),R=!0)},I);S.addEventListener("load",()=>{clearTimeout(A),R=!0,b()})}(S,()=>{if(Y){const b=serializeNodeWithId(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});b&&Y(S,b)}},ee),le}function getAugmentedNamespace$1(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var Yt={exports:{}},er=String,create$1=function(){return{isColorSupported:!1,reset:er,bold:er,dim:er,italic:er,underline:er,inverse:er,hidden:er,strikethrough:er,black:er,red:er,green:er,yellow:er,blue:er,magenta:er,cyan:er,white:er,gray:er,bgBlack:er,bgRed:er,bgGreen:er,bgYellow:er,bgBlue:er,bgMagenta:er,bgCyan:er,bgWhite:er}};Yt.exports=create$1(),Yt.exports.createColors=create$1;var tr=Yt.exports;const rr=getAugmentedNamespace$1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let sr=tr,nr=rr,ir=class CssSyntaxError extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=sr.isColorSupported),nr&&S&&(b=nr(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=sr.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var or=ir;ir.default=ir;var ar={};ar.isClean=Symbol("isClean"),ar.my=Symbol("my");const lr={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let cr=class Stringifier{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return lr[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize$1(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=lr[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var ur=cr;cr.default=cr;let hr=ur;function stringify$4$1(S,b){new hr(b).stringify(S)}var dr=stringify$4$1;stringify$4$1.default=stringify$4$1;let{isClean:gr,my:pr}=ar,fr=or,mr=ur,yr=dr;function cloneNode$1(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode$1(S,I)):("object"===A&&null!==R&&(R=cloneNode$1(R)),I[x]=R)}return I}let vr=class Node2{constructor(S={}){this.raws={},this[gr]=!1,this[pr]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode$1(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new fr(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[gr]){this[gr]=!1;let S=this;for(;S=S.parent;)S[gr]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new mr).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=yr){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var wr=vr;vr.default=vr;let Sr=wr,br=class Declaration extends Sr{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var Cr=br;br.default=br;var kr={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:Ir,SourceMapGenerator:Er}=rr,{existsSync:xr,readFileSync:Mr}=rr,{dirname:Rr,join:Tr}=rr;let Ar=class PreviousMap{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=Rr(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new Ir(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64$1(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=Rr(S),xr(S))return this.mapFile=S,Mr(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof Ir)return Er.fromSourceMap(b).toString();if(b instanceof Er)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=Tr(Rr(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var _r=Ar;Ar.default=Ar;let{SourceMapConsumer:Or,SourceMapGenerator:Dr}=rr,{fileURLToPath:Fr,pathToFileURL:Nr}=rr,{isAbsolute:Lr,resolve:Pr}=rr,{nanoid:Br}=kr,zr=rr,Ur=or,$r=_r,jr=Symbol("fromOffsetCache"),qr=Boolean(Or&&Dr),Wr=Boolean(Pr&&Lr),Hr=class Input{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!Wr||/^\w+:\/\//.test(b.from)||Lr(b.from)?this.file=b.from:this.file=Pr(b.from)),Wr&&qr){let S=new $r(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+Br(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new Ur(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new Ur(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(Nr&&(R.input.url=Nr(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[jr])I=this[jr];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[jr]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:Pr(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=Lr(D.source)?Nr(D.source):new URL(D.source,this.map.consumer().sourceRoot||Nr(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!Fr)throw new Error("file: protocol is not available in this PostCSS build");L.file=Fr(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var Vr=Hr;Hr.default=Hr,zr&&zr.registerInput&&zr.registerInput(Hr);let{SourceMapConsumer:Qr,SourceMapGenerator:Kr}=rr,{dirname:Gr,relative:Jr,resolve:Xr,sep:Zr}=rr,{pathToFileURL:Yr}=rr,es=Vr,ts=Boolean(Qr&&Kr),rs=Boolean(Gr&&Xr&&Jr&&Zr);var ss=class MapGenerator{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||Gr(S.file);!1===this.mapOpts.sourcesContent?(b=new Qr(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),rs&&ts&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=Kr.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Kr({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Kr({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?Gr(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Gr(Xr(I,this.mapOpts.annotation)));let x=Jr(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new es(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(Yr){let b=Yr(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===Zr&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let ns=wr,is=class Comment extends ns{constructor(S){super(S),this.type="comment"}};var os=is;is.default=is;let as,ls,cs,us,{isClean:hs,my:ds}=ar,gs=Cr,ps=os,fs=wr;function cleanSource$1(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource$1(S.nodes)),delete S.source,S))}function markDirtyUp$1(S){if(S[hs]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp$1(b)}let ms=class Container extends fs{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource$1(as(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new gs(S)]}else if(S.selector)S=[new ls(S)];else if(S.name)S=[new cs(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new ps(S)]}return S.map(S=>(S[ds]||Container.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[hs]&&markDirtyUp$1(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};ms.registerParse=S=>{as=S},ms.registerRule=S=>{ls=S},ms.registerAtRule=S=>{cs=S},ms.registerRoot=S=>{us=S};var ys=ms;ms.default=ms,ms.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,cs.prototype):"rule"===S.type?Object.setPrototypeOf(S,ls.prototype):"decl"===S.type?Object.setPrototypeOf(S,gs.prototype):"comment"===S.type?Object.setPrototypeOf(S,ps.prototype):"root"===S.type&&Object.setPrototypeOf(S,us.prototype),S[ds]=!0,S.nodes&&S.nodes.forEach(S=>{ms.rebuild(S)})};let vs,ws,Ss=ys,bs=class Document2 extends Ss{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new vs(new ws,this,S).stringify()}};bs.registerLazyResult=S=>{vs=S},bs.registerProcessor=S=>{ws=S};var Cs=bs;bs.default=bs;let ks=class Warning{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var Is=ks;ks.default=ks;let Es=Is,xs=class Result{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new Es(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var Ms=xs;xs.default=xs;const Rs="'".charCodeAt(0),Ts='"'.charCodeAt(0),As="\\".charCodeAt(0),_s="/".charCodeAt(0),Os="\n".charCodeAt(0),Ds=" ".charCodeAt(0),Fs="\f".charCodeAt(0),Ns="\t".charCodeAt(0),Ls="\r".charCodeAt(0),Ps="[".charCodeAt(0),Bs="]".charCodeAt(0),zs="(".charCodeAt(0),Us=")".charCodeAt(0),$s="{".charCodeAt(0),js="}".charCodeAt(0),qs=";".charCodeAt(0),Ws="*".charCodeAt(0),Hs=":".charCodeAt(0),Vs="@".charCodeAt(0),Qs=/[\t\n\f\r "#'()/;[\\\]{}]/g,Ks=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Gs=/.[\r\n"'(/\\]/,Js=/[\da-f]/i;let Xs=ys,Zs=class AtRule extends Xs{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var Ys=Zs;Zs.default=Zs,Xs.registerAtRule(Zs);let en,tn,rn=ys,sn=class Root extends rn{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new en(new tn,this,S).stringify()}};sn.registerLazyResult=S=>{en=S},sn.registerProcessor=S=>{tn=S};var nn=sn;sn.default=sn,rn.registerRoot(sn);let an={comma:S=>an.split(S,[","],!0),space:S=>an.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var cn=an;an.default=an;let un=ys,hn=cn,dn=class Rule extends un{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return hn.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var gn=dn;dn.default=dn,un.registerRule(dn);let pn=Cr,fn=function tokenizer(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case Os:case Ds:case Ns:case Ls:case Fs:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===Ds||I===Os||I===Ns||I===Ls||I===Fs);$=["space",j.slice(V,x)],V=x-1;break;case Ps:case Bs:case $s:case js:case Hs:case qs:case Us:{let S=String.fromCharCode(I);$=[S,S,V];break}case zs:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==Rs&&U!==Ts&&U!==Ds&&U!==Os&&U!==Ns&&U!==Fs&&U!==Ls){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===As;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||Gs.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case Rs:case Ts:R=I===Rs?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===As;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Vs:Qs.lastIndex=V+1,Qs.test(j),x=0===Qs.lastIndex?j.length-1:Qs.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case As:for(x=V,_=!0;j.charCodeAt(x+1)===As;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==_s&&I!==Ds&&I!==Os&&I!==Ns&&I!==Ls&&I!==Fs&&(x+=1,Js.test(j.charAt(x)))){for(;Js.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===Ds&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===_s&&j.charCodeAt(V+1)===Ws?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(Ks.lastIndex=V+1,Ks.test(j),x=0===Ks.lastIndex?j.length-1:Ks.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},mn=os,yn=Ys,vn=nn,wn=gn;const Sn={empty:!0,space:!0};var bn=class Parser{constructor(S){this.input=S,this.root=new vn,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new yn;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new mn;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=fn(this.input)}decl(S,b){let I=new pn;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition$1(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new wn;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",Sn[D]||Sn[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new wn;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let Cn=ys,kn=bn,In=Vr;function parse$3$1(S,b){let I=new In(S,b),x=new kn(I);try{x.parse()}catch(S){throw S}return x.root}var En=parse$3$1;parse$3$1.default=parse$3$1,Cn.registerParse(parse$3$1);let{isClean:xn,my:Mn}=ar,Rn=ss,Tn=dr,An=ys,_n=Cs,On=Ms,Dn=En,Fn=nn;const Nn={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Ln={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Pn={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise$1(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents$1(S){let b=!1,I=Nn[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack$1(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents$1(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks$1(S){return S[xn]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks$1(S)),S}let Bn={},zn=class LazyResult{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult||b instanceof On)x=cleanMarks$1(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=Dn;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[Mn]&&An.rebuild(x)}else x=cleanMarks$1(b);this.result=new On(S,x,I),this.helpers={...Bn,postcss:Bn,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!Ln[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Pn[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise$1(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[xn];){S[xn]=!0;let b=[toStack$1(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise$1(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise$1(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=Tn;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new Rn(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise$1(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[xn];)S[xn]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise$1(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[xn])return x[xn]=!0,void S.push(toStack$1(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[xn]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[xn]=!0;let b=getEvents$1(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[xn]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};zn.registerPostcss=S=>{Bn=S};var Un=zn;zn.default=zn,Fn.registerLazyResult(zn),_n.registerLazyResult(zn);let $n=ss,jn=dr,qn=En;const Wn=Ms;let Hn=class NoWorkResult{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=jn;this.result=new Wn(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new $n(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=qn;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var Vn=Hn;Hn.default=Hn;let Qn=Vn,Kn=Un,Gn=Cs,Jn=nn,Xn=class Processor{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new Kn(this,S,b):new Qn(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var Zn=Xn;Xn.default=Xn,Jn.registerProcessor(Xn),Gn.registerProcessor(Xn);let Yn=Cr,ei=_r,ti=os,ri=Ys,si=Vr,ni=nn,ii=gn;function fromJSON$1$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:si.prototype};I.map&&(I.map={...I.map,__proto__:ei.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new ni(x);if("decl"===x.type)return new Yn(x);if("rule"===x.type)return new ii(x);if("comment"===x.type)return new ti(x);if("atrule"===x.type)return new ri(x);throw new Error("Unknown node type: "+S.type)}var oi=fromJSON$1$1;fromJSON$1$1.default=fromJSON$1$1;let ai=or,li=Cr,ci=Un,ui=ys,hi=Zn,di=dr,gi=oi,pi=Cs,fi=Is,mi=os,yi=Ys,vi=Ms,wi=Vr,Si=En,bi=cn,Ci=gn,ki=nn,Ii=wr;function postcss$3(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new hi(S)}postcss$3.plugin=function plugin(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new hi).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss$3([creator(I)]).process(S,b)},creator},postcss$3.stringify=di,postcss$3.parse=Si,postcss$3.fromJSON=gi,postcss$3.list=bi,postcss$3.comment=S=>new mi(S),postcss$3.atRule=S=>new yi(S),postcss$3.decl=S=>new li(S),postcss$3.rule=S=>new Ci(S),postcss$3.root=S=>new ki(S),postcss$3.document=S=>new pi(S),postcss$3.CssSyntaxError=ai,postcss$3.Declaration=li,postcss$3.Container=ui,postcss$3.Processor=hi,postcss$3.Document=pi,postcss$3.Comment=mi,postcss$3.Warning=fi,postcss$3.AtRule=yi,postcss$3.Result=vi,postcss$3.Input=wi,postcss$3.Rule=Ci,postcss$3.Root=ki,postcss$3.Node=Ii,ci.registerPostcss(postcss$3),postcss$3.default=postcss$3;var Ei=Object.defineProperty,__publicField2=(S,b,I)=>((S,b,I)=>b in S?Ei(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I);function getAugmentedNamespace(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var xi={exports:{}},Mi=String,create=function(){return{isColorSupported:!1,reset:Mi,bold:Mi,dim:Mi,italic:Mi,underline:Mi,inverse:Mi,hidden:Mi,strikethrough:Mi,black:Mi,red:Mi,green:Mi,yellow:Mi,blue:Mi,magenta:Mi,cyan:Mi,white:Mi,gray:Mi,bgBlack:Mi,bgRed:Mi,bgGreen:Mi,bgYellow:Mi,bgBlue:Mi,bgMagenta:Mi,bgCyan:Mi,bgWhite:Mi}};xi.exports=create(),xi.exports.createColors=create;var Ri=xi.exports;const Ti=getAugmentedNamespace(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Ai=Ri,_i=Ti,Oi=class CssSyntaxError2 extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError2)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=Ai.isColorSupported),_i&&S&&(b=_i(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=Ai.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var Di=Oi;Oi.default=Oi;var Fi={};Fi.isClean=Symbol("isClean"),Fi.my=Symbol("my");const Ni={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Li=class Stringifier2{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return Ni[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=Ni[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var Pi=Li;Li.default=Li;let Bi=Pi;function stringify$4(S,b){new Bi(b).stringify(S)}var zi=stringify$4;stringify$4.default=stringify$4;let{isClean:Ui,my:$i}=Fi,ji=Di,qi=Pi,Wi=zi;function cloneNode(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode(S,I)):("object"===A&&null!==R&&(R=cloneNode(R)),I[x]=R)}return I}let Hi=class Node3{constructor(S={}){this.raws={},this[Ui]=!1,this[$i]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new ji(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[Ui]){this[Ui]=!1;let S=this;for(;S=S.parent;)S[Ui]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new qi).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=Wi){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var Vi=Hi;Hi.default=Hi;let Qi=Vi,Ki=class Declaration2 extends Qi{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var Gi=Ki;Ki.default=Ki;var Ji={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:Xi,SourceMapGenerator:Zi}=Ti,{existsSync:Yi,readFileSync:eo}=Ti,{dirname:to,join:ro}=Ti;let so=class PreviousMap2{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=to(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new Xi(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=to(S),Yi(S))return this.mapFile=S,eo(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof Xi)return Zi.fromSourceMap(b).toString();if(b instanceof Zi)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=ro(to(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var no=so;so.default=so;let{SourceMapConsumer:io,SourceMapGenerator:oo}=Ti,{fileURLToPath:ao,pathToFileURL:lo}=Ti,{isAbsolute:co,resolve:uo}=Ti,{nanoid:ho}=Ji,go=Ti,po=Di,fo=no,mo=Symbol("fromOffsetCache"),yo=Boolean(io&&oo),vo=Boolean(uo&&co),wo=class Input2{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!vo||/^\w+:\/\//.test(b.from)||co(b.from)?this.file=b.from:this.file=uo(b.from)),vo&&yo){let S=new fo(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+ho(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new po(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new po(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(lo&&(R.input.url=lo(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[mo])I=this[mo];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[mo]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:uo(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=co(D.source)?lo(D.source):new URL(D.source,this.map.consumer().sourceRoot||lo(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!ao)throw new Error("file: protocol is not available in this PostCSS build");L.file=ao(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var So=wo;wo.default=wo,go&&go.registerInput&&go.registerInput(wo);let{SourceMapConsumer:bo,SourceMapGenerator:Co}=Ti,{dirname:ko,relative:Io,resolve:Eo,sep:xo}=Ti,{pathToFileURL:Mo}=Ti,Ro=So,To=Boolean(bo&&Co),Ao=Boolean(ko&&Eo&&Io&&xo);var _o=class MapGenerator2{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||ko(S.file);!1===this.mapOpts.sourcesContent?(b=new bo(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Ao&&To&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=Co.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Co({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Co({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?ko(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=ko(Eo(I,this.mapOpts.annotation)));let x=Io(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new Ro(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(Mo){let b=Mo(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===xo&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let Oo=Vi,Do=class Comment2 extends Oo{constructor(S){super(S),this.type="comment"}};var Fo=Do;Do.default=Do;let No,Lo,Po,Bo,{isClean:zo,my:Uo}=Fi,$o=Gi,jo=Fo,qo=Vi;function cleanSource(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource(S.nodes)),delete S.source,S))}function markDirtyUp(S){if(S[zo]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp(b)}let Wo=class Container2 extends qo{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource(No(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new $o(S)]}else if(S.selector)S=[new Lo(S)];else if(S.name)S=[new Po(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new jo(S)]}return S.map(S=>(S[Uo]||Container2.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[zo]&&markDirtyUp(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Wo.registerParse=S=>{No=S},Wo.registerRule=S=>{Lo=S},Wo.registerAtRule=S=>{Po=S},Wo.registerRoot=S=>{Bo=S};var Ho=Wo;Wo.default=Wo,Wo.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,Po.prototype):"rule"===S.type?Object.setPrototypeOf(S,Lo.prototype):"decl"===S.type?Object.setPrototypeOf(S,$o.prototype):"comment"===S.type?Object.setPrototypeOf(S,jo.prototype):"root"===S.type&&Object.setPrototypeOf(S,Bo.prototype),S[Uo]=!0,S.nodes&&S.nodes.forEach(S=>{Wo.rebuild(S)})};let Vo,Qo,Ko=Ho,Go=class Document23 extends Ko{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Vo(new Qo,this,S).stringify()}};Go.registerLazyResult=S=>{Vo=S},Go.registerProcessor=S=>{Qo=S};var Jo=Go;Go.default=Go;let Xo=class Warning2{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var Zo=Xo;Xo.default=Xo;let Yo=Zo,ea=class Result2{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new Yo(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var ta=ea;ea.default=ea;const ra="'".charCodeAt(0),sa='"'.charCodeAt(0),na="\\".charCodeAt(0),ia="/".charCodeAt(0),oa="\n".charCodeAt(0),aa=" ".charCodeAt(0),la="\f".charCodeAt(0),ca="\t".charCodeAt(0),ua="\r".charCodeAt(0),ha="[".charCodeAt(0),da="]".charCodeAt(0),ga="(".charCodeAt(0),pa=")".charCodeAt(0),fa="{".charCodeAt(0),ma="}".charCodeAt(0),ya=";".charCodeAt(0),va="*".charCodeAt(0),wa=":".charCodeAt(0),Sa="@".charCodeAt(0),ba=/[\t\n\f\r "#'()/;[\\\]{}]/g,Ca=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,ka=/.[\r\n"'(/\\]/,Ia=/[\da-f]/i;let Ea=Ho,xa=class AtRule2 extends Ea{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var Ma=xa;xa.default=xa,Ea.registerAtRule(xa);let Ra,Ta,Aa=Ho,_a=class Root2 extends Aa{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new Ra(new Ta,this,S).stringify()}};_a.registerLazyResult=S=>{Ra=S},_a.registerProcessor=S=>{Ta=S};var Oa=_a;_a.default=_a,Aa.registerRoot(_a);let Da={comma:S=>Da.split(S,[","],!0),space:S=>Da.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var Fa=Da;Da.default=Da;let Na=Ho,La=Fa,Pa=class Rule2 extends Na{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return La.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var Ba=Pa;Pa.default=Pa,Na.registerRule(Pa);let za=Gi,Ua=function tokenizer2(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case oa:case aa:case ca:case ua:case la:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===aa||I===oa||I===ca||I===ua||I===la);$=["space",j.slice(V,x)],V=x-1;break;case ha:case da:case fa:case ma:case wa:case ya:case pa:{let S=String.fromCharCode(I);$=[S,S,V];break}case ga:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==ra&&U!==sa&&U!==aa&&U!==oa&&U!==ca&&U!==la&&U!==ua){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===na;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||ka.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case ra:case sa:R=I===ra?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===na;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Sa:ba.lastIndex=V+1,ba.test(j),x=0===ba.lastIndex?j.length-1:ba.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case na:for(x=V,_=!0;j.charCodeAt(x+1)===na;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==ia&&I!==aa&&I!==oa&&I!==ca&&I!==ua&&I!==la&&(x+=1,Ia.test(j.charAt(x)))){for(;Ia.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===aa&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===ia&&j.charCodeAt(V+1)===va?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(Ca.lastIndex=V+1,Ca.test(j),x=0===Ca.lastIndex?j.length-1:Ca.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},$a=Fo,ja=Ma,qa=Oa,Wa=Ba;const Ha={empty:!0,space:!0};var Va=class Parser2{constructor(S){this.input=S,this.root=new qa,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new ja;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new $a;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=Ua(this.input)}decl(S,b){let I=new za;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new Wa;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",Ha[D]||Ha[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new Wa;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let Qa=Ho,Ka=Va,Ga=So;function parse$3(S,b){let I=new Ga(S,b),x=new Ka(I);try{x.parse()}catch(S){throw S}return x.root}var Ja=parse$3;parse$3.default=parse$3,Qa.registerParse(parse$3);let{isClean:Xa,my:Za}=Fi,Ya=_o,el=zi,tl=Ho,rl=Jo,sl=ta,nl=Ja,il=Oa;const ol={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},al={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},ll={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents(S){let b=!1,I=ol[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks(S){return S[Xa]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks(S)),S}let cl={},ul=class LazyResult2{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult2||b instanceof sl)x=cleanMarks(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=nl;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[Za]&&tl.rebuild(x)}else x=cleanMarks(b);this.result=new sl(S,x,I),this.helpers={...cl,postcss:cl,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!al[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ll[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[Xa];){S[Xa]=!0;let b=[toStack(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=el;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new Ya(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[Xa];)S[Xa]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[Xa])return x[Xa]=!0,void S.push(toStack(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[Xa]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[Xa]=!0;let b=getEvents(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[Xa]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};ul.registerPostcss=S=>{cl=S};var hl=ul;ul.default=ul,il.registerLazyResult(ul),rl.registerLazyResult(ul);let dl=_o,gl=zi,pl=Ja;const fl=ta;let ml=class NoWorkResult2{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=gl;this.result=new fl(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new dl(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=pl;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var yl=ml;ml.default=ml;let vl=yl,wl=hl,Sl=Jo,bl=Oa,Cl=class Processor2{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new wl(this,S,b):new vl(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var kl=Cl;Cl.default=Cl,bl.registerProcessor(Cl),Sl.registerProcessor(Cl);let Il=Gi,El=no,xl=Fo,Ml=Ma,Rl=So,Tl=Oa,Al=Ba;function fromJSON$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:Rl.prototype};I.map&&(I.map={...I.map,__proto__:El.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new Tl(x);if("decl"===x.type)return new Il(x);if("rule"===x.type)return new Al(x);if("comment"===x.type)return new xl(x);if("atrule"===x.type)return new Ml(x);throw new Error("Unknown node type: "+S.type)}var _l=fromJSON$1;fromJSON$1.default=fromJSON$1;let Ol=Di,Dl=Gi,Fl=hl,Nl=Ho,Ll=kl,Pl=zi,Bl=_l,zl=Jo,Ul=Zo,$l=Fo,jl=Ma,ql=ta,Wl=So,Hl=Ja,Vl=Fa,Ql=Ba,Kl=Oa,Gl=Vi;function postcss(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new Ll(S)}postcss.plugin=function plugin2(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new Ll).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss([creator(I)]).process(S,b)},creator},postcss.stringify=Pl,postcss.parse=Hl,postcss.fromJSON=Bl,postcss.list=Vl,postcss.comment=S=>new $l(S),postcss.atRule=S=>new jl(S),postcss.decl=S=>new Dl(S),postcss.rule=S=>new Ql(S),postcss.root=S=>new Kl(S),postcss.document=S=>new zl(S),postcss.CssSyntaxError=Ol,postcss.Declaration=Dl,postcss.Container=Nl,postcss.Processor=Ll,postcss.Document=zl,postcss.Comment=$l,postcss.Warning=Ul,postcss.AtRule=jl,postcss.Result=ql,postcss.Input=Wl,postcss.Rule=Ql,postcss.Root=Kl,postcss.Node=Gl,Fl.registerPostcss(postcss),postcss.default=postcss;class BaseRRNode{constructor(...S){__publicField2(this,"parentElement",null),__publicField2(this,"parentNode",null),__publicField2(this,"ownerDocument"),__publicField2(this,"firstChild",null),__publicField2(this,"lastChild",null),__publicField2(this,"previousSibling",null),__publicField2(this,"nextSibling",null),__publicField2(this,"ELEMENT_NODE",1),__publicField2(this,"TEXT_NODE",3),__publicField2(this,"nodeType"),__publicField2(this,"nodeName"),__publicField2(this,"RRNodeType")}get childNodes(){const S=[];let b=this.firstChild;for(;b;)S.push(b),b=b.nextSibling;return S}contains(S){if(!(S instanceof BaseRRNode))return!1;if(S.ownerDocument!==this.ownerDocument)return!1;if(S===this)return!0;for(;S.parentNode;){if(S.parentNode===this)return!0;S=S.parentNode}return!1}appendChild(S){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(S,b){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(S){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}}const Jl={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Xl={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Zl={};function getUntaintedPrototype(S){if(Zl[S])return Zl[S];const b=globalThis[S],I=b.prototype,x=S in Jl?Jl[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in Xl?Xl[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return Zl[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?Zl[S]=A:I}catch{return I}}const Yl={};function getUntaintedAccessor(S,b,I){var x;const R=`${S}.${String(I)}`;if(Yl[R])return Yl[R].call(b);const A=getUntaintedPrototype(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(Yl[R]=_,_.call(b)):b[I]}const ec={};function getUntaintedMethod(S,b,I){const x=`${S}.${String(I)}`;if(ec[x])return ec[x].bind(b);const R=getUntaintedPrototype(S)[I];return"function"!=typeof R?b[I]:(ec[x]=R,R.bind(b))}function mutationObserverCtor(){return getUntaintedPrototype("MutationObserver").constructor}const tc={childNodes:function childNodes(S){return getUntaintedAccessor("Node",S,"childNodes")},parentNode:function parentNode(S){return getUntaintedAccessor("Node",S,"parentNode")},parentElement:function parentElement(S){return getUntaintedAccessor("Node",S,"parentElement")},textContent:function textContent(S){return getUntaintedAccessor("Node",S,"textContent")},contains:function contains(S,b){return getUntaintedMethod("Node",S,"contains")(b)},getRootNode:function getRootNode(S){return getUntaintedMethod("Node",S,"getRootNode")()},host:function host(S){return S&&"host"in S?getUntaintedAccessor("ShadowRoot",S,"host"):null},styleSheets:function styleSheets(S){return S.styleSheets},shadowRoot:function shadowRoot(S){return S&&"shadowRoot"in S?getUntaintedAccessor("Element",S,"shadowRoot"):null},querySelector:function querySelector(S,b){return getUntaintedAccessor("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll(S,b){return getUntaintedAccessor("Element",S,"querySelectorAll")(b)},mutationObserver:mutationObserverCtor};function on(S,b,I=document){const x={capture:!0,passive:!0};return I.addEventListener(S,b,x),()=>I.removeEventListener(S,b,x)}const rc="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let sc={map:{},getId:()=>(console.error(rc),-1),getNode:()=>(console.error(rc),null),removeNodeFromMap(){console.error(rc)},has:()=>(console.error(rc),!1),reset(){console.error(rc)}};function throttle(S,b,I={}){let x=null,R=0;return function(...A){const _=Date.now();R||!1!==I.leading||(R=_);const D=b-(_-R),L=this;D<=0||D>b?(x&&(clearTimeout(x),x=null),R=_,S.apply(L,A)):x||!1===I.trailing||(x=setTimeout(()=>{R=!1===I.leading?0:Date.now(),x=null,S.apply(L,A)},D))}}function hookSetter(S,b,I,x,R=window){const A=R.Object.getOwnPropertyDescriptor(S,b);return R.Object.defineProperty(S,b,x?I:{set(S){setTimeout(()=>{I.set.call(this,S)},0),A&&A.set&&A.set.call(this,S)}}),()=>hookSetter(S,b,A||{},!0)}function patch(S,b,I){try{if(!(b in S))return()=>{};const x=S[b],R=I(x);return"function"==typeof R&&(R.prototype=R.prototype||{},Object.defineProperties(R,{__rrweb_original__:{enumerable:!1,value:x}})),S[b]=R,()=>{S[b]=x}}catch{return()=>{}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(sc=new Proxy(sc,{get:(S,b,I)=>("map"===b&&console.error(rc),Reflect.get(S,b,I))}));let nc=Date.now;function getWindowScroll(S){var b,I,x,R;const A=S.document;return{left:A.scrollingElement?A.scrollingElement.scrollLeft:void 0!==S.pageXOffset?S.pageXOffset:A.documentElement.scrollLeft||(null==A?void 0:A.body)&&(null==(b=tc.parentElement(A.body))?void 0:b.scrollLeft)||(null==(I=null==A?void 0:A.body)?void 0:I.scrollLeft)||0,top:A.scrollingElement?A.scrollingElement.scrollTop:void 0!==S.pageYOffset?S.pageYOffset:(null==A?void 0:A.documentElement.scrollTop)||(null==A?void 0:A.body)&&(null==(x=tc.parentElement(A.body))?void 0:x.scrollTop)||(null==(R=null==A?void 0:A.body)?void 0:R.scrollTop)||0}}function getWindowHeight(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function getWindowWidth(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function closestElementOfNode(S){if(!S)return null;return S.nodeType===S.ELEMENT_NODE?S:tc.parentElement(S)}function isBlocked(S,b,I,x){if(!S)return!1;const R=closestElementOfNode(S);if(!R)return!1;try{if("string"==typeof b){if(R.classList.contains(b))return!0;if(x&&null!==R.closest("."+b))return!0}else if(classMatchesRegex(R,b,x))return!0}catch(S){}if(I){if(R.matches(I))return!0;if(x&&null!==R.closest(I))return!0}return!1}function isIgnored(S,b,I){return!("TITLE"!==S.tagName||!I.headTitleMutations)||-2===b.getId(S)}function isAncestorRemoved(S,b){if(isShadowRoot(S))return!1;const I=b.getId(S);if(!b.has(I))return!0;const x=tc.parentNode(S);return(!x||x.nodeType!==S.DOCUMENT_NODE)&&(!x||isAncestorRemoved(x,b))}function legacy_isTouchEvent(S){return Boolean(S.changedTouches)}function isSerializedIframe(S,b){return Boolean("IFRAME"===S.nodeName&&b.getMeta(S))}function isSerializedStylesheet(S,b){return Boolean("LINK"===S.nodeName&&S.nodeType===S.ELEMENT_NODE&&S.getAttribute&&"stylesheet"===S.getAttribute("rel")&&b.getMeta(S))}function hasShadowRoot(S){return!!S&&(S instanceof BaseRRNode&&"shadowRoot"in S?Boolean(S.shadowRoot):Boolean(tc.shadowRoot(S)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(nc=()=>(new Date).getTime());class StyleSheetMirror{constructor(){__publicField(this,"id",1),__publicField(this,"styleIDMap",new WeakMap),__publicField(this,"idStyleMap",new Map)}getId(S){return this.styleIDMap.get(S)??-1}has(S){return this.styleIDMap.has(S)}add(S,b){if(this.has(S))return this.getId(S);let I;return I=void 0===b?this.id++:b,this.styleIDMap.set(S,I),this.idStyleMap.set(I,S),I}getStyle(S){return this.idStyleMap.get(S)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function getShadowHost(S){var b;let I=null;return"getRootNode"in S&&(null==(b=tc.getRootNode(S))?void 0:b.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&tc.host(tc.getRootNode(S))&&(I=tc.host(tc.getRootNode(S))),I}function shadowHostInDom(S){const b=S.ownerDocument;if(!b)return!1;const I=function getRootShadowHost(S){let b,I=S;for(;b=getShadowHost(I);)I=b;return I}(S);return tc.contains(b,I)}function inDom(S){const b=S.ownerDocument;return!!b&&(tc.contains(b,S)||shadowHostInDom(S))}var ic=(S=>(S[S.DomContentLoaded=0]="DomContentLoaded",S[S.Load=1]="Load",S[S.FullSnapshot=2]="FullSnapshot",S[S.IncrementalSnapshot=3]="IncrementalSnapshot",S[S.Meta=4]="Meta",S[S.Custom=5]="Custom",S[S.Plugin=6]="Plugin",S))(ic||{}),oc=(S=>(S[S.Mutation=0]="Mutation",S[S.MouseMove=1]="MouseMove",S[S.MouseInteraction=2]="MouseInteraction",S[S.Scroll=3]="Scroll",S[S.ViewportResize=4]="ViewportResize",S[S.Input=5]="Input",S[S.TouchMove=6]="TouchMove",S[S.MediaInteraction=7]="MediaInteraction",S[S.StyleSheetRule=8]="StyleSheetRule",S[S.CanvasMutation=9]="CanvasMutation",S[S.Font=10]="Font",S[S.Log=11]="Log",S[S.Drag=12]="Drag",S[S.StyleDeclaration=13]="StyleDeclaration",S[S.Selection=14]="Selection",S[S.AdoptedStyleSheet=15]="AdoptedStyleSheet",S[S.CustomElement=16]="CustomElement",S))(oc||{}),ac=(S=>(S[S.MouseUp=0]="MouseUp",S[S.MouseDown=1]="MouseDown",S[S.Click=2]="Click",S[S.ContextMenu=3]="ContextMenu",S[S.DblClick=4]="DblClick",S[S.Focus=5]="Focus",S[S.Blur=6]="Blur",S[S.TouchStart=7]="TouchStart",S[S.TouchMove_Departed=8]="TouchMove_Departed",S[S.TouchEnd=9]="TouchEnd",S[S.TouchCancel=10]="TouchCancel",S))(ac||{}),cc=(S=>(S[S.Mouse=0]="Mouse",S[S.Pen=1]="Pen",S[S.Touch=2]="Touch",S))(cc||{}),uc=(S=>(S[S["2D"]=0]="2D",S[S.WebGL=1]="WebGL",S[S.WebGL2=2]="WebGL2",S))(uc||{}),hc=(S=>(S[S.Play=0]="Play",S[S.Pause=1]="Pause",S[S.Seeked=2]="Seeked",S[S.VolumeChange=3]="VolumeChange",S[S.RateChange=4]="RateChange",S))(hc||{}),dc=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(dc||{});function isNodeInLinkedList(S){return"__ln"in S}class DoubleLinkedList{constructor(){__publicField(this,"length",0),__publicField(this,"head",null),__publicField(this,"tail",null)}get(S){if(S>=this.length)throw new Error("Position outside of list range");let b=this.head;for(let I=0;I<S;I++)b=(null==b?void 0:b.next)||null;return b}addNode(S){const b={value:S,previous:null,next:null};if(S.__ln=b,S.previousSibling&&isNodeInLinkedList(S.previousSibling)){const I=S.previousSibling.__ln.next;b.next=I,b.previous=S.previousSibling.__ln,S.previousSibling.__ln.next=b,I&&(I.previous=b)}else if(S.nextSibling&&isNodeInLinkedList(S.nextSibling)&&S.nextSibling.__ln.previous){const I=S.nextSibling.__ln.previous;b.previous=I,b.next=S.nextSibling.__ln,S.nextSibling.__ln.previous=b,I&&(I.next=b)}else this.head&&(this.head.previous=b),b.next=this.head,this.head=b;null===b.next&&(this.tail=b),this.length++}removeNode(S){const b=S.__ln;this.head&&(b.previous?(b.previous.next=b.next,b.next?b.next.previous=b.previous:this.tail=b.previous):(this.head=b.next,this.head?this.head.previous=null:this.tail=null),S.__ln&&delete S.__ln,this.length--)}}const moveKey=(S,b)=>`${S}@${b}`;class MutationBuffer{constructor(){__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"texts",[]),__publicField(this,"attributes",[]),__publicField(this,"attributeMap",new WeakMap),__publicField(this,"removes",[]),__publicField(this,"mapRemoves",[]),__publicField(this,"movedMap",{}),__publicField(this,"addedSet",new Set),__publicField(this,"movedSet",new Set),__publicField(this,"droppedSet",new Set),__publicField(this,"removesSubTreeCache",new Set),__publicField(this,"mutationCb"),__publicField(this,"blockClass"),__publicField(this,"blockSelector"),__publicField(this,"maskTextClass"),__publicField(this,"maskTextSelector"),__publicField(this,"inlineStylesheet"),__publicField(this,"maskInputOptions"),__publicField(this,"maskTextFn"),__publicField(this,"maskInputFn"),__publicField(this,"keepIframeSrcFn"),__publicField(this,"recordCanvas"),__publicField(this,"inlineImages"),__publicField(this,"slimDOMOptions"),__publicField(this,"dataURLOptions"),__publicField(this,"doc"),__publicField(this,"mirror"),__publicField(this,"iframeManager"),__publicField(this,"stylesheetManager"),__publicField(this,"shadowDomManager"),__publicField(this,"canvasManager"),__publicField(this,"processedNodeManager"),__publicField(this,"unattachedDoc"),__publicField(this,"processMutations",S=>{S.forEach(this.processMutation),this.emit()}),__publicField(this,"emit",()=>{if(this.frozen||this.locked)return;const S=[],b=new Set,I=new DoubleLinkedList,getNextId=S=>{let b=S,I=-2;for(;-2===I;)b=b&&b.nextSibling,I=b&&this.mirror.getId(b);return I},pushAdd=x=>{const R=tc.parentNode(x);if(!R||!inDom(x))return;let A=!1;if(x.nodeType===Node.TEXT_NODE){const S=R.tagName;if("TEXTAREA"===S)return;"STYLE"===S&&this.addedSet.has(R)&&(A=!0)}const _=isShadowRoot(R)?this.mirror.getId(getShadowHost(x)):this.mirror.getId(R),D=getNextId(x);if(-1===_||-1===D)return I.addNode(x);const L=serializeNodeWithId(x,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:S=>{isSerializedIframe(S,this.mirror)&&this.iframeManager.addIframe(S),isSerializedStylesheet(S,this.mirror)&&this.stylesheetManager.trackLinkElement(S),hasShadowRoot(x)&&this.shadowDomManager.addShadowRoot(tc.shadowRoot(x),this.doc)},onIframeLoad:(S,b)=>{this.iframeManager.attachIframe(S,b),this.shadowDomManager.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{this.stylesheetManager.attachLinkElement(S,b)},cssCaptured:A});L&&(S.push({parentId:_,nextId:D,node:L}),b.add(L.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const S of this.movedSet)isParentRemoved(this.removesSubTreeCache,S)&&!this.movedSet.has(tc.parentNode(S))||pushAdd(S);for(const S of this.addedSet)isAncestorInSet(this.droppedSet,S)||isParentRemoved(this.removesSubTreeCache,S)?isAncestorInSet(this.movedSet,S)?pushAdd(S):this.droppedSet.add(S):pushAdd(S);let x=null;for(;I.length;){let S=null;if(x){const b=this.mirror.getId(tc.parentNode(x.value)),I=getNextId(x.value);-1!==b&&-1!==I&&(S=x)}if(!S){let b=I.tail;for(;b;){const I=b;if(b=b.previous,I){const b=this.mirror.getId(tc.parentNode(I.value));if(-1===getNextId(I.value))continue;if(-1!==b){S=I;break}{const b=I.value,x=tc.parentNode(b);if(x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const b=tc.host(x);if(-1!==this.mirror.getId(b)){S=I;break}}}}}}if(!S){for(;I.head;)I.removeNode(I.head.value);break}x=S.previous,I.removeNode(S.value),pushAdd(S.value)}const R={texts:this.texts.map(S=>{const b=S.node,I=tc.parentNode(b);return I&&"TEXTAREA"===I.tagName&&this.genTextAreaValueMutation(I),{id:this.mirror.getId(b),value:S.value}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),attributes:this.attributes.map(S=>{const{attributes:b}=S;if("string"==typeof b.style){const I=JSON.stringify(S.styleDiff),x=JSON.stringify(S._unchangedStyles);I.length<b.style.length&&(I+x).split("var(").length===b.style.split("var(").length&&(b.style=S.styleDiff)}return{id:this.mirror.getId(S.node),attributes:b}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),removes:this.removes,adds:S};(R.texts.length||R.attributes.length||R.removes.length||R.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(R))}),__publicField(this,"genTextAreaValueMutation",S=>{let b=this.attributeMap.get(S);b||(b={node:S,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(b),this.attributeMap.set(S,b)),b.attributes.value=Array.from(tc.childNodes(S),S=>tc.textContent(S)||"").join("")}),__publicField(this,"processMutation",S=>{if(!isIgnored(S.target,this.mirror,this.slimDOMOptions))switch(S.type){case"characterData":{const b=tc.textContent(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||b===S.oldValue||this.texts.push({value:needMaskingText(S.target,this.maskTextClass,this.maskTextSelector,!0)&&b?this.maskTextFn?this.maskTextFn(b,closestElementOfNode(S.target)):b.replace(/[\S]/g,"*"):b,node:S.target});break}case"attributes":{const b=S.target;let I=S.attributeName,x=S.target.getAttribute(I);if("value"===I){const S=getInputType(b);x=maskInputValue({element:b,maskInputOptions:this.maskInputOptions,tagName:b.tagName,type:S,value:x,maskInputFn:this.maskInputFn})}if(isBlocked(S.target,this.blockClass,this.blockSelector,!1)||x===S.oldValue)return;let R=this.attributeMap.get(S.target);if("IFRAME"===b.tagName&&"src"===I&&!this.keepIframeSrcFn(x)){if(__tsSafeContentDoc(b))return;I="rr_src"}if(R||(R={node:S.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(R),this.attributeMap.set(S.target,R)),"type"===I&&"INPUT"===b.tagName&&"password"===(S.oldValue||"").toLowerCase()&&b.setAttribute("data-rr-is-password","true"),!ignoreAttribute(b.tagName,I))if(R.attributes[I]=transformAttribute(this.doc,toLowerCase(b.tagName),toLowerCase(I),x),"style"===I){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(S){this.unattachedDoc=this.doc}const I=this.unattachedDoc.createElement("span");S.oldValue&&I.setAttribute("style",S.oldValue);for(const S of Array.from(b.style)){const x=b.style.getPropertyValue(S),A=b.style.getPropertyPriority(S);x!==I.style.getPropertyValue(S)||A!==I.style.getPropertyPriority(S)?R.styleDiff[S]=""===A?x:[x,A]:R._unchangedStyles[S]=[x,A]}for(const S of Array.from(I.style))""===b.style.getPropertyValue(S)&&(R.styleDiff[S]=!1)}else"open"===I&&"DIALOG"===b.tagName&&(b.matches("dialog:modal")?R.attributes.rr_open_mode="modal":R.attributes.rr_open_mode="non-modal");break}case"childList":if(isBlocked(S.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===S.target.tagName)return void this.genTextAreaValueMutation(S.target);S.addedNodes.forEach(b=>this.genAdds(b,S.target)),S.removedNodes.forEach(b=>{const I=this.mirror.getId(b),x=isShadowRoot(S.target)?this.mirror.getId(tc.host(S.target)):this.mirror.getId(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||isIgnored(b,this.mirror,this.slimDOMOptions)||!function isSerialized(S,b){return-1!==b.getId(S)}(b,this.mirror)||(this.addedSet.has(b)?(deepDelete(this.addedSet,b),this.droppedSet.add(b)):this.addedSet.has(S.target)&&-1===I||isAncestorRemoved(S.target,this.mirror)||(this.movedSet.has(b)&&this.movedMap[moveKey(I,x)]?deepDelete(this.movedSet,b):(this.removes.push({parentId:x,id:I,isShadow:!(!isShadowRoot(S.target)||!isNativeShadowDom(S.target))||void 0}),function processRemoves(S,b){const I=[S];for(;I.length;){const S=I.pop();b.has(S)||(b.add(S),tc.childNodes(S).forEach(S=>I.push(S)))}return}(b,this.removesSubTreeCache))),this.mapRemoves.push(b))})}}),__publicField(this,"genAdds",(S,b)=>{if(!this.processedNodeManager.inOtherBuffer(S,this)&&!this.addedSet.has(S)&&!this.movedSet.has(S)){if(this.mirror.hasNode(S)){if(isIgnored(S,this.mirror,this.slimDOMOptions))return;this.movedSet.add(S);let I=null;b&&this.mirror.hasNode(b)&&(I=this.mirror.getId(b)),I&&-1!==I&&(this.movedMap[moveKey(this.mirror.getId(S),I)]=!0)}else this.addedSet.add(S),this.droppedSet.delete(S);isBlocked(S,this.blockClass,this.blockSelector,!1)||(tc.childNodes(S).forEach(S=>this.genAdds(S)),hasShadowRoot(S)&&tc.childNodes(tc.shadowRoot(S)).forEach(b=>{this.processedNodeManager.add(b,this),this.genAdds(b,S)}))}})}init(S){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(b=>{this[b]=S[b]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function deepDelete(S,b){S.delete(b),tc.childNodes(b).forEach(b=>deepDelete(S,b))}function isParentRemoved(S,b,I){return 0!==S.size&&function _isParentRemoved(S,b,I){const x=tc.parentNode(b);return!!x&&S.has(x)}(S,b)}function isAncestorInSet(S,b){return 0!==S.size&&_isAncestorInSet(S,b)}function _isAncestorInSet(S,b){const I=tc.parentNode(b);return!!I&&(!!S.has(I)||_isAncestorInSet(S,I))}let gc;const callbackWrapper=S=>{if(!gc)return S;return(...b)=>{try{return S(...b)}catch(S){if(gc&&!0===gc(S))return;throw S}}},pc=[];function getEventTarget(S){try{if("composedPath"in S){const b=S.composedPath();if(b.length)return b[0]}else if("path"in S&&S.path.length)return S.path[0]}catch{}return S&&S.target}function initMutationObserver(S,b){const I=new MutationBuffer;pc.push(I),I.init(S);const x=new(mutationObserverCtor())(callbackWrapper(I.processMutations.bind(I)));return x.observe(b,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),x}function initMouseInteractionObserver({mouseInteractionCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){if(!1===A.mouseInteraction)return()=>{};const _=!0===A.mouseInteraction||void 0===A.mouseInteraction?{}:A.mouseInteraction,D=[];let L=null;return Object.keys(ac).filter(S=>Number.isNaN(Number(S))&&!S.endsWith("_Departed")&&!1!==_[S]).forEach(A=>{let _=toLowerCase(A);const B=(b=>A=>{const _=getEventTarget(A);if(isBlocked(_,x,R,!0))return;let D=null,B=b;if("pointerType"in A){switch(A.pointerType){case"mouse":D=cc.Mouse;break;case"touch":D=cc.Touch;break;case"pen":D=cc.Pen}D===cc.Touch&&(ac[b]===ac.MouseDown?B="TouchStart":ac[b]===ac.MouseUp&&(B="TouchEnd"))}else legacy_isTouchEvent(A)&&(D=cc.Touch);null!==D?(L=D,(B.startsWith("Touch")&&D===cc.Touch||B.startsWith("Mouse")&&D===cc.Mouse)&&(D=null)):ac[b]===ac.Click&&(D=L,L=null);const U=legacy_isTouchEvent(A)?A.changedTouches[0]:A;if(!U)return;const $=I.getId(_),{clientX:j,clientY:W}=U;callbackWrapper(S)({type:ac[B],id:$,x:j,y:W,...null!==D&&{pointerType:D}})})(A);if(window.PointerEvent)switch(ac[A]){case ac.MouseDown:case ac.MouseUp:_=_.replace("mouse","pointer");break;case ac.TouchStart:case ac.TouchEnd:return}D.push(on(_,B,b))}),callbackWrapper(()=>{D.forEach(S=>S())})}function initScrollObserver({scrollCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){return on("scroll",callbackWrapper(throttle(callbackWrapper(A=>{const _=getEventTarget(A);if(!_||isBlocked(_,x,R,!0))return;const D=I.getId(_);if(_===b&&b.defaultView){const I=getWindowScroll(b.defaultView);S({id:D,x:I.left,y:I.top})}else S({id:D,x:_.scrollLeft,y:_.scrollTop})}),A.scroll||100)),b)}const fc=["INPUT","TEXTAREA","SELECT"],mc=new WeakMap;function getNestedCSSRulePositions(S){return function recurse(S,b){if(hasNestedCSSRule("CSSGroupingRule")&&S.parentRule instanceof CSSGroupingRule||hasNestedCSSRule("CSSMediaRule")&&S.parentRule instanceof CSSMediaRule||hasNestedCSSRule("CSSSupportsRule")&&S.parentRule instanceof CSSSupportsRule||hasNestedCSSRule("CSSConditionRule")&&S.parentRule instanceof CSSConditionRule){const I=Array.from(S.parentRule.cssRules).indexOf(S);b.unshift(I)}else if(S.parentStyleSheet){const I=Array.from(S.parentStyleSheet.cssRules).indexOf(S);b.unshift(I)}return b}(S,[])}function getIdAndStyleId(S,b,I){let x,R;return S?(S.ownerNode?x=b.getId(S.ownerNode):R=I.getId(S),{styleId:R,id:x}):{}}function initAdoptedStyleSheetObserver({mirror:S,stylesheetManager:b},I){var x,R,A;let _=null;_="#document"===I.nodeName?S.getId(I):S.getId(tc.host(I));const D="#document"===I.nodeName?null==(x=I.defaultView)?void 0:x.Document:null==(A=null==(R=I.ownerDocument)?void 0:R.defaultView)?void 0:A.ShadowRoot,L=(null==D?void 0:D.prototype)?Object.getOwnPropertyDescriptor(null==D?void 0:D.prototype,"adoptedStyleSheets"):void 0;return null!==_&&-1!==_&&D&&L?(Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get(){var S;return null==(S=L.get)?void 0:S.call(this)},set(S){var I;const x=null==(I=L.set)?void 0:I.call(this,S);if(null!==_&&-1!==_)try{b.adoptStyleSheets(S,_)}catch(S){}return x}}),callbackWrapper(()=>{Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get:L.get,set:L.set})})):()=>{}}function initObservers(S,b={}){const I=S.doc.defaultView;if(!I)return()=>{};let x;!function mergeHooks(S,b){const{mutationCb:I,mousemoveCb:x,mouseInteractionCb:R,scrollCb:A,viewportResizeCb:_,inputCb:D,mediaInteractionCb:L,styleSheetRuleCb:B,styleDeclarationCb:U,canvasMutationCb:$,fontCb:j,selectionCb:W,customElementCb:H}=S;S.mutationCb=(...S)=>{b.mutation&&b.mutation(...S),I(...S)},S.mousemoveCb=(...S)=>{b.mousemove&&b.mousemove(...S),x(...S)},S.mouseInteractionCb=(...S)=>{b.mouseInteraction&&b.mouseInteraction(...S),R(...S)},S.scrollCb=(...S)=>{b.scroll&&b.scroll(...S),A(...S)},S.viewportResizeCb=(...S)=>{b.viewportResize&&b.viewportResize(...S),_(...S)},S.inputCb=(...S)=>{b.input&&b.input(...S),D(...S)},S.mediaInteractionCb=(...S)=>{b.mediaInteaction&&b.mediaInteaction(...S),L(...S)},S.styleSheetRuleCb=(...S)=>{b.styleSheetRule&&b.styleSheetRule(...S),B(...S)},S.styleDeclarationCb=(...S)=>{b.styleDeclaration&&b.styleDeclaration(...S),U(...S)},S.canvasMutationCb=(...S)=>{b.canvasMutation&&b.canvasMutation(...S),$(...S)},S.fontCb=(...S)=>{b.font&&b.font(...S),j(...S)},S.selectionCb=(...S)=>{b.selection&&b.selection(...S),W(...S)},S.customElementCb=(...S)=>{b.customElement&&b.customElement(...S),H(...S)}}(S,b),S.recordDOM&&(x=initMutationObserver(S,S.doc));const R=function initMoveObserver({mousemoveCb:S,sampling:b,doc:I,mirror:x}){if(!1===b.mousemove)return()=>{};const R="number"==typeof b.mousemove?b.mousemove:50,A="number"==typeof b.mousemoveCallback?b.mousemoveCallback:500;let _,D=[];const L=throttle(callbackWrapper(b=>{const I=Date.now()-_;S(D.map(S=>(S.timeOffset-=I,S)),b),D=[],_=null}),A),B=callbackWrapper(throttle(callbackWrapper(S=>{const b=getEventTarget(S),{clientX:I,clientY:R}=legacy_isTouchEvent(S)?S.changedTouches[0]:S;_||(_=nc()),D.push({x:I,y:R,id:x.getId(b),timeOffset:nc()-_}),L("undefined"!=typeof DragEvent&&S instanceof DragEvent?oc.Drag:S instanceof MouseEvent?oc.MouseMove:oc.TouchMove)}),R,{trailing:!1})),U=[on("mousemove",B,I),on("touchmove",B,I),on("drag",B,I)];return callbackWrapper(()=>{U.forEach(S=>S())})}(S),A=initMouseInteractionObserver(S),_=initScrollObserver(S),D=function initViewportResizeObserver({viewportResizeCb:S},{win:b}){let I=-1,x=-1;return on("resize",callbackWrapper(throttle(callbackWrapper(()=>{const b=getWindowHeight(),R=getWindowWidth();I===b&&x===R||(S({width:Number(R),height:Number(b)}),I=b,x=R)}),200)),b)}(S,{win:I}),L=function initInputObserver({inputCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,ignoreClass:A,ignoreSelector:_,maskInputOptions:D,maskInputFn:L,sampling:B,userTriggeredOnInput:U}){function eventHandler(S){let I=getEventTarget(S);const B=S.isTrusted,$=I&&I.tagName;if(I&&"OPTION"===$&&(I=tc.parentElement(I)),!I||!$||fc.indexOf($)<0||isBlocked(I,x,R,!0))return;if(I.classList.contains(A)||_&&I.matches(_))return;let j=I.value,W=!1;const H=getInputType(I)||"";"radio"===H||"checkbox"===H?W=I.checked:(D[$.toLowerCase()]||D[H])&&(j=maskInputValue({element:I,maskInputOptions:D,tagName:$,type:H,value:j,maskInputFn:L})),cbWithDedup(I,U?{text:j,isChecked:W,userTriggered:B}:{text:j,isChecked:W});const V=I.name;"radio"===H&&V&&W&&b.querySelectorAll(`input[type="radio"][name="${V}"]`).forEach(S=>{if(S!==I){const b=S.value;cbWithDedup(S,U?{text:b,isChecked:!W,userTriggered:!1}:{text:b,isChecked:!W})}})}function cbWithDedup(b,x){const R=mc.get(b);if(!R||R.text!==x.text||R.isChecked!==x.isChecked){mc.set(b,x);const R=I.getId(b);callbackWrapper(S)({...x,id:R})}}const $=("last"===B.input?["change"]:["input","change"]).map(S=>on(S,callbackWrapper(eventHandler),b)),j=b.defaultView;if(!j)return()=>{$.forEach(S=>S())};const W=j.Object.getOwnPropertyDescriptor(j.HTMLInputElement.prototype,"value"),H=[[j.HTMLInputElement.prototype,"value"],[j.HTMLInputElement.prototype,"checked"],[j.HTMLSelectElement.prototype,"value"],[j.HTMLTextAreaElement.prototype,"value"],[j.HTMLSelectElement.prototype,"selectedIndex"],[j.HTMLOptionElement.prototype,"selected"]];return W&&W.set&&$.push(...H.map(S=>hookSetter(S[0],S[1],{set(){callbackWrapper(eventHandler)({target:this,isTrusted:!1})}},!1,j))),callbackWrapper(()=>{$.forEach(S=>S())})}(S),B=function initMediaInteractionObserver({mediaInteractionCb:S,blockClass:b,blockSelector:I,mirror:x,sampling:R,doc:A}){const _=callbackWrapper(A=>throttle(callbackWrapper(R=>{const _=getEventTarget(R);if(!_||isBlocked(_,b,I,!0))return;const{currentTime:D,volume:L,muted:B,playbackRate:U,loop:$}=_;S({type:A,id:x.getId(_),currentTime:D,volume:L,muted:B,playbackRate:U,loop:$})}),R.media||500)),D=[on("play",_(hc.Play),A),on("pause",_(hc.Pause),A),on("seeked",_(hc.Seeked),A),on("volumechange",_(hc.VolumeChange),A),on("ratechange",_(hc.RateChange),A)];return callbackWrapper(()=>{D.forEach(S=>S())})}(S);let styleSheetObserver=()=>{},adoptedStyleSheetObserver=()=>{},styleDeclarationObserver=()=>{},fontObserver=()=>{};S.recordDOM&&(styleSheetObserver=function initStyleSheetObserver({styleSheetRuleCb:S,mirror:b,stylesheetManager:I},{win:x}){if(!x.CSSStyleSheet||!x.CSSStyleSheet.prototype)return()=>{};const R=x.CSSStyleSheet.prototype.insertRule;x.CSSStyleSheet.prototype.insertRule=new Proxy(R,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:D}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.addRule=function(S,b,I=this.cssRules.length){const R=`${S} { ${b} }`;return x.CSSStyleSheet.prototype.insertRule.apply(this,[R,I])};const A=x.CSSStyleSheet.prototype.deleteRule;let _,D;x.CSSStyleSheet.prototype.deleteRule=new Proxy(A,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:_}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.removeRule=function(S){return x.CSSStyleSheet.prototype.deleteRule.apply(this,[S])},x.CSSStyleSheet.prototype.replace&&(_=x.CSSStyleSheet.prototype.replace,x.CSSStyleSheet.prototype.replace=new Proxy(_,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replace:_}),x.apply(R,A)})})),x.CSSStyleSheet.prototype.replaceSync&&(D=x.CSSStyleSheet.prototype.replaceSync,x.CSSStyleSheet.prototype.replaceSync=new Proxy(D,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replaceSync:_}),x.apply(R,A)})}));const L={};canMonkeyPatchNestedCSSRule("CSSGroupingRule")?L.CSSGroupingRule=x.CSSGroupingRule:(canMonkeyPatchNestedCSSRule("CSSMediaRule")&&(L.CSSMediaRule=x.CSSMediaRule),canMonkeyPatchNestedCSSRule("CSSConditionRule")&&(L.CSSConditionRule=x.CSSConditionRule),canMonkeyPatchNestedCSSRule("CSSSupportsRule")&&(L.CSSSupportsRule=x.CSSSupportsRule));const B={};return Object.entries(L).forEach(([x,R])=>{B[x]={insertRule:R.prototype.insertRule,deleteRule:R.prototype.deleteRule},R.prototype.insertRule=new Proxy(B[x].insertRule,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:[...getNestedCSSRulePositions(R),D||0]}]}),x.apply(R,A)})}),R.prototype.deleteRule=new Proxy(B[x].deleteRule,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:[...getNestedCSSRulePositions(R),_]}]}),x.apply(R,A)})})}),callbackWrapper(()=>{x.CSSStyleSheet.prototype.insertRule=R,x.CSSStyleSheet.prototype.deleteRule=A,_&&(x.CSSStyleSheet.prototype.replace=_),D&&(x.CSSStyleSheet.prototype.replaceSync=D),Object.entries(L).forEach(([S,b])=>{b.prototype.insertRule=B[S].insertRule,b.prototype.deleteRule=B[S].deleteRule})})}(S,{win:I}),adoptedStyleSheetObserver=initAdoptedStyleSheetObserver(S,S.doc),styleDeclarationObserver=function initStyleDeclarationObserver({styleDeclarationCb:S,mirror:b,ignoreCSSAttributes:I,stylesheetManager:x},{win:R}){const A=R.CSSStyleDeclaration.prototype.setProperty;R.CSSStyleDeclaration.prototype.setProperty=new Proxy(A,{apply:callbackWrapper((R,_,D)=>{var L;const[B,U,$]=D;if(I.has(B))return A.apply(_,[B,U,$]);const{id:j,styleId:W}=getIdAndStyleId(null==(L=_.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(j&&-1!==j||W&&-1!==W)&&S({id:j,styleId:W,set:{property:B,value:U,priority:$},index:getNestedCSSRulePositions(_.parentRule)}),R.apply(_,D)})});const _=R.CSSStyleDeclaration.prototype.removeProperty;return R.CSSStyleDeclaration.prototype.removeProperty=new Proxy(_,{apply:callbackWrapper((R,A,D)=>{var L;const[B]=D;if(I.has(B))return _.apply(A,[B]);const{id:U,styleId:$}=getIdAndStyleId(null==(L=A.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(U&&-1!==U||$&&-1!==$)&&S({id:U,styleId:$,remove:{property:B},index:getNestedCSSRulePositions(A.parentRule)}),R.apply(A,D)})}),callbackWrapper(()=>{R.CSSStyleDeclaration.prototype.setProperty=A,R.CSSStyleDeclaration.prototype.removeProperty=_})}(S,{win:I}),S.collectFonts&&(fontObserver=function initFontObserver({fontCb:S,doc:b}){const I=b.defaultView;if(!I)return()=>{};const x=[],R=new WeakMap,A=I.FontFace;I.FontFace=function FontFace2(S,b,I){const x=new A(S,b,I);return R.set(x,{family:S,buffer:"string"!=typeof b,descriptors:I,fontSource:"string"==typeof b?b:JSON.stringify(Array.from(new Uint8Array(b)))}),x};const _=patch(b.fonts,"add",function(b){return function(I){return setTimeout(callbackWrapper(()=>{const b=R.get(I);b&&(S(b),R.delete(I))}),0),b.apply(this,[I])}});return x.push(()=>{I.FontFace=A}),x.push(_),callbackWrapper(()=>{x.forEach(S=>S())})}(S)));const U=function initSelectionObserver(S){const{doc:b,mirror:I,blockClass:x,blockSelector:R,selectionCb:A}=S;let _=!0;const D=callbackWrapper(()=>{const S=b.getSelection();if(!S||_&&(null==S?void 0:S.isCollapsed))return;_=S.isCollapsed||!1;const D=[],L=S.rangeCount||0;for(let b=0;b<L;b++){const A=S.getRangeAt(b),{startContainer:_,startOffset:L,endContainer:B,endOffset:U}=A;isBlocked(_,x,R,!0)||isBlocked(B,x,R,!0)||D.push({start:I.getId(_),startOffset:L,end:I.getId(B),endOffset:U})}A({ranges:D})});return D(),on("selectionchange",D)}(S),$=function initCustomElementObserver({doc:S,customElementCb:b}){const I=S.defaultView;return I&&I.customElements?patch(I.customElements,"define",function(S){return function(I,x,R){try{b({define:{name:I}})}catch(S){console.warn(`Custom element callback failed for ${I}`)}return S.apply(this,[I,x,R])}}):()=>{}}(S),j=[];for(const b of S.plugins)j.push(b.observer(b.callback,I,b.options));return callbackWrapper(()=>{pc.forEach(S=>S.reset()),null==x||x.disconnect(),R(),A(),_(),D(),L(),B(),styleSheetObserver(),adoptedStyleSheetObserver(),styleDeclarationObserver(),fontObserver(),U(),$(),j.forEach(S=>S())})}function hasNestedCSSRule(S){return void 0!==window[S]}function canMonkeyPatchNestedCSSRule(S){return Boolean(void 0!==window[S]&&window[S].prototype&&"insertRule"in window[S].prototype&&"deleteRule"in window[S].prototype)}class CrossOriginIframeMirror{constructor(S){__publicField(this,"iframeIdToRemoteIdMap",new WeakMap),__publicField(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=S}getId(S,b,I,x){const R=I||this.getIdToRemoteIdMap(S),A=x||this.getRemoteIdToIdMap(S);let _=R.get(b);return _||(_=this.generateIdFn(),R.set(b,_),A.set(_,b)),_}getIds(S,b){const I=this.getIdToRemoteIdMap(S),x=this.getRemoteIdToIdMap(S);return b.map(b=>this.getId(S,b,I,x))}getRemoteId(S,b,I){const x=I||this.getRemoteIdToIdMap(S);if("number"!=typeof b)return b;const R=x.get(b);return R||-1}getRemoteIds(S,b){const I=this.getRemoteIdToIdMap(S);return b.map(b=>this.getRemoteId(S,b,I))}reset(S){if(!S)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(S),this.iframeRemoteIdToIdMap.delete(S)}getIdToRemoteIdMap(S){let b=this.iframeIdToRemoteIdMap.get(S);return b||(b=new Map,this.iframeIdToRemoteIdMap.set(S,b)),b}getRemoteIdToIdMap(S){let b=this.iframeRemoteIdToIdMap.get(S);return b||(b=new Map,this.iframeRemoteIdToIdMap.set(S,b)),b}}class IframeManager{constructor(S){__publicField(this,"iframes",new WeakMap),__publicField(this,"crossOriginIframeMap",new WeakMap),__publicField(this,"crossOriginIframeMirror",new CrossOriginIframeMirror(genId)),__publicField(this,"crossOriginIframeStyleMirror"),__publicField(this,"crossOriginIframeRootIdMap",new WeakMap),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"wrappedEmit"),__publicField(this,"loadListener"),__publicField(this,"stylesheetManager"),__publicField(this,"recordCrossOriginIframes"),this.mutationCb=S.mutationCb,this.wrappedEmit=S.wrappedEmit,this.stylesheetManager=S.stylesheetManager,this.recordCrossOriginIframes=S.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=S.mirror,this.recordCrossOriginIframes&&window.__TS_IFRAME_BRIDGE_PARENT_REGISTER&&window.__TS_IFRAME_BRIDGE_PARENT_REGISTER(this)}addIframe(S){this.iframes.set(S,!0),S.contentWindow&&this.crossOriginIframeMap.set(S.contentWindow,S)}addLoadListener(S){this.loadListener=S}attachIframe(S,b){var I;this.mutationCb({adds:[{parentId:this.mirror.getId(S),nextId:null,node:b}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),null==(I=this.loadListener)||I.call(this,S),__tsSafeContentDoc(S)&&__tsSafeContentDoc(S).adoptedStyleSheets&&__tsSafeContentDoc(S).adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(__tsSafeContentDoc(S).adoptedStyleSheets,this.mirror.getId(__tsSafeContentDoc(S)))}handleMessage(S){const b=S;if("rrweb"!==b.data.type||b.origin!==b.data.origin)return;if(!S.source)return;const I=this.crossOriginIframeMap.get(S.source);if(!I)return;const x=this.transformCrossOriginEvent(I,b.data.event);x&&this.wrappedEmit(x,b.data.isCheckout)}transformCrossOriginEvent(S,b){var I;switch(b.type){case ic.FullSnapshot:{this.crossOriginIframeMirror.reset(S),this.crossOriginIframeStyleMirror.reset(S),this.replaceIdOnNode(b.data.node,S);const I=b.data.node.id;return this.crossOriginIframeRootIdMap.set(S,I),this.patchRootIdOnNode(b.data.node,I),{timestamp:b.timestamp,type:ic.IncrementalSnapshot,data:{source:oc.Mutation,adds:[{parentId:this.mirror.getId(S),nextId:null,node:b.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case ic.Meta:case ic.Load:case ic.DomContentLoaded:return!1;case ic.Plugin:return b;case ic.Custom:return this.replaceIds(b.data.payload,S,["id","parentId","previousId","nextId"]),b;case ic.IncrementalSnapshot:switch(b.data.source){case oc.Mutation:return b.data.adds.forEach(b=>{this.replaceIds(b,S,["parentId","nextId","previousId"]),this.replaceIdOnNode(b.node,S);const I=this.crossOriginIframeRootIdMap.get(S);I&&this.patchRootIdOnNode(b.node,I)}),b.data.removes.forEach(b=>{this.replaceIds(b,S,["parentId","id"])}),b.data.attributes.forEach(b=>{this.replaceIds(b,S,["id"])}),b.data.texts.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case oc.Drag:case oc.TouchMove:case oc.MouseMove:return b.data.positions.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case oc.ViewportResize:return!1;case oc.MediaInteraction:case oc.MouseInteraction:case oc.Scroll:case oc.CanvasMutation:case oc.Input:return this.replaceIds(b.data,S,["id"]),b;case oc.StyleSheetRule:case oc.StyleDeclaration:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleId"]),b;case oc.Font:return b;case oc.Selection:return b.data.ranges.forEach(b=>{this.replaceIds(b,S,["start","end"])}),b;case oc.AdoptedStyleSheet:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleIds"]),null==(I=b.data.styles)||I.forEach(b=>{this.replaceStyleIds(b,S,["styleId"])}),b}}return!1}replace(S,b,I,x){for(const R of x)(Array.isArray(b[R])||"number"==typeof b[R])&&(Array.isArray(b[R])?b[R]=S.getIds(I,b[R]):b[R]=S.getId(I,b[R]));return b}replaceIds(S,b,I){return this.replace(this.crossOriginIframeMirror,S,b,I)}replaceStyleIds(S,b,I){return this.replace(this.crossOriginIframeStyleMirror,S,b,I)}replaceIdOnNode(S,b){this.replaceIds(S,b,["id","rootId"]),"childNodes"in S&&S.childNodes.forEach(S=>{this.replaceIdOnNode(S,b)})}patchRootIdOnNode(S,b){S.type===dc.Document||S.rootId||(S.rootId=b),"childNodes"in S&&S.childNodes.forEach(S=>{this.patchRootIdOnNode(S,b)})}}class ShadowDomManager{constructor(S){__publicField(this,"shadowDoms",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"scrollCb"),__publicField(this,"bypassOptions"),__publicField(this,"mirror"),__publicField(this,"restoreHandlers",[]),this.mutationCb=S.mutationCb,this.scrollCb=S.scrollCb,this.bypassOptions=S.bypassOptions,this.mirror=S.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(S,b){if(!isNativeShadowDom(S))return;if(this.shadowDoms.has(S))return;this.shadowDoms.add(S);const I=initMutationObserver({...this.bypassOptions,doc:b,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},S);this.restoreHandlers.push(()=>I.disconnect()),this.restoreHandlers.push(initScrollObserver({...this.bypassOptions,scrollCb:this.scrollCb,doc:S,mirror:this.mirror})),setTimeout(()=>{S.adoptedStyleSheets&&S.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(S.adoptedStyleSheets,this.mirror.getId(tc.host(S))),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},S))},0)}observeAttachShadow(S){S.contentWindow&&__tsSafeContentDoc(S)&&this.patchAttachShadow(S.contentWindow.Element,__tsSafeContentDoc(S))}patchAttachShadow(S,b){const I=this;this.restoreHandlers.push(patch(S.prototype,"attachShadow",function(S){return function(x){const R=S.call(this,x),A=tc.shadowRoot(this);return A&&inDom(this)&&I.addShadowRoot(A,b),R}}))}reset(){this.restoreHandlers.forEach(S=>{try{S()}catch(S){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}for(var yc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",vc="undefined"==typeof Uint8Array?[]:new Uint8Array(256),wc=0;wc<64;wc++)vc[yc.charCodeAt(wc)]=wc;const Sc=new Map;const saveWebGLVar=(S,b,I)=>{if(!S||!isInstanceOfWebGLObject(S,b)&&"object"!=typeof S)return;const x=function variableListFor$1(S,b){let I=Sc.get(S);return I||(I=new Map,Sc.set(S,I)),I.has(b)||I.set(b,[]),I.get(b)}(I,S.constructor.name);let R=x.indexOf(S);return-1===R&&(R=x.length,x.push(S)),R};function serializeArg(S,b,I){if(S instanceof Array)return S.map(S=>serializeArg(S,b,I));if(null===S)return S;if(S instanceof Float32Array||S instanceof Float64Array||S instanceof Int32Array||S instanceof Uint32Array||S instanceof Uint8Array||S instanceof Uint16Array||S instanceof Int16Array||S instanceof Int8Array||S instanceof Uint8ClampedArray){return{rr_type:S.constructor.name,args:[Object.values(S)]}}if(S instanceof ArrayBuffer){return{rr_type:S.constructor.name,base64:function(S){var b,I=new Uint8Array(S),x=I.length,R="";for(b=0;b<x;b+=3)R+=yc[I[b]>>2],R+=yc[(3&I[b])<<4|I[b+1]>>4],R+=yc[(15&I[b+1])<<2|I[b+2]>>6],R+=yc[63&I[b+2]];return x%3==2?R=R.substring(0,R.length-1)+"=":x%3==1&&(R=R.substring(0,R.length-2)+"=="),R}(S)}}if(S instanceof DataView){return{rr_type:S.constructor.name,args:[serializeArg(S.buffer,b,I),S.byteOffset,S.byteLength]}}if(S instanceof HTMLImageElement){const b=S.constructor.name,{src:I}=S;return{rr_type:b,src:I}}if(S instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:S.toDataURL()}}if(S instanceof ImageData){return{rr_type:S.constructor.name,args:[serializeArg(S.data,b,I),S.width,S.height]}}if(isInstanceOfWebGLObject(S,b)||"object"==typeof S){return{rr_type:S.constructor.name,index:saveWebGLVar(S,b,I)}}return S}const serializeArgs=(S,b,I)=>S.map(S=>serializeArg(S,b,I)),isInstanceOfWebGLObject=(S,b)=>{const I=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(S=>"function"==typeof b[S]);return Boolean(I.find(I=>S instanceof b[I]))};function initCanvasContextObserver(S,b,I,x){const R=[];try{const A=patch(S.HTMLCanvasElement.prototype,"getContext",function(S){return function(R,...A){if(!isBlocked(this,b,I,!0)){const S=function getNormalizedContextName(S){return"experimental-webgl"===S?"webgl":S}(R);if("__context"in this||(this.__context=S),x&&["webgl","webgl2"].includes(S))if(A[0]&&"object"==typeof A[0]){const S=A[0];S.preserveDrawingBuffer||(S.preserveDrawingBuffer=!0)}else A.splice(0,1,{preserveDrawingBuffer:!0})}return S.apply(this,[R,...A])}});R.push(A)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{R.forEach(S=>S())}}function patchGLPrototype(S,b,I,x,R,A){const _=[],D=Object.getOwnPropertyNames(S);for(const L of D)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(L))try{if("function"!=typeof S[L])continue;const D=patch(S,L,function(S){return function(..._){const D=S.apply(this,_);if(saveWebGLVar(D,A,this),"tagName"in this.canvas&&!isBlocked(this.canvas,x,R,!0)){const S=serializeArgs(_,A,this),x={type:b,property:L,args:S};I(this.canvas,x)}return D}});_.push(D)}catch{const x=hookSetter(S,L,{set(S){I(this.canvas,{type:b,property:L,args:[S],setter:!0})}});_.push(x)}return _}const bc="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Cc="undefined"!=typeof window&&window.Blob&&new Blob([(kc=bc,Uint8Array.from(atob(kc),S=>S.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});var kc;function WorkerWrapper(S){let b;try{if(b=Cc&&(window.URL||window.webkitURL).createObjectURL(Cc),!b)throw"";const I=new Worker(b,{name:null==S?void 0:S.name});return I.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(b)}),I}catch(b){return new Worker("data:text/javascript;base64,"+bc,{name:null==S?void 0:S.name})}finally{b&&(window.URL||window.webkitURL).revokeObjectURL(b)}}class CanvasManager{constructor(S){__publicField(this,"pendingCanvasMutations",new Map),__publicField(this,"rafStamps",{latestId:0,invokeId:null}),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"resetObservers"),__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"processMutation",(S,b)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(S)||this.pendingCanvasMutations.set(S,[]),this.pendingCanvasMutations.get(S).push(b)});const{sampling:b="all",win:I,blockClass:x,blockSelector:R,recordCanvas:A,dataURLOptions:_}=S;this.mutationCb=S.mutationCb,this.mirror=S.mirror,A&&"all"===b&&this.initCanvasMutationObserver(I,x,R),A&&"number"==typeof b&&this.initCanvasFPSObserver(b,I,x,R,{dataURLOptions:_})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(S,b,I,x,R){const A=initCanvasContextObserver(b,I,x,!0),_=new Map,D=new WorkerWrapper;D.onmessage=S=>{const{id:b}=S.data;if(_.set(b,!1),!("base64"in S.data))return;const{base64:I,type:x,width:R,height:A}=S.data;this.mutationCb({id:b,type:uc["2D"],commands:[{property:"clearRect",args:[0,0,R,A]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:I}],type:x}]},0,0]}]})};const L=1e3/S;let B,U=0;const takeCanvasSnapshots=S=>{U&&S-U<L||(U=S,(()=>{const S=[];return b.document.querySelectorAll("canvas").forEach(b=>{isBlocked(b,I,x,!0)||S.push(b)}),S})().forEach(async S=>{var b;const I=this.mirror.getId(S);if(_.get(I))return;if(0===S.width||0===S.height)return;if(_.set(I,!0),["webgl","webgl2"].includes(S.__context)){const I=S.getContext(S.__context);!1===(null==(b=null==I?void 0:I.getContextAttributes())?void 0:b.preserveDrawingBuffer)&&I.clear(I.COLOR_BUFFER_BIT)}const x=await createImageBitmap(S);D.postMessage({id:I,bitmap:x,width:S.width,height:S.height,dataURLOptions:R.dataURLOptions},[x])})),B=requestAnimationFrame(takeCanvasSnapshots)};B=requestAnimationFrame(takeCanvasSnapshots),this.resetObservers=()=>{A(),cancelAnimationFrame(B)}}initCanvasMutationObserver(S,b,I){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const x=initCanvasContextObserver(S,b,I,!1),R=function initCanvas2DMutationObserver(S,b,I,x){const R=[],A=Object.getOwnPropertyNames(b.CanvasRenderingContext2D.prototype);for(const _ of A)try{if("function"!=typeof b.CanvasRenderingContext2D.prototype[_])continue;const A=patch(b.CanvasRenderingContext2D.prototype,_,function(R){return function(...A){return isBlocked(this.canvas,I,x,!0)||setTimeout(()=>{const I=serializeArgs(A,b,this);S(this.canvas,{type:uc["2D"],property:_,args:I})},0),R.apply(this,A)}});R.push(A)}catch{const I=hookSetter(b.CanvasRenderingContext2D.prototype,_,{set(b){S(this.canvas,{type:uc["2D"],property:_,args:[b],setter:!0})}});R.push(I)}return()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I),A=function initCanvasWebGLMutationObserver(S,b,I,x){const R=[];return R.push(...patchGLPrototype(b.WebGLRenderingContext.prototype,uc.WebGL,S,I,x,b)),void 0!==b.WebGL2RenderingContext&&R.push(...patchGLPrototype(b.WebGL2RenderingContext.prototype,uc.WebGL2,S,I,x,b)),()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I);this.resetObservers=()=>{x(),R(),A()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const setLatestRAFTimestamp=S=>{this.rafStamps.latestId=S,requestAnimationFrame(setLatestRAFTimestamp)};requestAnimationFrame(setLatestRAFTimestamp)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((S,b)=>{const I=this.mirror.getId(b);this.flushPendingCanvasMutationFor(b,I)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(S,b){if(this.frozen||this.locked)return;const I=this.pendingCanvasMutations.get(S);if(!I||-1===b)return;const x=I.map(S=>{const{type:b,...I}=S;return I}),{type:R}=I[0];this.mutationCb({id:b,type:R,commands:x}),this.pendingCanvasMutations.delete(S)}}class StylesheetManager{constructor(S){__publicField(this,"trackedLinkElements",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"adoptedStyleSheetCb"),__publicField(this,"styleMirror",new StyleSheetMirror),this.mutationCb=S.mutationCb,this.adoptedStyleSheetCb=S.adoptedStyleSheetCb}attachLinkElement(S,b){"_cssText"in b.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:b.id,attributes:b.attributes}]}),this.trackLinkElement(S)}trackLinkElement(S){this.trackedLinkElements.has(S)||(this.trackedLinkElements.add(S),this.trackStylesheetInLinkElement(S))}adoptStyleSheets(S,b){if(0===S.length)return;const I={id:b,styleIds:[]},x=[];for(const b of S){let S;this.styleMirror.has(b)?S=this.styleMirror.getId(b):(S=this.styleMirror.add(b),x.push({styleId:S,rules:Array.from(b.rules||CSSRule,(S,I)=>({rule:stringifyRule(S,b.href),index:I}))})),I.styleIds.push(S)}x.length>0&&(I.styles=x),this.adoptedStyleSheetCb(I)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(S){}}class ProcessedNodeManager{constructor(){__publicField(this,"nodeMap",new WeakMap),__publicField(this,"active",!1)}inOtherBuffer(S,b){const I=this.nodeMap.get(S);return I&&Array.from(I).some(S=>S!==b)}add(S,b){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(S,(this.nodeMap.get(S)||new Set).add(b))}destroy(){}}let Ic,Ec,xc,Mc=!1;try{if(2!==Array.from([1],S=>2*S)[0]){const S=document.createElement("iframe");document.body.appendChild(S),Array.from=(null==(_t=S.contentWindow)?void 0:_t.Array.from)||Array.from,document.body.removeChild(S)}}catch(err){console.debug("Unable to override Array.from",err)}const Rc=function createMirror$2(){return new Mirror}();function record(S={}){const{emit:b,checkoutEveryNms:I,checkoutEveryNth:x,blockClass:R="rr-block",blockSelector:A=null,ignoreClass:_="rr-ignore",ignoreSelector:D=null,maskTextClass:L="rr-mask",maskTextSelector:B=null,inlineStylesheet:U=!0,maskAllInputs:$,maskInputOptions:j,slimDOMOptions:W,maskInputFn:H,maskTextFn:V,hooks:Q,packFn:G,sampling:J={},dataURLOptions:X={},mousemoveWait:Y,recordDOM:ee=!0,recordCanvas:te=!1,recordCrossOriginIframes:re=!1,recordAfter:se=("DOMContentLoaded"===S.recordAfter?S.recordAfter:"load"),userTriggeredOnInput:ne=!1,collectFonts:ie=!1,inlineImages:oe=!1,plugins:ae,keepIframeSrcFn:le=()=>!1,ignoreCSSAttributes:ce=new Set([]),errorHandler:ue}=S;!function registerErrorHandler(S){gc=S}(ue);const he=!re||window.parent===window;let de=!1;if(!he)try{window.parent.document&&(de=!1)}catch(S){de=!0}if(he&&!b)throw new Error("emit function is required");if(!he&&!de)return()=>{};void 0!==Y&&void 0===J.mousemove&&(J.mousemove=Y),Rc.reset();const ge=!0===$?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==j?j:{password:!0},pe=!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===W,headMetaDescKeywords:"all"===W,headTitleMutations:"all"===W}:W||{};let fe;!function polyfill$1(S=window){"NodeList"in S&&!S.NodeList.prototype.forEach&&(S.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in S&&!S.DOMTokenList.prototype.forEach&&(S.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let me=0;const eventProcessor=S=>{for(const b of ae||[])b.eventProcessor&&(S=b.eventProcessor(S));return G&&!de&&(S=G(S)),S};Ic=(S,R)=>{var A;const _=S;if(_.timestamp=nc(),!(null==(A=pc[0])?void 0:A.isFrozen())||_.type===ic.FullSnapshot||_.type===ic.IncrementalSnapshot&&_.data.source===oc.Mutation||pc.forEach(S=>S.unfreeze()),he)null==b||b(eventProcessor(_),R);else if(de){const S={type:"rrweb",event:eventProcessor(_),origin:window.location.origin,isCheckout:R};window.__TS_IFRAME_BRIDGE&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom(S)}if(_.type===ic.FullSnapshot)fe=_,me=0;else if(_.type===ic.IncrementalSnapshot){if(_.data.source===oc.Mutation&&_.data.isAttachIframe)return;me++;const S=x&&me>=x,b=I&&_.timestamp-fe.timestamp>I;(S||b)&&Ec(!0)}};const wrappedMutationEmit=S=>{Ic({type:ic.IncrementalSnapshot,data:{source:oc.Mutation,...S}})},wrappedScrollEmit=S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.Scroll,...S}}),wrappedCanvasMutationEmit=S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.CanvasMutation,...S}}),ye=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.AdoptedStyleSheet,...S}})}),ve=new IframeManager({mirror:Rc,mutationCb:wrappedMutationEmit,stylesheetManager:ye,recordCrossOriginIframes:re,wrappedEmit:Ic});for(const S of ae||[])S.getMirror&&S.getMirror({nodeMirror:Rc,crossOriginIframeMirror:ve.crossOriginIframeMirror,crossOriginIframeStyleMirror:ve.crossOriginIframeStyleMirror});const we=new ProcessedNodeManager;xc=new CanvasManager({recordCanvas:te,mutationCb:wrappedCanvasMutationEmit,win:window,blockClass:R,blockSelector:A,mirror:Rc,sampling:J.canvas,dataURLOptions:X});const Se=new ShadowDomManager({mutationCb:wrappedMutationEmit,scrollCb:wrappedScrollEmit,bypassOptions:{blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskInputOptions:ge,dataURLOptions:X,maskTextFn:V,maskInputFn:H,recordCanvas:te,inlineImages:oe,sampling:J,slimDOMOptions:pe,iframeManager:ve,stylesheetManager:ye,canvasManager:xc,keepIframeSrcFn:le,processedNodeManager:we},mirror:Rc});Ec=(S=!1)=>{if(!ee)return;Ic({type:ic.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},S),ye.reset(),Se.init(),pc.forEach(S=>S.lock());const b=function snapshot(S,b){const{mirror:I=new Mirror,blockClass:x="rr-block",blockSelector:R=null,maskTextClass:A="rr-mask",maskTextSelector:_=null,inlineStylesheet:D=!0,inlineImages:L=!1,recordCanvas:B=!1,maskAllInputs:U=!1,maskTextFn:$,maskInputFn:j,slimDOM:W=!1,dataURLOptions:H,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee=()=>!1}=b||{};return serializeNodeWithId(S,{doc:S,mirror:I,blockClass:x,blockSelector:R,maskTextClass:A,maskTextSelector:_,skipChild:!1,inlineStylesheet:D,maskInputOptions:!0===U?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===U?{password:!0}:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===W,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===W?{}:W,dataURLOptions:H,inlineImages:L,recordCanvas:B,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee,newlyAddedElement:!1})}(document,{mirror:Rc,blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskAllInputs:ge,maskTextFn:V,maskInputFn:H,slimDOM:pe,dataURLOptions:X,recordCanvas:te,inlineImages:oe,onSerialize:S=>{isSerializedIframe(S,Rc)&&ve.addIframe(S),isSerializedStylesheet(S,Rc)&&ye.trackLinkElement(S),hasShadowRoot(S)&&Se.addShadowRoot(tc.shadowRoot(S),document)},onIframeLoad:(S,b)=>{ve.attachIframe(S,b),Se.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{ye.attachLinkElement(S,b)},keepIframeSrcFn:le});if(!b)return console.warn("Failed to snapshot the document");Ic({type:ic.FullSnapshot,data:{node:b,initialOffset:getWindowScroll(window)}},S),pc.forEach(S=>S.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,Rc.getId(document))};try{const S=[],observe=S=>{var b;return callbackWrapper(initObservers)({mutationCb:wrappedMutationEmit,mousemoveCb:(S,b)=>Ic({type:ic.IncrementalSnapshot,data:{source:b,positions:S}}),mouseInteractionCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.MouseInteraction,...S}}),scrollCb:wrappedScrollEmit,viewportResizeCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.ViewportResize,...S}}),inputCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.Input,...S}}),mediaInteractionCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.MediaInteraction,...S}}),styleSheetRuleCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.StyleSheetRule,...S}}),styleDeclarationCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.StyleDeclaration,...S}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:S=>Ic({type:ic.IncrementalSnapshot,data:{source:oc.Font,...S}}),selectionCb:S=>{Ic({type:ic.IncrementalSnapshot,data:{source:oc.Selection,...S}})},customElementCb:S=>{Ic({type:ic.IncrementalSnapshot,data:{source:oc.CustomElement,...S}})},blockClass:R,ignoreClass:_,ignoreSelector:D,maskTextClass:L,maskTextSelector:B,maskInputOptions:ge,inlineStylesheet:U,sampling:J,recordDOM:ee,recordCanvas:te,inlineImages:oe,userTriggeredOnInput:ne,collectFonts:ie,doc:S,maskInputFn:H,maskTextFn:V,keepIframeSrcFn:le,blockSelector:A,slimDOMOptions:pe,dataURLOptions:X,mirror:Rc,iframeManager:ve,stylesheetManager:ye,shadowDomManager:Se,processedNodeManager:we,canvasManager:xc,ignoreCSSAttributes:ce,plugins:(null==(b=null==ae?void 0:ae.filter(S=>S.observer))?void 0:b.map(S=>({observer:S.observer,options:S.options,callback:b=>Ic({type:ic.Plugin,data:{plugin:S.name,payload:b}})})))||[]},Q)};ve.addLoadListener(b=>{try{S.push(observe(__tsSafeContentDoc(b)))}catch(S){console.warn(S)}});const init=()=>{Ec(),S.push(observe(document)),Mc=!0};return"interactive"===document.readyState||"complete"===document.readyState?init():(S.push(on("DOMContentLoaded",()=>{Ic({type:ic.DomContentLoaded,data:{}}),"DOMContentLoaded"===se&&init()})),S.push(on("load",()=>{Ic({type:ic.Load,data:{}}),"load"===se&&init()},window))),()=>{S.forEach(S=>S()),we.destroy(),Mc=!1,function unregisterErrorHandler(){gc=void 0}()}}catch(S){console.warn(S)}}var Tc,Ac;record.addCustomEvent=(S,b)=>{if(!Mc)throw new Error("please add custom event after start recording");Ic({type:ic.Custom,data:{tag:S,payload:b}})},record.freezePage=()=>{pc.forEach(S=>S.freeze())},record.takeFullSnapshot=S=>{if(!Mc)throw new Error("please take full snapshot after start recording");Ec(S)},record.mirror=Rc,(Ac=Tc||(Tc={}))[Ac.NotStarted=0]="NotStarted",Ac[Ac.Running=1]="Running",Ac[Ac.Stopped=2]="Stopped";const _c=createLogger("RRWeb-Loader");let Oc=null,Dc=null;try{record?(Oc=record,Dc={record:record,addCustomEvent:record.addCustomEvent,freezePage:record.freezePage,takeFullSnapshot:record.takeFullSnapshot,mirror:record.mirror},console.log("%c[TraceScout] ✅ rrweb RECORD bundled","color: #00aa00; font-weight: bold;"),_c.log("rrweb record() statically imported and ready")):console.error("[TraceScout] ❌ rrweb record import found but not a function")}catch(j){console.error("[TraceScout] ❌ Static rrweb record import failed:",j.message),_c.warn("Static rrweb record import failed:",j.message)}async function loadRRWeb(){if(!Dc||!Dc.record)throw new Error("rrweb record not available - bundling failed");return Dc}function getRRWeb(){return Dc}function getRecord(){return Oc}function isRRWebLoaded(){return!!Dc}function getRRWebSource(){return{isBundled:!0,source:"bundled",details:"@rrweb/record bundled with SDK",isRecordOnly:!0}}var Fc=Uint8Array,Nc=Uint16Array,Lc=Int32Array,Pc=new Fc([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Bc=new Fc([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zc=new Fc([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(S,b){for(var I=new Nc(31),x=0;x<31;++x)I[x]=b+=1<<S[x-1];var R=new Lc(I[30]);for(x=1;x<30;++x)for(var A=I[x];A<I[x+1];++A)R[A]=A-I[x]<<5|x;return{b:I,r:R}},Uc=freb(Pc,2),$c=Uc.b,jc=Uc.r;$c[28]=258,jc[258]=28;for(var qc=freb(Bc,0),Wc=qc.b,Hc=qc.r,Vc=new Nc(32768),Qc=0;Qc<32768;++Qc){var Kc=(43690&Qc)>>1|(21845&Qc)<<1;Kc=(61680&(Kc=(52428&Kc)>>2|(13107&Kc)<<2))>>4|(3855&Kc)<<4,Vc[Qc]=((65280&Kc)>>8|(255&Kc)<<8)>>1}var hMap=function(S,b,I){for(var x=S.length,R=0,A=new Nc(b);R<x;++R)S[R]&&++A[S[R]-1];var _,D=new Nc(b);for(R=1;R<b;++R)D[R]=D[R-1]+A[R-1]<<1;if(I){_=new Nc(1<<b);var L=15-b;for(R=0;R<x;++R)if(S[R])for(var B=R<<4|S[R],U=b-S[R],$=D[S[R]-1]++<<U,j=$|(1<<U)-1;$<=j;++$)_[Vc[$]>>L]=B}else for(_=new Nc(x),R=0;R<x;++R)S[R]&&(_[R]=Vc[D[S[R]-1]++]>>15-S[R]);return _},Gc=new Fc(288);for(Qc=0;Qc<144;++Qc)Gc[Qc]=8;for(Qc=144;Qc<256;++Qc)Gc[Qc]=9;for(Qc=256;Qc<280;++Qc)Gc[Qc]=7;for(Qc=280;Qc<288;++Qc)Gc[Qc]=8;var Jc=new Fc(32);for(Qc=0;Qc<32;++Qc)Jc[Qc]=5;var Xc=hMap(Gc,9,0),Zc=hMap(Gc,9,1),Yc=hMap(Jc,5,0),eu=hMap(Jc,5,1),max=function(S){for(var b=S[0],I=1;I<S.length;++I)S[I]>b&&(b=S[I]);return b},bits=function(S,b,I){var x=b/8|0;return(S[x]|S[x+1]<<8)>>(7&b)&I},bits16=function(S,b){var I=b/8|0;return(S[I]|S[I+1]<<8|S[I+2]<<16)>>(7&b)},shft=function(S){return(S+7)/8|0},slc=function(S,b,I){return(null==b||b<0)&&(b=0),(null==I||I>S.length)&&(I=S.length),new Fc(S.subarray(b,I))},tu=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(S,b,I){var x=new Error(b||tu[S]);if(x.code=S,Error.captureStackTrace&&Error.captureStackTrace(x,err),!I)throw x;return x},wbits=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8},wbits16=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8,S[x+2]|=I>>16},hTree=function(S,b){for(var I=[],x=0;x<S.length;++x)S[x]&&I.push({s:x,f:S[x]});var R=I.length,A=I.slice();if(!R)return{t:su,l:0};if(1==R){var _=new Fc(I[0].s+1);return _[I[0].s]=1,{t:_,l:1}}I.sort(function(S,b){return S.f-b.f}),I.push({s:-1,f:25001});var D=I[0],L=I[1],B=0,U=1,$=2;for(I[0]={s:-1,f:D.f+L.f,l:D,r:L};U!=R-1;)D=I[I[B].f<I[$].f?B++:$++],L=I[B!=U&&I[B].f<I[$].f?B++:$++],I[U++]={s:-1,f:D.f+L.f,l:D,r:L};var j=A[0].s;for(x=1;x<R;++x)A[x].s>j&&(j=A[x].s);var W=new Nc(j+1),H=ln(I[U-1],W,0);if(H>b){x=0;var V=0,Q=H-b,G=1<<Q;for(A.sort(function(S,b){return W[b.s]-W[S.s]||S.f-b.f});x<R;++x){var J=A[x].s;if(!(W[J]>b))break;V+=G-(1<<H-W[J]),W[J]=b}for(V>>=Q;V>0;){var X=A[x].s;W[X]<b?V-=1<<b-W[X]++-1:++x}for(;x>=0&&V;--x){var Y=A[x].s;W[Y]==b&&(--W[Y],++V)}H=b}return{t:new Fc(W),l:H}},ln=function(S,b,I){return-1==S.s?Math.max(ln(S.l,b,I+1),ln(S.r,b,I+1)):b[S.s]=I},lc=function(S){for(var b=S.length;b&&!S[--b];);for(var I=new Nc(++b),x=0,R=S[0],A=1,w=function(S){I[x++]=S},_=1;_<=b;++_)if(S[_]==R&&_!=b)++A;else{if(!R&&A>2){for(;A>138;A-=138)w(32754);A>2&&(w(A>10?A-11<<5|28690:A-3<<5|12305),A=0)}else if(A>3){for(w(R),--A;A>6;A-=6)w(8304);A>2&&(w(A-3<<5|8208),A=0)}for(;A--;)w(R);A=1,R=S[_]}return{c:I.subarray(0,x),n:b}},clen=function(S,b){for(var I=0,x=0;x<b.length;++x)I+=S[x]*b[x];return I},wfblk=function(S,b,I){var x=I.length,R=shft(b+2);S[R]=255&x,S[R+1]=x>>8,S[R+2]=255^S[R],S[R+3]=255^S[R+1];for(var A=0;A<x;++A)S[R+A+4]=I[A];return 8*(R+4+x)},wblk=function(S,b,I,x,R,A,_,D,L,B,U){wbits(b,U++,I),++R[256];for(var $=hTree(R,15),j=$.t,W=$.l,H=hTree(A,15),V=H.t,Q=H.l,G=lc(j),J=G.c,X=G.n,Y=lc(V),ee=Y.c,te=Y.n,re=new Nc(19),se=0;se<J.length;++se)++re[31&J[se]];for(se=0;se<ee.length;++se)++re[31&ee[se]];for(var ne=hTree(re,7),ie=ne.t,oe=ne.l,ae=19;ae>4&&!ie[zc[ae-1]];--ae);var le,ce,ue,he,de=B+5<<3,ge=clen(R,Gc)+clen(A,Jc)+_,pe=clen(R,j)+clen(A,V)+_+14+3*ae+clen(re,ie)+2*re[16]+3*re[17]+7*re[18];if(L>=0&&de<=ge&&de<=pe)return wfblk(b,U,S.subarray(L,L+B));if(wbits(b,U,1+(pe<ge)),U+=2,pe<ge){le=hMap(j,W,0),ce=j,ue=hMap(V,Q,0),he=V;var fe=hMap(ie,oe,0);wbits(b,U,X-257),wbits(b,U+5,te-1),wbits(b,U+10,ae-4),U+=14;for(se=0;se<ae;++se)wbits(b,U+3*se,ie[zc[se]]);U+=3*ae;for(var me=[J,ee],ye=0;ye<2;++ye){var ve=me[ye];for(se=0;se<ve.length;++se){var we=31&ve[se];wbits(b,U,fe[we]),U+=ie[we],we>15&&(wbits(b,U,ve[se]>>5&127),U+=ve[se]>>12)}}}else le=Xc,ce=Gc,ue=Yc,he=Jc;for(se=0;se<D;++se){var Se=x[se];if(Se>255){wbits16(b,U,le[(we=Se>>18&31)+257]),U+=ce[we+257],we>7&&(wbits(b,U,Se>>23&31),U+=Pc[we]);var be=31&Se;wbits16(b,U,ue[be]),U+=he[be],be>3&&(wbits16(b,U,Se>>5&8191),U+=Bc[be])}else wbits16(b,U,le[Se]),U+=ce[Se]}return wbits16(b,U,le[256]),U+ce[256]},ru=new Lc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),su=new Fc(0),adler=function(){var S=1,b=0;return{p:function(I){for(var x=S,R=b,A=0|I.length,_=0;_!=A;){for(var D=Math.min(_+2655,A);_<D;++_)R+=x+=I[_];x=(65535&x)+15*(x>>16),R=(65535&R)+15*(R>>16)}S=x,b=R},d:function(){return(255&(S%=65521))<<24|(65280&S)<<8|(255&(b%=65521))<<8|b>>8}}},dopt=function(S,b,I,x,R){if(!R&&(R={l:1},b.dictionary)){var A=b.dictionary.subarray(-32768),_=new Fc(A.length+S.length);_.set(A),_.set(S,A.length),S=_,R.w=A.length}return function(S,b,I,x,R,A){var _=A.z||S.length,D=new Fc(x+_+5*(1+Math.ceil(_/7e3))+R),L=D.subarray(x,D.length-R),B=A.l,U=7&(A.r||0);if(b){U&&(L[0]=A.r>>3);for(var $=ru[b-1],j=$>>13,W=8191&$,H=(1<<I)-1,V=A.p||new Nc(32768),Q=A.h||new Nc(H+1),G=Math.ceil(I/3),J=2*G,hsh=function(b){return(S[b]^S[b+1]<<G^S[b+2]<<J)&H},X=new Lc(25e3),Y=new Nc(288),ee=new Nc(32),te=0,re=0,se=A.i||0,ne=0,ie=A.w||0,oe=0;se+2<_;++se){var ae=hsh(se),le=32767&se,ce=Q[ae];if(V[le]=ce,Q[ae]=le,ie<=se){var ue=_-se;if((te>7e3||ne>24576)&&(ue>423||!B)){U=wblk(S,L,0,X,Y,ee,re,ne,oe,se-oe,U),ne=te=re=0,oe=se;for(var he=0;he<286;++he)Y[he]=0;for(he=0;he<30;++he)ee[he]=0}var de=2,ge=0,pe=W,fe=le-ce&32767;if(ue>2&&ae==hsh(se-fe))for(var me=Math.min(j,ue)-1,ye=Math.min(32767,se),ve=Math.min(258,ue);fe<=ye&&--pe&&le!=ce;){if(S[se+de]==S[se+de-fe]){for(var we=0;we<ve&&S[se+we]==S[se+we-fe];++we);if(we>de){if(de=we,ge=fe,we>me)break;var Se=Math.min(fe,we-2),be=0;for(he=0;he<Se;++he){var Ce=se-fe+he&32767,ke=Ce-V[Ce]&32767;ke>be&&(be=ke,ce=Ce)}}}fe+=(le=ce)-(ce=V[le])&32767}if(ge){X[ne++]=268435456|jc[de]<<18|Hc[ge];var Ie=31&jc[de],Ee=31&Hc[ge];re+=Pc[Ie]+Bc[Ee],++Y[257+Ie],++ee[Ee],ie=se+de,++te}else X[ne++]=S[se],++Y[S[se]]}}for(se=Math.max(se,ie);se<_;++se)X[ne++]=S[se],++Y[S[se]];U=wblk(S,L,B,X,Y,ee,re,ne,oe,se-oe,U),B||(A.r=7&U|L[U/8|0]<<3,U-=7,A.h=Q,A.p=V,A.i=se,A.w=ie)}else{for(se=A.w||0;se<_+B;se+=65535){var xe=se+65535;xe>=_&&(L[U/8|0]=B,xe=_),U=wfblk(L,U+1,S.subarray(se,xe))}A.i=_}return slc(D,0,x+shft(U)+R)}(S,null==b.level?6:b.level,null==b.mem?R.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(S.length)))):20:12+b.mem,I,x,R)},wbytes=function(S,b,I){for(;I;++b)S[b]=I,I>>>=8};function zlibSync(S,b){b||(b={});var I=adler();I.p(S);var x=dopt(S,b,b.dictionary?6:2,4);return function(S,b){var I=b.level,x=0==I?0:I<6?1:9==I?3:2;if(S[0]=120,S[1]=x<<6|(b.dictionary&&32),S[1]|=31-(S[0]<<8|S[1])%31,b.dictionary){var R=adler();R.p(b.dictionary),wbytes(S,2,R.d())}}(x,b),wbytes(x,x.length-4,I.d()),x}function unzlibSync(S,b){return function(S,b,I,x){var R=S.length,A=x?x.length:0;if(!R||b.f&&!b.l)return I||new Fc(0);var _=!I,D=_||2!=b.i,L=b.i;_&&(I=new Fc(3*R));var cbuf=function(S){var b=I.length;if(S>b){var x=new Fc(Math.max(2*b,S));x.set(I),I=x}},B=b.f||0,U=b.p||0,$=b.b||0,j=b.l,W=b.d,H=b.m,V=b.n,Q=8*R;do{if(!j){B=bits(S,U,1);var G=bits(S,U+1,3);if(U+=3,!G){var J=S[(le=shft(U)+4)-4]|S[le-3]<<8,X=le+J;if(X>R){L&&err(0);break}D&&cbuf($+J),I.set(S.subarray(le,X),$),b.b=$+=J,b.p=U=8*X,b.f=B;continue}if(1==G)j=Zc,W=eu,H=9,V=5;else if(2==G){var Y=bits(S,U,31)+257,ee=bits(S,U+10,15)+4,te=Y+bits(S,U+5,31)+1;U+=14;for(var re=new Fc(te),se=new Fc(19),ne=0;ne<ee;++ne)se[zc[ne]]=bits(S,U+3*ne,7);U+=3*ee;var ie=max(se),oe=(1<<ie)-1,ae=hMap(se,ie,1);for(ne=0;ne<te;){var le,ce=ae[bits(S,U,oe)];if(U+=15&ce,(le=ce>>4)<16)re[ne++]=le;else{var ue=0,he=0;for(16==le?(he=3+bits(S,U,3),U+=2,ue=re[ne-1]):17==le?(he=3+bits(S,U,7),U+=3):18==le&&(he=11+bits(S,U,127),U+=7);he--;)re[ne++]=ue}}var de=re.subarray(0,Y),ge=re.subarray(Y);H=max(de),V=max(ge),j=hMap(de,H,1),W=hMap(ge,V,1)}else err(1);if(U>Q){L&&err(0);break}}D&&cbuf($+131072);for(var pe=(1<<H)-1,fe=(1<<V)-1,me=U;;me=U){var ye=(ue=j[bits16(S,U)&pe])>>4;if((U+=15&ue)>Q){L&&err(0);break}if(ue||err(2),ye<256)I[$++]=ye;else{if(256==ye){me=U,j=null;break}var ve=ye-254;if(ye>264){var we=Pc[ne=ye-257];ve=bits(S,U,(1<<we)-1)+$c[ne],U+=we}var Se=W[bits16(S,U)&fe],be=Se>>4;if(Se||err(3),U+=15&Se,ge=Wc[be],be>3&&(we=Bc[be],ge+=bits16(S,U)&(1<<we)-1,U+=we),U>Q){L&&err(0);break}D&&cbuf($+131072);var Ce=$+ve;if($<ge){var ke=A-ge,Ie=Math.min(ge,Ce);for(ke+$<0&&err(3);$<Ie;++$)I[$]=x[ke+$]}for(;$<Ce;++$)I[$]=I[$-ge]}}b.l=j,b.p=me,b.b=$,b.f=B,j&&(B=1,b.m=H,b.d=W,b.n=V)}while(!B);return $!=I.length&&_?slc(I,0,$):I.subarray(0,$)}(S.subarray(function(S,b){return(8!=(15&S[0])||S[0]>>4>7||(S[0]<<8|S[1])%31)&&err(6,"invalid zlib data"),(S[1]>>5&1)==+!b&&err(6,"invalid zlib data: "+(32&S[1]?"need":"unexpected")+" dictionary"),2+(S[1]>>3&4)}(S,b&&b.dictionary),-4),{i:2},b&&b.out,b&&b.dictionary)}var nu="undefined"!=typeof TextEncoder&&new TextEncoder,iu="undefined"!=typeof TextDecoder&&new TextDecoder;try{iu.decode(su,{stream:!0})}catch(j){}function strToU8(S,b){if(b){for(var I=new Fc(S.length),x=0;x<S.length;++x)I[x]=S.charCodeAt(x);return I}if(nu)return nu.encode(S);var R=S.length,A=new Fc(S.length+(S.length>>1)),_=0,w=function(S){A[_++]=S};for(x=0;x<R;++x){if(_+5>A.length){var D=new Fc(_+8+(R-x<<1));D.set(A),A=D}var L=S.charCodeAt(x);L<128||b?w(L):L<2048?(w(192|L>>6),w(128|63&L)):L>55295&&L<57344?(w(240|(L=65536+(1047552&L)|1023&S.charCodeAt(++x))>>18),w(128|L>>12&63),w(128|L>>6&63),w(128|63&L)):(w(224|L>>12),w(128|L>>6&63),w(128|63&L))}return slc(A,0,_)}function strFromU8(S,b){if(b){for(var I="",x=0;x<S.length;x+=16384)I+=String.fromCharCode.apply(null,S.subarray(x,x+16384));return I}if(iu)return iu.decode(S);var R=function(S){for(var b="",I=0;;){var x=S[I++],R=(x>127)+(x>223)+(x>239);if(I+R>S.length)return{s:b,r:slc(S,I-1)};R?3==R?(x=((15&x)<<18|(63&S[I++])<<12|(63&S[I++])<<6|63&S[I++])-65536,b+=String.fromCharCode(55296|x>>10,56320|1023&x)):b+=1&R?String.fromCharCode((31&x)<<6|63&S[I++]):String.fromCharCode((15&x)<<12|(63&S[I++])<<6|63&S[I++]):b+=String.fromCharCode(x)}}(S),A=R.s;return(I=R.r).length&&err(8),A}const ou=["token","key","secret","password","auth","api_key","apikey","access_token","refresh_token","jwt","bearer","credential","session_id","session","sid","ssid","private_token"];function sanitizeUrl(S){if(!S)return"";try{const b=new URL(S);for(const S of ou)b.searchParams.delete(S),b.searchParams.delete(S.toLowerCase()),b.searchParams.delete(S.toUpperCase());return scrubUrlValues(b.toString(),{mode:"delete"})}catch{return redactCardNumbers(S.replace(/[?&](token|key|secret|password|auth|api_key|apikey|access_token|jwt)=[^&]*/gi,"$1=[REDACTED]"))}}function hashCode(S){let b=0;for(let I=0;I<S.length;I++){b=(b<<5)-b+S.charCodeAt(I),b&=b}return Math.abs(b).toString(36)}function generateNetworkId(S,b,I,x){return`net_${b}_${hashCode(sanitizeUrl(x))}`}function generateConsoleId(S,b,I){return`log_${b}_${hashCode(String(I||"").substring(0,100))}`}function generateResourceId(S,b){return`res_${S}_${hashCode(b)}`}function flatNetworkFields(S){const b=S||{},I=b.requestUrl||b.url||"";return{method:b.method,url:I,status:"number"==typeof b.status?b.status:b.statusCode,duration:"number"==typeof b.durationMs?b.durationMs:b.duration,size:"number"==typeof b.responseSize?b.responseSize:b.size,error:b.error||b.errorMessage,resourceType:b.resourceType||(I?getResourceType(I):void 0)}}function extractNetworkRef(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=flatNetworkFields(S.data?.payload),R=sanitizeUrl(x.url),A={networkId:generateNetworkId(0,S.timestamp,x.method,R),timestamp:S.timestamp,method:x.method||"GET",url:R,status:x.status,duration:x.duration,size:x.size,type:I.replace("network_","")};return"network_resource"===I&&x.resourceType&&(A.resourceType=x.resourceType),A}function extractConsoleRef(S,b){if(5!==S.type)return null;if("console"!==S.data?.tag)return null;const I=S.data?.payload||{};let x="";I.args&&Array.isArray(I.args)?x=JSON.stringify(I.args).substring(0,100):I.message&&(x=String(I.message).substring(0,100));const R=generateConsoleId(0,S.timestamp,x);let A="";return I.message?(A=String(I.message).slice(0,100),I.message.length>100&&(A+="...")):I.args&&Array.isArray(I.args)&&(A=I.args.map(S=>String(S)).join(" ").slice(0,100),A.length>=100&&(A+="...")),{consoleId:R,timestamp:S.timestamp,level:I.level||"log",preview:A}}function extractResourceRef(S){if(5!==S.type)return null;if("network_resource"!==S.data?.tag)return null;const b=S.data?.payload||{};return{resourceId:generateResourceId(S.timestamp,b.url||""),timestamp:S.timestamp,method:b.method||"GET",url:b.url||"",status:b.status||0,resourceType:b.resourceType||"other",size:b.size||null,duration:b.duration||null}}function extractNetworkFull(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=S.data?.payload||{},R=flatNetworkFields(x),A=sanitizeUrl(R.url);return{id:generateNetworkId(0,S.timestamp,R.method,A),timestamp:S.timestamp,method:R.method||"GET",url:A,requestHeaders:x.requestHeaders||{},requestBody:x.requestBody||null,status:R.status,statusText:x.statusText,responseHeaders:x.responseHeaders||{},responseBody:x.responseBody||null,duration:R.duration,size:R.size,timing:x.timing,error:R.error}}function stripNetworkPayload(S){if(5!==S.type)return S;const b=S.data?.tag;if(!b||!b.startsWith("network_"))return S;const I=flatNetworkFields(S.data?.payload);return{...S,data:{tag:S.data.tag,payload:{method:I.method,url:I.url?scrubUrlValues(I.url):I.url,status:I.status,duration:I.duration,size:I.size,resourceType:I.resourceType,error:I.error}}}}const au="tracescout.network_request";function networkEnvelopeEvent(S){if(!S||5!==S.type)return null;const b=S.data?.tag;if(!b||!b.startsWith("network_"))return null;const I=S.data?.payload;return!I||"object"!=typeof I||Array.isArray(I)||"string"!=typeof I.eventId||0===I.eventId.length||"string"!=typeof I.eventType||0===I.eventType.length?null:{type:5,timestamp:S.timestamp,data:{tag:au,payload:I}}}function extractVersion(S,b){const I=S.match(b);return I?I[1]:"unknown"}function parseBrowserInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";return b.includes("edg/")?(I="Edge",x=extractVersion(S,/edg\/(\d+(\.\d+)?)/i)):b.includes("chrome")&&!b.includes("chromium")?(I="Chrome",x=extractVersion(S,/chrome\/(\d+(\.\d+)?)/i)):b.includes("firefox")?(I="Firefox",x=extractVersion(S,/firefox\/(\d+(\.\d+)?)/i)):b.includes("safari")&&!b.includes("chrome")?(I="Safari",x=extractVersion(S,/version\/(\d+(\.\d+)?)/i)):b.includes("opera")||b.includes("opr")?(I="Opera",x=extractVersion(S,/(?:opera|opr)\/(\d+(\.\d+)?)/i)):(b.includes("msie")||b.includes("trident"))&&(I="IE",x=extractVersion(S,/(?:msie |rv:)(\d+(\.\d+)?)/i)),{name:I,version:x}}function parseOSInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";if(b.includes("windows"))I="Windows",b.includes("windows nt 10")?x="10":b.includes("windows nt 6.3")?x="8.1":b.includes("windows nt 6.2")?x="8":b.includes("windows nt 6.1")&&(x="7");else if(b.includes("mac os x")){I="macOS";const b=S.match(/mac os x (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else if(b.includes("android"))I="Android",x=extractVersion(S,/android (\d+(\.\d+)?)/i);else if(b.includes("iphone")||b.includes("ipad")||b.includes("ipod")){I="iOS";const b=S.match(/os (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else b.includes("linux")&&(I="Linux");return{name:I,version:x}}function detectDeviceType(S){if(!S)return"desktop";const b=S.toLowerCase();return/mobile|android|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(b)?/ipad|tablet/i.test(b)||b.includes("android")&&!b.includes("mobile")?"tablet":"mobile":"desktop"}function detectTouchCapability(){return"undefined"!=typeof window&&("ontouchstart"in window||"undefined"!=typeof navigator&&navigator.maxTouchPoints>0)}function getConnectionInfo(){if("undefined"==typeof navigator||!navigator.connection)return null;const S=navigator.connection;return{effectiveType:S.effectiveType||null,downlink:S.downlink||null,rtt:S.rtt||null,saveData:S.saveData||!1}}function getMemoryInfo(){return"undefined"!=typeof navigator&&navigator.deviceMemory?{deviceMemory:navigator.deviceMemory}:null}function collectDeviceMetadata(){const S="undefined"!=typeof navigator?navigator.userAgent:null;return{screen:{width:"undefined"!=typeof screen?screen.width:null,height:"undefined"!=typeof screen?screen.height:null,colorDepth:"undefined"!=typeof screen?screen.colorDepth:null,pixelRatio:"undefined"!=typeof window?window.devicePixelRatio:null},viewport:{width:"undefined"!=typeof window?window.innerWidth:null,height:"undefined"!=typeof window?window.innerHeight:null},userAgent:S,language:"undefined"!=typeof navigator?navigator.language:null,languages:"undefined"!=typeof navigator?navigator.languages:null,platform:"undefined"!=typeof navigator?navigator.platform:null,connection:getConnectionInfo(),deviceType:detectDeviceType(S),touchCapable:detectTouchCapability(),memory:getMemoryInfo(),browser:parseBrowserInfo(S),os:parseOSInfo(S)}}function analyzeSnapshotsInEvents(S){const b=[];let I=-1;for(let x=0;x<S.length;x++){const R=S[x];2===R.type&&(b.push(R.timestamp),-1===I&&(I=x))}return{hasSnapshot:b.length>0,snapshotCount:b.length,snapshotTimestamps:b,firstSnapshotIndex:I}}function buildSnapshotIndex(S){const b=[];for(const I of S)if(I.snapshotInfo?.hasSnapshot)for(let S=0;S<I.events.length;S++){const x=I.events[S];2===x.type&&b.push({chunkSequence:I.sequence,timestamp:x.timestamp,eventIndex:S})}return b.sort((S,b)=>S.timestamp-b.timestamp),b}function findNearestSnapshotBefore(S,b){if(!S||0===S.length)return null;let I=0,x=S.length-1,R=null;for(;I<=x;){const A=Math.floor((I+x)/2),_=S[A];_.timestamp<=b?(R=_,I=A+1):x=A-1}return R}function getEventsAfterSnapshot(S,b,I){if(!S||!S.events)return[];const x=[];for(let R=b;R<S.events.length;R++){const b=S.events[R];if(!(b.timestamp<=I))break;x.push(b)}return x}function chunkHasSnapshot(S){return!0===S?.snapshotInfo?.hasSnapshot}function getSnapshotTimestamps(S){return S?.snapshotInfo?.snapshotTimestamps||[]}const lu=4;function createChunk(S){const{sequence:b,sessionId:I,events:x=[],networkRefs:R=[],consoleRefs:A=[],networkFullData:_=[],metadata:D={},isFirstChunk:L=!1,isLastChunk:B=!1}=S,U=x.map(S=>S.timestamp).filter(S=>"number"==typeof S),$=U.length>0?Math.min(...U):Date.now(),j=U.length>0?Math.max(...U):Date.now(),W=analyzeSnapshotsInEvents(x);return{version:4,chunkId:I?`${I}_chunk_${b}`:`chunk_${b}_${Date.now()}`,sequence:b,sessionId:I,startTimestamp:$,endTimestamp:j,eventCount:x.length,events:x,networkRefs:R,consoleRefs:A,networkFullData:_,snapshotInfo:{hasSnapshot:W.hasSnapshot,snapshotCount:W.snapshotCount,snapshotTimestamps:W.snapshotTimestamps,firstSnapshotIndex:W.firstSnapshotIndex},metadata:{...D,createdAt:Date.now(),isFirstChunk:L,isLastChunk:B,hasSnapshotInChunk:W.hasSnapshot}}}function isCompatibleVersion(S){return 4===S.version}class InactivityManager{constructor(S={}){this.inactivityTimeout=S.inactivityTimeout||3e5,this.maxInactivityDuration=S.maxInactivityDuration||18e5,this.maxSessionDuration=S.maxSessionDuration||36e5,this.enabled=!1!==S.enableInactivityDetection,this.lastActivityTime=Date.now(),this.isPaused=!1,this.pauseStartTime=null,this.totalPausedTime=0,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.inactivityTimer=null,this.sessionEndTimer=null,this.onPause=S.onPause||(()=>{}),this.onResume=S.onResume||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.enabled&&(this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now(),this.totalPausedTime=0,this.isPaused=!1,this.sessionEnded=!1,this.sessionEndReason=null,this.resetInactivityTimer(),this.logger.info?.(`[Inactivity] Detection enabled: pause after ${this.inactivityTimeout/1e3}s, end session after ${this.maxInactivityDuration/1e3}s`))}stop(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null)}trackActivity(S){if(!this.enabled)return;this.isUserActivityEvent(S)&&(this.lastActivityTime=Date.now(),this.isPaused&&this.resumeFromInactivity(),this.resetInactivityTimer())}isUserActivityEvent(S){if(3===S.type&&S.data){return[1,2,3,5,6,7].includes(S.data.source)}return!1}resetInactivityTimer(){if(Date.now()-this.sessionStartTime>this.maxSessionDuration)return this.logger.warn?.(`[Inactivity] Max session duration (${Math.round(this.maxSessionDuration/6e4)}min) exceeded - ending session`),void this.onMaxSessionDurationReached();this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout(()=>{this.onInactivityTimeout()},this.inactivityTimeout)}onInactivityTimeout(){if(this.isPaused)return;const S=Date.now()-this.lastActivityTime;this.logger.info?.(`[Inactivity] User inactive for ${Math.round(S/1e3)}s - pausing recording`),this.pauseForInactivity(),this.sessionEndTimer=setTimeout(()=>{this.onMaxInactivityReached()},this.maxInactivityDuration-this.inactivityTimeout)}pauseForInactivity(){this.isPaused||(this.isPaused=!0,this.pauseStartTime=Date.now(),this.onAddCustomEvent("inactivity",{action:"pause",inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}),this.logger.info?.("[Inactivity] Recording paused - waiting for user activity"),this.onPause({inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}))}resumeFromInactivity(){if(!this.isPaused)return;const S=Date.now()-this.pauseStartTime;this.totalPausedTime+=S;const b=Date.now()-this.sessionStartTime;if(b>this.maxSessionDuration)return this.logger.warn?.("[Inactivity] Max session duration exceeded during pause - ending session"),void this.onMaxSessionDurationReached();this.isPaused=!1,this.pauseStartTime=null,this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null),this.onAddCustomEvent("inactivity",{action:"resume",pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()}),this.logger.info?.(`[Inactivity] Recording resumed after ${Math.round(S/1e3)}s pause (session: ${Math.round(b/6e4)}min)`),this.onResume({pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()})}onMaxInactivityReached(){const S=Date.now()-this.lastActivityTime,b=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Inactivity] Max inactivity (${Math.round(S/1e3)}s) reached - ending session`),this.onAddCustomEvent("inactivity",{action:"session_ended",reason:"max_inactivity",inactiveFor:S,sessionDuration:b,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_inactivity")}onMaxSessionDurationReached(){const S=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Session] Max duration (${Math.round(S/6e4)}min) reached - ending session`),this.onAddCustomEvent("session_lifecycle",{action:"session_ended",reason:"max_duration",sessionDuration:S,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_duration")}endSession(S="manual"){this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.onSessionEnd({reason:S,duration:Date.now()-this.sessionStartTime,totalPausedTime:this.totalPausedTime})}shouldRecordEvent(S){return!this.isPaused||5===S.type}getState(){return{enabled:this.enabled,isPaused:this.isPaused,sessionEnded:this.sessionEnded,sessionEndReason:this.sessionEndReason,lastActivityTime:this.lastActivityTime,totalPausedTime:this.totalPausedTime,sessionDuration:Date.now()-this.sessionStartTime,timeSinceLastActivity:Date.now()-this.lastActivityTime}}updateConfig(S){void 0!==S.inactivityTimeout&&(this.inactivityTimeout=S.inactivityTimeout),void 0!==S.maxInactivityDuration&&(this.maxInactivityDuration=S.maxInactivityDuration),void 0!==S.maxSessionDuration&&(this.maxSessionDuration=S.maxSessionDuration),void 0!==S.enableInactivityDetection&&(this.enabled=S.enableInactivityDetection)}destroy(){this.stop(),this.onPause=null,this.onResume=null,this.onSessionEnd=null,this.onAddCustomEvent=null,this.logger=null}}class PageLifecycleManager{constructor(S={}){this.onFlush=S.onFlush||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.onSendBeacon=S.onSendBeacon||(()=>{}),this.getIsRecording=S.getIsRecording||(()=>!1),this.getCurrentChunkLength=S.getCurrentChunkLength||(()=>0),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.logger=S.logger||console,this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this._pageCloseFlushAttempted=!1}setup(){"undefined"!=typeof window&&(this._pageCloseFlushAttempted=!1,this._boundBeforeUnload=this._handleBeforeUnload.bind(this),this._boundPageHide=this._handlePageHide.bind(this),this._boundVisibilityChange=this._handleVisibilityChange.bind(this),window.addEventListener("beforeunload",this._boundBeforeUnload),window.addEventListener("pagehide",this._boundPageHide),document.addEventListener("visibilitychange",this._boundVisibilityChange),this.logger.info?.("[PageLifecycle] Page close handlers installed"))}remove(){"undefined"!=typeof window&&(this._boundBeforeUnload&&window.removeEventListener("beforeunload",this._boundBeforeUnload),this._boundPageHide&&window.removeEventListener("pagehide",this._boundPageHide),this._boundVisibilityChange&&document.removeEventListener("visibilitychange",this._boundVisibilityChange),this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this.logger.info?.("[PageLifecycle] Page close handlers removed"))}_handleBeforeUnload(S){this._flushOnPageClose("beforeunload")}_handlePageHide(S){this._flushOnPageClose("pagehide",S.persisted)}_handleVisibilityChange(){"hidden"===document.visibilityState&&this._flushOnPageClose("visibilitychange")}_flushOnPageClose(S,b=!1){if(this._pageCloseFlushAttempted)return void this.logger.log?.(`[PageLifecycle] Flush already attempted, skipping duplicate (${S})`);const I=this.getIsRecording(),x=this.getCurrentChunkLength();if(!I||0===x)return void this.logger.log?.(`[PageLifecycle] No pending events to flush on ${S}`);this._pageCloseFlushAttempted=!0,this.logger.log?.(`[PageLifecycle] Flushing ${x} events on ${S}`),this.onAddCustomEvent("session_lifecycle",{action:"page_close",trigger:S,persisted:b,timestamp:Date.now(),pendingEvents:x,sessionDuration:Date.now()-this.getSessionStartTime(),totalChunks:this.getChunkCounter()});const R=this.onFlush();R&&(R.metadata=R.metadata||{},R.metadata.isLastChunk=!0,R.metadata.closeTrigger=S,R.metadata.sessionEndedGracefully=!0,this.onSendBeacon(R,S))}resetFlushGuard(){this._pageCloseFlushAttempted=!1}getState(){return{handlersInstalled:null!==this._boundBeforeUnload,flushAttempted:this._pageCloseFlushAttempted}}destroy(){this.remove(),this.onFlush=null,this.onAddCustomEvent=null,this.onSendBeacon=null,this.getIsRecording=null,this.getCurrentChunkLength=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.logger=null}}class CheckpointManager{constructor(S={}){this.checkpointInterval=S.checkpointInterval||6e4,this.lastCheckpointTime=0,this.checkpointTimer=null,this.checkpointCount=0,this.checkpointAvailable=null,this.getRRWeb=S.getRRWeb||(()=>null),this.getIsRecording=S.getIsRecording||(()=>!1),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.getEventCount=S.getEventCount||(()=>0),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.checkpointTimer&&clearInterval(this.checkpointTimer),this.lastCheckpointTime=Date.now(),this.checkpointCount=0,this.checkpointTimer=setInterval(()=>{this.requestCheckpoint()},this.checkpointInterval),this.logger.info?.(`[Checkpoint] Timer started (interval: ${this.checkpointInterval/1e3}s)`)}stop(){this.checkpointTimer&&(clearInterval(this.checkpointTimer),this.checkpointTimer=null)}requestCheckpoint(){if(!this.getIsRecording())return;const S=Date.now();if(!(S-this.lastCheckpointTime<.9*this.checkpointInterval))try{const b=this.getRRWeb();let I=null;if(b&&("function"==typeof b.takeFullSnapshot?I=b.takeFullSnapshot:b.record&&"function"==typeof b.record.takeFullSnapshot&&(I=b.record.takeFullSnapshot)),I)try{I(),this.lastCheckpointTime=S,this.checkpointAvailable=!0,this.checkpointCount++,this.onAddCustomEvent("checkpoint",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),checkpointNumber:this.checkpointCount,snapshotRequested:!0}),this.logger.info?.(`[Checkpoint] #${this.checkpointCount} at ${Math.round((S-this.getSessionStartTime())/1e3)}s`)}catch(b){this.logger.warn?.("[Checkpoint] takeFullSnapshot error:",b.message),this.checkpointAvailable=!1,this._addCheckpointMarker(S,"takeFullSnapshot error: "+b.message)}else!1!==this.checkpointAvailable&&(this.logger.warn?.("[Checkpoint] Manual snapshots not available - relying on rrweb checkoutEveryNms"),this.checkpointAvailable=!1),this._addCheckpointMarker(S,"using rrweb auto-checkout")}catch(S){this.logger.warn?.("[Checkpoint] Request failed:",S.message),this._addCheckpointMarker(Date.now(),"Error: "+S.message)}}_addCheckpointMarker(S,b){this.onAddCustomEvent("checkpoint_marker",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),snapshotRequested:!1,reason:b})}takeManualCheckpoint(){this.logger.info?.("[Checkpoint] Manual checkpoint requested"),this.requestCheckpoint()}getState(){return{checkpointCount:this.checkpointCount,lastCheckpointTime:this.lastCheckpointTime,checkpointAvailable:this.checkpointAvailable,checkpointInterval:this.checkpointInterval,timerRunning:null!==this.checkpointTimer}}updateConfig(S){void 0!==S.checkpointInterval&&(this.checkpointInterval=S.checkpointInterval,this.checkpointTimer&&(this.stop(),this.start()))}destroy(){this.stop(),this.getRRWeb=null,this.getIsRecording=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.getEventCount=null,this.onAddCustomEvent=null,this.logger=null}}class RecorderMemoryManager{constructor(S={}){this.maxChunksInMemory=S.maxChunksInMemory||10,this.maxEventsPerSession=S.maxEventsPerSession||5e4,this.maxSessionBytes=S.maxSessionBytes||52428800,this.maxEventsInBuffer=S.maxEventsInBuffer||2e3,this.cleanupInterval=S.cleanupInterval||6e4,this.totalSessionBytes=0,this.cleanupTimer=null,this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=S.onForceFlush||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setDataReferences(S){this._allChunks=S.allChunks||null,this._events=S.events||null,this._eventDedupeCache=S.eventDedupeCache||null,this._eventStats=S.eventStats||null}start(){this.cleanupTimer||(this.totalSessionBytes=0,this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.cleanupInterval),this.logger.log?.("[Memory] Started periodic cleanup (60s interval)"))}stop(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.logger.log?.("[Memory] Stopped cleanup timer"))}trackBytes(S){return this.totalSessionBytes+=S,!(this.totalSessionBytes>this.maxSessionBytes)||(this.logger.warn?.(`[Memory] Session size limit reached (${Math.round(this.totalSessionBytes/1024/1024)}MB / ${Math.round(this.maxSessionBytes/1024/1024)}MB)`),!1)}checkEventLimit(S){return!(S>this.maxEventsPerSession)||(this.logger.warn?.(`[Memory] Max events per session (${this.maxEventsPerSession}) exceeded`),!1)}performCleanup(){const S=Date.now();let b={dedupeEntries:0,statsEvents:0,chunks:0,eventsBuffer:0};if(this._eventDedupeCache){const I=S-1e4;for(const[S,x]of this._eventDedupeCache.entries())x<I&&(this._eventDedupeCache.delete(S),b.dedupeEntries++)}if(this._eventStats?.lastMinuteEvents){const I=S-6e4,x=this._eventStats.lastMinuteEvents.length;this._eventStats.lastMinuteEvents=this._eventStats.lastMinuteEvents.filter(S=>S>I),b.statsEvents=x-this._eventStats.lastMinuteEvents.length}if(this._allChunks&&this._allChunks.length>this.maxChunksInMemory)for(;this._allChunks.length>this.maxChunksInMemory;)this._allChunks.shift(),b.chunks++;return this._events&&this._events.length>this.maxEventsInBuffer&&(this.logger.warn?.(`[Memory] Events buffer exceeded ${this.maxEventsInBuffer}, forcing flush`),this.onForceFlush()),(b.dedupeEntries>0||b.statsEvents>0||b.chunks>0)&&this.logger.log?.(`[Memory] Cleanup: ${b.dedupeEntries} dedupe entries, ${b.statsEvents} stat entries, ${b.chunks} chunks`),b}trimEventsArray(S=1e3){if(!this._events||this._events.length<=S)return 0;const b=this._events.length-S;return this._events.splice(0,b),this.logger.log&&this.logger.log?.(`[Memory] Cleared ${b} old events from events array`),b}trimChunksArray(){if(!this._allChunks||this._allChunks.length<=this.maxChunksInMemory)return null;const S=this._allChunks.shift();return this.logger.log?.(`[Memory] Removed old chunk ${S?.sequence} from memory (keeping ${this.maxChunksInMemory} chunks)`),S}getStats(){return{eventsInBuffer:this._events?.length||0,maxEventsInBuffer:this.maxEventsInBuffer,chunksInMemory:this._allChunks?.length||0,maxChunksInMemory:this.maxChunksInMemory,dedupeCacheSize:this._eventDedupeCache?.size||0,totalSessionBytes:this.totalSessionBytes,maxSessionBytes:this.maxSessionBytes,sessionSizePercent:Math.round(this.totalSessionBytes/this.maxSessionBytes*100),statsEventsTracked:this._eventStats?.lastMinuteEvents?.length||0,totalEventsRecorded:this._eventStats?.total||0,estimatedMemoryMB:this.estimateMemoryUsage()}}estimateMemoryUsage(){let S=0;if(S+=500*(this._events?.length||0),this._allChunks)for(const b of this._allChunks)S+=b.sizeBytes||5e4;return S+=100*(this._eventDedupeCache?.size||0),Math.round(S/1048576*100)/100}suggestGC(){if(this._allChunks)for(const S of this._allChunks)S._rawEvents&&(S._rawEvents=null);this.logger.log?.("[Memory] GC hint sent")}updateConfig(S){void 0!==S.maxChunksInMemory&&(this.maxChunksInMemory=S.maxChunksInMemory),void 0!==S.maxEventsPerSession&&(this.maxEventsPerSession=S.maxEventsPerSession),void 0!==S.maxSessionBytes&&(this.maxSessionBytes=S.maxSessionBytes),void 0!==S.maxEventsInBuffer&&(this.maxEventsInBuffer=S.maxEventsInBuffer)}reset(){this.totalSessionBytes=0}destroy(){this.stop(),this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=null,this.onSessionEnd=null,this.logger=null}}const cu={0:"DomContentLoaded",1:"Load",2:"FullSnapshot",3:"IncrementalSnapshot",4:"Meta",5:"Custom"};class EventOptimizer{constructor(S={}){this.samplingEnabled=S.enableSampling||!1,this.deduplicationEnabled=S.enableDeduplication||!1,this.mousemoveSampling=S.mousemoveSampling||1,this.scrollSampling=S.scrollSampling||1,this.mutationSampling=S.mutationSampling||1,this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0},this.eventDedupeCache=new Map,this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.logger=S.logger||console}getDedupeCache(){return this.eventDedupeCache}getEventStats(){return this.eventStats}shouldRecordEvent(S){const b=this.getEventTypeName(S.type);return!!["DomContentLoaded","Load","FullSnapshot","Meta","Custom"].includes(b)||!(this.samplingEnabled&&!this._applySampling(S))&&(!this.deduplicationEnabled||!this._isDuplicateEvent(S))}updateStats(S){this.eventStats.total++;const b=this.getEventTypeName(S.type);this.eventStats.byType[b]=(this.eventStats.byType[b]||0)+1;try{const I=JSON.stringify(S).length;this.eventStats.sizeByType[b]||(this.eventStats.sizeByType[b]={total:0,count:0,average:0}),this.eventStats.sizeByType[b].total+=I,this.eventStats.sizeByType[b].count++,this.eventStats.sizeByType[b].average=Math.round(this.eventStats.sizeByType[b].total/this.eventStats.sizeByType[b].count)}catch(S){}const I=Date.now();this.eventStats.lastMinuteEvents.push(I),this.eventStats.lastMinuteEvents=this.eventStats.lastMinuteEvents.filter(S=>I-S<6e4),this.eventStats.currentRate=this.eventStats.lastMinuteEvents.length}adaptToEventRate(){if(!this.samplingEnabled)return;const S=this.eventStats.currentRate;S>3e3?(this.mousemoveSampling=Math.max(.1,this.mousemoveSampling-.1),this.scrollSampling=Math.max(.2,this.scrollSampling-.1),this.logger.warn?.(`[Optimizer] High event rate (${S}/min), increasing sampling`)):S<600&&this.mousemoveSampling<.5&&(this.mousemoveSampling=Math.min(.5,this.mousemoveSampling+.05),this.scrollSampling=Math.min(.7,this.scrollSampling+.05))}_applySampling(S){if(3===S.type&&1===S.data?.source){if(Math.random()>=this.mousemoveSampling)return!1;if(S.data.positions&&S.data.positions.length>0){const b=S.data.positions[S.data.positions.length-1];if(Math.sqrt(Math.pow(b.x-this.lastMousePosition.x,2)+Math.pow(b.y-this.lastMousePosition.y,2))<5)return!1;this.lastMousePosition={x:b.x,y:b.y}}}return 3!==S.type||3!==S.data?.source||Math.random()<this.scrollSampling}_isDuplicateEvent(S){const b=this._getEventKey(S),I=Date.now();if(this.eventDedupeCache.has(b)){if(I-this.eventDedupeCache.get(b)<100)return!0}if(this.eventDedupeCache.set(b,I),this.eventDedupeCache.size>1e3){const S=I-5e3;for(const[b,I]of this.eventDedupeCache.entries())I<S&&this.eventDedupeCache.delete(b)}return!1}_getEventKey(S){if(3===S.type){const b=S.data?.source,I=S.data?.id,x=S.data?.action;return`${S.type}-${b}-${I}-${x}`}try{return`${S.type}-${JSON.stringify(S.data).substring(0,50)}`}catch(b){return`${S.type}-unknown`}}getEventTypeName(S){return cu[S]||`Unknown(${S})`}getOptimizationStats(){return{eventStats:{...this.eventStats},samplingRates:{mousemove:this.mousemoveSampling,scroll:this.scrollSampling},samplingEnabled:this.samplingEnabled,deduplicationEnabled:this.deduplicationEnabled,deduplicatedEvents:this.eventDedupeCache.size}}logOptimizationReport(){const S=this.getOptimizationStats();this.logger.info?.("📊 Optimization Report:"),this.logger.info?.(" Sampling: "+(S.samplingEnabled?"Enabled":"Disabled")),this.logger.info?.(" Deduplication: "+(S.deduplicationEnabled?"Enabled":"Disabled")),this.logger.info?.(` Event Rate: ${S.eventStats.currentRate}/min`),this.logger.info?.(` Total Events: ${S.eventStats.total}`),this.logger.info?.(` Deduplicated: ${S.deduplicatedEvents}`),S.samplingEnabled&&(this.logger.info?.(" Sampling Rates:"),this.logger.info?.(` Mouse Move: ${(100*S.samplingRates.mousemove).toFixed(0)}%`),this.logger.info?.(` Scroll: ${(100*S.samplingRates.scroll).toFixed(0)}%`)),this.logger.info?.(" Event Distribution:");for(const[b,I]of Object.entries(S.eventStats.byType)){const x=(I/S.eventStats.total*100).toFixed(1),R=S.eventStats.sizeByType[b]?.average||0;this.logger.info?.(` ${b}: ${I} (${x}%) - Avg: ${R}B`)}}updateConfig(S){void 0!==S.enableSampling&&(this.samplingEnabled=S.enableSampling),void 0!==S.enableDeduplication&&(this.deduplicationEnabled=S.enableDeduplication),void 0!==S.mousemoveSampling&&(this.mousemoveSampling=S.mousemoveSampling),void 0!==S.scrollSampling&&(this.scrollSampling=S.scrollSampling),void 0!==S.mutationSampling&&(this.mutationSampling=S.mutationSampling)}reset(){this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.eventDedupeCache.clear(),this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0}}destroy(){this.eventDedupeCache.clear(),this.eventStats=null,this.logger=null}}class ChunkManager{constructor(S={}){this.chunkDuration=S.chunkDuration||3e4,this.maxChunkSize=S.maxChunkSize||5e5,this.maxEventsPerChunk=S.maxEventsPerChunk||500,this.minFlushInterval=S.minFlushInterval||1e4,this.firstChunkFlushed=!1,this.firstChunkFlushTimeout=2e3,this.recordingStartTime=null,this._firstChunkTimer=null,this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.chunkTimer=null,this.sessionId=null,this.sdkContext=null,this.onChunkCreated=S.onChunkCreated||(()=>{}),this.onServerUpload=S.onServerUpload||null,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setSessionInfo(S){this.sessionId=S.sessionId,this.sdkContext=S.sdkContext}startRecording(){this.recordingStartTime=Date.now(),this.firstChunkFlushed=!1,this._firstChunkTimer&&clearTimeout(this._firstChunkTimer),this._firstChunkTimer=setTimeout(()=>{!this.firstChunkFlushed&&this.currentChunk.length>0&&(this.logger.info?.("[ChunkManager] Force-flushing first chunk (2s timeout)"),this.flush({force:!0})),this._firstChunkTimer=null},this.firstChunkFlushTimeout)}startTimer(){this.chunkTimer||(this.chunkTimer=setTimeout(()=>{this.flush(),this.startTimer()},this.chunkDuration))}stopTimer(){this.chunkTimer&&(clearTimeout(this.chunkTimer),this.chunkTimer=null)}resetTimer(){this.stopTimer(),this.startTimer()}addEvent(S){return this.currentChunk.push(S),!0}getCurrentChunkLength(){return this.currentChunk.length}checkFlush(){if(0===this.currentChunk.length)return!1;if(!this.firstChunkFlushed&&this.currentChunk.length>0){const S=this.currentChunk.some(S=>2===S.type);if(S)return this.logger.info?.("[ChunkManager] FullSnapshot detected - immediate flush"),this.flush({force:!0}),this.resetTimer(),!0}const S=this.estimateSize(this.currentChunk)>=this.maxChunkSize,b=this.currentChunk.length>=this.maxEventsPerChunk,I=Date.now()-this._lastFlushTime;return(S||!!(b&&I>=this.minFlushInterval))&&(this.flush(),this.resetTimer(),!0)}flush(S={}){if(this._isFlushing)return null;this._isFlushing=!0;try{if(0===this.currentChunk.length)return null;!this.firstChunkFlushed&&(this.firstChunkFlushed=!0,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.logger.info?.("[ChunkManager] First chunk flushed"));const S=this.currentChunk;this.currentChunk=[];const b=this.chunkCounter;this.chunkCounter++,this.sessionId||(this.sessionId=generateSessionId(),this.logger.warn(`[ChunkManager] sessionId was null at flush time for chunk ${b}, generated fallback: ${this.sessionId}`));const I=[],x=[],R=[],A=[];for(const b of S){const S=extractNetworkRef(b,this.sessionId);if(S){I.push(S);const x=extractNetworkFull(b,this.sessionId);x&&R.push(x),A.push(stripNetworkPayload(b));const _=networkEnvelopeEvent(b);_&&A.push(_);continue}const _=extractConsoleRef(b,this.sessionId);_?(x.push(_),A.push(b)):A.push(b)}const _={projectId:this.sdkContext?.projectId,environment:this.sdkContext?.environment,userId:this.sdkContext?.userId};0===b&&(_.device=collectDeviceMetadata());let D=createChunk({sequence:b,sessionId:this.sessionId,events:A,networkRefs:I,consoleRefs:x,networkFullData:R,metadata:_,isFirstChunk:0===b,isLastChunk:!1});return this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&(D=this.sdkContext.enrichChunk(D)),this.allChunks.push(D),this._lastFlushTime=Date.now(),this.onChunkCreated(D,b),this.onServerUpload&&this.sendToServer(D),D}finally{this._isFlushing=!1}}estimateSize(S){if(!S||0===S.length)return 0;try{if(S.length<=50)return JSON.stringify(S).length;const b=Math.min(50,Math.max(10,Math.floor(.1*S.length))),I=Math.floor(S.length/b);let x=0;for(let b=0;b<S.length;b+=I)x+=JSON.stringify(S[b]).length;const R=x/Math.ceil(S.length/I);return Math.ceil(R*S.length)+2*S.length}catch(S){return 0}}async sendToServer(S){if(this.onServerUpload)try{await this.onServerUpload(S),this.logger.info?.(`Chunk ${S.sequence} sent successfully`)}catch(S){this.logger.warn?.("Failed to send chunk to server:",S)}}getChunks(){return[...this.allChunks]}getChunkCounter(){return this.chunkCounter}setChunkCounter(S){this.chunkCounter=S}getCurrentChunk(){return[...this.currentChunk]}exportChunkedData(S="json"){const b={sessionId:this.sessionId,chunks:this.allChunks,totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length};return"json"===S?JSON.stringify(b,null,2):b}getStats(){const S=this.allChunks.reduce((S,b)=>S+(b.sizeBytes||0),0),b=this.estimateSize(this.currentChunk);return{totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length,currentChunkSize:b,totalSize:S,chunkCounter:this.chunkCounter,avgChunkSize:this.allChunks.length>0?Math.round(S/this.allChunks.length):0}}updateConfig(S){void 0!==S.chunkDuration&&(this.chunkDuration=S.chunkDuration),void 0!==S.maxChunkSize&&(this.maxChunkSize=S.maxChunkSize),void 0!==S.maxEventsPerChunk&&(this.maxEventsPerChunk=S.maxEventsPerChunk),void 0!==S.minFlushInterval&&(this.minFlushInterval=S.minFlushInterval)}reset(){this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.stopTimer(),this.firstChunkFlushed=!1,this.recordingStartTime=null,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null)}destroy(){this.stopTimer(),this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.currentChunk=[],this.allChunks=[],this.onChunkCreated=null,this.onServerUpload=null,this.onSessionEnd=null,this.sdkContext=null,this.logger=null}}class RecorderLogger{constructor(S,b=!1){const I=S.replace(/^\[|\]$/g,"");this.serviceLogger=createLogger(I),this.prefix=`[TraceScout][${S}]`,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.debug&&this.serviceLogger.log(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class Recorder{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[Recorder] No SDKContext provided - running in v1.x compatibility mode");const b=S.preset?Recorder.getPresetConfig(S.preset):{};if(this.config={emit:()=>{},checkoutEveryNms:6e4,checkoutEveryNth:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,debug:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},chunkDuration:3e4,maxChunkSize:5e5,onChunk:null,enableSampling:!1,enableDeduplication:!1,mousemoveSampling:1,scrollSampling:1,mutationSampling:1,inactivityTimeout:3e5,maxInactivityDuration:18e5,maxSessionDuration:36e5,enableInactivityDetection:!0,maxChunksInMemory:S.maxChunksInMemory||10,maxEventsPerSession:S.maxEventsPerSession||5e4,maxSessionBytes:S.maxSessionBytes||52428800,checkpointInterval:S.checkpointInterval||6e4,...b,...S},this.sdkContext&&"function"==typeof this.sdkContext.setDomPrivacy)try{this.sdkContext.setDomPrivacy(function deriveDomPrivacy(S){if(!S||"object"!=typeof S)return"disabled";if(!0===S.maskAllInputs)return"confirmed";const b="string"==typeof S.maskTextClass&&S.maskTextClass.length>0,I="string"==typeof S.blockClass&&S.blockClass.length>0;return b||I?"partial":"disabled"}(this.config))}catch{}this.events=[],this.isRecording=!1,this.stopFn=null,this.metadata={},this.sessionId=null,this.recordingStartTime=null,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.statusTimer=null,this.statusInterval=1e4,this.aggregationTimer=null,this.aggregationInterval=3e4,this.lastAggregationThresholdSec=0,this._uploadQueue=null,this.logger=new RecorderLogger("Recorder",this.config.debug),this._initializeModules()}_initializeModules(){this.inactivityManager=new InactivityManager({inactivityTimeout:this.config.inactivityTimeout,maxInactivityDuration:this.config.maxInactivityDuration,maxSessionDuration:this.config.maxSessionDuration,enableInactivityDetection:this.config.enableInactivityDetection,logger:this.logger,onPause:S=>this._onInactivityPause(S),onResume:S=>this._onInactivityResume(S),onSessionEnd:S=>this._onInactivitySessionEnd(S),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.pageLifecycleManager=new PageLifecycleManager({logger:this.logger,getIsRecording:()=>this.isRecording,getCurrentChunkLength:()=>this.chunkManager.getCurrentChunkLength(),getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),onFlush:()=>this.chunkManager.flush(),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b),onSendBeacon:(S,b)=>this._sendChunkWithBeacon(S,b)}),this.checkpointManager=new CheckpointManager({checkpointInterval:this.config.checkpointInterval,logger:this.logger,getRRWeb:()=>getRRWeb(),getIsRecording:()=>this.isRecording,getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),getEventCount:()=>this.events.length,onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.memoryManager=new RecorderMemoryManager({maxChunksInMemory:this.config.maxChunksInMemory,maxEventsPerSession:this.config.maxEventsPerSession,maxSessionBytes:this.config.maxSessionBytes,logger:this.logger,onForceFlush:()=>this.chunkManager.flush(),onSessionEnd:S=>this.endSession(S)}),this.eventOptimizer=new EventOptimizer({enableSampling:this.config.enableSampling,enableDeduplication:this.config.enableDeduplication,mousemoveSampling:this.config.mousemoveSampling,scrollSampling:this.config.scrollSampling,mutationSampling:this.config.mutationSampling,logger:this.logger}),this.chunkManager=new ChunkManager({chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize,logger:this.logger,onChunkCreated:(S,b)=>this._onChunkCreated(S,b),onServerUpload:this.config.serverUrl?S=>this.sendChunkToServer(S):null})}async start(S={}){if(this.isRecording)return this.logger.warn("Recording already in progress"),this.stopFn;this.logger.info("Starting session recording...");const b=this._getSessionResumeInfo();b.isResumed&&(this.logger.info(`[V3] Resuming session ${b.sessionId}, continuing from chunk ${b.lastChunkSequence}`),this.chunkManager.setChunkCounter(b.lastChunkSequence+1));try{const b=await loadRRWeb();this.sdkContext&&this.sdkContext.sessionId?this.sessionId=this.sdkContext.sessionId:this.sessionId=this.generateSessionId(),this.chunkManager.setSessionInfo({sessionId:this.sessionId,sdkContext:this.sdkContext});let I=0,x=Date.now();const R={...this.config,...S,emit:b=>{if(I++,this.config.debug&&I%50==0){const S=Date.now()-x;this.logger.log(`${I} events captured (${S}ms since last log)`),x=Date.now()}const R={...b,tracescoutVersion:"1.0.0",sessionId:this.getSessionId()},A=this.chunkManager.estimateSize([R]),_=2===R.type||4===R.type;if(A>1e6&&!_)return void(this.config.debug&&this.logger.warn(`Skipping extremely large event: ${A} bytes, type: ${R.type}`));if(!this.onEvent(R))return;this.chunkManager.addEvent(R),this.events.push(R),this.chunkManager.checkFlush();(S.emit||this.config.emit)(R)}};if(this.stopFn=b.record(R),this.isRecording=!0,this.recordingStartTime=Date.now(),this.sessionStartTime=Date.now(),this._rrweb=b,this.chunkManager&&(this.chunkManager.startRecording(),this.logger.info("[Recorder] First-chunk flush timer started (2s)")),this.memoryManager.setDataReferences({allChunks:this.chunkManager.allChunks,events:this.events,eventDedupeCache:this.eventOptimizer.getDedupeCache(),eventStats:this.eventOptimizer.getEventStats()}),this.config.enableStreamingStorage)try{const{ChunkedCompressedStorage:S}=await Promise.resolve().then(function(){return du});this.__streamStore=S,this.__streamStore.initSession(this.sessionId),this.logger.info("Streaming storage initialized")}catch(S){this.logger.warn("Failed to init streaming storage:",S)}return this.chunkManager.startTimer(),this.checkpointManager.start(),this.memoryManager.start(),this.inactivityManager.start(),this.pageLifecycleManager.setup(),this._startStatusTimer(),this.sessionEnded=!1,this.sessionEndReason=null,this._uploadQueue?.didIndexedDBFail?.()&&(this.logger.warn("[Recorder] IndexedDB failed - scheduling backup snapshot"),this._scheduleBackupSnapshot()),this._uploadQueue?.on&&this._uploadQueue.on("firstSnapshotUploadFailed",()=>{this.logger.warn("[Recorder] First snapshot upload failed 3x - taking immediate backup"),this._takeBackupSnapshot()}),this._setupSPANavigationDetection(),this.logger.info("🔴 Recording started",{sessionId:this.sessionId,startTime:this.recordingStartTime,chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize}),this.stopFn}catch(S){throw this.logger.error("Failed to load or initialize rrweb:",S),S}}stop(){if(!this.isRecording)return this.logger.warn("No recording in progress"),this.events;this.chunkManager.stopTimer(),this.checkpointManager.stop(),this.memoryManager.stop(),this.inactivityManager.stop(),this.pageLifecycleManager.remove(),this._stopStatusTimer(),this._cleanupSPANavigationDetection(),this._backupSnapshotTimer&&(clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=null),this.chunkManager.flush(),this.stopFn&&(this.stopFn(),this.stopFn=null),this._rrweb=null,this.isRecording=!1;const S=Date.now()-this.recordingStartTime;return this.logger.info("Recording stopped",{sessionId:this.sessionId,duration:S,eventCount:this.events.length,totalChunks:this.chunkManager.getChunks().length}),this.events}onEvent(S){return this.eventOptimizer.updateStats(S),this.inactivityManager.trackActivity(S),!!this.inactivityManager.shouldRecordEvent(S)&&(5===S.type||!!this.eventOptimizer.shouldRecordEvent(S)&&(this.eventOptimizer.adaptToEventRate(),!0))}addCustomEvent(S,b){if(!this.isRecording)return!1;if(!S||"string"!=typeof S)return!1;try{let I=b||{};this.sdkContext&&(I={...b,sessionId:this.sdkContext.sessionId,projectId:this.sdkContext.projectId,environment:this.sdkContext.environment,userId:this.sdkContext.userId});const x={type:5,data:{tag:S,payload:I},timestamp:Date.now(),tracescoutVersion:this.sdkContext?"2.0.0":"1.0.0",sessionId:this.getSessionId()};return!!this.onEvent(x)&&(this.chunkManager.addEvent(x),this.events.push(x),this.chunkManager.checkFlush(),!0)}catch(S){return this.logger.error("Failed to add custom event:",S),!1}}_setupSPANavigationDetection(){if("undefined"==typeof window||"undefined"==typeof history)return;this._lastKnownUrl=window.location.href,this._originalPushState=history.pushState,this._originalReplaceState=history.replaceState;const S=this;history.pushState=function(...b){const I=S._originalPushState.apply(this,b);return S._onSPANavigation("pushState"),I},history.replaceState=function(...b){const I=S._originalReplaceState.apply(this,b);return S._onSPANavigation("replaceState"),I},this._popstateHandler=()=>{S._onSPANavigation("popstate")},window.addEventListener("popstate",this._popstateHandler),this._hashchangeHandler=()=>{S._onSPANavigation("hashchange")},window.addEventListener("hashchange",this._hashchangeHandler),this.logger.info("SPA navigation detection enabled")}_onSPANavigation(S){const b=window.location.href;if(b===this._lastKnownUrl)return;const I=this._lastKnownUrl;if(this._lastKnownUrl=b,this.logger.info(`SPA navigation detected (${S}): ${I} → ${b}`),this.addCustomEvent("page_navigation",{url:b,previousUrl:I,title:document.title,navigationType:S,timestamp:Date.now()}),"function"==typeof this.config?.onSpaNavigation)try{this.config.onSpaNavigation(S,I,b)}catch(S){this.logger.warn?.("[Recorder] onSpaNavigation callback threw:",S)}setTimeout(()=>{this._takeFullSnapshotForNavigation(b)},100)}_takeFullSnapshotForNavigation(S){if(this._rrweb&&this.isRecording)try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info(`Taking full snapshot for SPA navigation to: ${S}`),this._rrweb.record.takeFullSnapshot()):this.logger.warn("rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("Failed to take full snapshot for SPA navigation:",S)}}_scheduleBackupSnapshot(){this._backupSnapshotTimer&&clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=setTimeout(()=>{if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] Chunk 0 already acked, skipping backup snapshot");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (2s safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}},2e3)}_takeBackupSnapshot(){if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] First snapshot ACKed - skipping backup");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}}_cleanupSPANavigationDetection(){"undefined"!=typeof window&&"undefined"!=typeof history&&(this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null),this._popstateHandler&&(window.removeEventListener("popstate",this._popstateHandler),this._popstateHandler=null),this._hashchangeHandler&&(window.removeEventListener("hashchange",this._hashchangeHandler),this._hashchangeHandler=null),this._lastKnownUrl=null,this.logger.info("SPA navigation detection disabled"))}_onInactivityPause(S){this.logger.info("[Inactivity] Recording paused")}_onInactivityResume(S){this.logger.info("[Inactivity] Recording resumed")}_onInactivitySessionEnd(S){this.endSession(S.reason)}_onChunkCreated(S,b){const I=this.memoryManager.trackBytes(S.sizeBytes||0);if(this.memoryManager.trimChunksArray(),this.memoryManager.trimEventsArray(1e3),I)if(this.memoryManager.checkEventLimit(this.events.length)){if(this._updateSessionChunkSequence(b),this.__streamStore)try{this.__streamStore.saveChunk(this.sessionId,b,S.events),this.__streamStore.updateSessionInfo(this.sessionId,b+1,this.events.length)}catch(S){}this.config.onChunk&&this.config.onChunk(S)}else this.endSession("max_events");else this.endSession("max_size")}endSession(S="manual"){this.logger.info(`[Session] Ending session: ${this.sessionId} (reason: ${S})`),this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.config.onSessionEnd&&this.config.onSessionEnd({sessionId:this.sessionId,reason:S,duration:Date.now()-this.sessionStartTime,totalEvents:this.events.length,totalPausedTime:this.inactivityManager.totalPausedTime})}_getSessionResumeInfo(){return this.sdkContext?.sessionManager?this.sdkContext.sessionManager.getResumeInfo():this.config.sessionManager?this.config.sessionManager.getResumeInfo():{isResumed:!1,sessionId:null,lastChunkSequence:0}}_updateSessionChunkSequence(S){this.sdkContext?.sessionManager?this.sdkContext.sessionManager.updateLastChunkSequence(S):this.config.sessionManager&&this.config.sessionManager.updateLastChunkSequence(S)}setUploadQueue(S){this._uploadQueue=S}_sendChunkWithBeacon(S,b){if(this._uploadQueue?.sendFinalChunkWithBeacon){if(this._uploadQueue.sendFinalChunkWithBeacon(S,b))return void this.logger.info(`[P0] Chunk ${S.sequence} sent via UploadQueue.sendFinalChunkWithBeacon`)}const I=this.sdkContext?.getChunkEndpoint?.()||(this.config.serverUrl?`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`:null);if(!I)return void(this.config.onChunk&&this.config.onChunk(S));const x={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],metadata:{...S.metadata,sentVia:"sendBeacon",closeTrigger:b},sizeBytes:S.sizeBytes},R=JSON.stringify(x);if("undefined"!=typeof navigator&&navigator.sendBeacon)try{const b=new Blob([R],{type:"application/json"});navigator.sendBeacon(I,b)?this.logger.info(`[P0] Chunk ${S.sequence} sent via sendBeacon`):this.config.onChunk&&this.config.onChunk(S)}catch(b){this.config.onChunk&&this.config.onChunk(S)}else this.config.onChunk&&this.config.onChunk(S)}async sendChunkToServer(S){try{const b={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],networkFullData:S._networkFullData||[],metadata:S.metadata,sizeBytes:S.sizeBytes},I=this.sdkContext?.getChunkEndpoint?.()||`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`,x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!x.ok)throw new Error(`Server responded with ${x.status}`);return await x.json()}catch(S){throw this.logger.warn("Failed to send chunk to server:",S),S}}_startStatusTimer(){this.statusTimer&&clearInterval(this.statusTimer),setTimeout(()=>this.logStatus(),1e3),this.statusTimer=setInterval(()=>{this.logStatus()},this.statusInterval),this.config.debug&&(this.aggregationTimer&&clearInterval(this.aggregationTimer),this.aggregationTimer=setInterval(()=>{this._maybeLogAggregationExport()},this.aggregationInterval))}_stopStatusTimer(){this.statusTimer&&(clearInterval(this.statusTimer),this.statusTimer=null),this.aggregationTimer&&(clearInterval(this.aggregationTimer),this.aggregationTimer=null),this.lastAggregationThresholdSec=0}logStatus(){if(!this.isRecording)return;const S=this.chunkManager.getStats(),b=Date.now()-this.recordingStartTime,I=Math.floor(b/1e3),x=Math.floor(I/60),R=I%60,fmtSize=S=>S>=1048576?`${(S/1048576).toFixed(1)}MB`:`${Math.round(S/1024)}KB`;this.logger.info(`📊 Session Status [${x}m ${R}s]:`,{totalEvents:this.events.length,totalSize:fmtSize(S.totalSize),currentChunk:`${S.currentChunkEvents} events (${fmtSize(S.currentChunkSize)})`,completedChunks:S.totalChunks})}_maybeLogAggregationExport(){if(!this.isRecording||!this.recordingStartTime)return;const S=Date.now()-this.recordingStartTime,b=Math.floor(S/this.aggregationInterval)*(this.aggregationInterval/1e3);if(b>0&&b!==this.lastAggregationThresholdSec){this.lastAggregationThresholdSec=b;try{const S=this.buildReplayExport();this.logger.info(`🧩 Session export (${b}s):`,S)}catch(S){this.logger.warn("Failed to export session data:",S)}}}getStatus(){return{isRecording:this.isRecording,eventCount:this.events.length,duration:this.isRecording?Date.now()-this.recordingStartTime:0}}getSessionId(){return this.sessionId||(this.sessionId=generateSessionId()),this.sessionId}getEvents(){return[...this.events]}getChunks(){return this.chunkManager.getChunks()}getMetadata(){return{...this.metadata,sessionId:this.sessionId,startTime:this.recordingStartTime,isRecording:this.isRecording,eventCount:this.events.length}}getConfig(){return{...this.config}}getMemoryStats(){return this.memoryManager.getStats()}getOptimizationStats(){return this.eventOptimizer.getOptimizationStats()}setMetadata(S){this.metadata={...this.metadata,...S}}updateConfig(S){this.config={...this.config,...S},void 0!==S.debug&&this.logger.updateDebugMode(S.debug),this.inactivityManager.updateConfig(S),this.eventOptimizer.updateConfig(S),this.chunkManager.updateConfig(S),this.memoryManager.updateConfig(S),this.checkpointManager.updateConfig(S)}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode(S)}clear(){this.events=[],this.logger.info("Events cleared")}pause(){this.isRecording?this.stopFn&&(this.stopFn(),this.stopFn=null,this.isRecording=!1,this.logger.info("Recording paused")):this.logger.warn("No recording to pause")}resume(){this.isRecording?this.logger.warn("Recording already active"):(this.start(),this.logger.info("Recording resumed"))}takeCheckpoint(){this.checkpointManager.takeManualCheckpoint()}flushChunk(){return this.chunkManager.flush()}exportEvents(){return JSON.stringify({sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:this.events,metadata:this.metadata},null,2)}exportChunkedData(S="json"){const b=this.chunkManager.getChunks(),I={sessionId:this.getSessionId(),startTime:this.recordingStartTime,chunks:b,totalChunks:b.length,totalEvents:this.events.length,metadata:this.metadata};return"json"===S?JSON.stringify(I,null,2):I}buildReplayExport(){const S=this.chunkManager.getChunks().map(S=>{if(S?.compressed)try{return this.decompressChunk(S)}catch(b){return S}return S}),b=[];for(const I of S)I?.events&&Array.isArray(I.events)&&b.push(...I.events);return{sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:b,chunks:S,totalChunks:S.length,totalEvents:b.length,metadata:this.metadata}}compressChunkSync(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}async compressChunk(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}decompressChunk(S){if(!S.compressed)return S;try{const b=S.compressedData||S.data,I=new Uint8Array(b);if("fflate"===S.compressionType){const S=strFromU8(unzlibSync(I));return JSON.parse(S)}return S}catch(b){return this.logger.error("Failed to decompress chunk:",b),S}}generateSessionId(){return generateSessionId()}getEventTypeName(S){return this.eventOptimizer.getEventTypeName(S)}analyzeLargestEvents(S=5){if(!this.events||0===this.events.length)return void this.logger.info("No events to analyze");const b=this.events.map((S,b)=>({index:b,type:S.type,size:this.chunkManager.estimateSize([S]),timestamp:S.timestamp}));b.sort((S,b)=>b.size-S.size),this.logger.info(`🔍 Top ${S} Largest Events:`),b.slice(0,S).forEach((S,b)=>{this.logger.info(`${b+1}. Event #${S.index}: ${S.type} - ${Math.round(S.size/1024)}KB`)})}logOptimizationReport(){this.eventOptimizer.logOptimizationReport()}static getPresetConfig(S){return{minimal:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:18e4,checkoutEveryNth:300,chunkDuration:9e4,maxChunkSize:2e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.3,scrollSampling:.5,debug:!1},production:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:45e3,maxChunkSize:3e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.7,scrollSampling:.8,debug:!1},standard:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:6e4,maxChunkSize:35e4,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.5,scrollSampling:.7,debug:!1},detailed:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0},checkoutEveryNms:6e4,checkoutEveryNth:100,chunkDuration:3e4,maxChunkSize:5e5,enableSampling:!1,enableDeduplication:!1,debug:!1},full:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!0,collectFonts:!0,slimDOMOptions:!1,checkoutEveryNms:3e4,checkoutEveryNth:50,chunkDuration:15e3,maxChunkSize:1e6,enableSampling:!1,enableDeduplication:!1,debug:!1}}[S]||{}}}const uu={MINIMAL:"minimal",STANDARD:"standard",DETAILED:"detailed",FULL:"full"},hu="pending_chunks";class IndexedDBQueue{constructor(S={}){if(this.db=null,this.isSupported="undefined"!=typeof indexedDB,this.initFailed=!1,this.maxItems=S.maxItems||100,this.onError=S.onError||(()=>{}),"undefined"!=typeof window&&!0===window.__TRACESCOUT_FORCE_DISABLE_INDEXEDDB)return console.warn("[IndexedDBQueue] Disabled via FORCE_DISABLE_INDEXEDDB flag"),this.isSupported=!1,void(this.initFailed=!0);this.isSupported&&this._initDB()}async _initDB(){if(this.isSupported)return new Promise((S,b)=>{const I=indexedDB.open("tracescout_queue",1);I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to open database:",b.target.error),this.isSupported=!1,this.initFailed=!0,S(null)},I.onsuccess=b=>{this.db=b.target.result,S(this.db)},I.onupgradeneeded=S=>{const b=S.target.result;if(!b.objectStoreNames.contains(hu)){const S=b.createObjectStore(hu,{keyPath:"id"});S.createIndex("sessionId","sessionId",{unique:!1}),S.createIndex("createdAt","createdAt",{unique:!1}),S.createIndex("priority","priority",{unique:!1})}}})}async _ensureDB(){if(!this.isSupported)return!1;if(!this.db)try{await this._initDB()}catch(S){return!1}return!!this.db}async enqueue(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([hu],"readwrite"),x=I.objectStore(hu),R={id:S.id||`queue_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:S.chunk?.sessionId||S.sessionId,chunk:S.chunk,priority:S.priority||"normal",attempts:S.attempts||0,createdAt:S.createdAt||Date.now(),lastAttempt:S.lastAttempt||null,error:S.error||null},A=x.add(R);A.onsuccess=()=>{b(!0)},A.onerror=S=>{if("ConstraintError"===S.target.error?.name){const S=x.put(R);S.onsuccess=()=>b(!0),S.onerror=()=>b(!1)}else console.warn("[IndexedDBQueue] Failed to enqueue:",S.target.error),b(!1)},I.oncomplete=async()=>{await this._enforceLimit()}}catch(S){console.warn("[IndexedDBQueue] Enqueue error:",S),b(!1)}})}async getAll(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([hu],"readonly"),I=b.objectStore(hu).getAll();I.onsuccess=b=>{const I=b.target.result||[],x={high:3,normal:2,low:1};I.sort((S,b)=>{const I=x[S.priority]||2,R=x[b.priority]||2;return I!==R?R-I:S.createdAt-b.createdAt}),S(I)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to get items:",b.target.error),S([])}}catch(b){console.warn("[IndexedDBQueue] GetAll error:",b),S([])}}):[]}async getBySession(S){return await this._ensureDB()?new Promise(b=>{try{const I=this.db.transaction([hu],"readonly").objectStore(hu),x=I.index("sessionId").getAll(S);x.onsuccess=S=>{b(S.target.result||[])},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to get by session:",S.target.error),b([])}}catch(S){console.warn("[IndexedDBQueue] GetBySession error:",S),b([])}}):[]}async remove(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([hu],"readwrite"),x=I.objectStore(hu).delete(S);x.onsuccess=()=>{b(!0)},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to remove:",S.target.error),b(!1)}}catch(S){console.warn("[IndexedDBQueue] Remove error:",S),b(!1)}})}async removeMany(S){if(!await this._ensureDB()||!S||0===S.length)return 0;let b=0;for(const I of S)await this.remove(I)&&b++;return b}async update(S,b){return!!await this._ensureDB()&&new Promise(I=>{try{const x=this.db.transaction([hu],"readwrite").objectStore(hu),R=x.get(S);R.onsuccess=S=>{const R=S.target.result;if(!R)return void I(!1);const A={...R,...b},_=x.put(A);_.onsuccess=()=>I(!0),_.onerror=()=>I(!1)},R.onerror=()=>I(!1)}catch(S){console.warn("[IndexedDBQueue] Update error:",S),I(!1)}})}async clear(){return!!await this._ensureDB()&&new Promise(S=>{try{const b=this.db.transaction([hu],"readwrite"),I=b.objectStore(hu).clear();I.onsuccess=()=>{S(!0)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to clear:",b.target.error),S(!1)}}catch(b){console.warn("[IndexedDBQueue] Clear error:",b),S(!1)}})}async count(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([hu],"readonly"),I=b.objectStore(hu).count();I.onsuccess=b=>{S(b.target.result)},I.onerror=()=>S(0)}catch(b){S(0)}}):0}async _enforceLimit(){const S=await this.count();if(S<=this.maxItems)return;const b=await this.getAll(),I=S-this.maxItems,x=[...b].sort((S,b)=>{const I={high:3,normal:2,low:1},x=I[S.priority]||2,R=I[b.priority]||2;return x!==R?x-R:S.createdAt-b.createdAt}),R=x.slice(0,I).map(S=>S.id);await this.removeMany(R),console.log(`[IndexedDBQueue] Removed ${R.length} old items to enforce limit of ${this.maxItems}`)}isAvailable(){return this.isSupported&&null!==this.db}didInitFail(){return!0===this.initFailed}close(){this.db&&(this.db.close(),this.db=null)}}class CircuitBreaker{constructor(S={}){this.threshold=S.threshold||5,this.resetTimeout=S.resetTimeout||6e4,this.halfOpenMaxAttempts=S.halfOpenMaxAttempts||1,this.failures=0,this.lastFailure=null,this.state="closed",this.halfOpenAttempts=0,this.logger=S.logger||console}canMakeRequest(){if("closed"===this.state)return!0;if("open"===this.state){return Date.now()-this.lastFailure>=this.resetTimeout&&(this.state="half-open",this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Transitioning to half-open state"),!0)}return"half-open"!==this.state||this.halfOpenAttempts<this.halfOpenMaxAttempts}recordSuccess(){"half-open"===this.state?(this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Circuit closed after successful request")):"closed"===this.state&&(this.failures=0)}recordFailure(){this.failures++,this.lastFailure=Date.now(),"half-open"===this.state?(this.state="open",this.halfOpenAttempts=0,this.logger.warn?.("[CircuitBreaker] Circuit reopened after failed test request")):"closed"===this.state&&this.failures>=this.threshold&&(this.state="open",this.logger.error?.(`[CircuitBreaker] Circuit OPENED after ${this.failures} consecutive failures`),this.logger.error?.(`[CircuitBreaker] Will retry after ${this.resetTimeout/1e3}s cooldown`))}recordHalfOpenAttempt(){"half-open"===this.state&&this.halfOpenAttempts++}getStatus(){return{state:this.state,failures:this.failures,lastFailure:this.lastFailure,threshold:this.threshold,resetTimeout:this.resetTimeout,timeUntilReset:"open"===this.state&&this.lastFailure?Math.max(0,this.resetTimeout-(Date.now()-this.lastFailure)):null,halfOpenAttempts:this.halfOpenAttempts,halfOpenMaxAttempts:this.halfOpenMaxAttempts}}reset(){this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Manually reset to closed state")}forceOpen(){this.state="open",this.lastFailure=Date.now(),this.logger.warn?.("[CircuitBreaker] Manually forced to open state")}updateConfig(S){void 0!==S.threshold&&(this.threshold=S.threshold),void 0!==S.resetTimeout&&(this.resetTimeout=S.resetTimeout),void 0!==S.halfOpenMaxAttempts&&(this.halfOpenMaxAttempts=S.halfOpenMaxAttempts)}destroy(){this.logger=null}}class NetworkMonitor{constructor(S={}){this.checkInterval=S.checkInterval||3e4,this.isOnline="undefined"==typeof navigator||navigator.onLine,this.onStatusChange=S.onStatusChange||(()=>{}),this.logger=S.logger||console,this.checkTimer=null,this._boundOnline=null,this._boundOffline=null}start(){"undefined"!=typeof window&&(this._boundOnline=()=>this._handleStatusChange(!0),this._boundOffline=()=>this._handleStatusChange(!1),window.addEventListener("online",this._boundOnline),window.addEventListener("offline",this._boundOffline),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval),this.logger.log?.("[NetworkMonitor] Started monitoring"))}stop(){"undefined"!=typeof window&&(this._boundOnline&&window.removeEventListener("online",this._boundOnline),this._boundOffline&&window.removeEventListener("offline",this._boundOffline)),this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null),this._boundOnline=null,this._boundOffline=null,this.logger.log?.("[NetworkMonitor] Stopped monitoring")}_handleStatusChange(S){const b=this.isOnline;this.isOnline=S,b!==S&&(this.logger.log?.("[NetworkMonitor] Status changed: "+(S?"online":"offline")),this.onStatusChange(S,b))}checkStatus(){if("undefined"==typeof navigator)return;const S=navigator.onLine;this.isOnline!==S&&this._handleStatusChange(S)}getStatus(){return this.isOnline}updateConfig(S){void 0!==S.checkInterval&&(this.checkInterval=S.checkInterval,this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval)))}destroy(){this.stop(),this.onStatusChange=null,this.logger=null}}class BeaconSender{constructor(S={}){this.endpoint=S.endpoint||"/api/sessions/upload",this.maxBeaconSize=S.maxBeaconSize||6e4,this.sdkContext=S.sdkContext||null,this.logger=S.logger||console}setEndpoint(S){this.endpoint=S}setSdkContext(S){this.sdkContext=S}send(S,b="unknown"){if(!S||!S.events||0===S.events.length)return this.logger.log?.("[BeaconSender] No events to send"),!1;const I=this._buildPayload(S,b),x=JSON.stringify(I),R=x.length;return R>this.maxBeaconSize?(this.logger.warn?.(`[BeaconSender] Payload too large (${R} bytes), using keepalive fetch`),this._sendWithKeepaliveFetch(x,b)):this._sendWithBeacon(x,b,R)||this._sendWithKeepaliveFetch(x,b)}_buildPayload(S,b){return{chunks:[{id:`final_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunkId:S.chunkId||`chunk_${S.sequence}`,sessionId:S.sessionId,data:S,compressed:!1,originalSize:this._estimateSize(S),projectId:S.metadata?.projectId||this.sdkContext?.projectId,environment:S.metadata?.environment||this.sdkContext?.environment}],batchId:`beacon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:1,sentVia:"sendBeacon",closeTrigger:b}}_sendWithBeacon(S,b,I){if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;try{const x=new Blob([S],{type:"application/json"});return navigator.sendBeacon(this.endpoint,x)?(this.logger.log?.(`[BeaconSender] ✅ Sent via sendBeacon (${b}, ${I} bytes)`),!0):(this.logger.warn?.("[BeaconSender] sendBeacon returned false"),!1)}catch(S){return this.logger.warn?.(`[BeaconSender] sendBeacon failed: ${S.message}`),!1}}_sendWithKeepaliveFetch(S,b){if("undefined"==typeof fetch)return this.logger.warn?.("[BeaconSender] fetch not available"),!1;try{const I={"Content-Type":"application/json","X-SDK-Version":"2.0.0","X-Sent-Via":"keepalive","X-Close-Trigger":b};return this.sdkContext&&(I["X-Project-ID"]=this.sdkContext.projectId||""),fetch(this.endpoint,{method:"POST",headers:I,body:S,keepalive:!0}).catch(S=>{this.logger.warn?.("[BeaconSender] keepalive fetch error:",S)}),this.logger.log?.(`[BeaconSender] ✅ Sent via keepalive fetch (${b})`),!0}catch(S){return this.logger.warn?.(`[BeaconSender] keepalive fetch failed: ${S.message}`),!1}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}updateConfig(S){void 0!==S.endpoint&&(this.endpoint=S.endpoint),void 0!==S.maxBeaconSize&&(this.maxBeaconSize=S.maxBeaconSize)}destroy(){this.sdkContext=null,this.logger=null}}class QueueMemoryManager{constructor(S={}){this.maxQueueSize=S.maxQueueSize||100,this.maxFailedQueueSize=S.maxFailedQueueSize||50,this.maxOfflineItems=S.maxOfflineItems||100,this.logger=S.logger||console}enforceLimit(S,b=this.maxQueueSize){if(S.length<b)return null;const I=S.findIndex(S=>"low"===S.priority);if(I>=0){const x=S.splice(I,1)[0];return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped low-priority chunk:`,x.chunk?.chunkId),x}const x=S.shift();return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped oldest chunk:`,x?.chunk?.chunkId),x}enforceFailedLimit(S){if(S.length<this.maxFailedQueueSize)return null;const b=S.shift();return this.logger.warn?.(`[QueueMemory] Failed queue at max (${this.maxFailedQueueSize}) - dropped oldest:`,b?.chunk?.chunkId),b}enforceOfflineLimit(S){if(S.length<=this.maxOfflineItems)return null;const b=S.pop();return this.logger.warn?.("[QueueMemory] Offline queue full - dropped oldest:",b?.chunk?.chunkId),b}calculateQueueBytes(S){return S.reduce((S,b)=>S+(b.originalSize||0),0)}getStats(S,b){const I=this.calculateQueueBytes(S),x=this.calculateQueueBytes(b);return{uploadQueueSize:S.length,uploadQueueBytes:I,failedQueueSize:b.length,failedQueueBytes:x,totalQueuedItems:S.length+b.length,totalQueuedBytes:I+x,maxQueueSize:this.maxQueueSize,maxFailedQueueSize:this.maxFailedQueueSize,maxOfflineItems:this.maxOfflineItems,uploadQueuePercent:Math.round(S.length/this.maxQueueSize*100),failedQueuePercent:Math.round(b.length/this.maxFailedQueueSize*100)}}forceCleanup(S,b,I={}){const{keepUploads:x=10,keepFailed:R=5,clearAll:A=!1}=I,_={uploadQueue:S.length,failedQueue:b.length};let D=0,L=0;A?(D=S.length,L=b.length,S.length=0,b.length=0):(S.length>x&&(D=S.length-x,S.splice(0,D)),b.length>R&&(L=b.length-R,b.splice(0,L)));const B={uploadQueue:S.length,failedQueue:b.length};return this.logger.log?.(`[QueueMemory] Force cleanup: removed ${D} uploads, ${L} failed items`),{before:_,after:B,removed:{uploadQueue:D,failedQueue:L}}}needsCleanup(S,b){const I=S.length/this.maxQueueSize,x=b.length/this.maxFailedQueueSize;return I>=.8||x>=.8}updateConfig(S){void 0!==S.maxQueueSize&&(this.maxQueueSize=S.maxQueueSize),void 0!==S.maxFailedQueueSize&&(this.maxFailedQueueSize=S.maxFailedQueueSize),void 0!==S.maxOfflineItems&&(this.maxOfflineItems=S.maxOfflineItems)}destroy(){this.logger=null}}class UploadQueue{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[UploadQueue] No SDKContext provided - running in v1.x compatibility mode");const b=this._generateEndpoint(S);this.config={endpoint:S.endpoint||b,batchSize:S.batchSize||5,maxRetries:S.maxRetries||3,retryDelay:S.retryDelay||1e3,maxRetryDelay:S.maxRetryDelay||3e4,uploadTimeout:S.uploadTimeout||3e4,enableOfflineQueue:!1!==S.enableOfflineQueue,maxOfflineItems:S.maxOfflineItems||100,networkCheckInterval:S.networkCheckInterval||3e4,enableCompression:!1!==S.enableCompression,compressionThreshold:S.compressionThreshold||1024,onUploadSuccess:S.onUploadSuccess||(()=>{}),onUploadError:S.onUploadError||(()=>{}),onNetworkChange:S.onNetworkChange||(()=>{}),onQueueEmpty:S.onQueueEmpty||(()=>{}),headers:S.headers||{},authToken:S.authToken||null,...S},this.uploadQueue=[],this.failedQueue=[],this.isUploading=!1,this._uploadLock=null,this.isQuotaExceeded=!1,this.uploadStats={totalUploaded:0,totalFailed:0,totalBytes:0,averageUploadTime:0,lastUploadTime:null},this.firstSnapshotAcked=!1,this.firstSnapshotChunkId=null,this.firstSnapshotAttempts=0,this._backupSnapshotRequested=!1,this._listeners=new Map,this.retryTimer=null,this._processingTimer=null,this.logger=S.logger||createLogger("UploadQueue"),this._initializeModules(S),this._startProcessing(),this._loadPersistentQueue()}on(S,b){this._listeners.has(S)||this._listeners.set(S,[]),this._listeners.get(S).push(b)}emit(S,...b){const I=this._listeners.get(S);if(I)for(const x of I)try{x(...b)}catch(b){this.logger.warn(`[UploadQueue] Event listener error for '${S}':`,b)}}_generateEndpoint(S){if(this.sdkContext){return`${S.baseUrl||resolveApiBaseUrl(S)}/api/projects/${this.sdkContext.projectId}/sessions/${this.sdkContext.sessionId}/chunks`}return"/api/sessions/upload"}_initializeModules(S){this.circuitBreaker=new CircuitBreaker({threshold:S.circuitBreakerThreshold||5,resetTimeout:S.circuitBreakerResetTimeout||6e4,halfOpenMaxAttempts:S.halfOpenMaxAttempts||1,logger:this.logger}),this.networkMonitor=new NetworkMonitor({checkInterval:this.config.networkCheckInterval,logger:this.logger,onStatusChange:(S,b)=>this._handleNetworkChange(S,b)}),this.networkMonitor.start(),this.beaconSender=new BeaconSender({endpoint:this.config.endpoint,sdkContext:this.sdkContext,logger:this.logger}),this.memoryManager=new QueueMemoryManager({maxQueueSize:S.maxQueueSize||100,maxFailedQueueSize:S.maxFailedQueueSize||50,maxOfflineItems:S.maxOfflineItems||100,logger:this.logger}),this.persistentQueue=new IndexedDBQueue({maxItems:this.config.maxOfflineItems,onError:S=>{this.logger.warn("[UploadQueue] IndexedDB error:",S)}})}async _loadPersistentQueue(){try{const S=await this.persistentQueue.getAll();if(S.length>0){this.logger.log(`[UploadQueue] Recovered ${S.length} items from persistent storage`);for(const b of S)this.uploadQueue.push(b);this._sortQueue(),this.networkMonitor.getStatus()&&!this.isUploading&&this._processQueue()}}catch(S){this.logger.warn("[UploadQueue] Failed to load persistent queue:",S)}}enqueue(S,b="normal"){if(this.isQuotaExceeded)return this.logger.warn("[UploadQueue] Quota exceeded - dropping chunk:",S.chunkId),!1;this.memoryManager.enforceLimit(this.uploadQueue);const I=this._validateChunk(S);if(!I.valid)return this.logger.error(`[UploadQueue] Invalid chunk rejected: ${I.reason}`,S),!1;try{const I=0===S.sequence||!0===S.isFirstChunk;I&&!this.firstSnapshotAcked&&(b="high",this.logger.log("[UploadQueue] Chunk 0 prioritized for immediate upload (contains FullSnapshot)"));const x={id:`upload_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunk:S,priority:b,attempts:0,createdAt:Date.now(),lastAttempt:null,error:null,compressed:!1,originalSize:this._estimateSize(S),compressedSize:null,isFirstChunk:I};if(I&&!this.firstSnapshotChunkId&&(this.firstSnapshotChunkId=x.id),this.networkMonitor.getStatus())this.uploadQueue.push(x),this._sortQueue();else{if(!this.config.enableOfflineQueue)return this.logger.warn("Network offline and offline queue disabled, dropping chunk:",S.chunkId),!1;this._addToOfflineQueue(x)}return this.logger.log(`Chunk queued for upload: ${S.chunkId} (queue size: ${this.uploadQueue.length})`),I&&this.networkMonitor.getStatus()&&!this.isUploading?(this.logger.log("[UploadQueue] Triggering immediate upload for chunk 0"),this._processQueue()):this.isUploading||this._processQueue(),x.id}catch(S){return this.logger.error("Failed to enqueue chunk:",S),!1}}async _processQueue(){if(!this.circuitBreaker.canMakeRequest())return void this.logger.warn("[UploadQueue] Circuit breaker is open - request blocked");if(this.isUploading||!this.networkMonitor.getStatus()||0===this.uploadQueue.length)return;if(this._uploadLock)return;let S;this._uploadLock=new Promise(b=>{S=b}),this.isUploading=!0,this.logger.log(`Processing upload queue (${this.uploadQueue.length} items)`);try{for(;this.uploadQueue.length>0&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest();){const S=this._createBatch();if(0===S.length)break;if(await this._uploadBatch(S))this.circuitBreaker.recordSuccess();else if(this.circuitBreaker.recordFailure(),"open"===this.circuitBreaker.getStatus().state){this.logger.warn("[UploadQueue] Circuit breaker opened - pausing uploads");break}await this._delay(100)}0===this.uploadQueue.length&&0===this.failedQueue.length&&(this.config.onQueueEmpty(),this.logger.log("Upload queue is empty"))}catch(S){this.logger.error("Error processing upload queue:",S),this.circuitBreaker.recordFailure()}finally{this.isUploading=!1,this._uploadLock=null,S(),this.failedQueue.length>0&&this._scheduleRetry()}}_createBatch(){const S=[],b=Math.min(this.config.batchSize,this.uploadQueue.length);this._sortQueue();for(let I=0;I<b;I++)this.uploadQueue.length>0&&S.push(this.uploadQueue.shift());return S}async _uploadBatch(S){const b=Date.now();try{this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&S.forEach(S=>{S.chunk=this.sdkContext.enrichChunk(S.chunk)});const I={chunks:(await this._processBatch(S)).map(S=>({id:S.id,chunkId:S.chunk.chunkId,sessionId:S.chunk.sessionId,data:S.compressed?S.compressedData:S.chunk,compressed:S.compressed,originalSize:S.originalSize,compressedSize:S.compressedSize||S.originalSize,projectId:S.chunk.projectId,environment:S.chunk.environment})),batchId:`batch_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:S.length},x=await this._makeRequest(I);if(x.ok){const I=await x.json().catch(()=>({}));if(I.results){const S=I.results.find(S=>429===S.code||"QUOTA_EXCEEDED"===S.data?.code);if(S)return this._handleQuotaExceeded(S.data||S),!1}const R=Date.now()-b;this._updateStats(S,R,!0);for(const b of S)try{await this.persistentQueue.remove(b.id)}catch(S){}for(const b of S)(b.id===this.firstSnapshotChunkId||b.isFirstChunk)&&(this.firstSnapshotAcked=!0,this.logger.log("[UploadQueue] ✓ First snapshot (chunk 0) acknowledged by server - session is replayable"));return S.forEach(S=>{this.config.onUploadSuccess(S.chunk,I)}),this.logger.log(`Batch uploaded successfully: ${S.length} chunks in ${R}ms`),!0}if(429===x.status){const S=await x.json().catch(()=>({}));return this._handleQuotaExceeded(S),!1}throw new Error(`Upload failed with status: ${x.status}`)}catch(b){return this.logger.error("Batch upload failed:",b),S.forEach(S=>{S.attempts++,S.lastAttempt=Date.now(),S.error=b.message,(S.id===this.firstSnapshotChunkId||S.isFirstChunk)&&S.attempts>=3&&!this._backupSnapshotRequested&&(this._backupSnapshotRequested=!0,this.logger.warn("[UploadQueue] First snapshot failed 3+ times - requesting backup"),this.emit("firstSnapshotUploadFailed")),S.attempts<this.config.maxRetries?(this.memoryManager.enforceFailedLimit(this.failedQueue),this.failedQueue.push(S)):(this._updateStats([S],0,!1),this.config.onUploadError(S.chunk,b),this.logger.error(`Chunk permanently failed after ${S.attempts} attempts: ${S.chunk.chunkId}`))}),!1}}_handleQuotaExceeded(S){this.isQuotaExceeded=!0,this.uploadQueue=[],this.failedQueue=[],console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been stopped.","color: #ff4444;"),S.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions`,"color: #ff4444;"),this.config.onUploadError(null,{code:"QUOTA_EXCEEDED",message:S.message||"Session quota exceeded",usage:S.usage}),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:quota_exceeded",{detail:S}))}async _processBatch(S){const b=[];for(const I of S)try{if(this.config.enableCompression&&I.originalSize>this.config.compressionThreshold){const S=await this._compressChunk(I.chunk);S.compressed&&S.compressedSize<I.originalSize&&(I.compressed=!0,I.compressedData=S.data,I.compressedSize=S.compressedSize)}b.push(I)}catch(S){this.logger.warn("Failed to process chunk, using original:",S),b.push(I)}return b}async _makeRequest(S){const b=new AbortController,I=setTimeout(()=>b.abort(),this.config.uploadTimeout);try{const x={"Content-Type":"application/json",...this.config.headers};this.sdkContext&&(x["X-Project-ID"]=this.sdkContext.projectId,x["X-Environment"]=this.sdkContext.environment||"production",x["X-SDK-Version"]="2.0.0");const R=await fetch(this.config.endpoint,{method:"POST",headers:x,body:JSON.stringify(S),signal:b.signal});return clearTimeout(I),R}catch(S){throw clearTimeout(I),S}}async _compressChunk(S){if(!this.config.enableCompression)return this.logger.debug("[UploadQueue] Compression disabled via config"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"!=typeof window&&!0===window.__TRACESCOUT_DISABLE_COMPRESSION)return this.logger.debug("[UploadQueue] Compression disabled via __TRACESCOUT_DISABLE_COMPRESSION"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"==typeof window||"undefined"==typeof CompressionStream)return{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};try{const b=JSON.stringify(S),I=(new TextEncoder).encode(b).length,x=new Blob([b],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),R=await new Response(x).arrayBuffer(),A=new Uint8Array(R),_=this._uint8ArrayToBase64(A),D=(100*(1-A.length/I)).toFixed(0),L=JSON.stringify(Array.from(A)).length,B=_.length+2;return this.logger.debug(`[UploadQueue] Compressed chunk: original=${I}B, gzip=${A.length}B (${D}% saved), base64=${B}B vs array=${L}B`),{compressed:!0,data:_,originalSize:I,compressedSize:A.length}}catch(b){return this.logger.warn("[UploadQueue] Compression failed, using uncompressed:",b.message),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)}}}_uint8ArrayToBase64(S){if(S.length<32768){let b="";for(let I=0;I<S.length;I++)b+=String.fromCharCode(S[I]);return btoa(b)}let b="";for(let I=0;I<S.length;I+=32768){const x=S.subarray(I,Math.min(I+32768,S.length));for(let S=0;S<x.length;S++)b+=String.fromCharCode(x[S])}return btoa(b)}_handleNetworkChange(S,b){this.logger.log("Network status changed: "+(S?"online":"offline")),this.config.onNetworkChange(S,b),S&&!b&&(this._sortQueue(),this.isUploading||this._processQueue())}_sortQueue(){const S={high:3,normal:2,low:1};this.uploadQueue.sort((b,I)=>{const x=S[b.priority]||2,R=S[I.priority]||2;return x!==R?R-x:b.createdAt-I.createdAt})}async _addToOfflineQueue(S){this.uploadQueue.unshift(S);try{await this.persistentQueue.enqueue(S),this.logger.log(`[UploadQueue] Item persisted to IndexedDB: ${S.id}`)}catch(S){this.logger.warn("[UploadQueue] Failed to persist to IndexedDB:",S)}const b=this.memoryManager.enforceOfflineLimit(this.uploadQueue);if(b)try{await this.persistentQueue.remove(b.id)}catch(S){}}_scheduleRetry(){this.retryTimer&&clearTimeout(this.retryTimer);const S=this.circuitBreaker.getStatus();if("open"===S.state){const b=S.timeUntilReset;if(b>0)return this.logger.warn(`[UploadQueue] Delaying retry until circuit resets in ${Math.round(b/1e3)}s`),void(this.retryTimer=setTimeout(()=>{this._scheduleRetry()},b+1e3))}const b=this.config.retryDelay,I=this.config.maxRetryDelay,x=this.failedQueue[0]?.attempts||0,R=b*Math.pow(2,x),A=Math.min(R,I),_=.25*A,D=2*(Math.random()-.5)*_,L=Math.max(b,Math.round(A+D));this.retryTimer=setTimeout(()=>{this.logger.log(`Retrying ${this.failedQueue.length} failed items (attempt ${x+1})`),this.uploadQueue.unshift(...this.failedQueue),this.failedQueue=[],!this.isUploading&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest()&&this._processQueue()},L),this.logger.log(`[Retry] Scheduled in ${L}ms`)}_startProcessing(){this._processingTimer=setInterval(()=>{!this.isUploading&&this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()},5e3)}_updateStats(S,b,I){if(I){this.uploadStats.totalUploaded+=S.length,this.uploadStats.lastUploadTime=Date.now();const I=this.uploadStats.averageUploadTime,x=this.uploadStats.totalUploaded;this.uploadStats.averageUploadTime=(I*(x-S.length)+b)/x}else this.uploadStats.totalFailed+=S.length;S.forEach(S=>{this.uploadStats.totalBytes+=S.compressedSize||S.originalSize})}_validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};if(0===S.events.length&&!S.metadata?.isLastChunk)return{valid:!1,reason:"Empty events array (non-final chunk)"};if("number"!=typeof S.startTimestamp||"number"!=typeof S.endTimestamp)return{valid:!1,reason:"Invalid timestamps"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}_delay(S){return new Promise(b=>setTimeout(b,S))}getStats(){return{...this.uploadStats,queueSize:this.uploadQueue.length,failedQueueSize:this.failedQueue.length,isOnline:this.networkMonitor.getStatus(),isUploading:this.isUploading,isQuotaExceeded:this.isQuotaExceeded,circuitBreaker:this.circuitBreaker.getStatus()}}getCircuitBreakerStatus(){return this.circuitBreaker.getStatus()}resetCircuitBreaker(){this.circuitBreaker.reset()}isQuotaExceededStatus(){return this.isQuotaExceeded}isFirstSnapshotAcked(){return this.firstSnapshotAcked}didIndexedDBFail(){return!!this.persistentQueue&&this.persistentQueue.didInitFail()}getQueue(){return{pending:[...this.uploadQueue],failed:[...this.failedQueue]}}clearQueue(){const S=this.uploadQueue.length+this.failedQueue.length;return this.uploadQueue=[],this.failedQueue=[],this.logger.log(`Cleared ${S} items from queue`),S}pause(){this.isUploading=!0,this.logger.log("Upload queue paused")}resume(){this.isUploading=!1,this.logger.log("Upload queue resumed"),this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()}updateConfig(S){this.config={...this.config,...S},this.logger.log("Upload queue configuration updated")}getMemoryStats(){return this.memoryManager.getStats(this.uploadQueue,this.failedQueue)}forceMemoryCleanup(S={}){return this.memoryManager.forceCleanup(this.uploadQueue,this.failedQueue,S)}sendFinalChunkWithBeacon(S,b="unknown"){const I=this._validateChunk(S);return I.valid?this.beaconSender.send(S,b):(this.logger.warn(`[Beacon] Invalid final chunk: ${I.reason}`),!1)}async getPersistentQueueStats(){return{persistentQueueSize:await this.persistentQueue.count(),isIndexedDBAvailable:this.persistentQueue.isAvailable()}}destroy(){this.networkMonitor.destroy(),this.retryTimer&&clearTimeout(this.retryTimer),this._processingTimer&&clearInterval(this._processingTimer),this.persistentQueue&&this.persistentQueue.close(),this.circuitBreaker.destroy(),this.beaconSender.destroy(),this.memoryManager.destroy(),this.clearQueue(),this.logger.log("Upload queue destroyed")}}class ChunkedCompressedStorage{static CHUNK_SIZE=50;static CHUNK_PREFIX="rrweb_chunk_";static logger=createLogger("ChunkedCompressedStorage");static initSession(S){sessionStorage.setItem(`${S}_info`,JSON.stringify({startTime:Date.now(),chunkCount:0,totalEvents:0,isActive:!0}))}static updateSessionInfo(S,b,I){try{const x=JSON.parse(sessionStorage.getItem(`${S}_info`)||"{}");x.chunkCount=b,x.totalEvents=I,sessionStorage.setItem(`${S}_info`,JSON.stringify(x))}catch(S){this.logger.warn("Failed to update session info",S)}}static compress(S){const b=zlibSync(strToU8(JSON.stringify(S)),{level:6});return Array.from(b)}static decompress(S){const b=strFromU8(unzlibSync(new Uint8Array(S)));return JSON.parse(b)}static saveChunk(S,b,I){try{const x=this.compress({events:I}),R=`${S}_${this.CHUNK_PREFIX}${b}`;return sessionStorage.setItem(R,JSON.stringify(x)),!0}catch(S){return this.logger.error("saveChunk failed",S),!1}}static loadChunk(S,b){const I=`${S}_${this.CHUNK_PREFIX}${b}`,x=sessionStorage.getItem(I);if(!x)return null;try{const S=JSON.parse(x);return this.decompress(S).events||[]}catch(S){return this.logger.warn("loadChunk failed",S),null}}static getChunkCount(S){const b=sessionStorage.getItem(`${S}_info`);return b&&JSON.parse(b).chunkCount||0}static async streamChunks(S,b={}){const{onChunkLoad:I=()=>{},onProgress:x=()=>{},onComplete:R=()=>{},chunkDelay:A=50,startChunk:_=0}=b,D=this.getChunkCount(S);for(let b=_;b<D;b++){const R=this.loadChunk(S,b);R&&R.length&&I(R,b),x(b+1,D),b<D-1&&A>0&&await new Promise(S=>setTimeout(S,A))}R()}static clearSession(S){Object.keys(sessionStorage).forEach(b=>{b.startsWith(S)&&sessionStorage.removeItem(b)}),sessionStorage.removeItem(`${S}_info`)}}var du=Object.freeze({__proto__:null,ChunkedCompressedStorage:ChunkedCompressedStorage});class SessionStorage{constructor(S={}){this.storageKey=S.storageKey||"__tracescout_sessions__",this.maxStorageSize=S.maxStorageSize||52428800,this.maxSessions=S.maxSessions||10,this.logger=S.logger||createLogger("SessionStorage")}storeChunk(S,b){try{const I=this.getSessions();return I[S]||(I[S]={chunks:[],metadata:{startTime:Date.now(),lastActivity:Date.now(),totalEvents:0,totalChunks:0}}),I[S].chunks.push(b),I[S].metadata.lastActivity=Date.now(),I[S].metadata.totalEvents+=b.eventCount,I[S].metadata.totalChunks+=1,this.calculateSize(I)>this.maxStorageSize&&this.cleanup(I),this.saveSessions(I),this.logger.log(`Stored chunk ${b.chunkId} for session ${S}`),!0}catch(S){return this.logger.error("Failed to store chunk:",S),!1}}getSessions(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.error("Failed to load sessions:",S),{}}}getSession(S){return this.getSessions()[S]||null}saveSessions(S){try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(b){if("QuotaExceededError"===b.name){this.logger.warn("Storage quota exceeded, performing emergency cleanup"),this.emergencyCleanup();try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(S){this.logger.error("Storage failed even after cleanup:",S)}}else this.logger.error("Failed to save sessions:",b)}}calculateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}cleanup(S){const b=Object.entries(S).sort(([,S],[,b])=>S.metadata.lastActivity-b.metadata.lastActivity);for(;this.calculateSize(S)>this.maxStorageSize&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed old session: ${I}`)}for(;Object.keys(S).length>this.maxSessions&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed session due to count limit: ${I}`)}}emergencyCleanup(){try{localStorage.removeItem(this.storageKey),this.logger.warn("Emergency cleanup: cleared all session storage")}catch(S){this.logger.error("Emergency cleanup failed:",S)}}removeSession(S){try{const b=this.getSessions();return!!b[S]&&(delete b[S],this.saveSessions(b),this.logger.log(`Removed session: ${S}`),!0)}catch(S){return this.logger.error("Failed to remove session:",S),!1}}getStorageStats(){try{const S=this.getSessions(),b=this.calculateSize(S),I=Object.keys(S).length;let x=0,R=0;return Object.values(S).forEach(S=>{x+=S.metadata.totalEvents,R+=S.metadata.totalChunks}),{totalSize:b,sessionCount:I,totalEvents:x,totalChunks:R,maxStorageSize:this.maxStorageSize,maxSessions:this.maxSessions,storageUsagePercent:Math.round(b/this.maxStorageSize*100)}}catch(S){return this.logger.error("Failed to get storage stats:",S),null}}exportSession(S,b="json"){try{const I=this.getSession(S);if(!I)return null;const x={sessionId:S,metadata:I.metadata,chunks:I.chunks,totalChunks:I.chunks.length,totalEvents:I.metadata.totalEvents,exportTimestamp:Date.now()};return"json"===b?JSON.stringify(x,null,2):x}catch(S){return this.logger.error("Failed to export session:",S),null}}importSession(S){try{const b="string"==typeof S?JSON.parse(S):S;if(!b.sessionId||!b.chunks)throw new Error("Invalid session data format");const I=this.getSessions();return I[b.sessionId]={chunks:b.chunks,metadata:b.metadata||{startTime:Date.now(),lastActivity:Date.now(),totalEvents:b.totalEvents||0,totalChunks:b.totalChunks||0}},this.saveSessions(I),this.logger.log(`Imported session: ${b.sessionId}`),!0}catch(S){return this.logger.error("Failed to import session:",S),!1}}clearAll(){try{return localStorage.removeItem(this.storageKey),this.logger.log("Cleared all sessions"),!0}catch(S){return this.logger.error("Failed to clear all sessions:",S),!1}}}var gu=Object.freeze({__proto__:null,BeaconSender:BeaconSender,CHUNK_FORMAT_VERSION:4,CheckpointManager:CheckpointManager,ChunkManager:ChunkManager,ChunkedCompressedStorage:ChunkedCompressedStorage,CircuitBreaker:CircuitBreaker,EventOptimizer:EventOptimizer,InactivityManager:InactivityManager,IndexedDBQueue:IndexedDBQueue,NETWORK_ENVELOPE_TAG:au,NetworkMonitor:NetworkMonitor,PageLifecycleManager:PageLifecycleManager,QueueMemoryManager:QueueMemoryManager,Recorder:Recorder,RecorderMemoryManager:RecorderMemoryManager,RecorderPresets:uu,SessionStorage:SessionStorage,UploadQueue:UploadQueue,analyzeSnapshotsInEvents:analyzeSnapshotsInEvents,buildSnapshotIndex:buildSnapshotIndex,chunkHasSnapshot:chunkHasSnapshot,collectDeviceMetadata:collectDeviceMetadata,createChunk:createChunk,detectDeviceType:detectDeviceType,detectTouchCapability:detectTouchCapability,extractConsoleRef:extractConsoleRef,extractNetworkFull:extractNetworkFull,extractNetworkRef:extractNetworkRef,extractResourceRef:extractResourceRef,findNearestSnapshotBefore:findNearestSnapshotBefore,generateConsoleId:generateConsoleId,generateNetworkId:generateNetworkId,generateResourceId:generateResourceId,getConnectionInfo:getConnectionInfo,getEventsAfterSnapshot:getEventsAfterSnapshot,getMemoryInfo:getMemoryInfo,getRRWeb:getRRWeb,getRRWebSource:getRRWebSource,getRecord:getRecord,getSnapshotTimestamps:getSnapshotTimestamps,hashCode:hashCode,isCompatibleVersion:isCompatibleVersion,isRRWebLoaded:isRRWebLoaded,loadRRWeb:loadRRWeb,networkEnvelopeEvent:networkEnvelopeEvent,parseBrowserInfo:parseBrowserInfo,parseOSInfo:parseOSInfo,sanitizeUrl:sanitizeUrl,stripNetworkPayload:stripNetworkPayload});"undefined"!=typeof window&&(window.TraceScout=At,At.setTransport=TraceScoutMonitoringCore.setTransport.bind(TraceScoutMonitoringCore));export{St as BODY_REDACTED_VALUE,BaseInterceptor,BeaconSender,lu as CHUNK_FORMAT_VERSION,U as CORE_WEB_VITALS_DEFAULTS,CheckpointManager,ChunkManager,ChunkedCompressedStorage,CircuitBreaker,ConfigManager,ConsoleInterceptor,CoreWebVitalsMonitor,_ as DEFAULT_CONFIG,B as DEFAULT_FIELD_PATTERNS,bt as DEFAULT_MAX_BODY_BYTES,wt as DEFAULT_MAX_BODY_SIZE,kt as DEFAULT_SENSITIVE_FIELDS,L as EVENT_TYPES,ErrorFingerprint,ErrorHandler,EventManager,EventOptimizer,FetchInterceptor,InactivityManager,IndexedDBQueue,A as LOCAL_STORAGE_KEYS,LogBuffer,LogManager,Logger,LoggingManager,Ct as MAX_BODY_BYTES_CEILING,au as NETWORK_ENVELOPE_TAG,NetworkMonitor,PageLifecycleManager,pe as PerformanceMonitor,PerformanceResourceObserver,PostMessageInterceptor,QueueMemoryManager,ft as REDACTED_VALUE,D as REPORTER_LOG_PREFIX,mt as RESOURCE_EXTENSIONS,Recorder,RecorderMemoryManager,uu as RecorderPresets,RemoteConfigService,ResourceInterceptor,SDKContext,pt as SENSITIVE_HEADERS,Ze as SENSITIVE_QUERY_PARAMS,ServiceLogger,ServiceManager,SessionManager,SessionStorage,TraceScoutMonitoringCore,UploadQueue,UserProfileManager,XHRInterceptor,analyzeSnapshotsInEvents,buildFieldDenylist,buildSnapshotIndex,captureRequestBody,captureResponseBody,chunkHasSnapshot,classifyMime,collectDeviceMetadata,createChunk,createLogger,createSensitiveHeaderSet,debounce,deepClone,At as default,detectDeviceType,detectTouchCapability,extractConsoleRef,extractNetworkFull,extractNetworkRef,extractRequestDetails,extractResourceRef,filterSensitiveHeaders,findNearestSnapshotBefore,generateConsoleId,generateId,generateNetworkId,generateResourceId,getConnectionInfo,getEventsAfterSnapshot,getMemoryInfo,getRRWeb,getRRWebSource,getRecord,getResourceType,getSensitiveHeadersList,getSnapshotTimestamps,handleRequestBody,handleResponseBody,hashCode,initializeErrorHandler,isApiEndpoint,isCompatibleVersion,isRRWebLoaded,isResourceUrl,isSensitiveField,isSensitiveHeader,isStaticResource,isTextualContentType,loadRRWeb,$ as loggingManager,At as monitoringCore,networkEnvelopeEvent,parseBrowserInfo,parseFormData,parseOSInfo,parseRequestUrl,parseUrl,redactFormUrlEncoded,redactObject,safeJsonParse,safeJsonStringify,safeMime,safeParseConsoleArgs,I as safeSessionStorage,b as safeStorage,safeStringify,splitSanitizedUrl,stripNetworkPayload,throttle$1 as throttle,truncateToBytes,x as typeUtils,utf8Bytes,R as utils,validateDomains,validateEndpoints,validateService};