4 lines
46 KiB
JavaScript
4 lines
46 KiB
JavaScript
"use strict";var D=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Se=Object.prototype.hasOwnProperty;var xe=(o,e)=>{for(var t in e)D(o,t,{get:e[t],enumerable:!0})},Re=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ee(e))!Se.call(o,r)&&r!==t&&D(o,r,{get:()=>e[r],enumerable:!(n=we(e,r))||n.enumerable});return o};var ke=o=>Re(D({},"__esModule",{value:!0}),o);var De={};xe(De,{BehaviorPlugin:()=>V,Client:()=>q,ErrorPlugin:()=>j,NetworkPlugin:()=>A,OfflinePlugin:()=>G,PerformancePlugin:()=>W,SamplingPlugin:()=>Z,addBreadcrumb:()=>me,captureEvent:()=>de,captureException:()=>ue,captureMessage:()=>le,default:()=>Oe,disable:()=>ye,enable:()=>be,flush:()=>ve,getClient:()=>ce,init:()=>ae,setExtra:()=>ge,setTag:()=>he,setTags:()=>fe,setUser:()=>pe});module.exports=ke(De);function ee(o){try{let e=o.match(/^(https?):\/\/([^@]+)@([^/]+)\/(.+)$/);if(!e)throw new Error("Invalid DSN format");let[,t,n,r,i]=e;return{protocol:t,publicKey:n,host:r,projectId:i}}catch(e){throw new Error(`Failed to parse DSN: ${e.message}`)}}function k(o){return`${o.protocol}://${o.host}/api/${o.projectId}/envelope/?sentry_key=${o.publicKey}`}function te(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[x]/g,()=>(Math.random()*16|0).toString(16))}function d(){return Date.now()}function y(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function T(o,e){return!e||e.length===0?!1:e.some(t=>typeof t=="string"?o.includes(t):t.test(o))}function Te(o){let e=5381,t=o.length;for(;t;)e=e*33^o.charCodeAt(--t);return e>>>0}function F(o){return Te(o).toString(16)}function L(o,e,t=[]){let n=t.slice(0,3).map(i=>`${i.filename}:${i.lineno||0}`).join("|"),r=e.replace(/['"]?\d+['"]?/g,"").replace(/\s+/g," ").trim();return F(`${o}:${r}:${n}`)}function P(o,e={}){if(!o)return[];let{captureNodeModules:t=!1,captureColumn:n=!0,relativePathOnly:r=!1,maxFrames:i}=e,s=[],a=o.split(`
|
|
`),c=typeof location!="undefined"?`${location.protocol}//${location.host}`:"";for(let p of a){let w=p.match(/^\s*at\s*(.+?)\s*\((.+?):(\d+):(\d+)\)\s*$/);if(w){let[,f,h,v,g]=w,E=h.includes("node_modules");if(!t&&E)continue;let S=h;r&&c&&h.startsWith(c)&&(S=h.substring(c.length)),s.push({filename:S,function:f,lineno:parseInt(v,10),colno:n?parseInt(g,10):void 0,in_app:!E})}else{let f=p.match(/^\s*at\s*(.+?)@(.+?):(\d+):(\d+)\s*$/);if(f){let[,v,g,E,S]=f,R=g.includes("node_modules");if(!t&&R)continue;let Y=g;r&&c&&g.startsWith(c)&&(Y=g.substring(c.length)),s.push({filename:Y,function:v||"<anonymous>",lineno:parseInt(E,10),colno:n?parseInt(S,10):void 0,in_app:!R});continue}let h=p.match(/^\s*at\s*(.+?):(\d+):(\d+)\s*$/);if(h){let[,v,g,E]=h,S=v.includes("node_modules");if(!t&&S)continue;let R=v;r&&c&&v.startsWith(c)&&(R=v.substring(c.length)),s.push({filename:R,lineno:parseInt(g,10),colno:n?parseInt(E,10):void 0,in_app:!S})}}}let u=s.reverse();return i!==void 0&&i>0?u.slice(0,i):u}function Le(o){let e=[{name:"WeChat",pattern:/MicroMessenger\/([\d.]+)/i},{name:"QQ Browser",pattern:/QIBrowser\/([\d.]+)/i},{name:"UC Browser",pattern:/UCBrowser\/([\d.]+)/i},{name:"Edge",pattern:/Edg\/([\d.]+)/i},{name:"Edge",pattern:/Edge\/([\d.]+)/i},{name:"Opera",pattern:/OPR\/([\d.]+)/i},{name:"Opera",pattern:/Opera\/([\d.]+)/i},{name:"Firefox",pattern:/Firefox\/([\d.]+)/i},{name:"Safari",pattern:/Version\/([\d.]+).*Safari/i},{name:"Chrome",pattern:/Chrome\/([\d.]+)/i},{name:"IE",pattern:/MSIE ([\d.]+)/i},{name:"IE",pattern:/Trident.*rv:([\d.]+)/i}];for(let t of e){let n=o.match(t.pattern);if(n){let r=n[1]||"",i=r.split(".")[0]||"";return{name:t.name,version:r,major:i}}}return{name:"Unknown",version:"",major:""}}function Pe(o){let e=[{name:"Windows 11",pattern:/Windows NT 10\.0.*Win64.*x64/i},{name:"Windows 10",pattern:/Windows NT 10\.0/i},{name:"Windows 8.1",pattern:/Windows NT 6\.3/i},{name:"Windows 8",pattern:/Windows NT 6\.2/i},{name:"Windows 7",pattern:/Windows NT 6\.1/i},{name:"Windows Vista",pattern:/Windows NT 6\.0/i},{name:"Windows XP",pattern:/Windows NT 5\.1/i},{name:"macOS",pattern:/Mac OS X ([\d_.]+)/i},{name:"iOS",pattern:/OS ([\d_.]+) like Mac OS X/i},{name:"Android",pattern:/Android ([\d.]+)/i},{name:"Android",pattern:/Android/i},{name:"Linux",pattern:/Linux/i}];for(let t of e){let n=o.match(t.pattern);if(n){let r=n[1]||"";return r&&(r=r.replace(/_/g,".")),{name:t.name,version:r}}}return{name:"Unknown",version:""}}function Ce(o){let e=/Mobile|Android|iPhone|iPod|BlackBerry|Windows Phone|Opera Mini/i.test(o),t=/Tablet|iPad|PlayBook|Kindle|Silk/i.test(o),n="desktop";t?n="tablet":e&&(n="mobile");let r="",i="",s=o.match(/iPhone/i),a=o.match(/iPad/i),c=o.match(/SM-([A-Z0-9]+)/i),u=o.match(/Pixel ([0-9A-Z]+)/i),p=o.match(/HUAWEI ([A-Z0-9]+)/i);return s?(r="Apple",i="iPhone"):a?(r="Apple",i="iPad"):c?(r="Samsung",i=c[1]):u?(r="Google",i=`Pixel ${u[1]}`):p&&(r="Huawei",i=p[1]),{type:n,vendor:r,model:i}}function ne(){let o=typeof navigator!="undefined"?navigator.userAgent:"",e=Le(o),t=Pe(o),n=Ce(o);return{browser:e,os:t,device:n,url:typeof location!="undefined"?location.href:"",referrer:typeof document!="undefined"?document.referrer:"",title:typeof document!="undefined"?document.title:"",language:typeof navigator!="undefined"?navigator.language:"",user_agent:o,screen_width:typeof screen!="undefined"?screen.width:0,screen_height:typeof screen!="undefined"?screen.height:0,viewport_width:typeof window!="undefined"?window.innerWidth:0,viewport_height:typeof window!="undefined"?window.innerHeight:0}}function b(){return typeof location!="undefined"?location.href:""}function re(){return typeof document!="undefined"?document.referrer:""}function x(o){if(!o)return o;try{let e=new URL(o),t=["password","passwd","pwd","token","access_token","refresh_token","api_key","apikey","key","secret","private_key","code","auth","id_token","idToken","session","session_id"],n=e.searchParams,r=!1;for(let i of Array.from(n.keys())){let s=i.toLowerCase().replace(/[-_]/g,"_");t.some(a=>s.includes(a))&&(n.set(i,"[Filtered]"),r=!0)}if(e.hash&&e.hash.length>1){let i=e.hash.substring(1);if(i.includes("=")){let s=new URLSearchParams(i),a=!1;for(let c of Array.from(s.keys())){let u=c.toLowerCase().replace(/[-_]/g,"_");t.some(p=>u.includes(p))&&(s.set(c,"[Filtered]"),a=!0)}a&&(e.hash="#"+s.toString(),r=!0)}}return r?e.toString():o}catch(e){return o}}function C(o,e=[]){return!e||e.length===0?!1:e.some(t=>{if(typeof t=="string"){if(t.includes("*")){let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(n).test(o)}return o.includes(t)}return t.test(o)})}var Me={Chrome:"c",Safari:"s",Firefox:"f",Edge:"e",Opera:"o",IE:"i",WeChat:"w","QQ Browser":"q","UC Browser":"u","Mobile Chrome":"cm","Mobile Safari":"sm"},Be={"Windows 11":"w11","Windows 10":"w10","Windows 8.1":"w81","Windows 8":"w8","Windows 7":"w7","Windows Vista":"wv","Windows XP":"wxp",macOS:"m",iOS:"i",Android:"a",Linux:"l"};function U(){let o=ne(),e=Me[o.browser.name]||o.browser.name.toLowerCase(),t=Be[o.os.name]||o.os.name.toLowerCase();return{browser:{name:e,version:o.browser.major},os:{name:t,version:o.os.version.split(".")[0]},device:{type:o.device.type,brand:o.device.vendor||void 0,model:o.device.model||void 0}}}function ie(){let o=ne(),e=`${o.browser.name}|${o.browser.major}|${o.os.name}|${o.os.version.split(".")[0]}|${o.device.type}|${o.device.vendor}|${o.device.model}|${o.language}`;return F(e).substring(0,16)}var Ie={enabled:!0,sampleRate:1,maxQueueSize:100,flushInterval:5e3,maxRetries:3,retryDelay:1e3,environment:"production",contextLevel:{fatal:{maxStackFrames:5,maxBreadcrumbs:20},error:{maxStackFrames:5,maxBreadcrumbs:10},warning:{maxStackFrames:3,maxBreadcrumbs:5},info:{maxStackFrames:0,maxBreadcrumbs:0},debug:{maxStackFrames:0,maxBreadcrumbs:0}}},M=class{constructor(e){this.contexts=null;this.contextId=null;this.contextReported=!1;this.config={...Ie,...e}}markContextReported(){this.contextReported=!0}get(e){return this.config[e]}getAll(){return{...this.config}}set(e,t){this.config[e]=t}setUser(e){this.config.user=e||void 0}setTags(e){this.config.tags={...this.config.tags||{},...e}}setTag(e,t){this.config.tags||(this.config.tags={}),this.config.tags[e]=t}setExtra(e,t){this.config.extra||(this.config.extra={}),this.config.extra[e]=t}isIgnoredError(e){return T(e,this.config.ignoreErrors||[])}getEncodedContext(){return this.contexts||(this.contexts=U()),this.contexts}applyToEvent(e,t=!0){var i,s,a,c;let n={...e};if(e.tags&&(n.tags={...e.tags}),e.request&&(n.request={...e.request}),"exception"in e&&e.exception){let u=e.exception;n.exception={...u,stacktrace:u.stacktrace?{...u.stacktrace,frames:u.stacktrace.frames?u.stacktrace.frames.map(p=>({...p})):void 0}:void 0}}e.breadcrumbs&&(n.breadcrumbs=e.breadcrumbs.map(u=>({...u}))),e.user&&(n.user={...e.user}),e.contexts&&(n.contexts={...e.contexts}),this.config.release&&(n.release=this.config.release),this.config.environment&&(n.environment=this.config.environment),this.config.user&&(n.user=this.config.user),this.config.tags&&(n.tags={...this.config.tags,...e.tags||{}}),n.request?n.request.url||(n.request.url=b()):n.request={url:b(),referrer:re()},this.contextId||(this.contextId=ie()),n.context_id=this.contextId;let r=this.applyContextLevel(n);return t&&!this.contextReported&&(this.contexts||(this.contexts=U()),r.contexts=this.contexts,r.env={b:(i=this.contexts.browser)==null?void 0:i.name,bv:(s=this.contexts.browser)==null?void 0:s.version,os:(a=this.contexts.os)==null?void 0:a.name,osv:(c=this.contexts.os)==null?void 0:c.version}),r}applyContextLevel(e){let t=this.config.contextLevel;if(!t)return e;let n=e.level||"error",r=t[n]||t.error,i={...e};if("exception"in e&&e.exception&&typeof e.exception=="object"){let s=e.exception;if(s.stacktrace&&typeof s.stacktrace=="object"){let a=s.stacktrace;Array.isArray(a.frames)&&(r.maxStackFrames===0?delete i.exception:i.exception={...s,stacktrace:{...a,frames:a.frames.slice(0,r.maxStackFrames)}})}}return e.breadcrumbs&&Array.isArray(e.breadcrumbs)&&(r.maxBreadcrumbs===0?delete i.breadcrumbs:i.breadcrumbs=e.breadcrumbs.slice(-r.maxBreadcrumbs)),i}};var B=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,[]),this.handlers.get(e).push(t)}off(e,t){let n=this.handlers.get(e);if(n){let r=n.indexOf(t);r>-1&&n.splice(r,1)}}emit(e,...t){let n=this.handlers.get(e);if(n)for(let r of n)try{r(...t)}catch(i){console.error("[LightSDK] EventBus handler error:",i)}}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}destroy(){this.handlers.clear()}};var I=class{constructor(e,t,n,r,i){this.queue=[];this.timer=null;this.lastFlushTime=0;this.isFlushing=!1;this.dedupeMap=new Map;this.pendingCounts=new Map;this.errorRateWindow={};this.paused=!1;this.pauseTimer=null;this.maxSize=e,this.flushInterval=t,this.eventBus=n,this.flushCallback=r,this.syncFlushCallback=i}start(){this.startTimer(),this.setupVisibilityListener()}startTimer(){this.timer||(this.timer=setInterval(()=>{(this.queue.length>0||this.pendingCounts.size>0)&&this.flush()},this.flushInterval))}setupVisibilityListener(){this.onVisibilityChange=()=>{document.hidden&&(this.queue.length>0||this.pendingCounts.size>0)&&this.flushSync()},typeof document!="undefined"&&document.addEventListener("visibilitychange",this.onVisibilityChange),this.onBeforeUnload=()=>{(this.queue.length>0||this.pendingCounts.size>0)&&this.flushSync()},this.onPagehide=()=>{(this.queue.length>0||this.pendingCounts.size>0)&&this.flushSync()},typeof window!="undefined"&&(window.addEventListener("beforeunload",this.onBeforeUnload),window.addEventListener("pagehide",this.onPagehide))}checkInfiniteLoop(e){let t=d(),n=t-1e3;this.errorRateWindow[e]||(this.errorRateWindow[e]=[]);let r=this.errorRateWindow[e];for(r.push(t);r.length>0&&r[0]<n;)r.shift();return r.length===0?(delete this.errorRateWindow[e],!1):r.length>10?(this.paused||(console.warn("[LightSDK] Infinite loop detected, pausing SDK for 60s",{fingerprint:e,count:r.length}),this.eventBus.emit("error",new Error("Infinite loop detected")),this.paused=!0,this.pauseTimer&&clearTimeout(this.pauseTimer),this.pauseTimer=setTimeout(()=>{this.paused=!1,this.errorRateWindow={},console.info("[LightSDK] Resumed after infinite loop detection")},6e4)),!0):!1}enqueue(e){if(this.paused)return;this.cleanupExpiredDedupeEntries();let t=this.getDedupeKey(e);if(t){if(this.checkInfiniteLoop(t))return;let n=d(),r=this.dedupeMap.get(t);if(r)if(n-r.lastTime<6e4){if(r.count>=3){if(!this.pendingCounts.has(t))this.pendingCounts.set(t,{count:1,ts_start:n,ts_end:n});else{let i=this.pendingCounts.get(t);i.count++,i.ts_end=n}return}r.count++,r.lastTime=n}else this.dedupeMap.set(t,{count:1,lastTime:n,firstReported:!0}),this.pendingCounts.delete(t);else this.dedupeMap.set(t,{count:1,lastTime:n,firstReported:!1})}this.queue.push(e),this.eventBus.emit("event",e),this.queue.length>=this.maxSize&&this.flush()}cleanupExpiredDedupeEntries(){if(this.dedupeMap.size<100&&Math.random()>.1)return;let e=d(),t=6e4;for(let[n,r]of this.dedupeMap)e-r.lastTime>t&&this.dedupeMap.delete(n)}buildCountEvents(){let e=[];for(let[t,n]of this.pendingCounts.entries()){let r={type:"count",fingerprint:t,count:n.count,ts_start:n.ts_start,ts_end:n.ts_end,timestamp:d(),level:"info"};e.push(r)}return e}getDedupeKey(e){if(e.type==="error"){let t=e;return t.fingerprint||t.message}return null}async flush(){if(this.queue.length===0&&this.pendingCounts.size===0||this.isFlushing)return;this.isFlushing=!0;let e=this.queue.splice(0,this.queue.length),t=this.buildCountEvents(),n=[...e,...t];this.lastFlushTime=d(),this.eventBus.emit("report",n);try{await this.flushCallback(n),this.pendingCounts.clear(),this.eventBus.emit("reported",n)}catch(r){throw e.forEach(i=>this.queue.unshift(i)),r}finally{this.isFlushing=!1}}flushSync(){if(this.queue.length===0&&this.pendingCounts.size===0)return;let e=this.queue.splice(0,this.queue.length),t=new Map(this.pendingCounts),n=this.buildCountEvents(),r=[...e,...n];this.lastFlushTime=d(),this.eventBus.emit("report",r);try{this.syncFlushCallback(r),this.pendingCounts.clear(),this.eventBus.emit("reported",r)}catch(i){console.error("[LightSDK] Sync flush failed",i),e.forEach(s=>this.queue.unshift(s));for(let[s,a]of t)this.pendingCounts.has(s)||this.pendingCounts.set(s,a)}}size(){return this.queue.length}destroy(){this.timer&&(clearInterval(this.timer),this.timer=null),this.pauseTimer&&(clearTimeout(this.pauseTimer),this.pauseTimer=null),typeof document!="undefined"&&this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange),typeof window!="undefined"&&(this.onBeforeUnload&&window.removeEventListener("beforeunload",this.onBeforeUnload),this.onPagehide&&window.removeEventListener("pagehide",this.onPagehide)),this.dedupeMap.clear(),this.pendingCounts.clear(),this.errorRateWindow={}}};var se={event_id:"eid",timestamp:"ts",start_timestamp:"sts",type:"t",level:"l",message:"m",platform:"p",release:"r",environment:"e",fingerprint:"fp",context_id:"cid",user:"u",tags:"tg",exception:"ex",request:"req",contexts:"ctx",breadcrumbs:"bc",transaction:"tx",duration:"d",spans:"sp",extra:"xt"},Qe=Object.fromEntries(Object.entries(se).map(([o,e])=>[e,o]));function oe(o){if(!o||typeof o!="object")return o;let e={};for(let[t,n]of Object.entries(o)){let r=se[t]||t;e[r]=n}return e}var _=class{constructor(e,t,n){this.useShortFields=!0;this.dsn=e,this.maxRetries=t,this.retryDelay=n}async report(e){if(e.length===0)return;let t=this.buildEnvelope(e),n=0;for(;n<=this.maxRetries;)try{await this.send(t,!1);return}catch(r){let i=r.status;if(i&&i>=400&&i<500||(n++,n>this.maxRetries))throw r;let s=Math.min(this.retryDelay*Math.pow(2,n-1),5e3);await this.delay(s)}}reportSync(e){if(e.length===0)return;let t=this.buildEnvelope(e);try{if(this.sendSync(t))return}catch(n){}this.sendViaImage(t)}buildEnvelope(e){let t=this.extractSharedMeta(e),n={event_id:te(),sent_at:new Date().toISOString(),meta:t};this.useShortFields&&(n._sf=1);let r=this.applyRelativeTimestamps(e,n),s=[JSON.stringify(n)];for(let a of r){let c=this.stripSharedFields(a,t);this.useShortFields&&(c=oe(c));let u=JSON.stringify(c),p=JSON.stringify({type:this.getEnvelopeType(a),length:u.length});s.push(p,u)}return s.join(`
|
|
`)}applyRelativeTimestamps(e,t){if(e.length<=1)return e;let n=[],r=e[0].timestamp?new Date(e[0].timestamp).getTime():Date.now();t._rt=1,t._bt=r;for(let i=0;i<e.length;i++){let s={...e[i]};if(i===0)n.push(s);else{let c=(s.timestamp?new Date(s.timestamp).getTime():Date.now())-r;if(delete s.timestamp,s._dts=c,s.start_timestamp){let p=new Date(s.start_timestamp).getTime()-r;delete s.start_timestamp,s._dsts=p}n.push(s)}}return n}extractSharedMeta(e){if(e.length===0)return{};let t=e[0],n={};t.release&&e.every(s=>s.release===t.release)&&(n.release=t.release),t.environment&&e.every(s=>s.environment===t.environment)&&(n.environment=t.environment),t.user&&e.every(s=>JSON.stringify(s.user)===JSON.stringify(t.user))&&(n.user=t.user);let r=t.env;return r&&(n.env=r),n}stripSharedFields(e,t){let n={...e};return t.release&&n.release===t.release&&delete n.release,t.environment&&n.environment===t.environment&&delete n.environment,t.user&&JSON.stringify(n.user)===JSON.stringify(t.user)&&delete n.user,t.env&&delete n.env,n}getEnvelopeType(e){switch(e.type){case"error":return"event";case"performance":return"transaction";default:return e.type}}async send(e,t=!1){let n=k(this.dsn);if(navigator.sendBeacon)try{let r=new Blob([e],{type:"application/x-sentry-envelope"});if(navigator.sendBeacon(n,r))return}catch(r){}if(typeof fetch=="function")try{let r=new AbortController,i=setTimeout(()=>r.abort(),1e4),s=await fetch(n,{method:"POST",body:e,headers:{"Content-Type":"application/x-sentry-envelope"},keepalive:!0,signal:r.signal});if(clearTimeout(i),s.ok)return;let a=new Error(`HTTP ${s.status}`);throw a.status=s.status,a}catch(r){throw r}if(typeof XMLHttpRequest!="undefined")return new Promise((r,i)=>{let s=new XMLHttpRequest;s.open("POST",n,!t),s.setRequestHeader("Content-Type","application/x-sentry-envelope"),s.timeout=1e4,s.onload=()=>{if(s.status>=200&&s.status<300)r();else{let a=new Error(`HTTP ${s.status}`);a.status=s.status,i(a)}},s.onerror=()=>i(new Error("Network error")),s.ontimeout=()=>i(new Error("Request timeout")),s.send(e)});throw new Error("No transport available")}sendSync(e){let t=k(this.dsn);if(navigator.sendBeacon)try{let n=new Blob([e],{type:"application/x-sentry-envelope"});return navigator.sendBeacon(t,n)}catch(n){return!1}if(typeof XMLHttpRequest!="undefined")try{let n=new XMLHttpRequest;return n.open("POST",t,!1),n.setRequestHeader("Content-Type","application/x-sentry-envelope"),n.send(e),n.status>=200&&n.status<300}catch(n){return!1}return!1}sendViaImage(e){try{let t=k(this.dsn),n=new Image,r=encodeURIComponent(btoa(e)),i=t.includes("?")?"&":"?";return n.src=t+i+"sentry_data="+r.substring(0,2e3),!0}catch(t){return!1}}delay(e){return new Promise(t=>setTimeout(t,e))}};var O=class{constructor(e){this.plugins=new Map;this.client=e}add(e){if(!this.plugins.has(e.name)){this.plugins.set(e.name,e);try{e.setup(this.client)}catch(t){console.error(`[LightSDK] Plugin "${e.name}" setup error:`,t)}}}remove(e){let t=this.plugins.get(e);if(t){if(t.destroy)try{t.destroy()}catch(n){console.error(`[LightSDK] Plugin "${e}" destroy error:`,n)}this.plugins.delete(e)}}get(e){return this.plugins.get(e)}has(e){return this.plugins.has(e)}applyBeforeReport(e){let t=e;for(let n of this.plugins.values())if(n.beforeReport)try{let r=n.beforeReport(t);if(r===null)return null;t=r}catch(r){console.error(`[LightSDK] Plugin "${n.name}" beforeReport error:`,r)}return t}applyAfterReport(e){for(let t of this.plugins.values())if(t.afterReport)try{t.afterReport(e)}catch(n){console.error(`[LightSDK] Plugin "${t.name}" afterReport error:`,n)}}destroy(){for(let e of this.plugins.values())if(e.destroy)try{e.destroy()}catch(t){console.error(`[LightSDK] Plugin "${e.name}" destroy error:`,t)}this.plugins.clear()}};var N=class{constructor(e){this.breadcrumbs=[];this.enabled=!0;var t,n,r,i;if(!e.dsn)throw new Error("DSN is required");this.dsn=ee(e.dsn),this.configManager=new M(e),this.eventBus=new B,this.reporter=new _(this.dsn,(t=this.configManager.get("maxRetries"))!=null?t:3,(n=this.configManager.get("retryDelay"))!=null?n:1e3),this.pluginManager=new O(this),this.queue=new I((r=this.configManager.get("maxQueueSize"))!=null?r:100,(i=this.configManager.get("flushInterval"))!=null?i:5e3,this.eventBus,async s=>this.flushEvents(s),s=>this.syncFlushEvents(s)),this.enabled=this.configManager.get("enabled")!==!1}get maxBreadcrumbs(){var e;return(e=this.configManager.get("maxBreadcrumbs"))!=null?e:20}get config(){return this.configManager.getAll()}init(){this.enabled&&(this.queue.start(),this.emit("ready"))}async flushEvents(e){let t=[];for(let i of e){let s=this.pluginManager.applyBeforeReport(i);s&&t.push(s)}if(t.length===0)return;let n=!0,r=[];for(let i of t){let s=this.configManager.applyToEvent(i,n);n=!1;let a=this.configManager.get("beforeSend"),c=a?a(s):s;c&&r.push(c)}if(r.length!==0){await this.reporter.report(r),this.configManager.markContextReported();for(let i of r)this.pluginManager.applyAfterReport(i)}}syncFlushEvents(e){let t=[];for(let i of e){let s=this.pluginManager.applyBeforeReport(i);s&&t.push(s)}if(t.length===0)return;let n=!0,r=[];for(let i of t){let s=this.configManager.applyToEvent(i,n);n=!1;let a=this.configManager.get("beforeSend"),c=a?a(s):s;c&&r.push(c)}r.length!==0&&(this.reporter.reportSync(r),this.configManager.markContextReported())}on(e,t){this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}emit(e,...t){this.eventBus.emit(e,...t)}captureException(e){if(!this.enabled)return;let t=this.buildErrorEvent(e);this.configManager.isIgnoredError(t.message)||(t.breadcrumbs=[...this.breadcrumbs],this.queue.enqueue(t))}captureMessage(e,t="info"){if(!this.enabled)return;let n={type:"error",level:t,message:e,timestamp:d(),breadcrumbs:[...this.breadcrumbs]};this.configManager.isIgnoredError(e)||this.queue.enqueue(n)}captureEvent(e){if(!this.enabled)return;let t={timestamp:d(),level:"info",breadcrumbs:[...this.breadcrumbs],...e};this.queue.enqueue(t)}buildErrorEvent(e){let t=d();if(e instanceof Error){let r=P(e.stack,{maxFrames:5}),i=L(e.name,e.message,r);return{type:"error",level:"error",message:e.message,timestamp:t,exception:{type:e.name,value:e.message,stacktrace:{frames:r}},fingerprint:i}}return{type:"error",level:"error",message:String(e),timestamp:t}}setUser(e){this.configManager.setUser(e)}setTag(e,t){this.configManager.setTag(e,t)}setTags(e){this.configManager.setTags(e)}setExtra(e,t){this.configManager.setExtra(e,t)}addBreadcrumb(e){let t={...e,timestamp:d()};this.breadcrumbs.push(t),this.breadcrumbs.length>this.maxBreadcrumbs&&this.breadcrumbs.shift()}async flush(){await this.queue.flush()}disable(){this.enabled=!1}enable(){this.enabled=!0}use(e){this.pluginManager.add(e)}destroy(){this.queue.destroy(),this.pluginManager.destroy(),this.eventBus.destroy(),this.breadcrumbs=[]}},q=N;var H=class{constructor(){this.name="error";this.version="1.0.0";this.config={maxStackFrames:5,captureNodeModules:!1,captureColumn:!0,relativePathOnly:!1,resourceSampleRate:.1}}setup(e){this.client=e,this.loadConfig(),this.setupGlobalError(),this.setupUnhandledRejection(),this.setupResourceError()}loadConfig(){let e=this.client.config;e&&y(e.error)&&(this.config={...this.config,...e.error}),e.ignoreErrors&&(this.config.ignoreErrors=[...this.config.ignoreErrors||[],...e.ignoreErrors]),e.ignoreUrls&&(this.config.ignoreUrls=[...this.config.ignoreUrls||[],...e.ignoreUrls]),e.includePaths&&(this.config.includePaths=[...this.config.includePaths||[],...e.includePaths])}shouldIgnoreError(e){return e?T(e,this.config.ignoreErrors||[]):!1}shouldIgnoreScriptUrl(e){return C(e,this.config.ignoreUrls||[])}shouldIncludePath(e){let t=this.config.includePaths||[];return t.length===0?!0:e.some(n=>t.some(r=>{var i;return typeof r=="string"?(i=n.filename)==null?void 0:i.includes(r):r.test(n.filename||"")}))}shouldSample(){var t;let e=(t=this.config.sampleRate)!=null?t:1;return e>=1?!0:e<=0?!1:Math.random()<e}shouldSampleResource(){var t;let e=(t=this.config.resourceSampleRate)!=null?t:.1;return e>=1?!0:e<=0?!1:Math.random()<e}setupGlobalError(){typeof window!="undefined"&&(this.originalOnError=window.onerror,window.onerror=(e,t,n,r,i)=>{try{if(this.originalOnError&&this.originalOnError.call(window,e,t,n,r,i),t&&this.shouldIgnoreScriptUrl(t))return!1;let s=this.buildErrorEvent(i||e,t,n,r);s&&this.client.captureEvent(s)}catch(s){console.error("[LightSDK] ErrorPlugin global error handler error:",s)}return!1})}setupUnhandledRejection(){typeof window!="undefined"&&(this.onUnhandledRejection=e=>{try{let t=e.reason,n=this.extractUrlFromReason(t);if(n&&this.shouldIgnoreScriptUrl(n))return;let r=this.buildErrorEvent(t);r&&(r.type==="error"&&(r.tags={...r.tags||{},unhandled:"true",promise:"true"}),this.client.captureEvent(r))}catch(t){console.error("[LightSDK] ErrorPlugin unhandledrejection handler error:",t)}},window.addEventListener("unhandledrejection",this.onUnhandledRejection))}extractUrlFromReason(e){if(e instanceof Error&&e.stack){let t=e.stack.match(/at\s+(?:.+?\s+)?\((https?:\/\/[^:]+):\d+:\d+\)/);if(t)return t[1];let n=e.stack.match(/(https?:\/\/[^\s)]+):\d+:\d+/);if(n)return n[1]}return null}setupResourceError(){typeof window!="undefined"&&(this.onResourceError=e=>{var i;let t=e.target;if(!t)return;let n=(i=t.tagName)==null?void 0:i.toLowerCase(),r=t.src||t.href;if(n&&r&&["img","script","link","audio","video"].includes(n))try{if(this.shouldIgnoreScriptUrl(r)||!this.shouldSampleResource())return;let s=`resource:${n}`,a=x(r);this.client.captureEvent({type:"error",level:"warning",message:`Resource load failed: ${n} ${a}`,timestamp:d(),fingerprint:s,tags:{resource_type:n,resource_url:a},exception:{type:"ResourceError",value:`Failed to load ${n} resource`}})}catch(s){console.error("[LightSDK] ErrorPlugin resource error handler error:",s)}},window.addEventListener("error",this.onResourceError,!0))}buildErrorEvent(e,t,n,r){let i=d();if(e instanceof Error){if(this.shouldIgnoreError(e.message))return null;let c=P(e.stack,{captureNodeModules:this.config.captureNodeModules,captureColumn:this.config.captureColumn,relativePathOnly:this.config.relativePathOnly,maxFrames:this.config.maxStackFrames});if(!this.shouldIncludePath(c)||!this.shouldSample())return null;let u=L(e.name,e.message,c);return{type:"error",level:"error",message:e.message,timestamp:i,exception:{type:e.name,value:e.message,stacktrace:{frames:c}},fingerprint:u}}let s=String(e);if(this.shouldIgnoreError(s))return null;let a=[];return t&&a.push({filename:t,lineno:n,colno:this.config.captureColumn?r:void 0,in_app:!0}),!this.shouldIncludePath(a)||!this.shouldSample()?null:{type:"error",level:"error",message:s,timestamp:i,exception:{type:"Error",value:s,stacktrace:{frames:a}}}}destroy(){typeof window!="undefined"&&(this.originalOnError!==void 0&&(window.onerror=this.originalOnError),this.onUnhandledRejection&&window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this.onResourceError&&window.removeEventListener("error",this.onResourceError,!0))}},j=H;var $=class{constructor(){this.name="performance";this.version="1.0.0";this.config={sampleRate:.1,captureLongTasks:!0,captureResources:!1,resourceSampleRate:.01,longTaskSampleRate:.05,captureNavigation:!0,captureFP:!0};this.observers=[];this.navLoadTimer=null;this.totalBlockingTime=0;this.fcpTime=null;this.lastLongTaskEndTime=0;this.ttiReported=!1;this.ttiTimer=null}setup(e){this.client=e,this.loadConfig(),this.observeWebVitals(),this.observeLongTasks(),this.observeNavigation(),this.observeResources()}loadConfig(){let e=this.client.config;e&&y(e.performance)&&(this.config={...this.config,...e.performance})}shouldSample(e="default"){var n,r,i;let t=(n=this.config.sampleRate)!=null?n:.1;return e==="resource"?t=(r=this.config.resourceSampleRate)!=null?r:.01:e==="longtask"?t=(i=this.config.longTaskSampleRate)!=null?i:.05:e==="vitals"&&(t=1),t>=1?!0:t<=0?!1:Math.random()<t}observeWebVitals(){typeof PerformanceObserver!="undefined"&&(this.config.captureFP&&this.observeFP(),this.observeLCP(),this.observeFID(),this.observeCLS(),this.observeFCP(),this.observeTTFB())}observeFP(){try{let e=new PerformanceObserver(t=>{let n=t.getEntriesByName("first-paint");n.length>0&&this.reportMetric("FP",n[0].startTime,"ms",{},"vitals")});e.observe({type:"paint",buffered:!0}),this.observers.push(e)}catch(e){}}observeLCP(){try{let e=new PerformanceObserver(t=>{let n=t.getEntries(),r=n[n.length-1];if(r){let i=r.renderTime||r.loadTime||r.startTime;this.reportMetric("LCP",i,"ms",{},"vitals")}});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch(e){}}observeFID(){try{let e=new PerformanceObserver(t=>{let n=t.getEntries();if(n.length>0){let r=n[0],i=r.processingStart-r.startTime;this.reportMetric("FID",i,"ms",{},"vitals")}});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch(e){}}observeCLS(){try{let e=0,t=0,n=[],r=new PerformanceObserver(i=>{let s=i.getEntries();for(let a of s)if(!a.hadRecentInput){let c=n[0],u=n[n.length-1];t&&a.startTime-((u==null?void 0:u.duration)||0)<1e3&&a.startTime-c.startTime<5e3?(t+=a.value||0,n.push(a)):(t=a.value||0,n=[a]),t>e&&(e=t,this.reportMetric("CLS",e,"",{},"vitals"))}});r.observe({type:"layout-shift",buffered:!0}),this.observers.push(r)}catch(e){}}observeFCP(){try{let e=new PerformanceObserver(t=>{let n=t.getEntriesByName("first-contentful-paint");n.length>0&&(this.fcpTime=n[0].startTime,this.lastLongTaskEndTime=n[0].startTime,this.reportMetric("FCP",n[0].startTime,"ms",{},"vitals"),this.scheduleTTI())});e.observe({type:"paint",buffered:!0}),this.observers.push(e)}catch(e){}}observeTTFB(){try{let e=new PerformanceObserver(t=>{let n=t.getEntriesByType("navigation");if(n.length>0){let r=n[0],i=r.responseStart-r.requestStart;this.reportMetric("TTFB",Math.max(0,i),"ms",{},"vitals")}});e.observe({type:"navigation",buffered:!0}),this.observers.push(e)}catch(e){}}observeLongTasks(){if(this.config.captureLongTasks)try{let e=new PerformanceObserver(t=>{let n=t.getEntries();for(let r of n){let i=r.startTime+r.duration;if(i>this.lastLongTaskEndTime&&(this.lastLongTaskEndTime=i),this.fcpTime!==null&&r.startTime>=this.fcpTime){let s=r.duration-50;s>0&&(this.totalBlockingTime+=s)}this.reportMetric("longtask",r.duration,"ms",{},"longtask"),this.scheduleTTI()}});e.observe({type:"longtask",buffered:!0}),this.observers.push(e)}catch(e){}}scheduleTTI(){this.ttiReported||(this.ttiTimer&&clearTimeout(this.ttiTimer),this.ttiTimer=setTimeout(()=>{if(this.ttiReported)return;this.ttiReported=!0;let e=Math.max(this.lastLongTaskEndTime,this.fcpTime||0);this.reportMetric("TTI",e,"ms",{},"vitals"),this.reportMetric("TBT",this.totalBlockingTime,"ms",{},"vitals")},5e3))}observeNavigation(){this.config.captureNavigation&&typeof performance!="undefined"&&(this.onLoad=()=>{this.navLoadTimer=setTimeout(()=>{let e=performance.timing;if(!e)return;let t=e.navigationStart,n={dom_ready:e.domContentLoadedEventEnd-t,load_time:e.loadEventEnd-t,dns:e.domainLookupEnd-e.domainLookupStart,tcp:e.connectEnd-e.connectStart,ssl:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,dom_parse:e.domInteractive-e.responseEnd};for(let[r,i]of Object.entries(n))i>0&&this.reportMetric(r,i,"ms");this.navLoadTimer=null},0)},window.addEventListener("load",this.onLoad))}observeResources(){if(this.config.captureResources&&typeof performance!="undefined")try{let e=new PerformanceObserver(t=>{let n=t.getEntriesByType("resource");for(let r of n)r.duration>1e3&&this.reportMetric("resource_slow",r.duration,"ms",{resource_name:r.name.substring(0,200),resource_type:r.initiatorType},"resource")});e.observe({type:"resource",buffered:!0}),this.observers.push(e)}catch(e){}}getRating(e,t){let r={LCP:{good:2500,poor:4e3},FCP:{good:1800,poor:3e3},FP:{good:1800,poor:3e3},FID:{good:100,poor:300},CLS:{good:.1,poor:.25},TTFB:{good:800,poor:1800}}[e];return!r||t<=r.good?"good":t<=r.poor?"needs-improvement":"poor"}reportMetric(e,t,n,r={},i="default"){if(!this.shouldSample(i))return;let s=this.getRating(e,t),a={type:"performance",level:"info",metric:e,value:Math.round(t*100)/100,unit:n,rating:s,timestamp:d(),tags:{metric:e,rating:s,...r}};this.client.captureEvent(a)}destroy(){for(let e of this.observers)try{e.disconnect()}catch(t){}this.observers=[],this.ttiTimer&&(clearTimeout(this.ttiTimer),this.ttiTimer=null),this.navLoadTimer&&(clearTimeout(this.navLoadTimer),this.navLoadTimer=null),typeof window!="undefined"&&this.onLoad&&window.removeEventListener("load",this.onLoad)}},W=$;var X=class{constructor(){this.name="network";this.version="1.0.0";this.config={captureXHR:!0,captureFetch:!0,captureSuccess:!1,captureBody:!1,captureRequestBody:!1,captureResponseBody:!1,captureRequestHeaders:["content-type","user-agent"],captureResponseHeaders:["content-type","content-length"],errorSampleRate:1,successSampleRate:.01,slowThreshold:3e3,slowSampleRate:1,ignoreStatusCodes:[]}}setup(e){this.client=e,this.loadConfig(),this.config.captureFetch&&this.patchFetch(),this.config.captureXHR&&this.patchXHR()}loadConfig(){let e=this.client.config;e&&y(e.network)&&(this.config={...this.config,...e.network}),e.ignoreUrls&&(this.config.ignoreUrls=[...this.config.ignoreUrls||[],...e.ignoreUrls])}shouldIgnore(e){return C(e,this.config.ignoreUrls||[])}shouldSample(e,t){var r,i,s,a;let n=e?(r=this.config.errorSampleRate)!=null?r:1:(i=this.config.successSampleRate)!=null?i:.01;return!e&&t>=((s=this.config.slowThreshold)!=null?s:3e3)&&(n=(a=this.config.slowSampleRate)!=null?a:1),n>=1?!0:n<=0?!1:Math.random()<n}patchFetch(){if(typeof fetch=="undefined")return;this.originalFetch=window.fetch;let e=this;window.fetch=function(t,n){let r=d(),i=typeof t=="string"?t:t instanceof URL?t.toString():t.url,s=(n==null?void 0:n.method)||"GET";if(e.shouldIgnore(i))return e.originalFetch.call(window,t,n);let a=x(i),c=e.originalFetch.call(window,t,n);return c.then(u=>{var h;let p=d()-r,w=u.ok,f=u.status;return(h=e.config.ignoreStatusCodes)!=null&&h.includes(f)||!e.shouldSample(!w,p)||(!w||e.config.captureSuccess)&&e.reportNetwork({sub_type:"fetch",method:s.toUpperCase(),url:a,status_code:f,duration:p,success:w,error:w?void 0:`HTTP ${f}`}),u},u=>{let p=d()-r;throw e.shouldSample(!0,p)&&e.reportNetwork({sub_type:"fetch",method:s.toUpperCase(),url:a,duration:p,success:!1,error:(u==null?void 0:u.message)||"Network error"}),u}),c}}patchXHR(){if(typeof XMLHttpRequest=="undefined")return;this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;let e=this;XMLHttpRequest.prototype.open=function(t,n){return this._lightMethod=t,this._lightUrl=typeof n=="string"?n:n.toString(),this._lightTracked=!1,e.originalXHROpen.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){let n=d(),r=this._lightMethod||"GET",i=this._lightUrl||"",s=this._lightTracked;if(e.shouldIgnore(i)||s)return e.originalXHRSend.apply(this,arguments);this._lightTracked=!0;let a=x(i),c=0;t&&typeof t=="string"&&(c=t.length);let u=this.onloadend;return this.onloadend=function(p){var v;let w=d()-n,f=this.status,h=f>=200&&f<300;if(!((v=e.config.ignoreStatusCodes)!=null&&v.includes(f))&&e.shouldSample(!h,w)&&(!h||e.config.captureSuccess)){let g=0;try{let E=this.getResponseHeader("content-length");E&&(g=parseInt(E,10)),!g&&this.responseText&&(g=this.responseText.length)}catch(E){}e.reportNetwork({sub_type:"xhr",method:r.toUpperCase(),url:a,status_code:f,duration:w,request_size:c||void 0,response_size:g||void 0,success:h,error:h?void 0:`HTTP ${f}`})}if(u)return u.call(this,p)},e.originalXHRSend.apply(this,arguments)}}reportNetwork(e){let t={type:"network",level:e.success?"info":"error",timestamp:d(),tags:{method:e.method,sub_type:e.sub_type,success:String(e.success)},...e};this.client.captureEvent(t)}destroy(){this.originalFetch&&(window.fetch=this.originalFetch),this.originalXHROpen&&(XMLHttpRequest.prototype.open=this.originalXHROpen),this.originalXHRSend&&(XMLHttpRequest.prototype.send=this.originalXHRSend)}},A=X;var K=class{constructor(){this.name="behavior";this.version="1.0.0";this.config={capturePV:!0,captureClick:!0,captureRoute:!0,captureDuration:!0,captureScroll:!0,clickThrottle:300,scrollThrottle:1e3,sampleRate:.01};this.lastClickTime=0;this.lastScrollTime=0;this.maxScrollDepth=0;this.pageEnterTime=0;this.scrollReported=!1}setup(e){this.client=e,this.loadConfig(),this.config.capturePV&&this.trackPV(),this.config.captureClick&&this.trackClick(),this.config.captureRoute&&this.trackRoute(),this.config.captureDuration&&this.trackPageDuration(),this.config.captureScroll&&this.trackScroll()}loadConfig(){let e=this.client.config;e&&y(e.behavior)&&(this.config={...this.config,...e.behavior})}shouldSample(){var t;let e=(t=this.config.sampleRate)!=null?t:.01;return e>=1?!0:e<=0?!1:Math.random()<e}getScrollDepth(){if(typeof window=="undefined"||typeof document=="undefined")return 0;let e=window.scrollY||document.documentElement.scrollTop,t=document.documentElement.scrollHeight,n=document.documentElement.clientHeight;return t<=n?100:Math.min(100,Math.round(e/(t-n)*100))}trackPV(){if(typeof window=="undefined")return;let e=b(),t=x(document.referrer||"");this.reportBehavior({sub_type:"pv",page_url:e,referrer:t,properties:{title:document.title,user_agent:navigator.userAgent,screen_width:screen.width,screen_height:screen.height,viewport_width:window.innerWidth,viewport_height:window.innerHeight,language:navigator.language}})}trackClick(){typeof document!="undefined"&&(this.onClick=e=>{var a,c,u;let t=d(),n=(a=this.config.clickThrottle)!=null?a:300;if(t-this.lastClickTime<n)return;this.lastClickTime=t;let r=e.target;if(!r||!r.tagName)return;let i=r.tagName.toLowerCase()||"";if(r.id&&(i+=`#${r.id}`),r.className&&typeof r.className=="string"){let p=r.className.split(" ").filter(Boolean).slice(0,3).join(".");p&&(i+=`.${p}`)}let s=(c=r.textContent)==null?void 0:c.trim().slice(0,50);this.reportBehavior({sub_type:"click",page_url:b(),properties:{selector:i,text:s||void 0,tag:(u=r.tagName)==null?void 0:u.toLowerCase(),x:e.clientX,y:e.clientY}})},document.addEventListener("click",this.onClick,!0))}trackRoute(){if(typeof window=="undefined")return;let e=b(),t=()=>{let r=b();if(r!==e){let i=e,s=r;e=r,this.reportBehavior({sub_type:"route",page_url:s,referrer:i,properties:{from:i,to:s}}),this.pageEnterTime=d(),this.maxScrollDepth=0,this.scrollReported=!1}};this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;let n=this;history.pushState=function(){let r=n.originalPushState.apply(this,arguments);return setTimeout(t,0),r},history.replaceState=function(){let r=n.originalReplaceState.apply(this,arguments);return setTimeout(t,0),r},this.onPopState=()=>{setTimeout(t,0)},this.onHashchange=()=>{setTimeout(t,0)},window.addEventListener("popstate",this.onPopState),window.addEventListener("hashchange",this.onHashchange)}trackPageDuration(){if(typeof window=="undefined")return;this.pageEnterTime=d();let e=()=>{let t=d()-this.pageEnterTime;t>1e3&&(this.config.captureScroll&&!this.scrollReported&&this.reportScroll(),this.reportBehavior({sub_type:"duration",page_url:b(),properties:{duration:t,max_scroll_depth:this.maxScrollDepth}}))};this.onVisibilityChange=()=>{document.hidden?e():this.pageEnterTime=d()},this.onBeforeUnload=e,this.onPagehide=e,document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("beforeunload",this.onBeforeUnload),window.addEventListener("pagehide",this.onPagehide)}trackScroll(){typeof window!="undefined"&&(this.onScroll=()=>{var r;let e=d(),t=(r=this.config.scrollThrottle)!=null?r:1e3;if(e-this.lastScrollTime<t)return;this.lastScrollTime=e;let n=this.getScrollDepth();n>this.maxScrollDepth&&(this.maxScrollDepth=n)},window.addEventListener("scroll",this.onScroll,{passive:!0}))}reportScroll(){this.scrollReported||(this.scrollReported=!0,this.reportBehavior({sub_type:"scroll",page_url:b(),properties:{max_depth:this.maxScrollDepth}}))}reportBehavior(e){if(!this.shouldSample())return;let t={type:"behavior",level:"info",timestamp:d(),tags:{sub_type:e.sub_type,page_url:b()},...e};this.client.captureEvent(t)}destroy(){typeof window!="undefined"&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.onPopState&&window.removeEventListener("popstate",this.onPopState),this.onHashchange&&window.removeEventListener("hashchange",this.onHashchange),this.onBeforeUnload&&window.removeEventListener("beforeunload",this.onBeforeUnload),this.onPagehide&&window.removeEventListener("pagehide",this.onPagehide),this.onScroll&&window.removeEventListener("scroll",this.onScroll)),typeof document!="undefined"&&(this.onClick&&document.removeEventListener("click",this.onClick,!0),this.onVisibilityChange&&document.removeEventListener("visibilitychange",this.onVisibilityChange))}},V=K;var _e="light-sentry-offline",m="events",z=1e3,Q=class{constructor(){this.name="offline";this.version="1.0.0";this.config={maxEvents:z};this.db=null;this.isOnline=!0;this.isSyncing=!1;this.pendingEvents=[]}setup(e){this.client=e,this.loadConfig(),this.initDatabase(),this.setupNetworkListeners()}loadConfig(){let e=this.client.config;e&&typeof e.offline=="object"&&(this.config={...this.config,...e.offline})}async initDatabase(){if(typeof indexedDB=="undefined"){console.warn("[LightSDK] OfflinePlugin: IndexedDB not available");return}return new Promise((e,t)=>{let n=indexedDB.open(_e,1);n.onerror=()=>{console.warn("[LightSDK] OfflinePlugin: Failed to open IndexedDB"),t(n.error)},n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=r=>{let i=r.target.result,s=r.oldVersion;i.objectStoreNames.contains(m)||i.createObjectStore(m,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})}})}setupNetworkListeners(){typeof window!="undefined"&&(this.isOnline=navigator.onLine,this.onOnline=()=>{console.info("[LightSDK] OfflinePlugin: Network online"),this.isOnline=!0,this.syncPendingEvents()},this.onOffline=()=>{console.info("[LightSDK] OfflinePlugin: Network offline"),this.isOnline=!1},window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline))}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async saveToIndexedDB(e){if(!this.db)return;let t=this.config.maxEvents||z,n=await this.getEventCount();return n>=t&&await this.deleteOldestEvents(n-t+1),new Promise((r,i)=>{let a=this.db.transaction([m],"readwrite").objectStore(m),c={id:this.generateId(),event:{...e,offline:!0},timestamp:d()},u=a.add(c);u.onsuccess=()=>r(),u.onerror=()=>i(u.error)})}getEventCount(){return this.db?new Promise((e,t)=>{let i=this.db.transaction([m],"readonly").objectStore(m).count();i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)}):Promise.resolve(0)}async deleteOldestEvents(e){if(!(!this.db||e<=0))return new Promise((t,n)=>{let a=this.db.transaction([m],"readwrite").objectStore(m).index("timestamp").openCursor(),c=0;a.onsuccess=u=>{let p=u.target.result;p&&c<e?(p.delete(),c++,p.continue()):t()},a.onerror=()=>n(a.error)})}async getAllStoredEvents(){return this.db?new Promise((e,t)=>{let s=this.db.transaction([m],"readonly").objectStore(m).index("timestamp").getAll();s.onsuccess=()=>{let a=s.result||[];a.sort((c,u)=>c.timestamp-u.timestamp),e(a)},s.onerror=()=>t(s.error)}):[]}async clearStoredEvents(){if(this.db)return new Promise((e,t)=>{let i=this.db.transaction([m],"readwrite").objectStore(m).clear();i.onsuccess=()=>e(),i.onerror=()=>t(i.error)})}async syncPendingEvents(){if(!(!this.isOnline||this.isSyncing)){this.isSyncing=!0,console.info("[LightSDK] OfflinePlugin: Syncing pending events");try{let e=0;for(;this.pendingEvents.length>0;){let n=this.pendingEvents.shift();try{this.client.captureEvent(n),e++}catch(r){console.error("[LightSDK] OfflinePlugin: Failed to re-enqueue memory event",r)}}let t=await this.getAllStoredEvents();if(t.length>0)for(let n of t)try{let r=n.event;this.client.captureEvent(r),e++}catch(r){console.error("[LightSDK] OfflinePlugin: Failed to re-enqueue event",r)}try{await this.client.flush()}catch(n){}await this.clearStoredEvents(),console.info(`[LightSDK] OfflinePlugin: Synced ${e} events`)}catch(e){console.error("[LightSDK] OfflinePlugin: Sync failed",e)}finally{this.isSyncing=!1}}}beforeReport(e){if(!this.isOnline){let n=this.config.maxEvents||z;return this.pendingEvents.length>=n&&this.pendingEvents.shift(),this.pendingEvents.push(e),this.savePendingEventsToDB(),null}let t={...e};return delete t.offline,t}savePendingEventsToDB(){if(this.pendingEvents.length===0)return;let e=this.pendingEvents.splice(0,this.pendingEvents.length),t=0,n=()=>{if(t>=e.length)return;let r=e[t];this.saveToIndexedDB(r).then(()=>{t++,n()}).catch(i=>{console.error("[LightSDK] OfflinePlugin: Failed to save event offline",i),this.pendingEvents.unshift(...e.slice(t))})};n()}destroy(){typeof window!="undefined"&&(this.onOnline&&window.removeEventListener("online",this.onOnline),this.onOffline&&window.removeEventListener("offline",this.onOffline)),this.db&&(this.db.close(),this.db=null)}},G=Q;var J=class{constructor(){this.name="sampling";this.version="1.0.0";this.config={rates:{error:1,performance:1,network:1,behavior:1}}}setup(e){this.client=e,this.loadConfig()}loadConfig(){let e=this.client.config;if(e&&y(e.sampling)){let t=e.sampling;"rates"in t&&y(t.rates)&&(this.config.rates={...this.config.rates,...t.rates})}}shouldSample(e){var r;let t=(r=this.client.config.sampleRate)!=null?r:1;if(t<=0)return!1;let n=this.getTypeRate(e);return t>=1?this.randomCheck(n):this.randomCheck(t*n)}getTypeRate(e){let t=this.config.rates||{},n=e.type;if(n==="count")return 1;let r=t[n];return r!==void 0?r:1}randomCheck(e){return e>=1?!0:e<=0?!1:Math.random()<e}beforeReport(e){return this.shouldSample(e)?e:null}destroy(){}},Z=J;var l=null;function ae(o){var r;let e=new q(o),t=[new G,new Z,new j],n=((r=o.plugins)==null?void 0:r.filter(i=>typeof i=="string"))||[];(n.includes("performance")||n.includes("all"))&&t.push(new W),(n.includes("network")||n.includes("all"))&&t.push(new A),(n.includes("behavior")||n.includes("all"))&&t.push(new V);for(let i of t)e.use(i);if(o.plugins)for(let i of o.plugins)typeof i=="object"&&i!==null&&"name"in i&&"setup"in i&&e.use(i);return e.init(),l=e,e}function ce(){return l}function ue(o){l==null||l.captureException(o)}function le(o,e){l==null||l.captureMessage(o,e)}function de(o){l==null||l.captureEvent(o)}function pe(o){l==null||l.setUser(o)}function he(o,e){l==null||l.setTag(o,e)}function fe(o){l==null||l.setTags(o)}function ge(o,e){l==null||l.setExtra(o,e)}function me(o){l==null||l.addBreadcrumb(o)}async function ve(){await(l==null?void 0:l.flush())}function ye(){l==null||l.disable()}function be(){l==null||l.enable()}var Oe={init:ae,getClient:ce,captureException:ue,captureMessage:le,captureEvent:de,setUser:pe,setTag:he,setTags:fe,setExtra:ge,addBreadcrumb:me,flush:ve,disable:ye,enable:be};
|