light-sentry-sdk/dist/index.cjs.js

4 lines
50 KiB
JavaScript

"use strict";var q=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Ce=Object.prototype.hasOwnProperty;var Le=(s,e)=>{for(var t in e)q(s,t,{get:e[t],enumerable:!0})},Te=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ke(e))!Ce.call(s,r)&&r!==t&&q(s,r,{get:()=>e[r],enumerable:!(n=Re(e,r))||n.enumerable});return s};var Pe=s=>Te(q({},"__esModule",{value:!0}),s);var Ue={};Le(Ue,{BehaviorPlugin:()=>J,Client:()=>j,ErrorPlugin:()=>X,NetworkPlugin:()=>Q,OfflinePlugin:()=>ee,PerformancePlugin:()=>z,SamplingPlugin:()=>ne,addBreadcrumb:()=>Ee,captureEvent:()=>ge,captureException:()=>he,captureMessage:()=>fe,default:()=>Ne,disable:()=>Se,enable:()=>xe,flush:()=>we,getClient:()=>pe,init:()=>de,setExtra:()=>be,setTag:()=>ve,setTags:()=>ye,setUser:()=>me});module.exports=Pe(Ue);function ie(s){try{let e=s.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 C(s){return`${s.protocol}://${s.host}/api/${s.projectId}/envelope/?sentry_key=${s.publicKey}`}function se(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[x]/g,()=>(Math.random()*16|0).toString(16))}function p(){return Date.now()}function b(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}function L(s,e){return!e||e.length===0?!1:e.some(t=>typeof t=="string"?s.includes(t):t.test(s))}function Me(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return e>>>0}function N(s){return Me(s).toString(16)}function T(s,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 N(`${s}:${r}:${n}`)}function P(s,e={}){if(!s)return[];let{captureNodeModules:t=!1,captureColumn:n=!0,relativePathOnly:r=!1,maxFrames:i}=e,o=[],a=s.split(`
`),u=typeof location!="undefined"?`${location.protocol}//${location.host}`:"";for(let h of a){let w=h.match(/^\s*at\s*(.+?)\s*\((.+?):(\d+):(\d+)\)\s*$/);if(w){let[,g,f,y,m]=w,S=f.includes("node_modules");if(!t&&S)continue;let x=f;r&&u&&f.startsWith(u)&&(x=f.substring(u.length)),o.push({filename:x,function:g,lineno:parseInt(y,10),colno:n?parseInt(m,10):void 0,in_app:!S})}else{let g=h.match(/^\s*at\s*(.+?)@(.+?):(\d+):(\d+)\s*$/);if(g){let[,y,m,S,x]=g,k=m.includes("node_modules");if(!t&&k)continue;let re=m;r&&u&&m.startsWith(u)&&(re=m.substring(u.length)),o.push({filename:re,function:y||"<anonymous>",lineno:parseInt(S,10),colno:n?parseInt(x,10):void 0,in_app:!k});continue}let f=h.match(/^\s*at\s*(.+?):(\d+):(\d+)\s*$/);if(f){let[,y,m,S]=f,x=y.includes("node_modules");if(!t&&x)continue;let k=y;r&&u&&y.startsWith(u)&&(k=y.substring(u.length)),o.push({filename:k,lineno:parseInt(m,10),colno:n?parseInt(S,10):void 0,in_app:!x})}}}let c=o.reverse();return i!==void 0&&i>0?c.slice(0,i):c}var U=!1;function M(s){U=s}function l(s,e,t){if(!U)return;let n=new Date().toISOString(),r=`[LightSDK][${s}]`;t!==void 0?console.log(`${r} ${n} ${e}`,t):console.log(`${r} ${n} ${e}`)}function H(s,e,t){if(!U)return;let n=new Date().toISOString(),r=`[LightSDK][${s}][ERROR]`;t!==void 0?console.error(`${r} ${n} ${e}`,t):console.error(`${r} ${n} ${e}`)}function De(s){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=s.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 Ie(s){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=s.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 Be(s){let e=/Mobile|Android|iPhone|iPod|BlackBerry|Windows Phone|Opera Mini/i.test(s),t=/Tablet|iPad|PlayBook|Kindle|Silk/i.test(s),n="desktop";t?n="tablet":e&&(n="mobile");let r="",i="",o=s.match(/iPhone/i),a=s.match(/iPad/i),u=s.match(/SM-([A-Z0-9]+)/i),c=s.match(/Pixel ([0-9A-Z]+)/i),h=s.match(/HUAWEI ([A-Z0-9]+)/i);return o?(r="Apple",i="iPhone"):a?(r="Apple",i="iPad"):u?(r="Samsung",i=u[1]):c?(r="Google",i=`Pixel ${c[1]}`):h&&(r="Huawei",i=h[1]),{type:n,vendor:r,model:i}}function oe(){let s=typeof navigator!="undefined"?navigator.userAgent:"",e=De(s),t=Ie(s),n=Be(s);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:s,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 E(){return typeof location!="undefined"?location.href:""}function ae(){return typeof document!="undefined"?document.referrer:""}function R(s){if(!s)return s;try{let e=new URL(s),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 o=i.toLowerCase().replace(/[-_]/g,"_");t.some(a=>o.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 o=new URLSearchParams(i),a=!1;for(let u of Array.from(o.keys())){let c=u.toLowerCase().replace(/[-_]/g,"_");t.some(h=>c.includes(h))&&(o.set(u,"[Filtered]"),a=!0)}a&&(e.hash="#"+o.toString(),r=!0)}}return r?e.toString():s}catch(e){return s}}function D(s,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(s)}return s.includes(t)}return t.test(s)})}var _e={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"},Oe={"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 $(){let s=oe(),e=_e[s.browser.name]||s.browser.name.toLowerCase(),t=Oe[s.os.name]||s.os.name.toLowerCase();return{browser:{name:e,version:s.browser.major},os:{name:t,version:s.os.version.split(".")[0]},device:{type:s.device.type,brand:s.device.vendor||void 0,model:s.device.model||void 0}}}function ue(){let s=oe(),e=`${s.browser.name}|${s.browser.major}|${s.os.name}|${s.os.version.split(".")[0]}|${s.device.type}|${s.device.vendor}|${s.device.model}|${s.language}`;return N(e).substring(0,16)}var Fe={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}}},I=class{constructor(e){this.contexts=null;this.contextId=null;this.contextReported=!1;this.config={...Fe,...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 L(e,this.config.ignoreErrors||[])}getEncodedContext(){return this.contexts||(this.contexts=$()),this.contexts}applyToEvent(e,t=!0){var i,o,a,u;let n={...e};if(e.tags&&(n.tags={...e.tags}),e.request&&(n.request={...e.request}),"exception"in e&&e.exception){let c=e.exception;n.exception={...c,stacktrace:c.stacktrace?{...c.stacktrace,frames:c.stacktrace.frames?c.stacktrace.frames.map(h=>({...h})):void 0}:void 0}}e.breadcrumbs&&(n.breadcrumbs=e.breadcrumbs.map(c=>({...c}))),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=E()):n.request={url:E(),referrer:ae()},this.contextId||(this.contextId=ue()),n.context_id=this.contextId;let r=this.applyContextLevel(n);return t&&!this.contextReported&&(this.contexts||(this.contexts=$()),r.contexts=this.contexts,r.env={b:(i=this.contexts.browser)==null?void 0:i.name,bv:(o=this.contexts.browser)==null?void 0:o.version,os:(a=this.contexts.os)==null?void 0:a.name,osv:(u=this.contexts.os)==null?void 0:u.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 o=e.exception;if(o.stacktrace&&typeof o.stacktrace=="object"){let a=o.stacktrace;Array.isArray(a.frames)&&(r.maxStackFrames===0?delete i.exception:i.exception={...o,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 _=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=p(),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(l("EventQueue","enqueue called",{type:e.type,level:e.level,message:"message"in e?e.message:void 0}),this.paused){l("EventQueue","enqueue skipped: queue paused (infinite loop detected)");return}this.cleanupExpiredDedupeEntries();let t=this.getDedupeKey(e);if(t){if(this.checkInfiniteLoop(t)){l("EventQueue","enqueue skipped: infinite loop detected",{fingerprint:t});return}let n=p(),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}l("EventQueue","enqueue skipped: deduped (count >= 3)",{fingerprint:t,count:r.count});return}r.count++,r.lastTime=n,l("EventQueue","Dedup count incremented",{fingerprint:t,count:r.count})}else this.dedupeMap.set(t,{count:1,lastTime:n,firstReported:!0}),this.pendingCounts.delete(t),l("EventQueue","Dedup entry reset (expired)",{fingerprint:t});else this.dedupeMap.set(t,{count:1,lastTime:n,firstReported:!1}),l("EventQueue","New dedup entry created",{fingerprint:t})}this.queue.push(e),l("EventQueue","Event added to queue",{queueSize:this.queue.length}),this.eventBus.emit("event",e),this.queue.length>=this.maxSize&&(l("EventQueue","Queue reached maxSize, triggering flush",{maxSize:this.maxSize}),this.flush())}cleanupExpiredDedupeEntries(){if(this.dedupeMap.size<100&&Math.random()>.1)return;let e=p(),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:p(),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(l("EventQueue","flush called",{queueSize:this.queue.length,pendingCounts:this.pendingCounts.size,isFlushing:this.isFlushing}),this.queue.length===0&&this.pendingCounts.size===0){l("EventQueue","flush skipped: queue is empty");return}if(this.isFlushing){l("EventQueue","flush skipped: already flushing");return}this.isFlushing=!0;let e=this.queue.splice(0,this.queue.length),t=this.buildCountEvents(),n=[...e,...t];l("EventQueue","flush events to callback",{total:n.length,events:e.length,countEvents:t.length}),this.lastFlushTime=p(),this.eventBus.emit("report",n);try{await this.flushCallback(n),this.pendingCounts.clear(),l("EventQueue","flush completed successfully"),this.eventBus.emit("reported",n)}catch(r){throw l("EventQueue","flush failed, returning events to queue",{error:r instanceof Error?r.message:String(r)}),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=p(),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(o=>this.queue.unshift(o));for(let[o,a]of t)this.pendingCounts.has(o)||this.pendingCounts.set(o,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 ce={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"},tt=Object.fromEntries(Object.entries(ce).map(([s,e])=>[e,s]));function le(s){if(!s||typeof s!="object")return s;let e={};for(let[t,n]of Object.entries(s)){let r=ce[t]||t;e[r]=n}return e}var O=class{constructor(e,t,n){this.useShortFields=!0;this.dsn=e,this.maxRetries=t,this.retryDelay=n}async report(e){if(l("Reporter","report called",{eventCount:e.length}),e.length===0){l("Reporter","report skipped: empty events");return}let t=this.buildEnvelope(e),n=C(this.dsn);l("Reporter","Envelope built",{envelopeSize:t.length,url:n});let r=0;for(;r<=this.maxRetries;)try{l("Reporter",`Sending request (attempt ${r+1}/${this.maxRetries+1})`),await this.send(t,!1),l("Reporter","Request succeeded");return}catch(i){let o=i.status;if(H("Reporter",`Request failed (attempt ${r+1})`,{status:o,error:i}),o&&o>=400&&o<500)throw i;if(r++,r>this.maxRetries)throw H("Reporter","All retries exhausted"),i;let a=Math.min(this.retryDelay*Math.pow(2,r-1),5e3);l("Reporter",`Retrying in ${a}ms`),await this.delay(a)}}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:se(),sent_at:new Date().toISOString(),meta:t};this.useShortFields&&(n._sf=1);let r=this.applyRelativeTimestamps(e,n),o=[JSON.stringify(n)];for(let a of r){let u=this.stripSharedFields(a,t);this.useShortFields&&(u=le(u));let c=JSON.stringify(u),h=JSON.stringify({type:this.getEnvelopeType(a),length:c.length});o.push(h,c)}return o.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 o={...e[i]};if(i===0)n.push(o);else{let u=(o.timestamp?new Date(o.timestamp).getTime():Date.now())-r;if(delete o.timestamp,o._dts=u,o.start_timestamp){let h=new Date(o.start_timestamp).getTime()-r;delete o.start_timestamp,o._dsts=h}n.push(o)}}return n}extractSharedMeta(e){if(e.length===0)return{};let t=e[0],n={};t.release&&e.every(o=>o.release===t.release)&&(n.release=t.release),t.environment&&e.every(o=>o.environment===t.environment)&&(n.environment=t.environment),t.user&&e.every(o=>JSON.stringify(o.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=C(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),o=await fetch(n,{method:"POST",body:e,headers:{"Content-Type":"application/x-sentry-envelope"},keepalive:!0,signal:r.signal});if(clearTimeout(i),o.ok)return;let a=new Error(`HTTP ${o.status}`);throw a.status=o.status,a}catch(r){throw r}if(typeof XMLHttpRequest!="undefined")return new Promise((r,i)=>{let o=new XMLHttpRequest;o.open("POST",n,!t),o.setRequestHeader("Content-Type","application/x-sentry-envelope"),o.timeout=1e4,o.onload=()=>{if(o.status>=200&&o.status<300)r();else{let a=new Error(`HTTP ${o.status}`);a.status=o.status,i(a)}},o.onerror=()=>i(new Error("Network error")),o.ontimeout=()=>i(new Error("Request timeout")),o.send(e)});throw new Error("No transport available")}sendSync(e){let t=C(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=C(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 F=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 K=class{constructor(e){this.breadcrumbs=[];this.enabled=!0;var t,n,r,i;if(!e.dsn)throw new Error("DSN is required");M(e.debug===!0),l("Client","Initializing SDK",{dsn:e.dsn,debug:e.debug,enabled:e.enabled!==!1}),this.dsn=ie(e.dsn),this.configManager=new I(e),this.eventBus=new B,this.reporter=new O(this.dsn,(t=this.configManager.get("maxRetries"))!=null?t:3,(n=this.configManager.get("retryDelay"))!=null?n:1e3),this.pluginManager=new F(this),this.queue=new _((r=this.configManager.get("maxQueueSize"))!=null?r:100,(i=this.configManager.get("flushInterval"))!=null?i:5e3,this.eventBus,async o=>this.flushEvents(o),o=>this.syncFlushEvents(o)),this.enabled=this.configManager.get("enabled")!==!1,l("Client","SDK initialized",{enabled:this.enabled})}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){l("Client","flushEvents start",{eventCount:e.length});let t=[];for(let i of e){let o=this.pluginManager.applyBeforeReport(i);o?t.push(o):l("Client","Event filtered by beforeReport plugin",{type:i.type,message:"message"in i?i.message:void 0})}if(t.length===0){l("Client","flushEvents: all events filtered by beforeReport");return}let n=!0,r=[];for(let i of t){let o=this.configManager.applyToEvent(i,n);n=!1;let a=this.configManager.get("beforeSend"),u=a?a(o):o;if(!u){l("Client","Event filtered by beforeSend",{type:i.type});continue}r.push(u)}if(r.length===0){l("Client","flushEvents: all events filtered by beforeSend");return}l("Client","Reporting events",{count:r.length}),await this.reporter.report(r),l("Client","Report completed successfully"),this.configManager.markContextReported();for(let i of r)this.pluginManager.applyAfterReport(i)}syncFlushEvents(e){let t=[];for(let i of e){let o=this.pluginManager.applyBeforeReport(i);o&&t.push(o)}if(t.length===0)return;let n=!0,r=[];for(let i of t){let o=this.configManager.applyToEvent(i,n);n=!1;let a=this.configManager.get("beforeSend"),u=a?a(o):o;u&&r.push(u)}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(l("Client","captureException called",{error:e instanceof Error?e.message:String(e)}),!this.enabled){l("Client","captureException skipped: SDK disabled");return}let t=this.buildErrorEvent(e);if(l("Client","Error event built",{type:t.type,message:t.message,fingerprint:t.fingerprint}),this.configManager.isIgnoredError(t.message)){l("Client","captureException skipped: error ignored by ignoreErrors");return}t.breadcrumbs=[...this.breadcrumbs],l("Client","Enqueue error event",{breadcrumbs:this.breadcrumbs.length}),this.queue.enqueue(t)}captureMessage(e,t="info"){if(!this.enabled)return;let n={type:"error",level:t,message:e,timestamp:p(),breadcrumbs:[...this.breadcrumbs]};this.configManager.isIgnoredError(e)||this.queue.enqueue(n)}captureEvent(e){if(!this.enabled)return;let t={timestamp:p(),level:"info",breadcrumbs:[...this.breadcrumbs],...e};this.queue.enqueue(t)}buildErrorEvent(e){let t=p();if(e instanceof Error){let r=P(e.stack,{maxFrames:5}),i=T(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:p()};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=[]}},j=K;var W=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&&b(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?L(e,this.config.ignoreErrors||[]):!1}shouldIgnoreScriptUrl(e){return D(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 o=this.buildErrorEvent(i||e,t,n,r);o&&this.client.captureEvent(o)}catch(o){console.error("[LightSDK] ErrorPlugin global error handler error:",o)}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 o=`resource:${n}`,a=R(r);this.client.captureEvent({type:"error",level:"warning",message:`Resource load failed: ${n} ${a}`,timestamp:p(),fingerprint:o,tags:{resource_type:n,resource_url:a},exception:{type:"ResourceError",value:`Failed to load ${n} resource`}})}catch(o){console.error("[LightSDK] ErrorPlugin resource error handler error:",o)}},window.addEventListener("error",this.onResourceError,!0))}buildErrorEvent(e,t,n,r){let i=p();if(e instanceof Error){if(this.shouldIgnoreError(e.message))return null;let u=P(e.stack,{captureNodeModules:this.config.captureNodeModules,captureColumn:this.config.captureColumn,relativePathOnly:this.config.relativePathOnly,maxFrames:this.config.maxStackFrames});if(!this.shouldIncludePath(u)||!this.shouldSample())return null;let c=T(e.name,e.message,u);return{type:"error",level:"error",message:e.message,timestamp:i,exception:{type:e.name,value:e.message,stacktrace:{frames:u}},fingerprint:c}}let o=String(e);if(this.shouldIgnoreError(o))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:o,timestamp:i,exception:{type:"Error",value:o,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))}},X=W;var A=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&&b(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 o=i.getEntries();for(let a of o)if(!a.hadRecentInput){let u=n[0],c=n[n.length-1];t&&a.startTime-((c==null?void 0:c.duration)||0)<1e3&&a.startTime-u.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 o=r.duration-50;o>0&&(this.totalBlockingTime+=o)}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 o=this.getRating(e,t),a={type:"performance",level:"info",metric:e,value:Math.round(t*100)/100,unit:n,rating:o,timestamp:p(),tags:{metric:e,rating:o,...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)}},z=A;var V=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&&b(e.network)&&(this.config={...this.config,...e.network}),e.ignoreUrls&&(this.config.ignoreUrls=[...this.config.ignoreUrls||[],...e.ignoreUrls])}shouldIgnore(e){return D(e,this.config.ignoreUrls||[])}shouldSample(e,t){var r,i,o,a;let n=e?(r=this.config.errorSampleRate)!=null?r:1:(i=this.config.successSampleRate)!=null?i:.01;return!e&&t>=((o=this.config.slowThreshold)!=null?o: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=p(),i=typeof t=="string"?t:t instanceof URL?t.toString():t.url,o=(n==null?void 0:n.method)||"GET";if(e.shouldIgnore(i))return e.originalFetch.call(window,t,n);let a=R(i),u=e.originalFetch.call(window,t,n);return u.then(c=>{var f;let h=p()-r,w=c.ok,g=c.status;return(f=e.config.ignoreStatusCodes)!=null&&f.includes(g)||!e.shouldSample(!w,h)||(!w||e.config.captureSuccess)&&e.reportNetwork({sub_type:"fetch",method:o.toUpperCase(),url:a,status_code:g,duration:h,success:w,error:w?void 0:`HTTP ${g}`}),c},c=>{let h=p()-r;throw e.shouldSample(!0,h)&&e.reportNetwork({sub_type:"fetch",method:o.toUpperCase(),url:a,duration:h,success:!1,error:(c==null?void 0:c.message)||"Network error"}),c}),u}}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=p(),r=this._lightMethod||"GET",i=this._lightUrl||"",o=this._lightTracked;if(e.shouldIgnore(i)||o)return e.originalXHRSend.apply(this,arguments);this._lightTracked=!0;let a=R(i),u=0;t&&typeof t=="string"&&(u=t.length);let c=this.onloadend;return this.onloadend=function(h){var y;let w=p()-n,g=this.status,f=g>=200&&g<300;if(!((y=e.config.ignoreStatusCodes)!=null&&y.includes(g))&&e.shouldSample(!f,w)&&(!f||e.config.captureSuccess)){let m=0;try{let S=this.getResponseHeader("content-length");S&&(m=parseInt(S,10)),!m&&this.responseText&&(m=this.responseText.length)}catch(S){}e.reportNetwork({sub_type:"xhr",method:r.toUpperCase(),url:a,status_code:g,duration:w,request_size:u||void 0,response_size:m||void 0,success:f,error:f?void 0:`HTTP ${g}`})}if(c)return c.call(this,h)},e.originalXHRSend.apply(this,arguments)}}reportNetwork(e){let t={type:"network",level:e.success?"info":"error",timestamp:p(),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)}},Q=V;var G=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&&b(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=E(),t=R(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,u,c;let t=p(),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 h=r.className.split(" ").filter(Boolean).slice(0,3).join(".");h&&(i+=`.${h}`)}let o=(u=r.textContent)==null?void 0:u.trim().slice(0,50);this.reportBehavior({sub_type:"click",page_url:E(),properties:{selector:i,text:o||void 0,tag:(c=r.tagName)==null?void 0:c.toLowerCase(),x:e.clientX,y:e.clientY}})},document.addEventListener("click",this.onClick,!0))}trackRoute(){if(typeof window=="undefined")return;let e=E(),t=()=>{let r=E();if(r!==e){let i=e,o=r;e=r,this.reportBehavior({sub_type:"route",page_url:o,referrer:i,properties:{from:i,to:o}}),this.pageEnterTime=p(),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=p();let e=()=>{let t=p()-this.pageEnterTime;t>1e3&&(this.config.captureScroll&&!this.scrollReported&&this.reportScroll(),this.reportBehavior({sub_type:"duration",page_url:E(),properties:{duration:t,max_scroll_depth:this.maxScrollDepth}}))};this.onVisibilityChange=()=>{document.hidden?e():this.pageEnterTime=p()},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=p(),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:E(),properties:{max_depth:this.maxScrollDepth}}))}reportBehavior(e){if(!this.shouldSample())return;let t={type:"behavior",level:"info",timestamp:p(),tags:{sub_type:e.sub_type,page_url:E()},...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))}},J=G;var qe="light-sentry-offline",v="events",Z=1e3,Y=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(qe,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,o=r.oldVersion;i.objectStoreNames.contains(v)||i.createObjectStore(v,{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([v],"readwrite").objectStore(v),u={id:this.generateId(),event:{...e,offline:!0},timestamp:p()},c=a.add(u);c.onsuccess=()=>r(),c.onerror=()=>i(c.error)})}getEventCount(){return this.db?new Promise((e,t)=>{let i=this.db.transaction([v],"readonly").objectStore(v).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([v],"readwrite").objectStore(v).index("timestamp").openCursor(),u=0;a.onsuccess=c=>{let h=c.target.result;h&&u<e?(h.delete(),u++,h.continue()):t()},a.onerror=()=>n(a.error)})}async getAllStoredEvents(){return this.db?new Promise((e,t)=>{let o=this.db.transaction([v],"readonly").objectStore(v).index("timestamp").getAll();o.onsuccess=()=>{let a=o.result||[];a.sort((u,c)=>u.timestamp-c.timestamp),e(a)},o.onerror=()=>t(o.error)}):[]}async clearStoredEvents(){if(this.db)return new Promise((e,t)=>{let i=this.db.transaction([v],"readwrite").objectStore(v).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)}},ee=Y;var te=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&&b(e.sampling)){let t=e.sampling;"rates"in t&&b(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){var n;return this.shouldSample(e)?e:(l("SamplingPlugin","Event dropped by sampling",{type:e.type,globalRate:(n=this.client.config.sampleRate)!=null?n:1,typeRate:this.getTypeRate(e)}),null)}destroy(){}},ne=te;var d=null;function de(s){var r;M(s.debug===!0),l("Index","init called",{dsn:s.dsn,debug:s.debug});let e=new j(s),t=[new ee,new ne,new X],n=((r=s.plugins)==null?void 0:r.filter(i=>typeof i=="string"))||[];(n.includes("performance")||n.includes("all"))&&t.push(new z),(n.includes("network")||n.includes("all"))&&t.push(new Q),(n.includes("behavior")||n.includes("all"))&&t.push(new J),l("Index","Registering plugins",{count:t.length,plugins:t.map(i=>i.name)});for(let i of t)e.use(i);if(s.plugins)for(let i of s.plugins)typeof i=="object"&&i!==null&&"name"in i&&"setup"in i&&e.use(i);return e.init(),d=e,l("Index","init completed, globalClient set"),e}function pe(){return d}function he(s){if(l("Index","captureException called",{hasClient:!!d}),!d){console.warn("[LightSDK] SDK not initialized. Call LightSentry.init() first.");return}d.captureException(s)}function fe(s,e){if(l("Index","captureMessage called",{hasClient:!!d}),!d){console.warn("[LightSDK] SDK not initialized. Call LightSentry.init() first.");return}d.captureMessage(s,e)}function ge(s){if(l("Index","captureEvent called",{hasClient:!!d}),!d){console.warn("[LightSDK] SDK not initialized. Call LightSentry.init() first.");return}d.captureEvent(s)}function me(s){d==null||d.setUser(s)}function ve(s,e){d==null||d.setTag(s,e)}function ye(s){d==null||d.setTags(s)}function be(s,e){d==null||d.setExtra(s,e)}function Ee(s){d==null||d.addBreadcrumb(s)}async function we(){await(d==null?void 0:d.flush())}function Se(){d==null||d.disable()}function xe(){d==null||d.enable()}var Ne={init:de,getClient:pe,captureException:he,captureMessage:fe,captureEvent:ge,setUser:me,setTag:ve,setTags:ye,setExtra:be,addBreadcrumb:Ee,flush:we,disable:Se,enable:xe};